Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(schema): orphan review, schema_stats and doctor consistency count undeclared page types (#5879, #5432)

garrytan8905ca86b99f
diff --git a/skills/brain-taxonomist/SKILL.md b/skills/brain-taxonomist/SKILL.md
index c1cd0ecff4..517c959d95 100644
--- a/skills/brain-taxonomist/SKILL.md
+++ b/skills/brain-taxonomist/SKILL.md
@@ -123,15 +123,23 @@ type is needed and let the schema-pack cathedral handle the proposal flow.
## Periodic Drift Detection
```bash
-# What pages have no type matching the active pack?
+# Which pages have no type matching the active pack? Counts untyped pages AND
+# pages whose type the pack neither declares nor aliases (undeclared_types).
gbrain schema review-orphans --json
-# What's the overall health?
-gbrain doctor --json | jq '.checks[] | select(.name == "schema_pack_consistency")'
+# Per-type audit of the stored corpus (stored_type_undeclared / stored_type_is_alias).
+gbrain schema lint --with-db --json
```
-When `schema_pack_consistency` warns at >10% untyped, run the EIIRP
-Phase 3 SCHEMA CHECK flow to surface candidate types via `schema detect`.
+Both commands run locally. Over MCP, the `run_doctor` report carries the
+same verdict as its `schema_pack_consistency` check (an undeclared type
+warns with code `page_type_undeclared`).
+
+When undeclared types show up, declare them in the pack
+(`gbrain schema add-type <type> --primitive <p> --prefix <dir/>`) or rewrite
+the pages with a declared type. When more than 10% of a source is untyped,
+run the EIIRP Phase 3 SCHEMA CHECK flow to surface candidate types via
+`schema detect`.
## Output Format
diff --git a/skills/eiirp/SKILL.md b/skills/eiirp/SKILL.md
index bf8141497c..4746d10350 100644
--- a/skills/eiirp/SKILL.md
+++ b/skills/eiirp/SKILL.md
@@ -397,7 +397,7 @@ Confirm:
- [ ] No DRY violations (no duplicated logic across skills)
- [ ] No MECE violations (no ambiguous routing between skills)
- [ ] Active schema pack updated if new content types emerged
-- [ ] `gbrain doctor` reports `schema_pack_consistency: ok`
+- [ ] `gbrain schema review-orphans --json` reports `orphan_count: 0` (no untyped pages and no undeclared types)
## Phase 7: REPORT — Summary
@@ -423,7 +423,7 @@ Confirm:
- DRY check: [clean]
- MECE audit: [clean]
- Active pack: [name] v[version]
-- schema_pack_consistency: [ok / warn — pct untyped]
+- schema review-orphans: [orphan_count 0 / N untyped + M undeclared-type pages]
```
## Output Format
@@ -449,7 +449,7 @@ EIIRP produces a single Phase 7 report block. Plain markdown:
- DRY check: [clean|N violations]
- MECE audit: [clean|N overlaps]
- Active pack: [name] v[version]
-- schema_pack_consistency: [ok|warn — N% untyped]
+- schema review-orphans: [0 orphans|N untyped + M undeclared-type pages]
```
Always machine-readable: stable section headers + bullet-per-item. The
@@ -526,5 +526,7 @@ reads it; doctor cross-references the pack version).
`brain/schema.md`.
- Phase 5 SKILL GRAPH AUDIT calls `gbrain check-resolvable` instead of
upstream `scripts/skill-dry-check.mjs`.
-- Phase 6 verification uses `gbrain doctor`'s schema_pack_consistency
- check (T7) for the persistent surface.
+- Phase 6 verification uses `gbrain schema review-orphans` (untyped pages
+ plus undeclared types, the same classification as `schema lint
+ --with-db`); over MCP, `run_doctor`'s schema_pack_consistency check
+ carries the same verdict.
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index c439b72a2c..8937bd96b9 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -403,7 +403,7 @@ export async function doctorReportRemote(
// schema_pack_consistency — % of pages typed against active pack
// schema_pack_source_drift — per-source pack divergence
checks.push(await checkSchemaPackActive(engine));
- checks.push(await checkSchemaPackConsistency(engine));
+ checks.push(await checkSchemaPackConsistency(engine, { sourceIds: opts.sourceIds }));
checks.push(await checkSchemaPackSourceDrift(engine));
// 7. v0.32.3 search-lite mode + per-key drift surface.
diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.ts
index 61908d9bba..a538797d79 100644
--- a/src/commands/doctor/schema-pack-checks.ts
+++ b/src/commands/doctor/schema-pack-checks.ts
@@ -5,13 +5,16 @@
*/
import type { BrainEngine } from '../../core/engine.ts';
import type { Check } from '../doctor.ts';
+import { redactConnectionInfo } from '../../core/audit/redact-connection-info.ts';
+import { loadActivePackForLocalEngine } from '../../core/schema-pack/best-effort.ts';
+import { sanitizeTypeForDisplay, storedTypeMissesPack } from '../../core/schema-pack/type-usage.ts';
// =================================================================
// v0.39 T7 + T9 — schema-pack doctor checks
// =================================================================
// Three checks per v0.38 CEO plan that never shipped at v0.38 time:
// schema_pack_active — does the active pack resolve cleanly?
-// schema_pack_consistency — what % of pages match the active pack?
+// schema_pack_consistency — do stored page types match the active pack?
// schema_pack_source_drift — do per-source packs disagree?
// All three are warn-only; never fail-block.
@@ -44,60 +47,110 @@ export async function checkSchemaPackActive(engine: BrainEngine): Promise<Check>
}
}
-export async function checkSchemaPackConsistency(engine: BrainEngine): Promise<Check> {
+const SCHEMA_PACK_DOCS = 'docs/architecture/schema-packs.md#undeclared-page-types';
+
+/**
+ * #5432: a check that could not read its input says "not verified" (warn),
+ * never ok. The redacted reason rides in `details.reason` for `--json`.
+ */
+function notVerified(err: unknown, fix: string): Omit<Check, 'name'> {
+ const reason = redactConnectionInfo(err instanceof Error ? err.message : String(err)).slice(0, 200);
+ return {
+ status: 'warn',
+ message: `Not verified: the check could not run (${reason}). Fix the cause, then re-run \`${fix}\`.`,
+ details: { code: 'not_verified', verified: false, reason, fix, docs: SCHEMA_PACK_DOCS },
+ };
+}
+
+interface SourceConformance {
+ source_id: string;
+ total: number;
+ untyped: number;
+ undeclared: number;
+ undeclared_types: Array<{ type: string; count: number }>;
+ pack: string | null;
+}
+
+/**
+ * #5879: pages match the active pack only when their stored type is a
+ * declared page type or an alias of one (`storedTypeMissesPack`, the same
+ * classification as `schema lint --with-db`). Each source is graded against
+ * its own resolved pack. Any undeclared type warns; untyped pages warn at
+ * >= 10% of a source.
+ */
+export async function checkSchemaPackConsistency(
+ engine: BrainEngine,
+ opts: { sourceIds?: string[] } = {},
+): Promise<Check> {
+ const scoped = opts.sourceIds !== undefined;
+ let rows: Array<{ src: string; type: string | null; n: string }>;
try {
- const rows = await engine.executeRaw<{ src: string; total: string | number; untyped: string | number }>(
- `SELECT
- source_id AS src,
- COUNT(*)::text AS total,
- COUNT(*) FILTER (WHERE type IS NULL OR type = '')::text AS untyped
- FROM pages
- WHERE deleted_at IS NULL
- GROUP BY source_id
- ORDER BY source_id`,
+ rows = await engine.executeRaw(
+ `SELECT COALESCE(source_id, 'default') AS src, type, COUNT(*)::text AS n
+ FROM pages
+ WHERE deleted_at IS NULL${scoped ? ' AND source_id = ANY($1::text[])' : ''}
+ GROUP BY source_id, type
+ ORDER BY source_id`,
+ scoped ? [opts.sourceIds] : [],
);
- if (rows.length === 0) {
- return { name: 'schema_pack_consistency', status: 'ok', message: 'No pages in any source — schema consistency N/A.' };
- }
- let worstPct = 0;
- let worstSrc = '';
- let worstUntyped = 0;
- let worstTotal = 0;
- for (const r of rows) {
- const total = Number(r.total);
- const untyped = Number(r.untyped);
- if (total === 0) continue;
- const pct = untyped / total;
- if (pct > worstPct) {
- worstPct = pct;
- worstSrc = r.src;
- worstUntyped = untyped;
- worstTotal = total;
- }
- }
- if (worstPct === 0) {
- return { name: 'schema_pack_consistency', status: 'ok', message: 'All pages match the active schema pack across every source.' };
- }
- const pctStr = (worstPct * 100).toFixed(1);
- if (worstPct >= 0.1) {
- return {
- name: 'schema_pack_consistency',
- status: 'warn',
- message: `Source \`${worstSrc}\`: ${worstUntyped} of ${worstTotal} pages (${pctStr}%) have no type matching the active pack. Run \`gbrain schema detect --source ${worstSrc}\` to propose a pack matching your content shape.`,
- };
- }
- return {
- name: 'schema_pack_consistency',
- status: 'ok',
- message: `${pctStr}% untyped at worst (source \`${worstSrc}\`) — under the 10% warn threshold.`,
- };
} catch (e) {
- return {
- name: 'schema_pack_consistency',
- status: 'ok',
- message: `Skipped: ${(e as Error).message}`,
- };
+ return { name: 'schema_pack_consistency', ...notVerified(e, 'gbrain schema review-orphans') };
+ }
+ if (rows.length === 0) {
+ return { name: 'schema_pack_consistency', status: 'ok', message: 'No pages in any source — schema consistency N/A.' };
+ }
+ const bySource = new Map<string, Array<{ type: string | null; n: number }>>();
+ for (const r of rows) {
+ const list = bySource.get(r.src) ?? [];
+ list.push({ type: r.type, n: Number(r.n) });
+ bySource.set(r.src, list);
+ }
+ const graded: SourceConformance[] = [];
+ const unresolved: string[] = [];
+ for (const [src, types] of bySource) {
+ const pack = await loadActivePackForLocalEngine(engine, { sourceId: src });
+ if (!pack) { unresolved.push(src); continue; }
+ const undeclaredTypes = types
+ .filter((t): t is { type: string; n: number } => !!t.type && storedTypeMissesPack(t.type, pack.manifest))
+ .map((t) => ({ type: t.type, count: t.n }))
+ .sort((a, b) => b.count - a.count || a.type.localeCompare(b.type));
+ graded.push({
+ source_id: src,
+ total: types.reduce((sum, t) => sum + t.n, 0),
+ untyped: types.filter((t) => !t.type).reduce((sum, t) => sum + t.n, 0),
+ undeclared: undeclaredTypes.reduce((sum, t) => sum + t.count, 0),
+ undeclared_types: undeclaredTypes,
+ pack: pack.manifest.name,
+ });
+ }
+ const details: Record<string, unknown> = { per_source: graded, unresolved_sources: unresolved, docs: SCHEMA_PACK_DOCS };
+ const problems: string[] = [];
+ for (const g of graded.filter((x) => x.undeclared > 0)) {
+ const sample = g.undeclared_types.slice(0, 5).map((t) => `'${sanitizeTypeForDisplay(t.type)}' (${t.count})`).join(', ');
+ problems.push(`Source \`${g.source_id}\`: ${g.undeclared} page(s) use ${g.undeclared_types.length} type(s) pack \`${g.pack}\` neither declares nor aliases: ${sample}. List them with \`gbrain schema review-orphans --source ${g.source_id}\`, then declare the type (\`gbrain schema add-type <type>\`, which takes its primitive and prefix) or retype the pages to a declared type.`);
}
+ const worst = graded.reduce<SourceConformance | null>((w, g) =>
+ g.total > 0 && (!w || g.untyped / g.total > w.untyped / w.total) ? g : w, null);
+ const worstPct = worst ? worst.untyped / worst.total : 0;
+ if (worst && worstPct >= 0.1) {
+ problems.push(`Source \`${worst.source_id}\`: ${worst.untyped} of ${worst.total} pages (${(worstPct * 100).toFixed(1)}%) have no type matching the active pack. Run \`gbrain schema detect --source ${worst.source_id}\` to propose a pack matching your content shape.`);
+ }
+ if (unresolved.length > 0) {
+ problems.push(`Not verified for ${unresolved.length} source(s) (${unresolved.join(', ')}): the active pack did not resolve. Run \`gbrain schema active\` to debug.`);
+ }
+ if (problems.length > 0) {
+ const code = graded.some((x) => x.undeclared > 0) ? 'page_type_undeclared' : unresolved.length > 0 ? 'not_verified' : 'pages_untyped';
+ return { name: 'schema_pack_consistency', status: 'warn', message: problems.join(' '), details: { ...details, code } };
+ }
+ if (!worst || worst.untyped === 0) {
+ return { name: 'schema_pack_consistency', status: 'ok', message: 'All pages match the active schema pack across every source.', details };
+ }
+ return {
+ name: 'schema_pack_consistency',
+ status: 'ok',
+ message: `${(worstPct * 100).toFixed(1)}% untyped at worst (source \`${worst.source_id}\`) — under the 10% warn threshold.`,
+ details,
+ };
}
export async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<Check> {
@@ -120,11 +173,7 @@ export async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<C
message: `Per-source pack divergence detected: ${distinctPacks.size} distinct packs across ${rows.length} sources. Run \`gbrain sources list\` then \`gbrain schema active --source <id>\` per source to audit.`,
};
} catch (e) {
- return {
- name: 'schema_pack_source_drift',
- status: 'ok',
- message: `Skipped: ${(e as Error).message}`,
- };
+ return { name: 'schema_pack_source_drift', ...notVerified(e, 'gbrain doctor') };
}
}
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index 423ab2250f..4ed3af2d5e 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -55,6 +55,7 @@ import { PACK_PRIMITIVES } from '../core/schema-pack/manifest-v1.ts';
import { bundledPackPath } from '../core/schema-pack/bundled-assets.ts';
import { gbrainPath, loadConfig, configPath, toEngineConfig, type GBrainConfig } from '../core/config.ts';
import { readDbSchemaPack } from '../core/schema-pack/best-effort.ts';
+import { sanitizeTypeForDisplay } from '../core/schema-pack/type-usage.ts';
export async function runSchema(args: string[]): Promise<void> {
const sub = args[0];
@@ -845,9 +846,13 @@ async function runReviewOrphansCmd(args: string[]): Promise<void> {
console.log(JSON.stringify({ schema_version: 1, ...result }, null, 2));
return;
}
- console.log(`Orphan pages (no active-pack type match): ${result.orphan_count}`);
+ console.log(`Orphan pages (no active-pack type match): ${result.orphan_count}`
+ + (result.pack ? ` (pack ${result.pack})` : ' (no active pack resolved: only untyped pages checked)'));
+ for (const u of result.undeclared_types) {
+ console.log(` type '${sanitizeTypeForDisplay(u.type)}' is not declared in the pack: ${u.count} page(s)`);
+ }
for (const o of result.orphans.slice(0, 20)) {
- console.log(` ${o.slug}`);
+ console.log(` ${o.slug}${o.reason === 'undeclared' ? ` (type ${sanitizeTypeForDisplay(o.type)})` : ' (untyped)'}`);
}
if (result.orphan_count > 20) {
console.log(` ... and ${result.orphan_count - 20} more (use --json to see all)`);
@@ -1005,8 +1010,11 @@ async function runStatsCmd(args: string[]): Promise<void> {
}
console.log(`Pack: ${result.pack_identity ?? '(no pack loaded)'}`);
console.log(`Total pages: ${result.aggregate.total_pages}`);
- console.log(`Typed: ${result.aggregate.typed_pages} (${(result.aggregate.coverage * 100).toFixed(1)}%)`);
+ console.log(`Typed: ${result.aggregate.typed_pages}; matching the active pack: ${(result.aggregate.coverage * 100).toFixed(1)}%`);
console.log(`Untyped: ${result.aggregate.untyped_pages}`);
+ if (result.aggregate.undeclared_pages > 0) {
+ console.log(`Undeclared type: ${result.aggregate.undeclared_pages} (not a page type or alias of the active pack; list them with \`gbrain schema review-orphans\`)`);
+ }
if (result.aggregate.by_type.length > 0) {
console.log(`\nBy type:`);
for (const t of result.aggregate.by_type) {
diff --git a/src/core/ops/schema-packs.ts b/src/core/ops/schema-packs.ts
index a79ad01f09..5f8a8886e8 100644
--- a/src/core/ops/schema-packs.ts
+++ b/src/core/ops/schema-packs.ts
@@ -221,28 +221,15 @@ const schema_review_orphans: Operation = {
scope: 'read',
handler: async (ctx, p) => {
const limit = Math.max(1, Math.min(10000, (p.limit as number) ?? 100));
- const scope = sourceScopeOpts(ctx);
- let where = `WHERE deleted_at IS NULL AND (type IS NULL OR type = '')`;
- const params: unknown[] = [];
- if (scope.sourceIds && scope.sourceIds.length > 0) {
- where += ` AND source_id = ANY($1::text[])`;
- params.push(scope.sourceIds);
- } else if (scope.sourceId) {
- where += ` AND source_id = $1`;
- params.push(scope.sourceId);
- }
+ const { loadActivePackBestEffort } = await import('../schema-pack/best-effort.ts');
+ const { findTypeOrphans } = await import('../schema-pack/review.ts');
+ const { isUndefinedTableError } = await import('../utils.ts');
+ const pack = await loadActivePackBestEffort(ctx);
try {
- const rows = await ctx.engine.executeRaw<{ slug: string; source_id: string }>(
- `SELECT slug, COALESCE(source_id, 'default') AS source_id FROM pages ${where} ORDER BY source_id, slug LIMIT ${limit}`,
- params,
- );
- return {
- schema_version: 1,
- orphan_count: rows.length,
- orphans: rows.map((r) => ({ slug: r.slug, source_id: r.source_id })),
- };
- } catch {
- return { schema_version: 1, orphan_count: 0, orphans: [] };
+ return { schema_version: 1, ...await findTypeOrphans(ctx.engine, pack?.manifest ?? null, sourceScopeOpts(ctx), limit) };
+ } catch (err) {
+ if (isUndefinedTableError(err)) return { schema_version: 1, orphan_count: 0, orphans: [], undeclared_types: [], pack: pack?.manifest.name ?? null, truncated: false };
+ throw err;
}
},
};
diff --git a/src/core/schema-pack/review.ts b/src/core/schema-pack/review.ts
index 1925a3e774..6aa7adefdd 100644
--- a/src/core/schema-pack/review.ts
+++ b/src/core/schema-pack/review.ts
@@ -13,6 +13,8 @@
import type { BrainEngine } from '../engine.ts';
import { runDetect } from './detect.ts';
import { loadActivePack } from './load-active.ts';
+import { loadActivePackForLocalEngine } from './best-effort.ts';
+import { storedTypeMissesPack, type TypeUsagePack } from './type-usage.ts';
import { loadConfig, gbrainPath, configPath } from '../config.ts';
import { existsSync, writeFileSync, mkdirSync, appendFileSync } from 'node:fs';
import { dirname } from 'node:path';
@@ -100,13 +102,87 @@ export async function runReviewCandidates(
// ----- T5 review-orphans ------------------------------------------
+export interface TypeOrphan {
+ slug: string;
+ source_id: string;
+ /** Stored `pages.type` ('' when untyped). */
+ type: string;
+ reason: 'untyped' | 'undeclared';
+}
+
+export interface TypeOrphansResult {
+ /** Every page in scope with no active-pack type match (not just the returned page). */
+ orphan_count: number;
+ orphans: TypeOrphan[];
+ /** Stored types the pack neither declares nor aliases, with page counts. */
+ undeclared_types: Array<{ type: string; count: number }>;
+ /** Active pack name, or null when no pack resolved (only untyped pages are then checked). */
+ pack: string | null;
+ /** True when orphan_count exceeds the returned orphans. */
+ truncated: boolean;
+}
+
+/**
+ * Pages with no active-pack type match: an empty type, or a type the pack
+ * neither declares nor aliases (`storedTypeMissesPack`, the same predicate as
+ * `schema lint --with-db`'s `stored_type_undeclared`). Shared by the
+ * `schema review-orphans` CLI and the `schema_review_orphans` MCP op.
+ */
+export async function findTypeOrphans(
+ engine: BrainEngine,
+ manifest: (TypeUsagePack & { name: string }) | null,
+ scope: { sourceId?: string; sourceIds?: string[] },
+ limit: number,
+): Promise<TypeOrphansResult> {
+ const params: unknown[] = [];
+ let where = 'deleted_at IS NULL';
+ if (scope.sourceIds && scope.sourceIds.length > 0) {
+ params.push(scope.sourceIds);
+ where += ` AND source_id = ANY($${params.length}::text[])`;
+ } else if (scope.sourceId) {
+ params.push(scope.sourceId);
+ where += ` AND source_id = $${params.length}`;
+ }
+ const typeRows = await engine.executeRaw<{ type: string | null; n: string }>(
+ `SELECT type, count(*)::text AS n FROM pages WHERE ${where} GROUP BY type`,
+ params,
+ );
+ const missing = typeRows.filter((r) => (manifest ? storedTypeMissesPack(r.type, manifest) : !r.type));
+ const undeclared = missing
+ .filter((r): r is { type: string; n: string } => !!r.type)
+ .map((r) => ({ type: r.type, count: Number(r.n) }))
+ .sort((a, b) => b.count - a.count || a.type.localeCompare(b.type));
+ const orphanCount = missing.reduce((sum, r) => sum + Number(r.n), 0);
+ if (orphanCount === 0) {
+ return { orphan_count: 0, orphans: [], undeclared_types: [], pack: manifest?.name ?? null, truncated: false };
+ }
+ const rowLimit = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 100;
+ const rows = await engine.executeRaw<{ slug: string; source_id: string; type: string | null }>(
+ `SELECT slug, COALESCE(source_id, 'default') AS source_id, type FROM pages
+ WHERE ${where} AND (type IS NULL OR type = '' OR type = ANY($${params.length + 1}::text[]))
+ ORDER BY source_id, slug
+ LIMIT ${rowLimit}`,
+ [...params, undeclared.map((u) => u.type)],
+ );
+ return {
+ orphan_count: orphanCount,
+ orphans: rows.map((r) => ({
+ slug: r.slug,
+ source_id: r.source_id,
+ type: r.type ?? '',
+ reason: r.type ? 'undeclared' : 'untyped',
+ })),
+ undeclared_types: undeclared,
+ pack: manifest?.name ?? null,
+ truncated: orphanCount > rows.length,
+ };
+}
+
export interface ReviewOrphansOpts {
sourceId?: string;
}
-export interface ReviewOrphansResult {
- orphans: Array<{ slug: string; source_id: string }>;
- orphan_count: number;
+export interface ReviewOrphansResult extends TypeOrphansResult {
source_id: string;
}
@@ -115,18 +191,7 @@ export async function runReviewOrphans(
opts: ReviewOrphansOpts = {},
): Promise<ReviewOrphansResult> {
const sourceId = opts.sourceId ?? 'default';
- const rows = await engine.executeRaw<{ slug: string; source_id: string }>(
- `SELECT slug, source_id FROM pages
- WHERE source_id = $1
- AND deleted_at IS NULL
- AND (type IS NULL OR type = '')
- ORDER BY slug
- LIMIT 1000`,
- [sourceId],
- );
- return {
- orphans: rows.map((r) => ({ slug: r.slug, source_id: r.source_id })),
- orphan_count: rows.length,
- source_id: sourceId,
- };
+ const pack = await loadActivePackForLocalEngine(engine, { sourceId });
+ const result = await findTypeOrphans(engine, pack?.manifest ?? null, { sourceId }, 1000);
+ return { ...result, source_id: sourceId };
}
diff --git a/src/core/schema-pack/stats.ts b/src/core/schema-pack/stats.ts
index f1fa2e26b1..b10d7f2a82 100644
--- a/src/core/schema-pack/stats.ts
+++ b/src/core/schema-pack/stats.ts
@@ -19,6 +19,7 @@ import type { BrainEngine } from '../engine.ts';
import { loadActivePackBestEffort } from './best-effort.ts';
import type { OperationContext } from '../operations.ts';
import { isUndefinedTableError } from '../utils.ts';
+import { storedTypeMissesPack, type TypeUsagePack } from './type-usage.ts';
export interface StatsOpts {
/** Single source scope. Omit + omit sourceIds for whole-brain aggregate. */
@@ -39,6 +40,12 @@ export interface PerSourceStats {
total_pages: number;
typed_pages: number;
untyped_pages: number;
+ /** Pages whose non-empty type the active pack neither declares nor aliases
+ * (0 when no pack resolved). */
+ undeclared_pages: number;
+ /** Share of pages whose type matches the active pack (declared or alias);
+ * untyped and undeclared pages both count against it. Without a resolved
+ * pack: share of pages with a non-empty type. */
coverage: number;
by_type: TypeStats[];
}
@@ -73,19 +80,20 @@ function computeCoverage(typed: number, total: number): number {
return Math.round((typed / total) * 10000) / 10000;
}
-function aggregateRows(rows: RawCountRow[]): PerSourceStats[] {
- const bySource = new Map<string, { typed: number; untyped: number; total: number; byType: Map<string, number> }>();
+function aggregateRows(rows: RawCountRow[], pack: TypeUsagePack | null): PerSourceStats[] {
+ const bySource = new Map<string, { typed: number; untyped: number; undeclared: number; total: number; byType: Map<string, number> }>();
for (const r of rows) {
const sid = r.source_id ?? 'default';
const cnt = parseInt(r.cnt, 10) || 0;
if (!bySource.has(sid)) {
- bySource.set(sid, { typed: 0, untyped: 0, total: 0, byType: new Map() });
+ bySource.set(sid, { typed: 0, untyped: 0, undeclared: 0, total: 0, byType: new Map() });
}
const bucket = bySource.get(sid)!;
if (r.type === null || r.type === '') {
bucket.untyped += cnt;
} else {
bucket.typed += cnt;
+ if (pack && storedTypeMissesPack(r.type, pack)) bucket.undeclared += cnt;
bucket.byType.set(r.type, (bucket.byType.get(r.type) ?? 0) + cnt);
}
bucket.total += cnt;
@@ -97,7 +105,8 @@ function aggregateRows(rows: RawCountRow[]): PerSourceStats[] {
total_pages: b.total,
typed_pages: b.typed,
untyped_pages: b.untyped,
- coverage: computeCoverage(b.typed, b.total),
+ undeclared_pages: b.undeclared,
+ coverage: computeCoverage(b.typed - b.undeclared, b.total),
by_type: [...b.byType.entries()]
.map(([type, count]) => ({ type, count }))
.sort((a, b) => b.count - a.count || a.type.localeCompare(b.type)),
@@ -109,11 +118,12 @@ function aggregateRows(rows: RawCountRow[]): PerSourceStats[] {
}
function mergeAggregate(per: PerSourceStats[]): PerSourceStats {
- let typed = 0, untyped = 0, total = 0;
+ let typed = 0, untyped = 0, undeclared = 0, total = 0;
const byType = new Map<string, number>();
for (const s of per) {
typed += s.typed_pages;
untyped += s.untyped_pages;
+ undeclared += s.undeclared_pages;
total += s.total_pages;
for (const t of s.by_type) byType.set(t.type, (byType.get(t.type) ?? 0) + t.count);
}
@@ -122,7 +132,8 @@ function mergeAggregate(per: PerSourceStats[]): PerSourceStats {
total_pages: total,
typed_pages: typed,
untyped_pages: untyped,
- coverage: computeCoverage(typed, total),
+ undeclared_pages: undeclared,
+ coverage: computeCoverage(typed - undeclared, total),
by_type: [...byType.entries()]
.map(([type, count]) => ({ type, count }))
.sort((a, b) => b.count - a.count || a.type.localeCompare(b.type)),
@@ -234,13 +245,13 @@ export async function runStatsCore(
opts: StatsOpts = {},
): Promise<StatsResult> {
const rows = await fetchCountRows(ctx.engine, opts);
- const per_source = aggregateRows(rows);
+ // Pack identity, conformance + dead-prefix scan — best-effort.
+ const pack = await loadActivePackBestEffort(ctx);
+ const per_source = aggregateRows(rows, pack?.manifest ?? null);
const aggregate = mergeAggregate(per_source);
- // Pack identity + dead-prefix scan — best-effort.
let pack_identity: string | null = null;
let dead_prefixes: DeadPrefixHint[] = [];
- const pack = await loadActivePackBestEffort(ctx);
if (pack) {
pack_identity = pack.identity;
dead_prefixes = await detectDeadPrefixes(ctx.engine, pack, opts);
diff --git a/src/core/schema-pack/type-usage.ts b/src/core/schema-pack/type-usage.ts
index d3d4efdd05..9199a1e209 100644
--- a/src/core/schema-pack/type-usage.ts
+++ b/src/core/schema-pack/type-usage.ts
@@ -50,6 +50,17 @@ export function classifyStoredType(type: string, pack: TypeUsagePack): StoredTyp
return { kind: 'undeclared' };
}
+/**
+ * Does a stored `pages.type` miss the active pack? True for an empty type
+ * (untyped) and for a type the pack neither declares nor aliases. Every
+ * pack-conformance surface (orphan review, schema_stats coverage, doctor
+ * schema_pack_consistency, `gbrain lint`) uses this one predicate so they
+ * agree with `schema lint --with-db`'s `stored_type_undeclared` rule.
+ */
+export function storedTypeMissesPack(type: string | null | undefined, pack: TypeUsagePack): boolean {
+ return !type || classifyStoredType(type, pack).kind === 'undeclared';
+}
+
/**
* Type strings come from user/agent frontmatter and get echoed into terminal
* warnings — strip control/non-printable characters (ANSI-escape hygiene) and
diff --git a/test/doctor-schema-pack-checks.test.ts b/test/doctor-schema-pack-checks.test.ts
index fd1d6681dd..2ae6fb666c 100644
--- a/test/doctor-schema-pack-checks.test.ts
+++ b/test/doctor-schema-pack-checks.test.ts
@@ -6,7 +6,8 @@
* - consistency picks the WORST source by untyped percentage;
* - warn fires at >= 10% (exactly 10.0% warns), stays ok at 9.9%;
* - empty brain -> ok / N-A;
- * - engine.executeRaw throwing -> check stays OK (fail-open, "Skipped: ...");
+ * - engine.executeRaw throwing -> warn "Not verified" with the reason in
+ * details (#5432: a check that read nothing never reports ok);
* - soft-deleted pages are excluded (deleted_at IS NULL filter);
* - source drift: 0 or same-value schema_pack.source.* config rows -> ok,
* 2 distinct values -> warn naming the distinct-pack count.
@@ -125,11 +126,13 @@ describe('schema_pack_consistency', () => {
expect(check.message).toBe('All pages match the active schema pack across every source.');
});
- test('engine.executeRaw throwing -> check stays ok (fail-open), never throws', async () => {
+ test('engine.executeRaw throwing -> warn not verified (#5432), never throws', async () => {
const check = await checkSchemaPackConsistency(throwingEngine);
expect(check.name).toBe('schema_pack_consistency');
- expect(check.status).toBe('ok'); // pinned: fail-open, NOT warn/fail
- expect(check.message).toBe('Skipped: boom-executeRaw');
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Not verified');
+ expect(check.message).toContain('boom-executeRaw');
+ expect(check.details).toMatchObject({ code: 'not_verified', verified: false, reason: 'boom-executeRaw' });
});
});
@@ -167,9 +170,10 @@ describe('schema_pack_source_drift', () => {
expect(check.message).toContain('gbrain sources list');
});
- test('engine.executeRaw throwing -> check stays ok (fail-open), never throws', async () => {
+ test('engine.executeRaw throwing -> warn not verified (#5432), never throws', async () => {
const check = await checkSchemaPackSourceDrift(throwingEngine);
- expect(check.status).toBe('ok'); // pinned: fail-open, NOT warn/fail
- expect(check.message).toBe('Skipped: boom-executeRaw');
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Not verified');
+ expect(check.details).toMatchObject({ code: 'not_verified', verified: false, reason: 'boom-executeRaw' });
});
});
diff --git a/test/operations-schema-pack.test.ts b/test/operations-schema-pack.test.ts
index 9e5574ea42..8414dace27 100644
--- a/test/operations-schema-pack.test.ts
+++ b/test/operations-schema-pack.test.ts
@@ -244,7 +244,10 @@ describe('schema_review_orphans', () => {
);
}
const result = await operationsByName.schema_review_orphans!.handler(ctxOf(), { limit: 2 }) as Record<string, unknown>;
- expect(result.orphan_count).toBe(2);
+ // #5879: limit caps the returned rows; orphan_count is the true total.
+ expect((result.orphans as unknown[]).length).toBe(2);
+ expect(result.orphan_count).toBe(5);
+ expect(result.truncated).toBe(true);
});
});
diff --git a/test/schema-pack-type-conformance.test.ts b/test/schema-pack-type-conformance.test.ts
new file mode 100644
index 0000000000..9351134590
--- /dev/null
+++ b/test/schema-pack-type-conformance.test.ts
@@ -0,0 +1,160 @@
+/**
+ * #5879 — every pack-conformance surface agrees with `schema lint --with-db`:
+ * a page whose stored type the active pack neither declares nor aliases is
+ * NOT a type match. Pre-fix, `schema_review_orphans` (MCP), `schema
+ * review-orphans` (CLI core), `schema_stats` coverage and doctor
+ * `schema_pack_consistency` only counted empty types, so a brain full of
+ * undeclared types read as fully conforming.
+ *
+ * Pack pinned to the bundled gbrain-base-v2 through the DB-plane
+ * `schema_pack` key (tier 4), with an empty GBRAIN_HOME.
+ */
+import { afterAll, beforeAll, beforeEach, afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { runReviewOrphans } from '../src/core/schema-pack/review.ts';
+import { runStatsCore } from '../src/core/schema-pack/stats.ts';
+import { checkSchemaPackConsistency } from '../src/commands/doctor/schema-pack-checks.ts';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+let engine: PGLiteEngine;
+let tmpHome: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ _resetPackCacheForTests();
+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-5879-'));
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+});
+
+afterEach(() => {
+ _resetPackCacheForTests();
+ rmSync(tmpHome, { recursive: true, force: true });
+});
+
+const env = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: tmpHome, GBRAIN_SCHEMA_PACK: undefined }, fn);
+
+async function seed(slug: string, type: string, sourceId = 'default'): Promise<void> {
+ if (sourceId !== 'default') {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [sourceId]);
+ }
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, source_path, type, title, compiled_truth, timeline, content_hash)
+ VALUES ($1, $2, $3, $4, $1, '', '', '')`,
+ [slug, sourceId, `${slug}.md`, type],
+ );
+}
+
+/** note (declared), memo (alias of note), 3x meeting-transcript (undeclared), 1 untyped. */
+async function seedMixed(): Promise<void> {
+ await seed('notes/a', 'note');
+ await seed('notes/b', 'memo');
+ for (const n of [1, 2, 3]) await seed(`meetings/2026-01-0${n}-sync-transcript`, 'meeting-transcript');
+ await seed('misc/untyped', '');
+}
+
+function ctxOf(sourceId?: string): OperationContext {
+ return {
+ engine,
+ config: {},
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false,
+ remote: false,
+ sourceId,
+ } as unknown as OperationContext;
+}
+
+describe('#5879 orphan review counts undeclared stored types', () => {
+ test('schema_review_orphans op: undeclared + untyped are orphans; declared and alias types are not', async () => {
+ await seedMixed();
+ const result = await env(() => operationsByName.schema_review_orphans!.handler(ctxOf(), {})) as Record<string, any>;
+ expect(result.orphan_count).toBe(4);
+ expect(result.pack).toBe('gbrain-base-v2');
+ expect(result.undeclared_types).toEqual([{ type: 'meeting-transcript', count: 3 }]);
+ const bySlug = Object.fromEntries((result.orphans as Array<{ slug: string; reason: string }>).map((o) => [o.slug, o.reason]));
+ expect(bySlug['misc/untyped']).toBe('untyped');
+ expect(bySlug['meetings/2026-01-01-sync-transcript']).toBe('undeclared');
+ expect(bySlug['notes/a']).toBeUndefined();
+ expect(bySlug['notes/b']).toBeUndefined();
+ });
+
+ test('schema_review_orphans op surfaces a query failure instead of returning orphan_count 0', async () => {
+ const broken = {
+ ...ctxOf(),
+ engine: {
+ getConfig: async () => 'gbrain-base-v2',
+ executeRaw: async () => { throw new Error('permission denied for table pages'); },
+ } as unknown as BrainEngine,
+ } as OperationContext;
+ await expect(env(() => operationsByName.schema_review_orphans!.handler(broken, {}))).rejects.toThrow('permission denied');
+ });
+
+ test('schema review-orphans CLI core reports the same set for its source', async () => {
+ await seedMixed();
+ await seed('other/x', 'banana', 'side-src');
+ const result = await env(() => runReviewOrphans(engine, { sourceId: 'default' }));
+ expect(result.orphan_count).toBe(4);
+ expect(result.undeclared_types.map((u) => u.type)).toEqual(['meeting-transcript']);
+ expect(result.orphans.some((o) => o.slug === 'other/x')).toBe(false);
+ });
+});
+
+describe('#5879 schema_stats coverage', () => {
+ test('undeclared types count against coverage', async () => {
+ await seedMixed();
+ const result = await env(() => runStatsCore(ctxOf()));
+ expect(result.aggregate.total_pages).toBe(6);
+ expect(result.aggregate.typed_pages).toBe(5);
+ expect(result.aggregate.undeclared_pages).toBe(3);
+ // 2 of 6 pages (note + memo) match the pack.
+ expect(result.aggregate.coverage).toBe(0.3333);
+ });
+});
+
+describe('#5879 doctor schema_pack_consistency', () => {
+ test('undeclared stored types warn with a stable code and the review command', async () => {
+ await seed('notes/a', 'note');
+ for (const n of [1, 2]) await seed(`reports/drift-2026-01-0${n}`, 'report');
+ const check = await env(() => checkSchemaPackConsistency(engine));
+ expect(check.status).toBe('warn');
+ expect(check.details?.code).toBe('page_type_undeclared');
+ expect(check.message).toContain("'report' (2)");
+ expect(check.message).toContain('gbrain schema review-orphans --source default');
+ expect(check.message).not.toContain('All pages match');
+ });
+
+ test('an alias-typed page is a pack match', async () => {
+ await seed('notes/a', 'note');
+ await seed('notes/b', 'memo');
+ const check = await env(() => checkSchemaPackConsistency(engine));
+ expect(check.status).toBe('ok');
+ expect(check.message).toBe('All pages match the active schema pack across every source.');
+ });
+
+ test('remote doctor scope: sources outside the grant are not read', async () => {
+ await seed('notes/a', 'note');
+ await seed('other/x', 'banana', 'side-src');
+ const scoped = await env(() => checkSchemaPackConsistency(engine, { sourceIds: ['default'] }));
+ expect(scoped.status).toBe('ok');
+ expect(JSON.stringify(scoped)).not.toContain('side-src');
+ const all = await env(() => checkSchemaPackConsistency(engine));
+ expect(all.status).toBe('warn');
+ expect(all.message).toContain('side-src');
+ });
+});