Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(health): brain_score timeline component grades only entity/temporal pack types (#5828)
garrytand35a2169a281
diff --git a/src/cli.ts b/src/cli.tsindex 034e9d26e6..71b7f271c4 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -1739,7 +1739,7 @@ export function formatResult(lines.push(`Timeline coverage (entity pages): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);}if (h.timeline_coverage_score !== undefined) {- lines.push(`Timeline density (all pages): ${h.timeline_coverage_score}/15 (whole-brain brain-score component)`);+ lines.push(`Timeline density (entity and event pages): ${h.timeline_coverage_score}/15 (brain-score component)`);}if (Array.isArray(h.most_connected) && h.most_connected.length > 0) {lines.push('Most connected entities:');diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 84ca85f94f..d6b7a544e4 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -102,7 +102,7 @@ async function runGraphCoverage(ctx: DoctorContext): Promise<Check[]> {const parts = [`embed ${health.embed_coverage_score}/35`,`links ${health.link_density_score}/25`,- `timeline density (all pages) ${health.timeline_coverage_score}/15`,+ `timeline density (entity and event pages) ${health.timeline_coverage_score}/15`,`orphans ${health.no_orphans_score}/15`,`dead-links ${health.no_dead_links_score}/10`,];diff --git a/src/core/orphan-policy.ts b/src/core/orphan-policy.tsindex b266c4053b..48197e0e74 100644--- a/src/core/orphan-policy.ts+++ b/src/core/orphan-policy.ts@@ -144,3 +144,6 @@ export function shouldExcludeFromOrphanReporting(return false;}++/** #5828: the brain_score timeline component's graded subset of the linkable scope. */+export { gradeTimelinePages } from './timeline-grading.ts';diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex da51ea5fcc..9b5d92d21b 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -116,7 +116,7 @@ import { finalizeLastSeen } from './chronicle/last-seen.ts';import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery } from './search/sql-ranking.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';-import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';+import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides, gradeTimelinePages } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from './quarantine.ts';@@ -2861,7 +2861,7 @@ export class PGLiteEngine implements BrainEngine {.filter(row => !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides, { type: row.type }));const linkablePageCount = linkablePages.length;const orphanPages = linkablePages.filter(row => row.islanded).length;- const linkableTimelinePages = linkablePages.filter(row => row.has_timeline).length;+ const { graded: timelineGradedCount, withTimeline: linkableTimelinePages } = await gradeTimelinePages(this, linkablePages); // #5828const deadLinks = Number(r.dead_links);const linkCount = Number(r.link_count);@@ -2870,7 +2870,7 @@ export class PGLiteEngine implements BrainEngine {// components (same vacuous-truth rule as the empty-brain fix below):// an all-archive brain has no curated graph to penalize.const timelineCoverageDensity =- linkablePageCount > 0 ? Math.min(linkableTimelinePages / linkablePageCount, 1) : 1;+ timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;// Bug 11 — per-component points. Sum equals brainScore by constructiondiff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 8abd7b1091..03e58de848 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -108,7 +108,7 @@ import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaimport { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';import { PageMissingError } from './engine-errors.ts';-import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';+import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides, gradeTimelinePages } from './orphan-policy.ts';import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT, quarantineFilterFragment } from './quarantine.ts';@@ -2680,7 +2680,7 @@ export class PostgresEngine implements BrainEngine {!shouldExcludeFromOrphanReporting(row.slug, orphanOverrides, { type: row.type }));const linkablePageCount = linkablePages.length;const orphanPages = linkablePages.filter(row => row.islanded).length;- const linkableTimelinePages = linkablePages.filter(row => row.has_timeline).length;+ const { graded: timelineGradedCount, withTimeline: linkableTimelinePages } = await gradeTimelinePages(this, linkablePages); // #5828const deadLinks = Number(h.dead_links);const linkCount = Number(h.link_count);@@ -2690,7 +2690,7 @@ export class PostgresEngine implements BrainEngine {// components (same vacuous-truth rule as the empty-brain fix below):// an all-archive brain has no curated graph to penalize.const timelineCoverageWhole =- linkablePageCount > 0 ? Math.min(linkableTimelinePages / linkablePageCount, 1) : 1;+ timelineGradedCount > 0 ? Math.min(linkableTimelinePages / timelineGradedCount, 1) : 1;const noOrphans = linkablePageCount > 0 ? 1 - (orphanPages / linkablePageCount) : 1;const noDeadLinks = pageCount > 0 ? 1 - Math.min(deadLinks / pageCount, 1) : 1;// Per-component points. Sum equals brainScore by construction.diff --git a/src/core/timeline-grading.ts b/src/core/timeline-grading.tsnew file mode 100644index 0000000000..0c171d7c39--- /dev/null+++ b/src/core/timeline-grading.ts@@ -0,0 +1,40 @@+/**+ * #5828: which pages the brain_score timeline component grades.+ *+ * The 15-point timeline component rewards pages that have a history or are+ * events, so it grades only linkable pages whose type's active-pack+ * primitive is `entity` or `temporal` (aliases resolve to their canonical+ * type). Reference documents (`media`, `concept`, `annotation`) have no+ * events to record and are not graded. Types the pack does not declare,+ * untyped pages, and every page when no pack resolves stay graded, so a+ * brain only changes when its pack says a type is a document.+ */+import type { BrainEngine } from './engine.ts';+import { loadActivePackForLocalEngine } from './schema-pack/best-effort.ts';+import { classifyStoredType } from './schema-pack/type-usage.ts';++const TIMELINE_PRIMITIVES: ReadonlySet<string> = new Set(['entity', 'temporal']);++export async function loadTimelineGradedPredicate(+ engine: Pick<BrainEngine, 'getConfig'>,+): Promise<(type: string) => boolean> {+ const pack = await loadActivePackForLocalEngine(engine);+ if (!pack) return () => true;+ const primitiveOf = new Map(pack.manifest.page_types.map((t) => [t.name, t.primitive as string]));+ return (type) => {+ if (!type) return true;+ const cls = classifyStoredType(type, pack.manifest);+ if (cls.kind === 'undeclared') return true;+ return TIMELINE_PRIMITIVES.has(primitiveOf.get(cls.kind === 'canonical' ? type : cls.canonical) ?? '');+ };+}++/** Linkable pages the timeline component grades, and how many of them carry a timeline row. */+export async function gradeTimelinePages(+ engine: Pick<BrainEngine, 'getConfig'>,+ linkablePages: ReadonlyArray<{ type: string; has_timeline: boolean }>,+): Promise<{ graded: number; withTimeline: number }> {+ const isGraded = await loadTimelineGradedPredicate(engine);+ const graded = linkablePages.filter((row) => isGraded(row.type));+ return { graded: graded.length, withTimeline: graded.filter((row) => row.has_timeline).length };+}diff --git a/test/brain-score-timeline-grading.test.ts b/test/brain-score-timeline-grading.test.tsnew file mode 100644index 0000000000..035c2ad98e--- /dev/null+++ b/test/brain-score-timeline-grading.test.ts@@ -0,0 +1,98 @@+/**+ * #5828 — the brain_score timeline component grades only pages whose+ * active-pack primitive is `entity` or `temporal`. Pre-fix its denominator+ * was every linkable page, so a brain whose events all had timeline rows+ * still read 2/15 when it also held reference notes, and the only way to+ * 15/15 was stamping non-event rows onto every document.+ *+ * Repro shape from the issue: 10 meetings (temporal, one timeline row each)+ * + 90 undated reference notes (concept), all linked.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';+import { withEnv } from './helpers/with-env.ts';+import { loadTimelineGradedPredicate } from '../src/core/timeline-grading.ts';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-5828-'));+const env = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined }, fn);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ _resetPackCacheForTests();+ await engine.setConfig('schema_pack', 'gbrain-base-v2');+});++async function seed(meetings: number, notes: number, extraType?: string): Promise<void> {+ const slugs: string[] = [];+ for (let i = 0; i < meetings; i++) {+ const slug = `meetings/2026-01-${String(i + 1).padStart(2, '0')}-example-sync`;+ await engine.putPage(slug, { type: 'meeting', title: `Example sync ${i}`, compiled_truth: `Notes from example sync ${i}.`, frontmatter: {} });+ await engine.addTimelineEntry(slug, { date: `2026-01-${String(i + 1).padStart(2, '0')}`, source: 'meeting', summary: 'Sync held' });+ slugs.push(slug);+ }+ for (let i = 0; i < notes; i++) {+ const slug = `notes/reference-${i}`;+ await engine.putPage(slug, { type: extraType ?? 'note', title: `Reference ${i}`, compiled_truth: `Reference text ${i}.`, frontmatter: {} });+ slugs.push(slug);+ }+ for (let i = 1; i < slugs.length; i++) {+ await engine.addLink(slugs[i - 1], slugs[i], '', 'related');+ await engine.addLink(slugs[i], slugs[i - 1], '', 'related');+ }+}++describe('#5828 timeline component grades entity/temporal pages only', () => {+ test('events all on the timeline + undated reference notes -> full timeline points', async () => {+ await seed(10, 90);+ const h = await env(() => engine.getHealth());+ expect(h.linkable_page_count).toBe(100);+ expect(h.timeline_coverage_score).toBe(15);+ });++ test('an event missing its row still costs points', async () => {+ await seed(10, 90);+ await engine.executeRaw(`DELETE FROM timeline_entries WHERE page_id IN (SELECT id FROM pages WHERE slug LIKE 'meetings/2026-01-0%')`);+ const h = await env(() => engine.getHealth());+ // 1 of 10 meetings keeps its row (2026-01-10).+ expect(h.timeline_coverage_score).toBe(Math.round((1 / 10) * 15));+ });++ test('types the pack does not declare stay graded', async () => {+ await seed(10, 10, 'research-memo-example');+ const h = await env(() => engine.getHealth());+ expect(h.timeline_coverage_score).toBe(Math.round((10 / 20) * 15));+ });++ test('predicate: aliases resolve to their canonical primitive; no pack grades everything', async () => {+ const graded = await env(() => loadTimelineGradedPredicate(engine));+ expect(graded('person')).toBe(true);+ expect(graded('meeting')).toBe(true);+ expect(graded('email-thread')).toBe(true); // alias of email (temporal)+ expect(graded('note')).toBe(false);+ expect(graded('memo')).toBe(false); // alias of note (concept)+ expect(graded('writing')).toBe(false);+ expect(graded('undeclared-example')).toBe(true);+ expect(graded('')).toBe(true);+ await engine.setConfig('schema_pack', 'no-such-pack-example');+ _resetPackCacheForTests();+ const fallback = await env(() => loadTimelineGradedPredicate(engine));+ expect(fallback('note')).toBe(true);+ });+});diff --git a/test/doctor-timeline-metric-labels-2298.test.ts b/test/doctor-timeline-metric-labels-2298.test.tsindex d138adf415..e9fb89dda3 100644--- a/test/doctor-timeline-metric-labels-2298.test.ts+++ b/test/doctor-timeline-metric-labels-2298.test.ts@@ -5,8 +5,10 @@* - Metric A `timeline_coverage` (entity-scoped, fraction 0–1):* 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, 0–15 brain-score component):- * all pages WITH a timeline entry / all pages+ * - Metric B `timeline_coverage_score` (0–15 brain-score component):+ * linkable pages whose active-pack primitive is entity/temporal WITH a+ * timeline entry / those pages (#5828: reference documents such as+ * `note` are not graded)* -> surfaced by `brain_score` component breakdown AND (separately) CLI.** The two have DIFFERENT numerators/denominators. This PR labels each@@ -18,7 +20,7 @@* - 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.+ * Canonical PGLite fixture via resetPgliteState.*/import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';@@ -39,8 +41,9 @@ async function seedFourPages(eng: PGLiteEngine): Promise<void> {// it counted, Metric A reads 3/7 and Metric B 3/9, breaking every pinned// number below). THREE served entity pages carry timeline entries:// Metric A (entity-scoped): 3/6 = 50% (same 50% the contract pins)- // Metric B (whole-brain): 3/8 -> round(15 * 0.375) = 6/15- // The two stay provably distinct (50% vs 40%).+ // Metric B (entity/temporal): 3/6 -> round(15 * 0.5) = 8/15 (#5828: the+ // two `note` pages are concept-primitive documents and are not graded)+ // The two stay distinct numbers (50% vs 53%).await sql`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)VALUES@@ -83,19 +86,19 @@ describe('issue #2298 — numeric denominator semantics', () => {expect(Math.round((health.timeline_coverage ?? 0) * 100)).toBe(50);});- test('whole-brain timeline density = 3/8 -> score 6/15 (8 total pages, 3 with timeline)', async () => {+ test('timeline density = 3/6 entity/temporal pages -> score 8/15 (notes not graded, #5828)', async () => {await seedFourPages(engine);const health = await engine.getHealth();expect(health.timeline_coverage_score).toBeDefined();- expect(health.timeline_coverage_score).toBe(6);+ expect(health.timeline_coverage_score).toBe(8);});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(6);- // 50% (entity, /6) != 40% (whole-brain, 6/15). Provably distinct.+ expect(health.timeline_coverage_score ?? 0).toBe(8);+ // 50% (entity, /6) != 53% (rounded brain-score points, 8/15).expect(Math.round(((health.timeline_coverage_score ?? 0) / 15) * 100)).not.toBe(50);});});@@ -112,18 +115,16 @@ describe('issue #2298 — doctor rendered-message contract', () => {expect(graph!.message).not.toMatch(/timeline \(entity, brain score\)/);});- test('brain_score renders whole-brain density label 6/15', async () => {+ test('brain_score renders the entity-and-event density label 8/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) 6/15');+ expect(brain!.message).toContain('timeline density (entity and event pages) 8/15');// wrong labels must NOT be present- expect(brain!.message).not.toMatch(/timeline 6\/15/);+ expect(brain!.message).not.toMatch(/timeline 8\/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) 6/15')[0] + 'timeline density (all pages) 6/15';- expect(timelinePart).not.toMatch(/entity/);+ expect(brain!.message).not.toContain('timeline density (all pages)');});});@@ -139,7 +140,7 @@ describe('issue #2298 — CLI get_health rendered-output contract', () => {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).toContain('Timeline density (entity and event pages): 4/15');expect(out).not.toContain('undefined/15');expect(out).not.toContain('Timeline coverage (entities)');expect(out).not.toMatch(/timeline \(entity, brain score\)/);@@ -149,13 +150,13 @@ describe('issue #2298 — CLI get_health rendered-output contract', () => {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('Timeline density (entity and event 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).toContain('Timeline density (entity and event pages): 4/15');expect(out).not.toContain('Timeline coverage (entity pages)');expect(out).not.toContain('undefined/15');});@@ -163,7 +164,7 @@ describe('issue #2298 — CLI get_health rendered-output contract', () => {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('Timeline density (entity and event pages)');expect(out).not.toContain('undefined/15');});});