Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(onboard): coverage, MCP onboarding counts and NER targets read the active pack's entity types (#4772)
garrytanc808b4f1c487
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex c9bdc68a62..fa24543639 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -20,7 +20,7 @@ Key files:- `src/core/schema-pack/query-types.ts` — expands scalar/multiple type filters through the selected engine's active alias graph. Scalar and array filters retain intersection semantics; explicit empty arrays deny before any engine/cache access. Missing packs yield an empty filter that consumers return as no results, never as an unrestricted query; DB lookup failures propagate through keyword, hybrid and image readers. Mixed-pack explicit source scopes refuse rather than arbitrarily choosing a closure. Used by hybrid search and the search/query keyword-only/image bypasses; typed hybrid requests bypass semantic result caching. Tests: `test/schema-engine-isolation.serial.test.ts`, `test/ops-search-types.test.ts`.-- `src/core/schema-pack/entity-types.ts` — #4772: the one answer to "is this stored type an entity" for the counters. `entityTypesFromPack(manifest)` returns the pack's `primitive: entity` type names (plus undeclared aliases of them) and the legacy names (`entity`, `person`, `company`, `organization`) the pack leaves undeclared; a pack that declares a legacy name under another primitive reclassified it and wins. `resolveEntityTypes(engine, scope)` resolves per source (every requested source id, or brain-wide: the brain's pack plus every registered source with a `schema_pack.source.<id>` override) into an `EntityTypeFilter` (default list + per-source lists that differ), and returns `pack_unavailable` with an empty filter when any pack in scope fails to load (the `best-effort.ts` null contract: empty filter, never hardcoded defaults). `entityTypePredicateSql(alias, filter)` renders it as a parameter-bound `sqlFragment`. Consumers: `engine-sql/health.ts` through `HealthDeps.entityTypes` (both engines delegate), `commands/doctor/checks/graph-health.ts` (`graph_coverage`, `orphan_ratio`). Writer/dispatcher sites (`onboard/checks.ts`, `extract-ner.ts`, `mentions/policy.ts`) still carry their own lists. Lazy-imports the pack loader so the engines can import it statically.+- `src/core/schema-pack/entity-types.ts` — #4772: the one answer to "is this stored type an entity" for the counters. `entityTypesFromPack(manifest)` returns the pack's `primitive: entity` type names (plus undeclared aliases of them) and the legacy names (`entity`, `person`, `company`, `organization`) the pack leaves undeclared; a pack that declares a legacy name under another primitive reclassified it and wins. `resolveEntityTypes(engine, scope)` resolves per source (every requested source id, or brain-wide: the brain's pack plus every registered source with a `schema_pack.source.<id>` override) into an `EntityTypeFilter` (default list + per-source lists that differ), and returns `pack_unavailable` with an empty filter when any pack in scope fails to load (the `best-effort.ts` null contract: empty filter, never hardcoded defaults). `entityTypePredicateSql(alias, filter)` renders it as a parameter-bound `sqlFragment`. Consumers: `engine-sql/health.ts` through `HealthDeps.entityTypes` (both engines delegate), `commands/doctor/checks/graph-health.ts` (`graph_coverage`, `orphan_ratio`), `onboard/checks.ts` (`entity_link_coverage`, `timeline_coverage`, and `visibleEntityCoverageSql` for `onboard/impact-capture.ts`; a pack that does not load warns `entity_types_unavailable`), `onboard/mcp-onboarding.ts` (the three entity counts are `null` with `entityTypesStatus: pack_unavailable`; the timeline result predicate) and `extract-ner.ts` (the target-type map; `pack_unavailable` when a source's pack does not load). `mentions/policy.ts` keeps its own linkable-type union. Pinned by `test/onboard-entity-types-pack-4772.test.ts`. Lazy-imports the pack loader so the engines can import it statically.- `src/core/schema-pack/best-effort.ts` — `loadActivePackBestEffort(ctx)` returns `ResolvedPack | null`. Single source of truth for the pack-aware wiring sites. `null` means EMPTY FILTER (NOT hardcoded defaults, which would silently violate the pack). Threads the tier-4 DB-plane `schema_pack` from `ctx.engine`, so every caller resolves the SAME pack `schema active` / `get_active_schema_pack` report. `readDbSchemaPack(engine?)` is the ONE spelling of that tier-4 read (null-safe, propagates DB read failures, trims missing/empty values to undefined) — shared by both loaders here, the CLI inspection verbs (`schema show/graph/lint/explain`, via `readDbSchemaPackConfig` in `src/commands/schema.ts`, which keeps the cfg-null gate so an unconfigured home never cold-creates a PGLite dir) and the MCP `schema_lint`/`schema_graph`/`schema_explain_type` ops. `loadActivePackForLocalEngine(engine)` is the `remote: false` + FILE-ONLY-config variant for local engine-backed surfaces. Pinned by `test/schema-pack-best-effort.test.ts`, `test/operations-schema-pack.test.ts`, `test/schema-cli-db-config.test.ts`.- `src/core/schema-pack/type-usage.ts` — stored-type classifier behind the alias-footgun visibility surfaces: `classifyStoredType(type, pack)` → canonical | alias_of (with the canonical type + `path_prefixes[0]` filing directory) | undeclared, over a STRUCTURAL pack shape so import-file's thin `activePack` and the full manifest both satisfy it. `sanitizeTypeForDisplay` strips control chars + caps length (type strings come from frontmatter and get echoed into terminals); `renderTypeWarningSummary` renders the once-per-type-per-run lines. Consumers: `importFromContent` (advisory `ImportResult.type_warning` at the typeExplicit site — the type is still stored literally, zero filing change), sync/import summary aggregation (+ `SyncResult.type_warnings` so worker-driven syncs surface counts in job results), the `stored_type_is_alias`/`stored_type_undeclared` data-plane lint rules, all gated by config `schema.type_warnings` (default on; lint rules always active). `storedTypeMissesPack(type, pack)` (empty type, or undeclared) is the one predicate every pack-conformance surface uses: `findTypeOrphans` (`schema-pack/review.ts`), `schema_stats` coverage, doctor `schema_pack_consistency`, `gbrain lint`'s `type-undeclared` rule. Pinned by `test/schema-type-usage.test.ts` and `test/schema-pack-type-conformance.test.ts`.- `src/core/schema-pack/lint-rules.ts` — 14 pure rule functions. `withMutation`'s pre-write validation gate composes the 10 file-plane rules; the 4 DB-aware rules (`extractable_empty_corpus`, `mutation_count_anomaly`, `stored_type_is_alias`, `stored_type_undeclared`) need an engine (CLI `--with-db`; the stored-type pair accepts `LintOpts.sourceId` scoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCP `schema_lint` + the pre-write validation gate. File-plane rule `link_regex_catastrophic_backtrack` — advisory ReDoS pre-screen flagging the classic nested-quantifier shapes (`(a+)+`, `(a*)*`, `(a+)*`, `(\w+)+`) in a link_type's `inference.regex` via `NESTED_QUANTIFIER_RE`. WARNING not error: a hard reject would disable the whole pack on upgrade (pages fall back to legacy typing). The runtime input-length cap in `redos-guard.ts` is the actual safety net; this rule tells the pack author to fix the pattern.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 8ba639e825..6faeed5c53 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1004,6 +1004,14 @@ More: [docs/guides/troubleshooting.md#embedding-state](../../docs/guides/troubleMore: [docs/guides/move-to-postgres.md#graduated-datastore](../../docs/guides/move-to-postgres.md#graduated-datastore)+### entity_types_unavailable++<a id="entity_types_unavailable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A schema pack in scope did not load, so the entity page types are unknown; onboarding's entity_link_coverage and timeline_coverage warn instead of grading the old hardcoded type list. | Entity types come from the active pack per source (the get_health predicate). Grading a fixed person/company list would count the wrong population on a pack with its own entity types, so the checks name the sources whose pack failed. | Run gbrain schema active --json (add --source <id> for a named source) to see which pack is active and why it did not load; fix or reinstall the pack, then gbrain onboard --json. | agent | `gbrain doctor --json` | 1 | no |+### eval_suite_unwired<a id="eval_suite_unwired"></a>diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 5aaf24b941..113315261d 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -188,6 +188,10 @@ export const CODES = {embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },embedding_width_mismatch: { class: 'caller', summary: "The embedding model cannot produce the width of the brain's vector column; nothing was changed." },engine_graduated: { class: 'caller', summary: "A client opened a PGLite brain that moved to Postgres; its old path holds a tombstone.", docs: 'docs/guides/move-to-postgres.md#graduated-datastore' },+ // wave 18b (GBRA-106) #4772: onboarding coverage checks read entity types from the active pack(s).+ entity_types_unavailable: { class: 'unavailable', summary: "A schema pack in scope did not load, so the entity page types are unknown; onboarding's entity_link_coverage and timeline_coverage warn instead of grading the old hardcoded type list.",+ why: "Entity types come from the active pack per source (the get_health predicate). Grading a fixed person/company list would count the wrong population on a pack with its own entity types, so the checks name the sources whose pack failed.",+ suggestion: 'Run gbrain schema active --json (add --source <id> for a named source) to see which pack is active and why it did not load; fix or reinstall the pack, then gbrain onboard --json.' },eval_suite_unwired: { class: 'caller', summary: "`gbrain eval run-all` was asked for a suite it does not run in-process (longmemeval or replay); nothing ran.", why: "run-all runs only wired suites (brainbench). Recording a skipped run and exiting 0 would read as a completed sweep with no numbers behind it.", suggestion: 'Run each requested suite with its own command (`gbrain eval longmemeval <dataset.jsonl> --mode <mode> --record`, `gbrain eval replay --mode <mode>`), once per mode, or drop it from --suites.' },export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "The drain retries a failed managed atom batch on its own up to 3 times per content (then holds it, code held_failed); this code reports a failed explicit retry, or a failure the drain cannot attribute to a checkpoint, so the same input is not paid for again without approval." },diff --git a/src/core/extract-ner.ts b/src/core/extract-ner.tsindex b366c24912..8a8d23b7a1 100644--- a/src/core/extract-ner.ts+++ b/src/core/extract-ner.ts@@ -22,6 +22,8 @@ import { isCrossSourceLinksEnabled } from './link-extraction.ts';import { inferLinkTypeFromPack } from './schema-pack/link-inference.ts';import { loadActivePackForLocalEngine, packSupportsNerInference } from './schema-pack/best-effort.ts';import { isQuarantined } from './quarantine.ts';+import { renderFragment, sqlFragment } from './engine-sql/fragment.ts';+import { entityTypePredicateSql, resolveEntityTypes } from './schema-pack/entity-types.ts';export interface ExtractNerOpts {/** When true: enumerate but don't write. */@@ -46,7 +48,7 @@ export interface ExtractNerResult {pages: number;/** Typed-NER links created (or would-have-created in dry-run). */created: number;- /** Pages where the active schema pack had no link_types at all. */+ /** The active schema pack had no NER inference rules, or a pack in scope did not load (entity types unknown). */pack_unavailable: boolean;}@@ -131,6 +133,7 @@ export async function extractNerLinks(// without an N+1 getPage round-trip. Pulls the slug→type map from// listAllPageRefs + a single listPages projection.const targetTypeMap = await buildTargetTypeMap(engine);+ if (!targetTypeMap) return { pages: 0, created: 0, pack_unavailable: true };const allRefs = opts.sourceIdFilter? (await engine.listAllPageRefs()).filter((r) => r.source_id === opts.sourceIdFilter)@@ -202,23 +205,17 @@ export async function extractNerLinks(}/**- * Helper: build a Map<sourceId::slug → type> for all entity-typed pages.- * One round-trip via listPages. Targets cached at extraction-start so- * inferNerLinkType doesn't pay an N+1 cost per mention.+ * Helper: build a Map<sourceId::slug → type> for the entity-typed pages, by+ * the active pack(s) per source (#4772, the get_health predicate bound in+ * SQL). One round-trip; targets cached at extraction-start so+ * inferNerLinkType doesn't pay an N+1 cost per mention. Null when a pack in+ * scope did not load (entity types unknown); an engine error throws.*/-async function buildTargetTypeMap(engine: BrainEngine): Promise<Map<string, string>> {- const map = new Map<string, string>();- try {- const result = await engine.executeRaw<{ slug: string; source_id: string; type: string }>(- `SELECT slug, source_id, type FROM pages- WHERE type IN ('person', 'company', 'organization', 'entity')- AND deleted_at IS NULL`,- );- for (const row of result) {- map.set(`${row.source_id}::${row.slug}`, row.type);- }- } catch {- // Engine error → empty map; inferNerLinkType returns null for unknown types.- }- return map;+async function buildTargetTypeMap(engine: BrainEngine): Promise<Map<string, string> | null> {+ const entityTypes = await resolveEntityTypes(engine, null);+ if (entityTypes.status === 'pack_unavailable') return null;+ const sql = renderFragment(sqlFragment`SELECT p.slug, p.source_id, p.type FROM pages p+ WHERE ${entityTypePredicateSql('p', entityTypes.filter)} AND p.deleted_at IS NULL`);+ const rows = await engine.executeRaw<{ slug: string; source_id: string; type: string }>(sql.text, sql.params);+ return new Map(rows.map((row) => [`${row.source_id}::${row.slug}`, row.type]));}diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex 12c6afc6b0..22d4d2c935 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -21,6 +21,8 @@ import type { BrainEngine } from '../engine.ts';import type { RemediationStep } from '../remediation-step.ts';import { makeRemediationStep } from '../remediation-step.ts';import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';+import { renderFragment, sqlFragment, trustedSql, type SqlFragment } from '../engine-sql/fragment.ts';+import { entityTypePredicateSql, resolveEntityTypes, type EntityTypeFilter, type EntityTypeResolution } from '../schema-pack/entity-types.ts';import type { Action } from '../agent-output.ts';import { embeddingEnablement, type ReadinessState } from '../readiness.ts';import { embeddingsDisabled } from '../embedding-disabled.ts';@@ -60,9 +62,35 @@ async function safeCount(engine: BrainEngine, sql: string, params: unknown[] = [}}-const VISIBLE_ENTITY_PREDICATE = `p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND ${QUARANTINE_FILTER_FRAGMENT}`;+/** #4772: a live, visible page whose type the active pack(s) declare as an entity, per source (the get_health predicate). */+function visibleEntityPredicate(filter: EntityTypeFilter): SqlFragment {+ return sqlFragment`${entityTypePredicateSql('p', filter)} AND p.deleted_at IS NULL AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}`;+}++/**+ * A pack in scope did not load, so the entity population is unknown: a warn+ * with `entity_types_unavailable`, never a coverage read over an empty or+ * legacy list.+ */+function entityTypesUnavailableResult(name: string, resolution: Extract<EntityTypeResolution, { status: 'pack_unavailable' }>): OnboardCheckResult {+ const where = resolution.unresolved.filter(Boolean);+ return {+ check: {+ name, status: 'warn',+ message: `Entity types unknown: could not resolve the active schema pack${where.length ? ` for source${where.length > 1 ? 's' : ''} ${where.map((id) => `'${id}'`).join(', ')}` : ''}, so ${name} cannot be graded. Run \`gbrain schema active --json\` to debug.`,+ details: { code: 'entity_types_unavailable', entity_types_status: 'pack_unavailable', unresolved_sources: where },+ fix: { argv: ['gbrain', 'schema', 'active', '--json', ...(where.length ? ['--source', where[0]!] : [])], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Read-only: shows which pack is active, the tier it comes from and why it did not load.', verify: { argv: ['gbrain', 'doctor', '--only', name, '--json'] } },+ },+ remediations: [],+ };+}++/** Count the visible entity pages under `filter`. */+async function countVisibleEntities(engine: BrainEngine, filter: EntityTypeFilter): Promise<number> {+ const sql = renderFragment(sqlFragment`SELECT COUNT(*) AS count FROM pages p WHERE ${visibleEntityPredicate(filter)}`);+ return safeCount(engine, sql.text, sql.params);+}/*** Coverage is a ratio over the visible entity population, and below@@ -93,22 +121,22 @@ export const TIMELINE_COVERAGE_FEATURE: CoverageFeature = { table: 'timeline_ent* remediation impact capture both read coverage through this query, so a* `gbrain onboard --history` row measures the population the check grades.*/-export function visibleEntityCoverageSql(feature: CoverageFeature, sampleClause = ''): string {- return `WITH sampled_entities AS (+export function visibleEntityCoverageSql(feature: CoverageFeature, filter: EntityTypeFilter, sampleClause = ''): { text: string; params: unknown[] } {+ return renderFragment(sqlFragment`WITH sampled_entities AS (SELECT p.id- FROM pages p ${sampleClause}- WHERE ${VISIBLE_ENTITY_PREDICATE}+ FROM pages p ${trustedSql(sampleClause)}+ WHERE ${visibleEntityPredicate(filter)})SELECTCOUNT(*)::int AS sample_size,COUNT(*) FILTER (WHERE EXISTS (SELECT 1- FROM ${feature.table} f- WHERE f.${feature.pageIdColumn} = s.id+ FROM ${trustedSql(feature.table)} f+ WHERE f.${trustedSql(feature.pageIdColumn)} = s.id))::int AS matched- FROM sampled_entities s`;+ FROM sampled_entities s`);}interface EntityCoverageSample {@@ -132,9 +160,11 @@ async function sampleVisibleEntityCoverage(engine: BrainEngine,sampleClause: string,feature: CoverageFeature,+ filter: EntityTypeFilter,): Promise<EntityCoverageSample> {try {- const result = await engine.executeRaw(visibleEntityCoverageSql(feature, sampleClause));+ const sql = visibleEntityCoverageSql(feature, filter, sampleClause);+ const result = await engine.executeRaw(sql.text, sql.params);const rows = (result as { rows?: Array<Record<string, unknown>> } | undefined)?.rows?? (result as Array<Record<string, unknown>> | undefined)?? [];@@ -291,11 +321,9 @@ export async function checkEntityLinkCoverage(): Promise<OnboardCheckResult> {// Total visible entity pages. Quarantined pages are hidden from the brain,// so they are outside both the coverage numerator and denominator.- const totalEntities = await safeCount(- engine,- `SELECT COUNT(*) AS count FROM pages p- WHERE ${VISIBLE_ENTITY_PREDICATE}`,- );+ const entityTypes = await resolveEntityTypes(engine, null);+ if (entityTypes.status === 'pack_unavailable') return entityTypesUnavailableResult('entity_link_coverage', entityTypes);+ const totalEntities = await countVisibleEntities(engine, entityTypes.filter);const ungraded = ungradedCoverageResult('entity_link_coverage', totalEntities);if (ungraded) return ungraded;@@ -311,6 +339,7 @@ export async function checkEntityLinkCoverage(engine,sampleClause,LINK_COVERAGE_FEATURE,+ entityTypes.filter,);const { coverage, ci } = coverageWithConfidence(sample);@@ -374,11 +403,9 @@ export async function checkEntityLinkCoverage(export async function checkTimelineCoverage(engine: BrainEngine,): Promise<OnboardCheckResult> {- const totalEntities = await safeCount(- engine,- `SELECT COUNT(*) AS count FROM pages p- WHERE ${VISIBLE_ENTITY_PREDICATE}`,- );+ const entityTypes = await resolveEntityTypes(engine, null);+ if (entityTypes.status === 'pack_unavailable') return entityTypesUnavailableResult('timeline_coverage', entityTypes);+ const totalEntities = await countVisibleEntities(engine, entityTypes.filter);const ungraded = ungradedCoverageResult('timeline_coverage', totalEntities);if (ungraded) return ungraded;@@ -393,6 +420,7 @@ export async function checkTimelineCoverage(engine,sampleClause,TIMELINE_COVERAGE_FEATURE,+ entityTypes.filter,);const { coverage, ci } = coverageWithConfidence(sample);const pct = Math.round(coverage * 100);diff --git a/src/core/onboard/impact-capture.ts b/src/core/onboard/impact-capture.tsindex 8206513582..99eb7230bd 100644--- a/src/core/onboard/impact-capture.ts+++ b/src/core/onboard/impact-capture.ts@@ -27,6 +27,7 @@ import type { BrainEngine } from './../engine.ts';import type { RemediationStep } from '../remediation-step.ts';import { loadOrphanPolicyOverrides, shouldExcludeFromOrphanReporting } from '../orphan-policy.ts';import { LINK_COVERAGE_FEATURE, TIMELINE_COVERAGE_FEATURE, visibleEntityCoverageSql } from './checks.ts';+import { resolveEntityTypes } from '../schema-pack/entity-types.ts';export type MetricName =| 'orphan_count'@@ -99,7 +100,10 @@ export async function captureMetric(case 'entity_link_coverage':case 'timeline_coverage': {const feature = metric === 'entity_link_coverage' ? LINK_COVERAGE_FEATURE : TIMELINE_COVERAGE_FEATURE;- const [row] = await engine.executeRaw<{ sample_size: number; matched: number }>(visibleEntityCoverageSql(feature));+ const entityTypes = await resolveEntityTypes(engine, null);+ if (entityTypes.status === 'pack_unavailable') return null;+ const sql = visibleEntityCoverageSql(feature, entityTypes.filter);+ const [row] = await engine.executeRaw<{ sample_size: number; matched: number }>(sql.text, sql.params);const population = Number(row?.sample_size ?? 0);// An empty population is vacuously covered.return population === 0 ? 1 : Number(row?.matched ?? 0) / population;diff --git a/src/core/onboard/mcp-onboarding.ts b/src/core/onboard/mcp-onboarding.tsindex a8d0b4bcde..4dd328c4df 100644--- a/src/core/onboard/mcp-onboarding.ts+++ b/src/core/onboard/mcp-onboarding.ts@@ -18,13 +18,14 @@ import { gbrainPath, type GBrainConfig } from '../config.ts';import { configReadiness } from '../readiness.ts';import { recallStagesFor } from '../interop-notices.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';+import { renderFragment, sqlFragment, type SqlFragment } from '../engine-sql/fragment.ts';+import { entityTypePredicateSql, resolveEntityTypes, type EntityTypeFilter } from '../schema-pack/entity-types.ts';export const LINK_COVERAGE_MIN = 0.7;export const TIMELINE_COVERAGE_MIN = 0.9;const TTL_MS = 6 * 60 * 60 * 1000;const REFRESH_BUDGET_MS = 3000;const IDLE_POLL_MS = 250;-const ENTITY_TYPES: ReadonlySet<string> = new Set(['person', 'company', 'organization', 'entity']);/** The six counts init's nudge reports; null when that probe failed or hit the budget. */export interface OnboardCounts {@@ -39,25 +40,34 @@ export interface OnboardCounts {partial: boolean;checksRan: number;checksAttempted: number;+ /** #4772: `pack_unavailable` when a pack in scope did not load; the entity counts are then null (unknown), never a legacy-list read. */+ entityTypesStatus?: 'resolved' | 'pack_unavailable';}-const COUNT_SQL = [- `SELECT COUNT(*) AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE cc.embedding IS NULL AND p.deleted_at IS NULL AND ${EMBED_SKIP_FILTER_FRAGMENT}`,- `SELECT COUNT(*) AS count FROM pages- WHERE type IN ('person', 'company', 'organization', 'entity')- AND deleted_at IS NULL`,- `SELECT COUNT(*) AS count FROM pages p- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`,- `SELECT COUNT(*) AS count FROM pages p- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)`,- `SELECT COUNT(*) AS count FROM takes`,- `SELECT COUNT(*) AS count FROM pages WHERE deleted_at IS NULL`,-] as const;+/** The six counts; the three entity counts bind the active pack's entity types per source (#4772, the get_health predicate). */+function countSql(filter: EntityTypeFilter): Array<{ text: string; params: unknown[] }> {+ const isEntity = entityTypePredicateSql('p', filter);+ const entity = (extra: SqlFragment) => renderFragment(sqlFragment`SELECT COUNT(*) AS count FROM pages p WHERE ${isEntity} AND p.deleted_at IS NULL${extra}`);+ return [+ { text: `SELECT COUNT(*) AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.embedding IS NULL AND p.deleted_at IS NULL AND ${EMBED_SKIP_FILTER_FRAGMENT}`, params: [] },+ entity(sqlFragment``),+ entity(sqlFragment` AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`),+ entity(sqlFragment` AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)`),+ { text: `SELECT COUNT(*) AS count FROM takes`, params: [] },+ { text: `SELECT COUNT(*) AS count FROM pages WHERE deleted_at IS NULL`, params: [] },+ ];+}+const ENTITY_COUNT_INDEXES = new Set([1, 2, 3]);++/** Whether `type` is an entity type in `sourceId` (or brain-wide) under the active pack(s); false when a pack did not load. */+async function isEntityType(engine: BrainEngine, type: unknown, sourceId: unknown): Promise<boolean> {+ if (typeof type !== 'string' || !type) return false;+ const resolution = await resolveEntityTypes(engine, typeof sourceId === 'string' && sourceId ? [sourceId] : null);+ if (resolution.status !== 'resolved') return false;+ const { types, per_source } = resolution.filter;+ return (per_source.find(b => b.source_id === sourceId)?.types ?? types).includes(type);+}/*** Run the six counts. Parallel by default (init); with `between`, one at a@@ -67,18 +77,23 @@ const COUNT_SQL = [export async function collectOnboardOpportunities(engine: BrainEngine, signal: AbortSignal, between?: () => Promise<void>,): Promise<OnboardCounts> {- const run = (sql: string) => engine.executeRaw<{ count: string | number }>(sql, [], { signal });+ const entityTypes = await resolveEntityTypes(engine, null);+ const unavailable = entityTypes.status === 'pack_unavailable';+ const run = async (sql: { text: string; params: unknown[] }, i: number): Promise<PromiseSettledResult<{ count: string | number }[]>> => {+ if (unavailable && ENTITY_COUNT_INDEXES.has(i)) return { status: 'rejected', reason: new Error('entity types unknown: a schema pack did not load') };+ return engine.executeRaw<{ count: string | number }>(sql.text, sql.params, { signal })+ .then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason }));+ };+ const statements = countSql(entityTypes.filter);let results: PromiseSettledResult<{ count: string | number }[]>[];if (between) {results = [];- for (const sql of COUNT_SQL) {+ for (const [i, sql] of statements.entries()) {await between();- results.push(signal.aborted- ? { status: 'rejected', reason: new Error('onboard count budget exceeded') }- : await run(sql).then(value => ({ status: 'fulfilled' as const, value }), reason => ({ status: 'rejected' as const, reason })));+ results.push(signal.aborted ? { status: 'rejected', reason: new Error('onboard count budget exceeded') } : await run(sql, i));}} else {- results = await Promise.allSettled(COUNT_SQL.map(run));+ results = await Promise.all(statements.map(run));}const n = results.map(r => (r.status === 'fulfilled' ? (r.value.length > 0 ? Number(r.value[0].count) : 0) : null));const [staleChunks, entities, linkedEntities, timelineEntities, takes, pages] = n;@@ -87,7 +102,7 @@ export async function collectOnboardOpportunities(return {staleChunks, entities, linkedEntities, timelineEntities, takes, pages,linkCoverage: coverage(linkedEntities), timelineCoverage: coverage(timelineEntities),- partial: checksRan < results.length, checksRan, checksAttempted: results.length,+ partial: checksRan < results.length, checksRan, checksAttempted: results.length, entityTypesStatus: entityTypes.status,};}@@ -309,7 +324,7 @@ function classNotice(cls: OnboardClass, s: OnboardSnapshot, render: RenderContexconst VECTOR_MISS_STAGES: ReadonlySet<string> = new Set(['embed_unavailable', 'keyword_only_no_embedding_provider', 'embed_timeout', 'vector_arm_failed']);async function pageLacksTimeline(engine: BrainEngine, result: Record<string, unknown>): Promise<boolean> {- if (!ENTITY_TYPES.has(String(result.type ?? ''))) return false;+ if (!(await isEntityType(engine, result.type, result.source_id))) return false;if (Array.isArray(result.timeline_entries)) return result.timeline_entries.length === 0;if (typeof result.id !== 'number' && typeof result.id !== 'string') return false;const rows = await engine.executeRaw(`SELECT 1 FROM timeline_entries WHERE page_id = $1 LIMIT 1`, [result.id]);@@ -338,7 +353,7 @@ async function evidenceFor(cls: OnboardClass, e: CallEvidence): Promise<boolean>return e.op !== 'entity' || (r.found === true && card.backlink_count === 0);case 'timeline_coverage':if (e.op === 'get_timeline') return Array.isArray(e.result) && e.result.length === 0;- if (e.op === 'entity') return r.found === true && ENTITY_TYPES.has(String(card.entity?.type ?? '')) && !card.last_touched?.last_timeline_date;+ if (e.op === 'entity') return r.found === true && !card.last_touched?.last_timeline_date && await isEntityType(e.engine, card.entity?.type, r.source_id);return pageLacksTimeline(e.engine, r);case 'no_takes':return true;diff --git a/test/init-nudge.test.ts b/test/init-nudge.test.tsindex 009c4d53e7..8df64d468d 100644--- a/test/init-nudge.test.ts+++ b/test/init-nudge.test.ts@@ -43,12 +43,15 @@ function stubEngine(counts: ProbeCounts): BrainEngine {if (sql.includes('FROM takes')) return counts.takes ?? 0;if (sql.includes('FROM links')) return counts.linked ?? 0;if (sql.includes('timeline_entries')) return counts.timeline ?? 0;- if (sql.includes("type IN ('person'")) return counts.entities ?? 0;+ if (sql.includes('p.type = ANY(')) return counts.entities ?? 0;// 6th probe: SELECT COUNT(*) FROM pages WHERE deleted_at IS NULLreturn counts.pages ?? 0;};return {+ // #4772: the entity counts resolve the active pack first (no overrides: gbrain-base).+ getConfig: async () => null,executeRaw: async (sql: string) => {+ if (sql.includes('FROM config c')) return [];const r = route(sql);if (r instanceof Error) throw r;return [{ count: r }];diff --git a/test/onboard-coverage-invariants.test.ts b/test/onboard-coverage-invariants.test.tsindex 6bb4628b62..25bb9aafd2 100644--- a/test/onboard-coverage-invariants.test.ts+++ b/test/onboard-coverage-invariants.test.ts@@ -68,7 +68,9 @@ describe('onboard entity coverage invariants', () => {let call = 0;const postgres = {kind: 'postgres',+ getConfig: async () => null,async executeRaw(sql: string) {+ if (sql.includes('FROM config c')) return [];queries.push(sql);call++;if (call === 1) return [{ count: 100_000 }];@@ -91,7 +93,9 @@ describe('onboard entity coverage invariants', () => {let call = 0;const postgres = {kind: 'postgres',- async executeRaw() {+ getConfig: async () => null,+ async executeRaw(sql: string) {+ if (sql.includes('FROM config c')) return [];call++;if (call === 1) return [{ count: 100_000 }];return [{ matched: 12_000, sample_size: 10_000 }];diff --git a/test/onboard-entity-types-pack-4772.test.ts b/test/onboard-entity-types-pack-4772.test.tsnew file mode 100644index 0000000000..0c015fb662--- /dev/null+++ b/test/onboard-entity-types-pack-4772.test.ts@@ -0,0 +1,196 @@+/**+ * #4772 — onboarding coverage, the MCP onboarding counts and NER typed edges+ * read the active pack's entity types per source, like get_health.+ *+ * Protects: `checkEntityLinkCoverage` / `checkTimelineCoverage`,+ * `collectOnboardOpportunities`, the MCP timeline-coverage result predicate+ * and `extractNerLinks`' target-type map count the page types the active+ * pack(s) declare `primitive: entity`, resolved per source; a pack in scope+ * that does not load makes the checks warn `entity_types_unavailable` and the+ * counts unknown, never a read of the old hardcoded list.+ * Fails when: any of them goes back to `type IN ('person', 'company',+ * 'organization', 'entity')` (a `venue` entity counts 0 and gets no typed+ * edge; a broken pack silently grades person pages).+ * Why new: test/health-entity-types-pack.test.ts covers get_health only; the+ * onboarding and NER readers kept their own lists.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';+import { checkEntityLinkCoverage, checkTimelineCoverage } from '../src/core/onboard/checks.ts';+import { collectOnboardOpportunities, __resetMcpOnboardingForTests, __warmOnboardingCacheForTests } from '../src/core/onboard/mcp-onboarding.ts';+import { dispatchToolCall, __resetBackupNoticeForTests, type ToolResult } from '../src/mcp/dispatch.ts';+import { STARTER_OPS } from '../src/mcp/surface.ts';+import { extractNerLinks } from '../src/core/extract-ner.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import { PACKS, SRC_X, putTyped, seedPerSourcePacks, seedUnavailablePack, writeEntityTypePacks } from './helpers/entity-types-pack-fixture.ts';++const VENUE_PACK = 'venue-4772';+const VENUES = ['blue-hall', 'red-room', 'green-stage', 'gray-arena', 'gold-club', 'teal-loft'];++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-4772-onboard-'));+const env = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined, GBRAIN_NO_ONBOARD_NUDGE: undefined }, fn);++function writeVenuePack(): void {+ const dir = join(home, '.gbrain', 'schema-packs', VENUE_PACK);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'pack.yaml'), [+ 'api_version: gbrain-schema-pack-v1', `name: ${VENUE_PACK}`, 'version: 1.0.0', 'description: ""',+ 'gbrain_min_version: 0.38.0', 'extends: null', 'borrow_from: []',+ 'page_types:',+ ' - name: venue', ' primitive: entity', ' path_prefixes: ["venues/"]', ' aliases: []',+ ' - name: person', ' primitive: entity', ' path_prefixes: ["people/"]', ' aliases: []',+ ' - name: note', ' primitive: concept', ' path_prefixes: ["notes/"]', ' aliases: []',+ 'link_types:',+ ' - name: performed_at', ' inference:', ' page_type: venue', ' regex: \\bperformed at\\b', ' ner_only: true',+ 'frontmatter_links: []', 'takes_kinds:', ' - fact', 'enrichable_types: []', 'filing_rules: []', '',+ ].join('\n'), 'utf-8');+}++/** Six venue pages (a pack entity type, no legacy name), three with an inbound link and a timeline entry. */+async function seedVenues(): Promise<void> {+ await engine.setConfig('schema_pack', VENUE_PACK);+ await putTyped(engine, 'notes/plain', 'note');+ for (const [i, v] of VENUES.entries()) {+ await putTyped(engine, `venues/${v}`, 'venue');+ if (i >= 3) continue;+ await engine.addLinksBatch([{ from_slug: 'notes/plain', to_slug: `venues/${v}`, link_type: 'mentions', link_source: 'manual' }]);+ await engine.addTimelineEntry(`venues/${v}`, { date: '2026-01-02', source: 'test', summary: 'opened' });+ }+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ writeEntityTypePacks(home);+ writeVenuePack();+});++afterAll(async () => {+ __resetMcpOnboardingForTests();+ __resetBackupNoticeForTests();+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetPackCacheForTests();+ __resetMcpOnboardingForTests();+ __resetBackupNoticeForTests();+});++describe('#4772 onboard coverage checks follow the active pack', () => {+ test('a pack that declares venue as an entity grades the venue pages', async () => {+ await env(async () => {+ await seedVenues();+ const link = await checkEntityLinkCoverage(engine);+ expect(link.check.status, link.check.message).toBe('warn');+ expect(link.check.message).toContain('Coverage 50%');+ const timeline = await checkTimelineCoverage(engine);+ expect(timeline.check.status, timeline.check.message).toBe('warn');+ expect(timeline.check.message).toContain('50%');+ });+ });++ test('two sources with different packs count per source, never a union of names', async () => {+ await env(async () => {+ await seedPerSourcePacks(engine);+ const link = await checkEntityLinkCoverage(engine);+ expect(link.check.message, 'X widgets (2) + Y gadget (1)').toContain('Only 3 entity pages');+ });+ });++ test('a pack that does not load warns entity_types_unavailable instead of grading the legacy list', async () => {+ await env(async () => {+ await seedUnavailablePack(engine, PACKS.missing);+ for (const check of [await checkEntityLinkCoverage(engine), await checkTimelineCoverage(engine)]) {+ expect(check.check.status).toBe('warn');+ expect(check.check.details).toMatchObject({ code: 'entity_types_unavailable', entity_types_status: 'pack_unavailable' });+ expect(check.check.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'schema', 'active']);+ expect(check.remediations).toEqual([]);+ }+ });+ });++ test("one source's override that does not load names that source", async () => {+ await env(async () => {+ await seedPerSourcePacks(engine);+ await engine.setConfig(`schema_pack.source.${SRC_X}`, PACKS.missing);+ const link = await checkEntityLinkCoverage(engine);+ expect(link.check.details).toMatchObject({ code: 'entity_types_unavailable', unresolved_sources: [SRC_X] });+ expect(link.check.fix?.argv).toEqual(['gbrain', 'schema', 'active', '--json', '--source', SRC_X]);+ });+ });+});++describe('#4772 MCP onboarding counts follow the active pack', () => {+ test('venue entities are counted', async () => {+ await env(async () => {+ await seedVenues();+ const counts = await collectOnboardOpportunities(engine, new AbortController().signal);+ expect(counts).toMatchObject({ entities: 6, linkedEntities: 3, timelineEntities: 3, entityTypesStatus: 'resolved' });+ });+ });++ test('per-source packs count per source', async () => {+ await env(async () => {+ await seedPerSourcePacks(engine);+ const counts = await collectOnboardOpportunities(engine, new AbortController().signal);+ expect(counts.entities).toBe(3);+ });+ });++ test('a pack that does not load leaves the entity counts unknown, not the legacy list', async () => {+ await env(async () => {+ await seedUnavailablePack(engine, PACKS.missing);+ const counts = await collectOnboardOpportunities(engine, new AbortController().signal);+ expect(counts).toMatchObject({ entities: null, linkedEntities: null, timelineEntities: null, entityTypesStatus: 'pack_unavailable', partial: true });+ expect(counts.pages).toBe(6);+ });+ });++ test('a venue page without a timeline gets the timeline-coverage notice', async () => {+ await env(async () => {+ await seedVenues();+ await __warmOnboardingCacheForTests(engine as never);+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', allowedOps: new Set(STARTER_OPS), surface: 'starter' as const };+ const result: ToolResult = await dispatchToolCall(engine as never, 'get_page', { slug: 'venues/teal-loft' }, opts);+ const codes = ((result._meta?.gbrain_notices ?? []) as Array<{ code: string }>).map(n => n.code);+ expect(codes).toContain('onboard_timeline_coverage');+ });+ });+});++describe('#4772 NER target types follow the active pack', () => {+ test('a mention of a venue entity gets the typed edge the pack infers', async () => {+ await env(async () => {+ await engine.setConfig('schema_pack', VENUE_PACK);+ await engine.putPage('venues/blue-hall-example', { title: 'Blue Hall Example', type: 'venue' as never, compiled_truth: 'A concert hall.' });+ await engine.putPage('people/ana-example', { title: 'Ana Example', type: 'person' as never, compiled_truth: 'Ana Example performed at Blue Hall Example last spring.' });+ const result = await extractNerLinks(engine);+ expect(result.pack_unavailable).toBe(false);+ const links = await engine.getLinks('people/ana-example');+ expect(links.filter(l => l.link_type === 'performed_at').map(l => l.to_slug)).toEqual(['venues/blue-hall-example']);+ });+ });++ test('a source override that does not load reports pack_unavailable and writes nothing', async () => {+ await env(async () => {+ await engine.setConfig('schema_pack', VENUE_PACK);+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('${SRC_X}', '${SRC_X}') ON CONFLICT (id) DO NOTHING`);+ await engine.setConfig(`schema_pack.source.${SRC_X}`, PACKS.missing);+ await engine.putPage('venues/blue-hall-example', { title: 'Blue Hall Example', type: 'venue' as never, compiled_truth: 'A concert hall.' });+ await engine.putPage('people/ana-example', { title: 'Ana Example', type: 'person' as never, compiled_truth: 'Ana Example performed at Blue Hall Example last spring.' });+ const result = await extractNerLinks(engine);+ expect(result).toEqual({ pages: 0, created: 0, pack_unavailable: true });+ expect(await engine.getLinks('people/ana-example')).toEqual([]);+ });+ });+});