Compare commits

..
Author SHA1 Message Date
b05ebf6e4a fix(doctor): scope timeline labels to disambiguate entity coverage vs brain-score component (#2298)
doctor and the get_health CLI surface printed two different timeline
metrics under one ambiguous 'timeline' label: the entity-scoped
timeline_coverage fraction (eligible entity pages with a timeline entry)
and the whole-brain timeline_coverage_score brain-score component (all
pages with a timeline entry, 0-15). Different numerators AND
denominators, indistinguishable in output.

Label-only fix, scoring unchanged:
- graph_coverage check: 'entity timeline coverage N%'
- brain_score breakdown: 'timeline density (all pages) N/15'
- get_health CLI: 'Timeline coverage (entity pages)' plus a new
  'Timeline density (all pages): N/15' line when the score is present

Adds test/doctor-timeline-metric-labels-2298.test.ts pinning the
denominator semantics, the rendered doctor messages, and the CLI
guard matrix (fails on master, passes here).

Takeover of #2761.

Co-authored-by: TurgutKural <TurgutKural@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:18:54 -07:00
5 changed files with 168 additions and 104 deletions
+4 -1
View File
@@ -935,7 +935,10 @@ export function formatResult(opName: string, result: unknown): string {
lines.push(`Link coverage (entities): ${(h.link_coverage * 100).toFixed(1)}%`);
}
if (h.timeline_coverage !== undefined) {
lines.push(`Timeline coverage (entities): ${(h.timeline_coverage * 100).toFixed(1)}%`);
lines.push(`Timeline coverage (entity pages): ${(h.timeline_coverage * 100).toFixed(1)}%`);
}
if (h.timeline_coverage_score !== undefined) {
lines.push(`Timeline density (all pages): ${h.timeline_coverage_score}/15 (whole-brain brain-score component)`);
}
if (Array.isArray(h.most_connected) && h.most_connected.length > 0) {
lines.push('Most connected entities:');
+3 -3
View File
@@ -5868,12 +5868,12 @@ export async function buildChecks(
message: `Only code/test fixture entity pages found (${entityCount}); graph_coverage not applicable`,
});
} else if (linkCoverage >= 0.5 && timelineCoverage >= 0.5) {
checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity link coverage ${linkPct}%, timeline ${timelinePct}%` });
checks.push({ name: 'graph_coverage', status: 'ok', message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}%` });
} else {
checks.push({
name: 'graph_coverage',
status: 'warn',
message: `Entity link coverage ${linkPct}%, timeline ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
message: `Entity link coverage ${linkPct}%, entity timeline coverage ${timelinePct}% (${eligibleEntityCount} entity pages). Run: gbrain extract all`,
});
}
@@ -5885,7 +5885,7 @@ export async function buildChecks(
const parts = [
`embed ${health.embed_coverage_score}/35`,
`links ${health.link_density_score}/25`,
`timeline ${health.timeline_coverage_score}/15`,
`timeline density (all pages) ${health.timeline_coverage_score}/15`,
`orphans ${health.no_orphans_score}/15`,
`dead-links ${health.no_dead_links_score}/10`,
];
+6 -17
View File
@@ -18,7 +18,6 @@
import type { BrainEngine } from '../engine.ts';
import { loadActivePackBestEffort } from './best-effort.ts';
import type { OperationContext } from '../operations.ts';
import { isUndefinedTableError } from '../utils.ts';
export interface StatsOpts {
/** Single source scope. Omit + omit sourceIds for whole-brain aggregate. */
@@ -165,17 +164,9 @@ async function fetchCountRows(engine: BrainEngine, opts: StatsOpts): Promise<Raw
`;
try {
return await engine.executeRaw<RawCountRow>(sql, params);
} catch (err) {
// ONLY swallow the genuine "pages table doesn't exist yet" case
// (empty / pre-init brain). #2466: the old bare `catch {}` masked
// EVERY error — so any engine-level failure (connection, version
// skew, a query incompatibility) was silently converted to 0 rows,
// printing "Total pages: 0" on a populated brain and cascading into
// false "100% coverage" + a starved `schema suggest`. Surface
// everything that is not a missing-table error so the real failure
// is visible instead of hidden behind a fake zero.
if (isUndefinedTableError(err)) return [];
throw err;
} catch {
// Empty / pre-init brain: pages table may not exist yet.
return [];
}
}
@@ -213,11 +204,9 @@ async function detectDeadPrefixes(
if (cnt === 0) {
hints.push({ type: t.name, prefix });
}
} catch (err) {
// #2466: only skip on the genuine "no pages table yet" case;
// rethrow any other engine error so it isn't silently masked.
if (isUndefinedTableError(err)) continue;
throw err;
} catch {
// Skip on engine error (no pages table yet, etc.).
continue;
}
}
}
@@ -0,0 +1,155 @@
/**
* Issue #2298 — timeline metric presentation contract.
*
* Authoritative upstream semantics (src/core/types.ts):
* - Metric A `timeline_coverage` (entity-scoped, fraction 01):
* eligible entity pages WITH a timeline entry / eligible entity pages
* -> surfaced by `graph_coverage` check AND `get_health` CLI entity line.
* - Metric B `timeline_coverage_score` (whole-brain, 015 brain-score component):
* all pages WITH a timeline entry / all pages
* -> surfaced by `brain_score` component breakdown AND (separately) CLI.
*
* The two have DIFFERENT numerators/denominators. This PR labels each
* explicitly and keeps BOTH the entity CLI line and the whole-brain line.
*
* Tests (no private EriadorMu data, no production/home DB, no network):
* - numeric denominator assertions (Metric A = 50%, Metric B = 4/15)
* - doctor rendered-message assertions (exact labels, no ambiguous old label)
* - CLI rendered-output assertions (exact lines, guard matrix)
* - red/green: same assertions FAIL on origin/master, PASS on this branch
*
* Scoring formula UNCHANGED. Canonical PGLite fixture via resetPgliteState.
*/
import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { buildChecks } from '../src/commands/doctor.ts';
import { formatResult } from '../src/cli.ts';
let engine: PGLiteEngine;
async function seedFourPages(eng: PGLiteEngine): Promise<void> {
const sql = sqlQueryForEngine(eng);
// 2 eligible entity pages, 2 technical/non-entity pages.
// Only ONE entity page has a timeline entry; only ONE total page does.
await sql`
INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
VALUES
('acme-example', 'default', 'company', 'Acme', '', '{}', 'h1', now(), now()),
('alice-example', 'default', 'person', 'Alice', '', '{}', 'h2', now(), now()),
('technical-a', 'default', 'note', 'Tech A', '', '{}', 'h3', now(), now()),
('technical-b', 'default', 'note', 'Tech B', '', '{}', 'h4', now(), now())
`;
const companyId = (await sql`SELECT id FROM pages WHERE slug='acme-example'`)[0].id as number;
await sql`INSERT INTO timeline_entries (page_id, date, source, summary, detail)
VALUES (${companyId}, CURRENT_DATE, 'test', 'milestone', '{}')`;
}
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
});
afterAll(async () => {
await engine.disconnect();
});
beforeEach(async () => {
await resetPgliteState(engine);
});
describe('issue #2298 — numeric denominator semantics', () => {
test('entity timeline coverage = 1/2 = 50% (2 eligible entities, 1 with timeline)', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(health.timeline_coverage).toBeDefined();
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
});
test('whole-brain timeline density = 1/4 -> score 4/15 (4 total pages, 1 with timeline)', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(health.timeline_coverage_score).toBeDefined();
expect(health.timeline_coverage_score).toBe(4);
});
test('the two metrics use independent denominators', async () => {
await seedFourPages(engine);
const health = await engine.getHealth();
expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);
expect(health.timeline_coverage_score ?? 0).toBe(4);
// 50% (entity, /2) != 26.7% (whole-brain, /4). Provably distinct.
expect(Math.round(((health.timeline_coverage_score ?? 0) / 15) * 100)).not.toBe(50);
});
});
describe('issue #2298 — doctor rendered-message contract', () => {
test('graph_coverage renders entity-scoped label with 50%', async () => {
await seedFourPages(engine);
const checks = await buildChecks(engine, [], null);
const graph = checks.find((c) => c.name === 'graph_coverage');
expect(graph, 'graph_coverage check must be present').toBeDefined();
expect(graph!.message).toContain('entity timeline coverage 50%');
// ambiguous old label must NOT be present
expect(graph!.message).not.toMatch(/timeline 50%/);
expect(graph!.message).not.toMatch(/timeline \(entity, brain score\)/);
});
test('brain_score renders whole-brain density label 4/15', async () => {
await seedFourPages(engine);
const checks = await buildChecks(engine, [], null);
const brain = checks.find((c) => c.name === 'brain_score');
expect(brain, 'brain_score check must be present').toBeDefined();
expect(brain!.message).toContain('timeline density (all pages) 4/15');
// wrong labels must NOT be present
expect(brain!.message).not.toMatch(/timeline 4\/15/);
expect(brain!.message).not.toMatch(/timeline \(entity, brain score\)/);
// brain-score component must NOT carry the word "entity" (it is whole-brain)
const timelinePart = brain!.message.split('timeline density (all pages) 4/15')[0] + 'timeline density (all pages) 4/15';
expect(timelinePart).not.toMatch(/entity/);
});
});
describe('issue #2298 — CLI get_health rendered-output contract', () => {
function fakeHealth(overrides: Record<string, unknown>): any {
return {
embed_coverage: 1, missing_embeddings: 0, stale_pages: 0, orphan_pages: 0,
link_coverage: 1, timeline_coverage: 0.5, timeline_coverage_score: 4,
most_connected: [], ...overrides,
};
}
test('both entity and whole-brain lines render, no undefined/15', () => {
const out = formatResult('get_health', fakeHealth({}));
expect(out).toContain('Timeline coverage (entity pages): 50.0%');
expect(out).toContain('Timeline density (all pages): 4/15');
expect(out).not.toContain('undefined/15');
expect(out).not.toContain('Timeline coverage (entities)');
expect(out).not.toMatch(/timeline \(entity, brain score\)/);
expect(out).not.toMatch(/bare "timeline 4\/15"/);
});
test('guard matrix: entity present, whole-brain absent -> only entity line', () => {
const out = formatResult('get_health', fakeHealth({ timeline_coverage_score: undefined }));
expect(out).toContain('Timeline coverage (entity pages): 50.0%');
expect(out).not.toContain('Timeline density (all pages)');
expect(out).not.toContain('undefined/15');
});
test('guard matrix: whole-brain present, entity absent -> only whole-brain line', () => {
const out = formatResult('get_health', fakeHealth({ timeline_coverage: undefined }));
expect(out).toContain('Timeline density (all pages): 4/15');
expect(out).not.toContain('Timeline coverage (entity pages)');
expect(out).not.toContain('undefined/15');
});
test('guard matrix: both absent -> neither timeline line, never undefined/15', () => {
const out = formatResult('get_health', fakeHealth({ timeline_coverage: undefined, timeline_coverage_score: undefined }));
expect(out).not.toContain('Timeline coverage (entity pages)');
expect(out).not.toContain('Timeline density (all pages)');
expect(out).not.toContain('undefined/15');
});
});
-83
View File
@@ -222,89 +222,6 @@ describe('runStatsCore — JSON envelope shape', () => {
});
});
describe('runStatsCore — #2466 catch-narrowing (real count + error surfacing)', () => {
// #2466: `gbrain schema stats` reported "Total pages: 0" on a populated
// PGLite brain. The bug was a bare `catch {}` in fetchCountRows (and a
// sibling in detectDeadPrefixes) that converted ANY engine error into 0
// rows. The COUNT query itself is valid on PGLite (proven below), so the
// regression pins two things: (a) a populated brain reports the real,
// non-zero count through the full runStatsCore path; (b) a non-missing-
// table engine error is rethrown, not masked into a fake zero.
it('reports the real non-zero count on a populated PGLite brain (no false 0)', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// Seed a realistic mix: typed, untyped, multiple types — like the
// 169-page brain in the bug report (scaled down).
for (let i = 0; i < 12; i++) {
const type = i % 3 === 0 ? '' : (i % 3 === 1 ? 'person' : 'company');
await seedPage(`notes/p${i}`, { type, sourcePath: `notes/p${i}.md` });
}
const result = await runStatsCore(ctxOf());
// The core regression: NOT zero.
expect(result.aggregate.total_pages).toBe(12);
expect(result.aggregate.typed_pages).toBe(8);
expect(result.aggregate.untyped_pages).toBe(4);
// And coverage is the honest ratio, not the vacuous 1.0 a 0/0 prints.
expect(result.aggregate.coverage).not.toBe(1.0);
});
});
it('fetchCountRows rethrows a non-missing-table engine error instead of masking it as 0 pages', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// No pack → detectDeadPrefixes is skipped, isolating the throw to the
// fetchCountRows catch we narrowed. The count query (the GROUP BY one)
// throws a column-level error (SQLSTATE 42703) — the exact class the
// old bare `catch {}` swallowed into 0 rows; everything else succeeds.
__setPackLocatorForTests(() => null);
const boom = Object.assign(new Error('column "type" does not exist'), { code: '42703' });
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) throw boom; // the fetchCountRows query
return [];
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
await expect(runStatsCore(ctx)).rejects.toThrow('column "type" does not exist');
});
});
it('fetchCountRows still degrades to empty (no throw) on a genuine missing pages table', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {
// Pre-init brain shape: the count query hits a missing pages table
// (SQLSTATE 42P01). This is the ONLY case the narrowed catch swallows.
__setPackLocatorForTests(() => null);
const missing = Object.assign(new Error('relation "pages" does not exist'), { code: '42P01' });
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) throw missing;
return [];
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
const result = await runStatsCore(ctx);
expect(result.aggregate.total_pages).toBe(0);
expect(result.per_source).toEqual([]);
});
});
it('detectDeadPrefixes rethrows a non-missing-table error (sibling catch)', async () => {
await withEnv({ GBRAIN_HOME: tmpDir, GBRAIN_SCHEMA_PACK: 'tiny' }, async () => {
seedTinyPack('tiny', [{ name: 'person', prefix: 'people/' }]);
// fetchCountRows (the GROUP BY query) succeeds → []; the per-prefix
// dead-prefix LIKE query then throws a non-missing-table error, which
// must surface through the narrowed sibling catch.
const stubEngine = {
executeRaw: async (sql: string) => {
if (/GROUP BY source_id/.test(sql)) return []; // count query: empty brain, fine
throw Object.assign(new Error('division by zero'), { code: '22012' }); // the LIKE query
},
} as unknown as PGLiteEngine;
const ctx = { ...ctxOf(), engine: stubEngine } as unknown as OperationContext;
await expect(runStatsCore(ctx)).rejects.toThrow('division by zero');
});
});
});
describe('runStatsCore — type/untyped split', () => {
it('treats empty-string type as untyped (not its own bucket)', async () => {
await withEnv({ GBRAIN_SCHEMA_PACK: undefined }, async () => {