Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(engine-sql): get_health as a SQL aggregate in engine-sql/health.ts

garrytanfe2865482c62
diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsv
index f5bc04ce81..c38676eb32 100644
--- a/scripts/engine-sql-baseline.tsv
+++ b/scripts/engine-sql-baseline.tsv
@@ -13,6 +13,7 @@ migrated cjk-search
migrated code-edges
migrated facts
migrated files
+migrated health
migrated links
migrated pages
migrated salience
@@ -28,7 +29,6 @@ method src/core/pglite-engine.ts PGLiteEngine.findOntologyConflicts
method src/core/pglite-engine.ts PGLiteEngine.getAllConfig
method src/core/pglite-engine.ts PGLiteEngine.getConfig
method src/core/pglite-engine.ts PGLiteEngine.getDreamVerdict
-method src/core/pglite-engine.ts PGLiteEngine.getHealth
method src/core/pglite-engine.ts PGLiteEngine.getIngestLog
method src/core/pglite-engine.ts PGLiteEngine.getOntology
method src/core/pglite-engine.ts PGLiteEngine.getRawData
@@ -59,7 +59,6 @@ method src/core/postgres-engine.ts PostgresEngine.findOntologyConflicts
method src/core/postgres-engine.ts PostgresEngine.getAllConfig
method src/core/postgres-engine.ts PostgresEngine.getConfig
method src/core/postgres-engine.ts PostgresEngine.getDreamVerdict
-method src/core/postgres-engine.ts PostgresEngine.getHealth
method src/core/postgres-engine.ts PostgresEngine.getIngestLog
method src/core/postgres-engine.ts PostgresEngine.getOntology
method src/core/postgres-engine.ts PostgresEngine.getRawData
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d83f5a962..dd9239d5b5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,8 +20,8 @@ src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2232 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 332 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line)
-src/core/pglite-engine.ts 3117 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108)
-src/core/postgres-engine.ts 3130 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133)
+src/core/pglite-engine.ts 2915 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202)
+src/core/postgres-engine.ts 2914 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2112 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field)
src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
diff --git a/src/core/engine-sql/health.ts b/src/core/engine-sql/health.ts
new file mode 100644
index 0000000000..3ed7779108
--- /dev/null
+++ b/src/core/engine-sql/health.ts
@@ -0,0 +1,263 @@
+/**
+ * Health: `getHealth` once for both engines (FOUNDATIONS 1, F4a).
+ *
+ * Three statements, no per-page rows returned to TypeScript:
+ * 1. counters: page, chunk and link counts, embedding coverage, missing
+ * embeddings, dead links, entity link/timeline coverage;
+ * 2. the linkable scope (live, unquarantined pages the shared orphan policy
+ * keeps, rendered in SQL by `orphanExclusionSql`) grouped by page type,
+ * with islanded and with-timeline counts per type. The brain_score
+ * timeline component's pack-aware grading (#5828) applies per type here;
+ * 3. `most_connected`: in-scope link endpoints grouped per entity page.
+ * Statement 2 is separate because, folded into statement 1, the combined
+ * plan cost crosses Postgres's JIT thresholds on a 20k-page brain and JIT
+ * compilation alone costs more than the query.
+ *
+ * Planner robustness: PGLite has no autovacuum, so a brain can be queried
+ * before its first ANALYZE. Without statistics the planner underestimates
+ * every filtered relation and picks nested loops that re-scan a subquery or
+ * materialized set per outer row. The per-page and per-link checks that
+ * were exposed to that (linkable flags, entity link coverage, endpoint scope
+ * in `most_connected`, the chunk-to-page lookup) are written as primary-key
+ * lookups the planner cannot reorder: scalar subqueries, or a LATERAL
+ * subquery fenced with OFFSET 0. They stay linear with or without statistics.
+ *
+ * Scope (#4592): `sourceIds` > `sourceId` > brain-wide; duplicate ids count
+ * once. Every count, coverage numerator and denominator, degree and the
+ * islanded predicate confine to the scope; a link contributes only when both
+ * endpoints are in scope, so a granted-to-ungranted edge never leaks the far
+ * side through a degree or rescues a page from orphan-hood. Page-scoped
+ * counts exclude soft-deleted pages (#1305); chunk and link counts stay raw,
+ * matching getStats. Endpoint liveness (gbrain#4153): an inbound link counts
+ * only when its source page is live, an outbound link only when its target
+ * is. Quarantined pages (#4280) leave the entity denominators and the
+ * linkable scope; machine leaf types leave the linkable scope through the
+ * policy.
+ *
+ * Both engines ran these reads on the pool with no scope transaction, so the
+ * statements take `LegacyUnscopedRead`.
+ */
+import type { BrainHealth } from '../types.ts';
+import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../types.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';
+import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
+import { loadOrphanPolicyOverrides, orphanExclusionSql } from '../orphan-policy.ts';
+import { loadTimelineGradedPredicate } from '../timeline-grading.ts';
+import { quoteIdentifier } from '../search/embedding-column.ts';
+import type { LegacyUnscopedRead } from './brands.ts';
+import { sqlFragment, trustedSql } from './fragment.ts';
+import { compileRowNormalizer } from './normalize.ts';
+
+/** What getHealth needs from its engine besides the executor. */
+export interface HealthDeps {
+ /** Name of the registry-active embedding column (legacy column when the registry is unreadable). */
+ embeddingColumn(): Promise<string>;
+ countStalePagesForExtraction(opts: { sourceId?: string; versionTs: string }): Promise<number>;
+ getConfig(key: string): Promise<string | null>;
+}
+
+interface LinkableTypeGroup {
+ type: string;
+ linkable: number;
+ islanded: number;
+ with_timeline: number;
+}
+
+interface HealthAggregateRow {
+ page_count: number;
+ embed_coverage: number;
+ dead_links: number;
+ missing_embeddings: number;
+ link_count: number;
+ entity_page_count: number;
+ link_coverage: number;
+ timeline_coverage: number;
+}
+
+const normalizeAggregate = compileRowNormalizer<HealthAggregateRow>({
+ page_count: 'bigint',
+ dead_links: 'bigint',
+ missing_embeddings: 'bigint',
+ link_count: 'bigint',
+ entity_page_count: 'bigint',
+});
+
+export async function getHealth(
+ exec: LegacyUnscopedRead,
+ opts: { sourceId?: string; sourceIds?: string[] } | undefined,
+ deps: HealthDeps,
+): Promise<BrainHealth> {
+ const requested = opts?.sourceIds ?? (opts?.sourceId ? [opts.sourceId] : null);
+ const scope = requested === null ? null : [...new Set(requested)];
+ const [column, orphanOverrides, isTimelineGraded] = await Promise.all([
+ deps.embeddingColumn(),
+ loadOrphanPolicyOverrides(deps),
+ loadTimelineGradedPredicate(deps),
+ ]);
+ const col = trustedSql(quoteIdentifier(column));
+ const inScope = {
+ p: scope === null ? sqlFragment`` : sqlFragment`AND p.source_id = ANY(${scope}::text[])`,
+ src: scope === null ? sqlFragment`` : sqlFragment`AND src.source_id = ANY(${scope}::text[])`,
+ tgt: scope === null ? sqlFragment`` : sqlFragment`AND tgt.source_id = ANY(${scope}::text[])`,
+ };
+ // Endpoint checks by primary key; NULL (not true) when the row is missing.
+ const liveSrc = sqlFragment`(SELECT src.deleted_at IS NULL ${inScope.src} FROM pages src WHERE src.id = l.from_page_id)`;
+ const liveTgt = sqlFragment`(SELECT tgt.deleted_at IS NULL ${inScope.tgt} FROM pages tgt WHERE tgt.id = l.to_page_id)`;
+ const srcInScope = sqlFragment`(SELECT TRUE ${inScope.src} FROM pages src WHERE src.id = l.from_page_id)`;
+ const tgtInScope = sqlFragment`(SELECT TRUE ${inScope.tgt} FROM pages tgt WHERE tgt.id = l.to_page_id)`;
+ const deadLinkScope = scope === null
+ ? sqlFragment``
+ : sqlFragment`AND EXISTS (SELECT 1 FROM pages src WHERE src.id = l.from_page_id ${inScope.src})`;
+ const linkCountScope = scope === null
+ ? sqlFragment``
+ : sqlFragment`WHERE EXISTS (SELECT 1 FROM pages src WHERE src.id = l.from_page_id ${inScope.src})
+ AND EXISTS (SELECT 1 FROM pages tgt WHERE tgt.id = l.to_page_id ${inScope.tgt})`;
+
+ const { rows: [aggregate] } = await exec.run(sqlFragment`
+ WITH entity_pages AS (
+ SELECT p.id FROM pages p
+ WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
+ AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}
+ ${inScope.p}
+ ),
+ chunk_pages AS (
+ SELECT cc.page_id, count(*) AS chunks, count(*) FILTER (WHERE cc.${col} IS NOT NULL) AS embedded
+ FROM content_chunks cc
+ GROUP BY cc.page_id
+ ),
+ chunk_totals AS (
+ SELECT COALESCE(sum(c.chunks) FILTER (WHERE f.eligible), 0) AS eligible,
+ COALESCE(sum(c.embedded) FILTER (WHERE f.eligible), 0) AS eligible_embedded,
+ COALESCE(sum(c.chunks - c.embedded) FILTER (WHERE f.eligible AND f.live), 0) AS missing
+ FROM chunk_pages c
+ CROSS JOIN LATERAL (
+ SELECT p.deleted_at IS NULL AS live,
+ NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip') AS eligible
+ FROM pages p
+ WHERE p.id = c.page_id ${inScope.p}
+ OFFSET 0
+ ) f
+ )
+ SELECT
+ (SELECT count(*) FROM pages p WHERE p.deleted_at IS NULL ${inScope.p}) AS page_count,
+ (SELECT CASE WHEN eligible = 0 THEN 1.0 ELSE eligible_embedded::float / eligible::float END
+ FROM chunk_totals)::float AS embed_coverage,
+ (SELECT count(*) FROM links l
+ WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
+ ${deadLinkScope}) AS dead_links,
+ (SELECT missing::bigint FROM chunk_totals) AS missing_embeddings,
+ (SELECT count(*) FROM links l ${linkCountScope}) AS link_count,
+ (SELECT count(*) FROM entity_pages) AS entity_page_count,
+ (SELECT count(*) FROM entity_pages e
+ WHERE EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id AND ${liveSrc}))::float /
+ GREATEST((SELECT count(*) FROM entity_pages), 1)::float AS link_coverage,
+ (SELECT count(*) FROM entity_pages e
+ WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
+ GREATEST((SELECT count(*) FROM entity_pages), 1)::float AS timeline_coverage
+ `);
+ const h = normalizeAggregate(aggregate);
+
+ const { rows: linkableGroups } = await exec.run<LinkableTypeGroup>(sqlFragment`
+ WITH linkable_pages AS MATERIALIZED (
+ SELECT p.type,
+ (NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id AND ${liveSrc})
+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND ${liveTgt})) AS islanded,
+ EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) AS has_timeline
+ FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}
+ ${inScope.p}
+ AND NOT ${orphanExclusionSql('p', orphanOverrides)}
+ )
+ SELECT type, count(*)::int AS linkable,
+ (count(*) FILTER (WHERE islanded))::int AS islanded,
+ (count(*) FILTER (WHERE has_timeline))::int AS with_timeline
+ FROM linkable_pages
+ GROUP BY type
+ ORDER BY type
+ `);
+
+ const farInScope = {
+ to: scope === null ? sqlFragment`` : sqlFragment`AND ${tgtInScope}`,
+ from: scope === null ? sqlFragment`` : sqlFragment`AND ${srcInScope}`,
+ };
+ const { rows: connected } = await exec.run<{ slug: string; link_count: number }>(sqlFragment`
+ WITH entity_pages AS (
+ SELECT p.id, p.slug FROM pages p
+ WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
+ AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}
+ ${inScope.p}
+ ),
+ endpoints AS (
+ SELECT e.id, e.slug, 0 AS hit FROM entity_pages e
+ UNION ALL
+ SELECT e.id, e.slug, 1 AS hit FROM entity_pages e
+ JOIN links l ON l.from_page_id = e.id ${farInScope.to}
+ UNION ALL
+ SELECT e.id, e.slug, 1 AS hit FROM entity_pages e
+ JOIN links l ON l.to_page_id = e.id AND l.from_page_id <> l.to_page_id ${farInScope.from}
+ )
+ SELECT slug, sum(hit)::int AS link_count
+ FROM endpoints
+ GROUP BY id, slug
+ ORDER BY link_count DESC, slug COLLATE "C", id
+ LIMIT 5
+ `);
+
+ const stalePages = scope === null
+ ? await deps.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })
+ : (await Promise.all(scope.map(sourceId =>
+ deps.countStalePagesForExtraction({ sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS }),
+ ))).reduce((a, b) => a + b, 0);
+
+ let linkablePageCount = 0;
+ let orphanPages = 0;
+ let timelineGradedCount = 0;
+ let linkableTimelinePages = 0;
+ for (const group of linkableGroups) {
+ linkablePageCount += Number(group.linkable);
+ orphanPages += Number(group.islanded);
+ if (!isTimelineGraded(group.type)) continue;
+ timelineGradedCount += Number(group.linkable);
+ linkableTimelinePages += Number(group.with_timeline);
+ }
+
+ const pageCount = h.page_count;
+ const embedCoverage = Number(h.embed_coverage);
+ const deadLinks = h.dead_links;
+ const linkCount = h.link_count;
+ const linkDensity = pageCount > 0 ? Math.min(linkCount / pageCount, 1) : 0;
+ // A brain with no linkable (or no graded) pages gets full marks for the
+ // orphan / timeline components: there is no curated graph to penalize.
+ const timelineDensity = timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;
+ const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;
+ const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
+ // Empty brains (pageCount === 0) score 100/100: nothing to embed, link or orphan.
+ const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
+ const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
+ const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineDensity * 15);
+ const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
+ const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
+ // gbrain#4147: below the small-N floor the entity ratios report null.
+ const coverageGraded = h.entity_page_count >= MIN_ENTITY_PAGES_FOR_COVERAGE;
+
+ return {
+ page_count: pageCount,
+ linkable_page_count: linkablePageCount,
+ embed_coverage: embedCoverage,
+ stale_pages: stalePages,
+ orphan_pages: orphanPages,
+ missing_embeddings: h.missing_embeddings,
+ brain_score: embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore,
+ dead_links: deadLinks,
+ entity_page_count: h.entity_page_count,
+ link_coverage: coverageGraded ? Number(h.link_coverage) : null,
+ timeline_coverage: coverageGraded ? Number(h.timeline_coverage) : null,
+ most_connected: connected.map(c => ({ slug: c.slug, link_count: Number(c.link_count) })),
+ embed_coverage_score: embedCoverageScore,
+ link_density_score: linkDensityScore,
+ timeline_coverage_score: timelineCoverageScore,
+ no_orphans_score: noOrphansScore,
+ no_dead_links_score: noDeadLinksScore,
+ };
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 4661899cc8..d14559aaef 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -111,15 +111,12 @@ import type {
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, rowToChunk, rowToSearchResult, isUndefinedTableError, warnOncePerProcess } from './utils.ts';
import { executeRawJsonb, type SqlValue } from './sql-query.ts';
import { sanitizeForJsonb, sanitizeText, buildLinkRows, buildTimelineRows } from './batch-rows.ts';
-import { PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';
+import { PAGE_SORT_SQL } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';
import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
-import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides, gradeTimelinePages } from './orphan-policy.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
-import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from './quarantine.ts';
import {
vectorCastSuffix,
resolveActiveEmbeddingColumnFromEngine,
@@ -138,6 +135,7 @@ import { scopedRead, unscopedExecutor } from './engine-sql/brands.ts';
import * as codeEdgesImpl from './engine-sql/code-edges.ts';
import { getEdgesByChunk as getEdgesByChunkPglite, type PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';
import * as salienceImpl from './engine-sql/salience.ts';
+import * as healthImpl from './engine-sql/health.ts';
import * as pagesImpl from './engine-sql/pages.ts';
import * as tagsImpl from './engine-sql/tags.ts';
import * as linksImpl from './engine-sql/links.ts';
@@ -2601,211 +2599,11 @@ export class PGLiteEngine implements BrainEngine {
}
async getHealth(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<BrainHealth> {
- // Combined metrics from master (brain_score components: dead_links, link_count,
- // pages_with_timeline) and v0.10.3 graph layer (link_coverage, timeline_coverage,
- // most_connected). Both coexist: master's brain_score is the composite
- // dashboard, v0.10.3 metrics give entity-page-level granularity.
- // #1305: every page-scoped count here excludes soft-deleted rows — same
- // posture as getStats — so brain_score moves when the user deletes pages.
- // Chunk/link counts stay raw (storage until the purge phase), matching
- // getStats, and destructive-removal counts elsewhere deliberately stay raw.
- // S2: coverage + missing_embeddings key on the registry-ACTIVE column.
- // #4592: optional source scope — parity with postgres-engine.getHealth
- // (bound as $1, never interpolated; both-endpoint rule for link-derived
- // numbers; out-of-scope endpoints can't rescue a page from orphan-hood).
- const scope: string[] | null = opts?.sourceIds ?? (opts?.sourceId ? [opts.sourceId] : null);
- const colId = await this.activeEmbeddingColId({ fallbackToLegacy: true });
- const { rows: [h] } = await this.db.query(`
- WITH scoped_pages AS (
- SELECT id, slug, frontmatter, deleted_at, source_id FROM pages p
- WHERE ($1::text[] IS NULL OR p.source_id = ANY($1))
- ),
- entity_pages AS (
- -- #4280: quarantined entity shells are not served memory — keep them
- -- out of the link/timeline coverage denominators (parity with
- -- onboard's VISIBLE_ENTITY_PREDICATE).
- SELECT id, slug FROM scoped_pages WHERE id IN (
- SELECT id FROM pages WHERE type IN ('entity', 'person', 'company') AND deleted_at IS NULL
- AND ${quarantineFilterFragment('pages')}
- )
- )
- SELECT
- (SELECT count(*) FROM scoped_pages WHERE deleted_at IS NULL) as page_count,
- -- Parity with postgres-engine: stored-VECTOR truth over ELIGIBLE
- -- chunks (embedding, not embedded_at; embed_skip excluded from BOTH
- -- sides; zero eligible = vacuous 100%).
- (SELECT CASE
- WHEN count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')) = 0
- THEN 1.0
- ELSE count(*) FILTER (WHERE cc.${colId} IS NOT NULL
- AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
- / count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
- END
- FROM content_chunks cc
- JOIN scoped_pages p ON p.id = cc.page_id) as embed_coverage,
- 0 as stale_pages,
- -- Bug 11 — orphan = islanded (no inbound AND no outbound). The raw
- -- list is filtered in TS using the shared orphan-reporting policy.
- 0 as orphan_pages,
- (SELECT count(*) FROM links l
- WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
- AND ($1::text[] IS NULL
- OR EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id))
- ) as dead_links,
- -- Parity with postgres-engine.ts: same predicate as
- -- buildStaleChunkWhere / countStaleChunks, i.e. what 'embed --stale'
- -- actually processes. 'embedding IS NULL' (not embedded_at, which can
- -- be non-NULL while embedding is NULL) and embed_skip excluded, so the
- -- count can reach zero and the embed.stale remediation can converge.
- (SELECT count(*) FROM content_chunks cc
- JOIN scoped_pages p ON p.id = cc.page_id
- WHERE cc.${colId} IS NULL AND p.deleted_at IS NULL
- AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
- ) as missing_embeddings,
- (SELECT count(*) FROM links l
- WHERE ($1::text[] IS NULL
- OR (EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id)
- AND EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.to_page_id)))) as link_count,
- (SELECT count(*) FROM entity_pages) as entity_page_count,
- -- gbrain#4153 consistency: an inbound link counts toward coverage
- -- only when its SOURCE page is live — the same endpoint-liveness rule
- -- the islanded predicate below applies, so an entity whose only
- -- inbound link comes from a soft-deleted page can't read as covered
- -- AND islanded in one payload.
- (SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM links l
- JOIN scoped_pages src ON src.id = l.from_page_id
- WHERE l.to_page_id = e.id AND src.deleted_at IS NULL))::float /
- GREATEST((SELECT count(*) FROM entity_pages), 1)::float as link_coverage,
- (SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
- GREATEST((SELECT count(*) FROM entity_pages), 1)::float as timeline_coverage
- `, [scope]);
-
- // Top 5 most connected entities by total link count (in + out).
- // X8 (#4592): a degree counts an edge only when its FAR endpoint is in
- // scope too — parity with postgres-engine's rule and comment.
- const { rows: connected } = await this.db.query(`
- SELECT p.slug,
- (SELECT count(*) FROM links l
- WHERE (l.from_page_id = p.id
- AND ($1::text[] IS NULL
- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.to_page_id AND fp.source_id = ANY($1))))
- OR (l.to_page_id = p.id
- AND ($1::text[] IS NULL
- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.from_page_id AND fp.source_id = ANY($1))))
- )::int as link_count
- FROM pages p
- WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
- AND ${QUARANTINE_FILTER_FRAGMENT}
- AND ($1::text[] IS NULL OR p.source_id = ANY($1))
- ORDER BY link_count DESC
- LIMIT 5
- `, [scope]);
-
- // Per-page flags for the linkable scope: orphan_pages and the
- // no-orphans / timeline-coverage DENOMINATORS are all computed over
- // pages the shared orphan-reporting policy considers linkable (the same
- // scope `gbrain orphans` and doctor's orphan_ratio use), so one doctor
- // report cannot carry two contradictory orphan/coverage numbers.
- // Archive (raw/), generated, and daily-log pages are not expected to
- // participate in the curated graph. Filtered in TS because the policy
- // includes per-brain config overrides.
- // gbrain#4153: endpoint liveness in BOTH directions — an inbound link
- // only counts when its SOURCE page is live (the invariant
- // findOrphanPages documents), and an outbound link only counts when its
- // TARGET is live. Without this, get_health's orphan_pages disagreed with
- // `gbrain orphans` whenever a soft-deleted page still linked to (or was
- // linked from) a live one.
- // #4592: out-of-scope endpoints cannot rescue a page from orphan-hood.
- // #4280: quarantined pages drop out of the linkable scope in SQL;
- // machine leaf types (atom/conversation/source) drop out through the
- // shared policy below via p.type.
- const { rows: pageScopeRows } = await this.db.query(`
- SELECT p.slug, p.type,
- (NOT EXISTS (SELECT 1 FROM links l
- JOIN pages src ON src.id = l.from_page_id
- WHERE l.to_page_id = p.id AND src.deleted_at IS NULL
- AND ($1::text[] IS NULL OR src.source_id = ANY($1)))
- AND NOT EXISTS (SELECT 1 FROM links l
- JOIN pages tgt ON tgt.id = l.to_page_id
- WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL
- AND ($1::text[] IS NULL OR tgt.source_id = ANY($1)))) as islanded,
- EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
- FROM pages p
- WHERE p.deleted_at IS NULL
- AND ${QUARANTINE_FILTER_FRAGMENT}
- AND ($1::text[] IS NULL OR p.source_id = ANY($1))
- `, [scope]);
-
- const r = h as Record<string, unknown>;
- const pageCount = Number(r.page_count);
- const embedCoverage = Number(r.embed_coverage);
- // Scoped: sum the scalar-sourceId counter per grant (parity with
- // postgres-engine; the unmatchable __all__ scalar fail-closes to 0).
- const stalePages = scope === null
- ? await this.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })
- : (await Promise.all(scope.map(sid =>
- this.countStalePagesForExtraction({ sourceId: sid, versionTs: LINK_EXTRACTOR_VERSION_TS }),
- ))).reduce((a, b) => a + b, 0);
- const orphanOverrides = await loadOrphanPolicyOverrides(this);
- const linkablePages = (pageScopeRows as { slug: string; type: string; islanded: boolean; has_timeline: boolean }[])
- .filter(row => !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides, { type: row.type }));
- const linkablePageCount = linkablePages.length;
- const orphanPages = linkablePages.filter(row => row.islanded).length;
- const { graded: timelineGradedCount, withTimeline: linkableTimelinePages } = await gradeTimelinePages(this, linkablePages); // #5828
- const deadLinks = Number(r.dead_links);
- const linkCount = Number(r.link_count);
-
- const linkDensity = pageCount > 0 ? Math.min(linkCount / pageCount, 1) : 0;
- // linkablePageCount === 0 gets full marks for the orphan / timeline
- // components (same vacuous-truth rule as the empty-brain fix below):
- // an all-archive brain has no curated graph to penalize.
- const timelineCoverageDensity =
- timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;
- const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;
- const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
- // Bug 11 — per-component points. Sum equals brainScore by construction
- // so `doctor` can render a breakdown that adds up to the total.
- //
- // v0.37.10.0: empty brains (pageCount === 0) get FULL marks (100/100),
- // not 0. Semantically an empty brain has no coverage problem to penalize
- // — there's nothing to embed, nothing to link, nothing to orphan. The
- // pre-fix "empty = 0" caused fresh-init brains to score as critically
- // unhealthy on `gbrain doctor`, which was a structural surprise to users
- // who'd just successfully run init.
- const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
- const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
- const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineCoverageDensity * 15);
- const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
- const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
- const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
-
- return {
- page_count: pageCount,
- linkable_page_count: linkablePageCount,
- embed_coverage: embedCoverage,
- stale_pages: stalePages,
- orphan_pages: orphanPages,
- missing_embeddings: Number(r.missing_embeddings),
- brain_score: brainScore,
- dead_links: deadLinks,
- entity_page_count: Number(r.entity_page_count),
- // gbrain#4147: below the small-N floor the ratio is statistically
- // meaningless (0/0 used to read as a hard 0%), so it reports null and
- // consumers suppress both the percentage and its remediation actions.
- link_coverage: Number(r.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(r.link_coverage) : null,
- timeline_coverage: Number(r.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(r.timeline_coverage) : null,
- most_connected: (connected as { slug: string; link_count: number }[]).map(c => ({
- slug: c.slug,
- link_count: Number(c.link_count),
- })),
- embed_coverage_score: embedCoverageScore,
- link_density_score: linkDensityScore,
- timeline_coverage_score: timelineCoverageScore,
- no_orphans_score: noOrphansScore,
- no_dead_links_score: noDeadLinksScore,
- };
+ return healthImpl.getHealth(unscopedExecutor(this.engineSql, 'health: unscoped on master (EO4 inventory)'), opts, {
+ embeddingColumn: async () => (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name,
+ countStalePagesForExtraction: (o) => this.countStalePagesForExtraction(o),
+ getConfig: (key) => this.getConfig(key),
+ });
}
// Ingest log
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 22f0eb4d45..a52481e1e5 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -94,7 +94,7 @@ import type {
EmotionalWeightInputRow, EmotionalWeightWriteRow,
EnrichCandidatesOpts, EnrichCandidate,
} from './types.ts';
-import { GBrainError, PAGE_SORT_SQL, MIN_ENTITY_PAGES_FOR_COVERAGE } from './types.ts';
+import { GBrainError, PAGE_SORT_SQL } from './types.ts';
import { finalizeLastSeen } from './chronicle/last-seen.ts';
import * as db from './db.ts';
import { ConnectionManager, DEFAULT_DIRECT_POOL_SIZE } from './connection-manager.ts';
@@ -108,16 +108,14 @@ import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defa
import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
import { PageMissingError } from './engine-errors.ts';
-import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides, gradeTimelinePages } from './orphan-policy.ts';
-import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
-import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from './quarantine.ts';
import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import * as factsImpl from './engine-sql/facts.ts';
import * as takesImpl from './engine-sql/takes.ts';
import * as codeEdgesImpl from './engine-sql/code-edges.ts';
import * as salienceImpl from './engine-sql/salience.ts';
+import * as healthImpl from './engine-sql/health.ts';
import * as pagesImpl from './engine-sql/pages.ts';
import * as tagsImpl from './engine-sql/tags.ts';
import * as linksImpl from './engine-sql/links.ts';
@@ -2392,225 +2390,11 @@ export class PostgresEngine implements BrainEngine {
}
async getHealth(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<BrainHealth> {
- const sql = this.sql;
- // #4592: optional source scope — same contract as getStats. Every count,
- // coverage numerator AND denominator, degree, and the islanded predicate
- // confine to the scope; a link only contributes when BOTH endpoints are
- // in scope (a granted→ungranted edge must not leak the far side's
- // existence through a degree or rescue a page from orphan-hood).
- const scope: string[] | null = opts?.sourceIds ?? (opts?.sourceId ? [opts.sourceId] : null);
- // Bug 11 doc-drift fix — orphan_pages means "islanded" (no inbound AND
- // no outbound links). The raw islanded list is filtered through the same
- // policy as `gbrain orphans` so convention pages do not count against
- // dashboard health.
- // #1305: every page-scoped count here excludes soft-deleted rows — same
- // posture as getStats — so brain_score moves when the user deletes pages.
- // Chunk/link counts stay raw (storage until the purge phase), matching
- // getStats, and destructive-removal counts elsewhere deliberately stay raw.
- // S2: coverage + missing_embeddings key on the registry-ACTIVE column.
- const colId = await this.activeEmbeddingColId({ fallbackToLegacy: true });
- const [h] = await sql`
- WITH scoped_pages AS (
- SELECT id, slug, frontmatter, deleted_at, source_id FROM pages p
- WHERE (${scope}::text[] IS NULL OR p.source_id = ANY(${scope}))
- ),
- entity_pages AS (
- -- #4280: quarantined entity shells are not served memory — keep them
- -- out of the link/timeline coverage denominators (parity with
- -- onboard's VISIBLE_ENTITY_PREDICATE).
- SELECT id, slug FROM scoped_pages WHERE id IN (
- SELECT id FROM pages WHERE type IN ('entity', 'person', 'company') AND deleted_at IS NULL
- AND ${sql.unsafe(quarantineFilterFragment('pages'))}
- )
- )
- SELECT
- (SELECT count(*) FROM scoped_pages WHERE deleted_at IS NULL) as page_count,
- -- Coverage is the stored-VECTOR truth over ELIGIBLE chunks: keyed on
- -- embedding (not embedded_at, which a schema rebuild leaves stale) and
- -- excluding embed_skip pages from BOTH sides so a brain with zero
- -- remediable work can't read as under-covered. Zero eligible chunks =
- -- vacuous 100%, matching missing_embeddings' exclusion below.
- (SELECT CASE
- WHEN count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')) = 0
- THEN 1.0
- ELSE count(*) FILTER (WHERE cc.${sql.unsafe(colId)} IS NOT NULL
- AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
- / count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
- END
- FROM content_chunks cc
- JOIN scoped_pages p ON p.id = cc.page_id) as embed_coverage,
- 0 as stale_pages,
- 0 as orphan_pages,
- (SELECT count(*) FROM links l
- WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
- AND (${scope}::text[] IS NULL
- OR EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id))
- ) as dead_links,
- -- missing_embeddings uses the same predicate as the thing that
- -- resolves it: buildStaleChunkWhere / countStaleChunks, i.e. what
- -- 'embed --stale' actually processes. Two divergences existed:
- -- 1. embedded_at vs embedding. upsertChunks resets BOTH to NULL
- -- when chunk_text changes, but the stale-chunk predicate keys
- -- on 'embedding IS NULL' deliberately (see the CONSISTENCY note
- -- on that upsert) because embedded_at can be non-NULL while
- -- embedding is NULL. Health should agree with the embedder.
- -- 2. embed_skip pages were counted here but excluded there, so
- -- chunks the author opted out of read as permanently "missing"
- -- and the count could never reach zero.
- -- Effect of the mismatch: computeRecommendations emits an embed.stale
- -- step from a number that 'embed --stale' reports as 0, so the step
- -- cannot move it and 'doctor --remediate' re-plans it every pass.
- (SELECT count(*) FROM content_chunks cc
- JOIN scoped_pages p ON p.id = cc.page_id
- WHERE cc.${sql.unsafe(colId)} IS NULL AND p.deleted_at IS NULL
- AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
- ) as missing_embeddings,
- (SELECT count(*) FROM links l
- WHERE (${scope}::text[] IS NULL
- OR (EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id)
- AND EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.to_page_id)))) as link_count,
- (SELECT count(*) FROM entity_pages) as entity_page_count,
- -- gbrain#4153 consistency: an inbound link counts toward coverage
- -- only when its SOURCE page is live — the same endpoint-liveness rule
- -- the islanded predicate below applies, so an entity whose only
- -- inbound link comes from a soft-deleted page can't read as covered
- -- AND islanded in one payload.
- (SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM links l
- JOIN scoped_pages src ON src.id = l.from_page_id
- WHERE l.to_page_id = e.id AND src.deleted_at IS NULL))::float /
- GREATEST((SELECT count(*) FROM entity_pages), 1)::float as link_coverage,
- (SELECT count(*) FROM entity_pages e
- WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
- GREATEST((SELECT count(*) FROM entity_pages), 1)::float as timeline_coverage
- `;
-
- // X8 (#4592): a degree counts an edge only when its FAR endpoint is in
- // scope too — otherwise a granted→ungranted edge leaks through the count.
- // NULL scope keeps the historical raw degree (far-endpoint EXISTS against
- // an unfiltered pages row is FK-total for live links; dead links kept by
- // the OR NOT EXISTS arm so unscoped output is byte-identical).
- const connected = await sql`
- SELECT p.slug,
- (SELECT count(*) FROM links l
- WHERE (l.from_page_id = p.id
- AND (${scope}::text[] IS NULL
- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.to_page_id AND fp.source_id = ANY(${scope}))))
- OR (l.to_page_id = p.id
- AND (${scope}::text[] IS NULL
- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.from_page_id AND fp.source_id = ANY(${scope}))))
- )::int as link_count
- FROM pages p
- WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
- AND ${sql.unsafe(QUARANTINE_FILTER_FRAGMENT)}
- AND (${scope}::text[] IS NULL OR p.source_id = ANY(${scope}))
- ORDER BY link_count DESC
- LIMIT 5
- `;
-
- // Per-page flags for the linkable scope: orphan_pages and the
- // no-orphans / timeline-coverage DENOMINATORS are all computed over
- // pages the shared orphan-reporting policy considers linkable (the same
- // scope `gbrain orphans` and doctor's orphan_ratio use), so one doctor
- // report cannot carry two contradictory orphan/coverage numbers.
- // Archive (raw/), generated, and daily-log pages are not expected to
- // participate in the curated graph. Filtered in TS because the policy
- // includes per-brain config overrides. PGLite path has the same logic.
- // gbrain#4153: endpoint liveness in BOTH directions — an inbound link
- // only counts when its SOURCE page is live (the invariant
- // findOrphanPages documents), and an outbound link only counts when its
- // TARGET is live. Without this, get_health's orphan_pages disagreed with
- // `gbrain orphans` whenever a soft-deleted page still linked to (or was
- // linked from) a live one.
- // #4592: out-of-scope endpoints cannot rescue a page from orphan-hood —
- // the caller's graph IS its grant.
- // #4280: quarantined pages drop out of the linkable scope in SQL;
- // machine leaf types (atom/conversation/source) drop out through the
- // shared policy below via p.type.
- const pageScopeRows = await sql<{ slug: string; type: string; islanded: boolean; has_timeline: boolean }[]>`
- SELECT p.slug, p.type,
- (NOT EXISTS (SELECT 1 FROM links l
- JOIN pages src ON src.id = l.from_page_id
- WHERE l.to_page_id = p.id AND src.deleted_at IS NULL
- AND (${scope}::text[] IS NULL OR src.source_id = ANY(${scope})))
- AND NOT EXISTS (SELECT 1 FROM links l
- JOIN pages tgt ON tgt.id = l.to_page_id
- WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL
- AND (${scope}::text[] IS NULL OR tgt.source_id = ANY(${scope})))) as islanded,
- EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
- FROM pages p
- WHERE p.deleted_at IS NULL
- AND ${sql.unsafe(QUARANTINE_FILTER_FRAGMENT)}
- AND (${scope}::text[] IS NULL OR p.source_id = ANY(${scope}))
- `;
-
- const pageCount = Number(h.page_count);
- const embedCoverage = Number(h.embed_coverage);
- // Scoped: sum the scalar-sourceId counter per grant (grants are small);
- // the unmatchable __all__ sentinel scalar fail-closes to 0 naturally.
- const stalePages = scope === null
- ? await this.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })
- : (await Promise.all(scope.map(sid =>
- this.countStalePagesForExtraction({ sourceId: sid, versionTs: LINK_EXTRACTOR_VERSION_TS }),
- ))).reduce((a, b) => a + b, 0);
- const orphanOverrides = await loadOrphanPolicyOverrides(this);
- const linkablePages = pageScopeRows.filter(row =>
- !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides, { type: row.type }));
- const linkablePageCount = linkablePages.length;
- const orphanPages = linkablePages.filter(row => row.islanded).length;
- const { graded: timelineGradedCount, withTimeline: linkableTimelinePages } = await gradeTimelinePages(this, linkablePages); // #5828
- const deadLinks = Number(h.dead_links);
- const linkCount = Number(h.link_count);
-
- // brain_score: 0-100 weighted average
- const linkDensity = pageCount > 0 ? Math.min(linkCount / pageCount, 1) : 0;
- // linkablePageCount === 0 gets full marks for the orphan / timeline
- // components (same vacuous-truth rule as the empty-brain fix below):
- // an all-archive brain has no curated graph to penalize.
- const timelineCoverageWhole =
- timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;
- const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;
- const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
- // Per-component points. Sum equals brainScore by construction.
- //
- // v0.37.10.0: empty brains (pageCount === 0) get FULL marks (100/100),
- // not 0. Semantically an empty brain has no coverage problem to penalize
- // — there's nothing to embed, nothing to link, nothing to orphan. The
- // pre-fix "empty = 0" caused fresh-init brains to score as critically
- // unhealthy on `gbrain doctor`, which was a structural surprise to users
- // who'd just successfully run init. PGLite path has the same fix.
- const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
- const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
- const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineCoverageWhole * 15);
- const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
- const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
- const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
-
- return {
- page_count: pageCount,
- linkable_page_count: linkablePageCount,
- embed_coverage: embedCoverage,
- stale_pages: stalePages,
- orphan_pages: orphanPages,
- missing_embeddings: Number(h.missing_embeddings),
- brain_score: brainScore,
- dead_links: deadLinks,
- entity_page_count: Number(h.entity_page_count),
- // gbrain#4147: below the small-N floor the ratio is statistically
- // meaningless (0/0 used to read as a hard 0%), so it reports null and
- // consumers suppress both the percentage and its remediation actions.
- link_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.link_coverage) : null,
- timeline_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.timeline_coverage) : null,
- most_connected: (connected as unknown as { slug: string; link_count: number }[]).map(c => ({
- slug: c.slug,
- link_count: Number(c.link_count),
- })),
- embed_coverage_score: embedCoverageScore,
- link_density_score: linkDensityScore,
- timeline_coverage_score: timelineCoverageScore,
- no_orphans_score: noOrphansScore,
- no_dead_links_score: noDeadLinksScore,
- };
+ return healthImpl.getHealth(unscopedExecutor(this.engineSql, 'health: unscoped on master (EO4 inventory)'), opts, {
+ embeddingColumn: async () => (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name,
+ countStalePagesForExtraction: (o) => this.countStalePagesForExtraction(o),
+ getConfig: (key) => this.getConfig(key),
+ });
}
// Ingest log
diff --git a/test/engine-sql-health-equality.test.ts b/test/engine-sql-health-equality.test.ts
new file mode 100644
index 0000000000..d1cf64f40c
--- /dev/null
+++ b/test/engine-sql-health-equality.test.ts
@@ -0,0 +1,115 @@
+/**
+ * F4a: get_health moved into one aggregate statement (`engine-sql/health.ts`)
+ * with the orphan policy rendered in SQL. Contract protected: every
+ * `BrainHealth` field equals the pre-F4a implementation (kept verbatim as
+ * `test/helpers/legacy-get-health.ts`) for every scope shape, on the existing
+ * fixtures (the E2E markdown corpus, the #4592 source-scope seed) and on
+ * seeded random graphs that hit every orphan-policy rule, quarantine,
+ * soft-delete, self-links, cross-source links, embed_skip and pack-graded
+ * timeline types. A regression in any predicate (scope, liveness, policy,
+ * grading, degree) changes a field and fails here. The Postgres twin is
+ * `test/e2e/engine-sql-health-parity.test.ts`.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import {
+ HEALTH_SRC_A,
+ expectHealthMatchesLegacy,
+ importE2eMarkdownFixtures,
+ seedRandomHealthGraph,
+ seedSourceScopeFixture,
+} from './helpers/health-equality-fixtures.ts';
+
+let engine: PGLiteEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-f4a-health-'));
+const env = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined }, fn);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetPackCacheForTests();
+});
+
+describe('F4a getHealth equals the pre-F4a implementation field by field (PGLite)', () => {
+ test('empty brain', async () => {
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, 'empty'));
+ expect(all.brain_score).toBe(100);
+ });
+
+ test('#4592 source-scope fixture', async () => {
+ await seedSourceScopeFixture(engine);
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, 'source-scope'));
+ expect(all.page_count).toBe(3);
+ });
+
+ test('E2E markdown fixture corpus', async () => {
+ const files = await importE2eMarkdownFixtures(engine);
+ expect(files).toBeGreaterThan(10);
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, 'e2e-corpus'));
+ expect(all.page_count).toBeGreaterThan(10);
+ });
+
+ for (const seed of [1, 7, 42]) {
+ test(`seeded random graph ${seed}`, async () => {
+ await seedRandomHealthGraph(engine, seed);
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, `random-${seed}`));
+ expect(all.linkable_page_count).toBeGreaterThan(0);
+ expect(all.linkable_page_count).toBeLessThan(all.page_count);
+ expect(all.orphan_pages).toBeGreaterThan(0);
+ expect(all.most_connected.length).toBe(5);
+ });
+ }
+
+ test('seeded random graph under an active schema pack (pack-graded timeline types)', async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await seedRandomHealthGraph(engine, 99);
+ await env(() => expectHealthMatchesLegacy(engine, 'random-pack'));
+ });
+
+ test('a duplicated source id in a grant counts once (stale_pages included)', async () => {
+ await seedSourceScopeFixture(engine);
+ const once = await env(() => engine.getHealth({ sourceIds: [HEALTH_SRC_A] }));
+ expect(once.stale_pages).toBeGreaterThan(0);
+ expect(await env(() => engine.getHealth({ sourceIds: [HEALTH_SRC_A, HEALTH_SRC_A] }))).toEqual(once);
+ });
+
+ // PGLite has no autovacuum: a brain can be read before its first ANALYZE.
+ // The pre-F4a statements (and a join-based rewrite) planned nested loops
+ // that re-scan a whole relation per row there: 40 s scoped on 8,000 pages.
+ // The migrated statements stay linear (about 0.15 s on the same brain).
+ test('stays linear on a brain without planner statistics (8,000 pages, scoped and unscoped)', async () => {
+ const n = 8000;
+ await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth, source_id)
+ SELECT CASE WHEN g % 10 = 0 THEN 'daily/d-' || g WHEN g % 7 = 0 THEN 'people/p-' || g ELSE 'notes/n-' || g END,
+ (ARRAY['person', 'company', 'note', 'concept', 'meeting', 'atom'])[1 + g % 6], 'Page ' || g, 'body', 'default'
+ FROM generate_series(1, ${n}) g`);
+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type)
+ SELECT b.lo + (g::bigint * 7919) % ${n}, b.lo + (g::bigint * 104729) % ${n}, 'fixture'
+ FROM generate_series(1, ${n * 2}) g, (SELECT min(id) AS lo FROM pages) b
+ ON CONFLICT DO NOTHING`);
+ await engine.executeRaw(`INSERT INTO timeline_entries (page_id, date, summary) SELECT id, '2026-01-01', 'event ' || id FROM pages WHERE id % 3 = 0`);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text) SELECT id, 0, 'chunk' FROM pages`);
+ for (const scope of [undefined, { sourceIds: ['default'] }]) {
+ const started = performance.now();
+ const health = await env(() => engine.getHealth(scope));
+ expect(health.page_count).toBe(n);
+ expect(performance.now() - started).toBeLessThan(5000);
+ }
+ }, 60_000);
+});
diff --git a/test/helpers/health-equality-fixtures.ts b/test/helpers/health-equality-fixtures.ts
new file mode 100644
index 0000000000..e15f14a22b
--- /dev/null
+++ b/test/helpers/health-equality-fixtures.ts
@@ -0,0 +1,233 @@
+/**
+ * Fixtures and the field-by-field comparison for the F4a get_health
+ * migration: the single-statement `engine.getHealth` must equal the pre-F4a
+ * implementation (`legacyGetHealth`) on every field, every scope shape and
+ * both engines. Used by `test/engine-sql-health-equality.test.ts` (PGLite)
+ * and `test/e2e/engine-sql-health-parity.test.ts` (Postgres, PgBouncer).
+ */
+import { expect } from 'bun:test';
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { extname, join, relative, resolve } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { BrainHealth } from '../../src/core/types.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { resolveActiveEmbeddingColumnFromEngine, quoteIdentifier } from '../../src/core/search/embedding-column.ts';
+import { legacyGetHealth } from './legacy-get-health.ts';
+
+export const HEALTH_SRC_A = 'healthsrca';
+export const HEALTH_SRC_B = 'healthsrcb';
+
+/** Every scope shape the op layer can hand the engine, plus the fail-closed ones. */
+export const HEALTH_SCOPES: Array<{ sourceId?: string; sourceIds?: string[] } | undefined> = [
+ undefined,
+ {},
+ { sourceId: 'default' },
+ { sourceId: HEALTH_SRC_A },
+ { sourceIds: [HEALTH_SRC_A] },
+ { sourceIds: [HEALTH_SRC_B] },
+ { sourceIds: [HEALTH_SRC_A, HEALTH_SRC_B] },
+ { sourceIds: [HEALTH_SRC_B, 'default', HEALTH_SRC_A] },
+ { sourceIds: [] },
+ { sourceId: '__all__' },
+];
+
+function mulberry32(seed: number): () => number {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Slug shapes that hit every orphan-policy rule, its near misses and the override config. */
+const SLUG_SHAPES: Array<(n: number) => string> = [
+ (n) => `notes/note-${n}`,
+ (n) => `people/person-${n}`,
+ (n) => `companies/acme-example-${n}`,
+ (n) => `concepts/idea-${n}`,
+ (n) => `output/report-${n}`,
+ (n) => `scratch/tmp-${n}`,
+ (n) => `wiki/raw/import-${n}`,
+ (n) => `journal/daily/day-${n}`,
+ (n) => `daily-notes/day-${n}`,
+ (n) => `life/events/2026-01-0${n % 9 + 1}-${n}`,
+ (n) => `life/diary/entry-${n}`,
+ (n) => `2026-02-${String(n % 28 + 1).padStart(2, '0')}`,
+ (n) => `2026-02-${String(n % 28 + 1).padStart(2, '0')}-standup-${n}`,
+ (n) => `2026-02-3x-${n}`,
+ (n) => `agents/agent-${n}/soul`,
+ (n) => `agents/agent-${n}/souls`,
+ (n) => `agents/agent-${n}/memory/dreaming/d-${n}`,
+ (n) => `agents/agent-${n}/notes/plan`,
+ (n) => `_brain-${n}`,
+ (n) => `topics/t-${n}/_index`,
+ (n) => `topics/t-${n}/readme`,
+ (n) => `topics/t-${n}/log`,
+ (n) => `topics/t-${n}/logbook`,
+ () => 'readme',
+ (n) => `private-area/secret-${n}`,
+ (n) => `one-off-${n % 3}`,
+ (n) => `inbox/item-${n}`,
+ (n) => `entities/e-${n}`,
+];
+
+const TYPES = ['person', 'company', 'entity', 'note', 'concept', 'meeting', 'atom', 'conversation', 'source', 'media'];
+
+async function ensureSources(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name) VALUES ('${HEALTH_SRC_A}', '${HEALTH_SRC_A}'), ('${HEALTH_SRC_B}', '${HEALTH_SRC_B}')
+ ON CONFLICT (id) DO NOTHING`,
+ );
+}
+
+async function pageIds(engine: BrainEngine): Promise<number[]> {
+ return (await engine.executeRaw<{ id: number }>(`SELECT id FROM pages ORDER BY id`)).map(r => Number(r.id));
+}
+
+async function embedChunks(engine: BrainEngine, chunkIds: number[]): Promise<void> {
+ if (chunkIds.length === 0) return;
+ const column = (await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name;
+ const [{ fmt }] = await engine.executeRaw<{ fmt: string }>(
+ `SELECT format_type(a.atttypid, a.atttypmod) AS fmt FROM pg_attribute a
+ WHERE a.attrelid = 'content_chunks'::regclass AND a.attname = $1`,
+ [column],
+ );
+ const dims = Number(/\((\d+)\)/.exec(fmt)?.[1] ?? 0);
+ await engine.executeRaw(
+ `UPDATE content_chunks SET ${quoteIdentifier(column)} = (array_fill(0.01::float4, ARRAY[${dims}])::vector)::${fmt}
+ WHERE id = ANY($1::int[])`,
+ [chunkIds],
+ );
+}
+
+/**
+ * A seeded random graph over three sources: every orphan-policy slug shape,
+ * every page type, quarantined and embed_skip pages, soft-deleted pages,
+ * self-links and cross-source links, timeline rows, embedded and unembedded
+ * chunks, and per-brain orphan overrides.
+ */
+export async function seedRandomHealthGraph(engine: BrainEngine, seed: number, pagesPerSource = 60): Promise<void> {
+ const rand = mulberry32(seed);
+ const pick = <T>(xs: readonly T[]) => xs[Math.floor(rand() * xs.length)];
+ await ensureSources(engine);
+ let n = 0;
+ for (const sourceId of ['default', HEALTH_SRC_A, HEALTH_SRC_B]) {
+ for (let i = 0; i < pagesPerSource; i++) {
+ n++;
+ const slug = pick(SLUG_SHAPES)(n);
+ const frontmatter: Record<string, unknown> = {};
+ if (rand() < 0.08) frontmatter.quarantine = { reason: 'junk_pattern', detail: 'fixture' };
+ if (rand() < 0.1) frontmatter.embed_skip = true;
+ await engine.putPage(slug, { type: pick(TYPES) as never, title: `Page ${n}`, compiled_truth: `Body ${n}.`, frontmatter }, { sourceId });
+ }
+ }
+ const ids = await pageIds(engine);
+ const links: string[] = [];
+ for (let i = 0; i < ids.length; i++) {
+ const from = pick(ids);
+ const to = rand() < 0.05 ? from : pick(ids);
+ links.push(`(${from}, ${to}, 'fixture-${i % 4}')`);
+ }
+ // Hubs with distinct degrees, so the top of most_connected has no ties.
+ const people = (await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE type IN ('person', 'company', 'entity') AND deleted_at IS NULL ORDER BY id LIMIT 3`,
+ )).map(r => Number(r.id));
+ people.forEach((hub, rank) => {
+ for (let k = 0; k < 40 - rank * 10; k++) links.push(`(${pick(ids)}, ${hub}, 'hub-${k}')`);
+ });
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ${links.join(', ')} ON CONFLICT DO NOTHING`,
+ );
+ const timeline: string[] = [];
+ for (const id of ids) if (rand() < 0.3) timeline.push(`(${id}, '2026-03-0${Math.floor(rand() * 9) + 1}', 'event ${id}')`);
+ if (timeline.length) await engine.executeRaw(`INSERT INTO timeline_entries (page_id, date, summary) VALUES ${timeline.join(', ')} ON CONFLICT DO NOTHING`);
+ const chunks: string[] = [];
+ for (const id of ids) {
+ const count = Math.floor(rand() * 3);
+ for (let c = 0; c < count; c++) chunks.push(`(${id}, ${c}, 'chunk ${id}-${c}')`);
+ }
+ if (chunks.length) {
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text) VALUES ${chunks.join(', ')} ON CONFLICT DO NOTHING`);
+ const chunkIds = (await engine.executeRaw<{ id: number }>(`SELECT id FROM content_chunks ORDER BY id`)).map(r => Number(r.id));
+ await embedChunks(engine, chunkIds.filter(() => rand() < 0.6));
+ }
+ const doomed = ids.filter(() => rand() < 0.1);
+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE id = ANY($1::int[])`, [doomed]);
+ await engine.setConfig('orphans.exclude_prefixes', 'private-area/, agents/agent-1');
+ await engine.setConfig('orphans.exclude_slugs', 'one-off-1, one-off-2');
+}
+
+/** The #4592 source-scope fixture (test/stats-health-source-scope.test.ts) on this file's sources. */
+export async function seedSourceScopeFixture(engine: BrainEngine): Promise<void> {
+ await ensureSources(engine);
+ const put = (sourceId: string, slug: string, type: string) =>
+ engine.putPage(slug, { title: slug, type: type as never, compiled_truth: `# ${slug}\n` }, { sourceId });
+ await put(HEALTH_SRC_A, 'people/alice-example', 'person');
+ await put(HEALTH_SRC_A, 'notes/alpha', 'note');
+ await put(HEALTH_SRC_B, 'people/bob-example', 'person');
+ const id = async (slug: string) => Number((await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE slug = $1`, [slug]))[0].id);
+ const [alice, alpha, bob] = [await id('people/alice-example'), await id('notes/alpha'), await id('people/bob-example')];
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type) VALUES (${alpha}, ${alice}, 'wikilink'), (${alice}, ${bob}, 'wikilink'), (${bob}, ${alpha}, 'wikilink')`,
+ );
+ await engine.executeRaw(`INSERT INTO timeline_entries (page_id, date, summary) VALUES (${alice}, '2026-08-01', 'a'), (${bob}, '2026-08-02', 'b')`);
+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text) VALUES (${alice}, 0, 'a'), (${alpha}, 0, 'b'), (${bob}, 0, 'c')`);
+}
+
+/** The markdown corpus under test/e2e/fixtures, imported the way the E2E suite imports it. */
+export async function importE2eMarkdownFixtures(engine: BrainEngine): Promise<number> {
+ const root = resolve(import.meta.dir, '../e2e/fixtures');
+ const files: string[] = [];
+ const walk = (dir: string) => {
+ for (const entry of readdirSync(dir).sort()) {
+ const full = join(dir, entry);
+ if (statSync(full).isDirectory()) walk(full);
+ else if (extname(entry) === '.md') files.push(full);
+ }
+ };
+ walk(root);
+ for (const file of files) {
+ const content = readFileSync(file, 'utf-8');
+ const parsed = parseMarkdown(content, relative(root, file));
+ await importFromContent(engine, parsed.slug, content, { noEmbed: true });
+ }
+ return files.length;
+}
+
+/**
+ * The old `most_connected` ordered by count only, so equal counts came back in
+ * an unspecified order. Counts must match position by position; slugs must
+ * match exactly above the lowest count in the list, and as a subset of the
+ * old list's tie group at the cut (both pick from the same tie group).
+ */
+function expectSameMostConnected(actual: BrainHealth['most_connected'], expected: BrainHealth['most_connected'], label: string): void {
+ expect(actual.map(m => m.link_count), `${label}: most_connected counts`).toEqual(expected.map(m => m.link_count));
+ if (expected.length === 0) return;
+ const cut = expected[expected.length - 1].link_count;
+ const above = (xs: BrainHealth['most_connected']) => xs.filter(m => m.link_count > cut).map(m => m.slug).sort();
+ expect(above(actual), `${label}: most_connected slugs above the cut`).toEqual(above(expected));
+ const sorted = [...actual].sort((a, b) => b.link_count - a.link_count || (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
+ expect(actual, `${label}: ties break by slug (code point order)`).toEqual(sorted);
+}
+
+/** Field-by-field equality of the migrated getHealth against the pre-F4a implementation. */
+export async function expectHealthMatchesLegacy(engine: BrainEngine, label: string): Promise<BrainHealth[]> {
+ const results: BrainHealth[] = [];
+ for (const scope of HEALTH_SCOPES) {
+ const tag = `${label} scope=${JSON.stringify(scope)}`;
+ const expected = await legacyGetHealth(engine, scope);
+ const actual = await engine.getHealth(scope);
+ expect(Object.keys(actual).sort(), `${tag}: field set`).toEqual(Object.keys(expected).sort());
+ for (const key of Object.keys(expected) as Array<keyof BrainHealth>) {
+ if (key === 'most_connected') continue;
+ expect(actual[key], `${tag}: ${key}`).toEqual(expected[key]);
+ }
+ expectSameMostConnected(actual.most_connected, expected.most_connected, tag);
+ results.push(actual);
+ }
+ return results;
+}
diff --git a/test/helpers/legacy-get-health.ts b/test/helpers/legacy-get-health.ts
new file mode 100644
index 0000000000..59cfd40769
--- /dev/null
+++ b/test/helpers/legacy-get-health.ts
@@ -0,0 +1,157 @@
+/**
+ * The pre-F4a `getHealth` (v0.60.34.0, both engines), kept verbatim as a test
+ * oracle: three statements plus the per-page orphan policy filtered in
+ * TypeScript. `test/engine-sql-health-equality.test.ts` asserts the migrated
+ * single-statement implementation (`src/core/engine-sql/health.ts`) returns
+ * the same value for every field on the same fixtures and scopes.
+ *
+ * Runs through `engine.executeRaw` so one copy serves PGLite and Postgres
+ * (the two engines carried byte-equivalent SQL; only the bind syntax
+ * differed). `most_connected` is returned as the engine produced it; the old
+ * `ORDER BY link_count DESC` had no tie-break, so callers compare it with
+ * `normalizeMostConnected` when ties straddle the top-5 cut.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { BrainHealth } from '../../src/core/types.ts';
+import { MIN_ENTITY_PAGES_FOR_COVERAGE } from '../../src/core/types.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';
+import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from '../../src/core/quarantine.ts';
+import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides, gradeTimelinePages } from '../../src/core/orphan-policy.ts';
+import { resolveActiveEmbeddingColumnFromEngine, quoteIdentifier } from '../../src/core/search/embedding-column.ts';
+
+export async function legacyGetHealth(
+ engine: BrainEngine,
+ opts?: { sourceId?: string; sourceIds?: string[] },
+): Promise<BrainHealth> {
+ const scope: string[] | null = opts?.sourceIds ?? (opts?.sourceId ? [opts.sourceId] : null);
+ const colId = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name);
+ const [h] = await engine.executeRaw<Record<string, unknown>>(`
+ WITH scoped_pages AS (
+ SELECT id, slug, frontmatter, deleted_at, source_id FROM pages p
+ WHERE ($1::text[] IS NULL OR p.source_id = ANY($1))
+ ),
+ entity_pages AS (
+ SELECT id, slug FROM scoped_pages WHERE id IN (
+ SELECT id FROM pages WHERE type IN ('entity', 'person', 'company') AND deleted_at IS NULL
+ AND ${quarantineFilterFragment('pages')}
+ )
+ )
+ SELECT
+ (SELECT count(*) FROM scoped_pages WHERE deleted_at IS NULL) as page_count,
+ (SELECT CASE
+ WHEN count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')) = 0
+ THEN 1.0
+ ELSE count(*) FILTER (WHERE cc.${colId} IS NOT NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ / count(*) FILTER (WHERE NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip'))::float
+ END
+ FROM content_chunks cc
+ JOIN scoped_pages p ON p.id = cc.page_id) as embed_coverage,
+ (SELECT count(*) FROM links l
+ WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
+ AND ($1::text[] IS NULL
+ OR EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id))
+ ) as dead_links,
+ (SELECT count(*) FROM content_chunks cc
+ JOIN scoped_pages p ON p.id = cc.page_id
+ WHERE cc.${colId} IS NULL AND p.deleted_at IS NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
+ ) as missing_embeddings,
+ (SELECT count(*) FROM links l
+ WHERE ($1::text[] IS NULL
+ OR (EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.from_page_id)
+ AND EXISTS (SELECT 1 FROM scoped_pages sp WHERE sp.id = l.to_page_id)))) as link_count,
+ (SELECT count(*) FROM entity_pages) as entity_page_count,
+ (SELECT count(*) FROM entity_pages e
+ WHERE EXISTS (SELECT 1 FROM links l
+ JOIN scoped_pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = e.id AND src.deleted_at IS NULL))::float /
+ GREATEST((SELECT count(*) FROM entity_pages), 1)::float as link_coverage,
+ (SELECT count(*) FROM entity_pages e
+ WHERE EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = e.id))::float /
+ GREATEST((SELECT count(*) FROM entity_pages), 1)::float as timeline_coverage
+ `, [scope]);
+
+ const connected = await engine.executeRaw<{ slug: string; link_count: number }>(`
+ SELECT p.slug,
+ (SELECT count(*) FROM links l
+ WHERE (l.from_page_id = p.id
+ AND ($1::text[] IS NULL
+ OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.to_page_id AND fp.source_id = ANY($1))))
+ OR (l.to_page_id = p.id
+ AND ($1::text[] IS NULL
+ OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.from_page_id AND fp.source_id = ANY($1))))
+ )::int as link_count
+ FROM pages p
+ WHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL
+ AND ${QUARANTINE_FILTER_FRAGMENT}
+ AND ($1::text[] IS NULL OR p.source_id = ANY($1))
+ ORDER BY link_count DESC
+ LIMIT 5
+ `, [scope]);
+
+ const pageScopeRows = await engine.executeRaw<{ slug: string; type: string; islanded: boolean; has_timeline: boolean }>(`
+ SELECT p.slug, p.type,
+ (NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages src ON src.id = l.from_page_id
+ WHERE l.to_page_id = p.id AND src.deleted_at IS NULL
+ AND ($1::text[] IS NULL OR src.source_id = ANY($1)))
+ AND NOT EXISTS (SELECT 1 FROM links l
+ JOIN pages tgt ON tgt.id = l.to_page_id
+ WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL
+ AND ($1::text[] IS NULL OR tgt.source_id = ANY($1)))) as islanded,
+ EXISTS (SELECT 1 FROM timeline_entries te WHERE te.page_id = p.id) as has_timeline
+ FROM pages p
+ WHERE p.deleted_at IS NULL
+ AND ${QUARANTINE_FILTER_FRAGMENT}
+ AND ($1::text[] IS NULL OR p.source_id = ANY($1))
+ `, [scope]);
+
+ const pageCount = Number(h.page_count);
+ const embedCoverage = Number(h.embed_coverage);
+ const stalePages = scope === null
+ ? await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })
+ : (await Promise.all(scope.map(sid =>
+ engine.countStalePagesForExtraction({ sourceId: sid, versionTs: LINK_EXTRACTOR_VERSION_TS }),
+ ))).reduce((a, b) => a + b, 0);
+ const orphanOverrides = await loadOrphanPolicyOverrides(engine);
+ const linkablePages = pageScopeRows.filter(row =>
+ !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides, { type: row.type }));
+ const linkablePageCount = linkablePages.length;
+ const orphanPages = linkablePages.filter(row => row.islanded).length;
+ const { graded: timelineGradedCount, withTimeline: linkableTimelinePages } = await gradeTimelinePages(engine, linkablePages);
+ const deadLinks = Number(h.dead_links);
+ const linkCount = Number(h.link_count);
+
+ const linkDensity = pageCount > 0 ? Math.min(linkCount / pageCount, 1) : 0;
+ const timelineCoverageWhole =
+ timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;
+ const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;
+ const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;
+ const embedCoverageScore = pageCount === 0 ? 35 : Math.round(embedCoverage * 35);
+ const linkDensityScore = pageCount === 0 ? 25 : Math.round(linkDensity * 25);
+ const timelineCoverageScore = pageCount === 0 ? 15 : Math.round(timelineCoverageWhole * 15);
+ const noOrphansScore = pageCount === 0 ? 15 : Math.round(noOrphans * 15);
+ const noDeadLinksScore = pageCount === 0 ? 10 : Math.round(noDeadLinks * 10);
+ const brainScore = embedCoverageScore + linkDensityScore + timelineCoverageScore + noOrphansScore + noDeadLinksScore;
+
+ return {
+ page_count: pageCount,
+ linkable_page_count: linkablePageCount,
+ embed_coverage: embedCoverage,
+ stale_pages: stalePages,
+ orphan_pages: orphanPages,
+ missing_embeddings: Number(h.missing_embeddings),
+ brain_score: brainScore,
+ dead_links: deadLinks,
+ entity_page_count: Number(h.entity_page_count),
+ link_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.link_coverage) : null,
+ timeline_coverage: Number(h.entity_page_count) >= MIN_ENTITY_PAGES_FOR_COVERAGE ? Number(h.timeline_coverage) : null,
+ most_connected: connected.map(c => ({ slug: c.slug, link_count: Number(c.link_count) })),
+ embed_coverage_score: embedCoverageScore,
+ link_density_score: linkDensityScore,
+ timeline_coverage_score: timelineCoverageScore,
+ no_orphans_score: noOrphansScore,
+ no_dead_links_score: noDeadLinksScore,
+ };
+}
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index 8e92de0a08..2fbf68142f 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -753,7 +753,7 @@ export const EXTRA_READ_CASES: SqlCase[] = [
...variants('searchTitles', [['default', (e) => e.searchTitles('alice example', { sourceId: SRC })]]),
...variants('searchVector', [['default', (e) => e.searchVector(EMB, { sourceId: SRC }), [[/AS eligible/, [{ eligible: 0 }]]]]]),
...variants('getStats', [['default', (e) => e.getStats(), [[/as page_count/, [{ page_count: 0, chunk_count: 0, embedded_count: 0, link_count: 0, tag_count: 0, timeline_entry_count: 0 }]]]]]),
- ...variants('getHealth', [['default', (e) => e.getHealth(), [[/WITH scoped_pages/, [{ page_count: 0, embed_coverage: 1, dead_links: 0, missing_embeddings: 0, link_count: 0, entity_page_count: 0, link_coverage: 0, timeline_coverage: 0 }]]]]]),
+ ...variants('getHealth', [['default', (e) => e.getHealth(), [[/WITH scoped_pages/, [{ page_count: 0, embed_coverage: 1, dead_links: 0, missing_embeddings: 0, link_count: 0, entity_page_count: 0, link_coverage: 0, timeline_coverage: 0, linkable_by_type: [] }]]]]]),
...variants('getRawData', [['default', (e) => e.getRawData(SLUG)]]),
...variants('getIngestLog', [['default', (e) => e.getIngestLog()]]),
...variants('getConfig', [['default', (e) => e.getConfig('embedding_model')]]),