Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): unlinked_facts check (#5836)

garrytan4cec50613594
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 6046fc9bea..6db7bcf08b 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -9,6 +9,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
+- `src/commands/doctor/checks/unlinked-facts.ts` — `unlinked_facts` (#5836), registered before `search_mode` and mirrored in `doctorReportRemote`: per the doctor's source scope (`--source`, else every source; the caller's grant remotely), the unlinked share of the newest 100,000 active facts per source (`idx_facts_since` LATERAL walk), the 7-day unlinked share of new facts, `no_subject` judgments and the 7-day `linked` tiers from `fact_relink_attempts`, fence-owned unlinked rows (row_num or source_markdown_slug set), origins (`mcp:put_page`, extraction, remember) and 7-day write-time inferred links by tier (`entity inferred from <tier>` context, bare or after ` — `). Warns when over 25% of at least 20 new facts are unlinked, facts judged `no_subject` excluded; the fix is `gbrain facts relink --dry-run`, and the remote report asks the brain host operator to run it. Without `fact_relink_attempts` the relink figures are null and nothing is excluded. Tests: `test/doctor-unlinked-facts.test.ts`.
- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.
diff --git a/src/commands/doctor/checks/unlinked-facts.ts b/src/commands/doctor/checks/unlinked-facts.ts
new file mode 100644
index 0000000000..c725614dd9
--- /dev/null
+++ b/src/commands/doctor/checks/unlinked-facts.ts
@@ -0,0 +1,171 @@
+/**
+ * unlinked_facts (#5836): how many active facts carry no entity, so recall by
+ * entity and the conflict sweep never see them, and whether new writes keep
+ * adding to the pile.
+ *
+ * Reports, per the doctor's source scope (`--source`, else every source; the
+ * caller's grant on the remote path): the unlinked share of the newest
+ * active facts per source (capped so a 1M-fact brain stays fast), the
+ * unlinked share of facts created in the last 7 days, how many facts
+ * `gbrain facts relink` already judged to have no subject (`no_subject`),
+ * the fence-owned unlinked rows (row_num or source_markdown_slug set: relink
+ * rewrites their fence row), the top origins of unlinked facts, and the
+ * 7-day links by tier from write-time inference and from relink.
+ *
+ * Warns when more than 25% of at least 20 new facts (facts judged
+ * no_subject excluded) are unlinked. Every query is bounded by created_at
+ * through idx_facts_since (source_id, created_at DESC WHERE expired_at IS
+ * NULL) or by primary key; without fact_relink_attempts (a brain before
+ * v187) the relink figures are omitted and nothing is excluded.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import { AUDIT_ROW_SOURCES } from '../../../core/facts/audit-sources.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+export const UNLINKED_NEW_SHARE_WARN = 0.25;
+export const UNLINKED_NEW_MIN_FACTS = 20;
+/** Newest active facts per source the overall share is computed over. */
+export const UNLINKED_WINDOW_PER_SOURCE = 100_000;
+
+export interface UnlinkedFactsStats {
+ sources: number;
+ window: { active: number; unlinked: number; fence_owned: number; capped: boolean };
+ new_7d: { facts: number; unlinked: number; no_subject: number };
+ no_subject: number | null;
+ origins: Array<{ origin: string; unlinked: number }>;
+ inferred_7d: { page: number; mention: number };
+ relinked_7d: Record<string, number> | null;
+}
+
+const ACTIVE = `f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now()) AND f.source <> ALL($2::text[])`;
+const ORIGIN = `CASE WHEN f.source = 'mcp:put_page' THEN 'mcp:put_page'
+ WHEN f.source LIKE 'mcp:%' OR f.source LIKE 'sync:%' OR f.source LIKE 'hook:%' OR f.source IN ('file_upload', 'code_import') THEN 'extraction'
+ ELSE 'remember' END`;
+const INFERRED = `(f.context LIKE 'entity inferred from %' OR f.context LIKE '% — entity inferred from %')`;
+const INFERRED_TIER = `substring(f.context from 'entity inferred from ([a-z]+)')`;
+
+const n = (v: unknown) => Number(v ?? 0);
+
+/** Null when the brain has no facts table (nothing to report). */
+export async function unlinkedFactsStats(engine: BrainEngine, sourceIds?: readonly string[]): Promise<UnlinkedFactsStats | null> {
+ const [tables] = await engine.executeRaw<{ facts: string | null; attempts: string | null }>(
+ `SELECT to_regclass('facts')::text AS facts, to_regclass('fact_relink_attempts')::text AS attempts`);
+ if (!tables?.facts) return null;
+ const hasAttempts = !!tables.attempts;
+ const ids = sourceIds?.length ? [...sourceIds] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map((r) => r.id);
+ const audit = [...AUDIT_ROW_SOURCES];
+ const windowRows = await engine.executeRaw<{ source_id: string; origin: string; active: number; unlinked: number; fence_owned: number }>(
+ `SELECT s.id AS source_id, w.origin, COUNT(*)::int AS active, COUNT(*) FILTER (WHERE w.unlinked)::int AS unlinked,
+ COUNT(*) FILTER (WHERE w.unlinked AND w.fence_owned)::int AS fence_owned
+ FROM unnest($1::text[]) AS s(id) CROSS JOIN LATERAL (
+ SELECT ${ORIGIN} AS origin, f.entity_slug IS NULL AS unlinked,
+ (f.row_num IS NOT NULL OR f.source_markdown_slug IS NOT NULL) AS fence_owned
+ FROM facts f WHERE f.source_id = s.id AND ${ACTIVE}
+ ORDER BY f.created_at DESC LIMIT $3) w
+ GROUP BY s.id, w.origin`,
+ [ids, audit, UNLINKED_WINDOW_PER_SOURCE],
+ );
+ const perSource = new Map<string, number>();
+ const byOrigin = new Map<string, number>();
+ for (const r of windowRows) {
+ perSource.set(r.source_id, (perSource.get(r.source_id) ?? 0) + n(r.active));
+ if (n(r.unlinked) > 0) byOrigin.set(r.origin, (byOrigin.get(r.origin) ?? 0) + n(r.unlinked));
+ }
+ const judged = hasAttempts
+ ? `EXISTS (SELECT 1 FROM fact_relink_attempts a WHERE a.source_id = f.source_id AND a.fact_id = f.id AND a.outcome = 'no_subject')`
+ : 'false';
+ const [recent] = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT COUNT(*)::int AS facts, COUNT(*) FILTER (WHERE f.entity_slug IS NULL)::int AS unlinked,
+ COUNT(*) FILTER (WHERE f.entity_slug IS NULL AND ${judged})::int AS no_subject,
+ COUNT(*) FILTER (WHERE ${INFERRED} AND ${INFERRED_TIER} = 'page')::int AS inferred_page,
+ COUNT(*) FILTER (WHERE ${INFERRED} AND ${INFERRED_TIER} = 'mention')::int AS inferred_mention
+ FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.created_at >= now() - interval '7 days' AND ${ACTIVE}`,
+ [ids, audit],
+ );
+ let noSubject: number | null = null;
+ let relinked: Record<string, number> | null = null;
+ if (hasAttempts) {
+ const rows = await engine.executeRaw<{ outcome: string; tier: string | null; n: number }>(
+ `SELECT outcome, tier, COUNT(*)::int AS n FROM fact_relink_attempts
+ WHERE source_id = ANY($1::text[])
+ AND (outcome = 'no_subject' OR (outcome = 'linked' AND attempted_at >= now() - interval '7 days'))
+ GROUP BY outcome, tier`,
+ [ids],
+ );
+ noSubject = rows.filter((r) => r.outcome === 'no_subject').reduce((sum, r) => sum + n(r.n), 0);
+ relinked = {};
+ for (const r of rows.filter((x) => x.outcome === 'linked')) relinked[r.tier ?? 'unknown'] = (relinked[r.tier ?? 'unknown'] ?? 0) + n(r.n);
+ }
+ return {
+ sources: ids.length,
+ window: {
+ active: windowRows.reduce((sum, r) => sum + n(r.active), 0),
+ unlinked: windowRows.reduce((sum, r) => sum + n(r.unlinked), 0),
+ fence_owned: windowRows.reduce((sum, r) => sum + n(r.fence_owned), 0),
+ capped: [...perSource.values()].some((c) => c >= UNLINKED_WINDOW_PER_SOURCE),
+ },
+ new_7d: { facts: n(recent?.facts), unlinked: n(recent?.unlinked), no_subject: n(recent?.no_subject) },
+ no_subject: noSubject,
+ origins: [...byOrigin].map(([origin, unlinked]) => ({ origin, unlinked })).sort((a, b) => b.unlinked - a.unlinked || a.origin.localeCompare(b.origin)),
+ inferred_7d: { page: n(recent?.inferred_page), mention: n(recent?.inferred_mention) },
+ relinked_7d: relinked,
+ };
+}
+
+const pct = (part: number, whole: number) => whole > 0 ? `${(100 * part / whole).toFixed(1)}%` : '0%';
+
+/**
+ * The check body (status, message, details) for the stats. `thinClient`: the caller cannot run relink itself (the
+ * remote doctor path), so the hint asks the brain host operator to.
+ */
+export function unlinkedFactsVerdict(stats: UnlinkedFactsStats | null, opts: { thinClient?: boolean } = {}): Omit<Check, 'name'> {
+ if (!stats) return { status: 'ok', message: 'No facts table yet; nothing to link.' };
+ const { window: w, new_7d: recent } = stats;
+ const eligible = recent.facts - recent.no_subject;
+ const unlinkedNew = recent.unlinked - recent.no_subject;
+ const warn = eligible >= UNLINKED_NEW_MIN_FACTS && unlinkedNew / eligible > UNLINKED_NEW_SHARE_WARN;
+ const hint = opts.thinClient
+ ? 'ask the brain host operator to run: gbrain facts relink --dry-run'
+ : 'preview links: gbrain facts relink --dry-run';
+ if (w.active === 0 && recent.facts === 0) return { status: 'ok', message: 'No active facts yet; nothing to link.', details: { ...stats, fix: hint } };
+ const parts = [
+ `${pct(w.unlinked, w.active)} of ${w.active} active facts have no entity (${w.unlinked}${w.capped ? `; newest ${UNLINKED_WINDOW_PER_SOURCE} per source` : ''}; ${w.fence_owned} fence-owned)`,
+ `last 7 days: ${pct(unlinkedNew, eligible)} of ${eligible} new facts unlinked`,
+ stats.no_subject === null ? 'relink history unavailable (fact_relink_attempts missing)' : `${stats.no_subject} judged no_subject`,
+ `7-day links: inferred page ${stats.inferred_7d.page}, mention ${stats.inferred_7d.mention}${stats.relinked_7d ? `; relink ${Object.entries(stats.relinked_7d).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([t, c]) => `${t} ${c}`).join(', ') || 'none'}` : ''}`,
+ ];
+ if (stats.origins.length > 0) parts.push(`top origins: ${stats.origins.slice(0, 3).map((o) => `${o.origin} ${o.unlinked}`).join(', ')}`);
+ return {
+ status: warn ? 'warn' : 'ok',
+ message: `${parts.join('; ')}${warn || w.unlinked > 0 ? `. ${warn ? `Over ${UNLINKED_NEW_SHARE_WARN * 100}% of new facts are unlinked; ` : ''}${hint}` : ''}`,
+ details: { ...stats, new_7d: { ...recent, eligible, unlinked_eligible: unlinkedNew }, fix: hint },
+ };
+}
+
+/**
+ * The `doctorReportRemote` copy: indexed counts inside the caller's source grant. A remote caller (anything not
+ * strictly `remote: false`) cannot run relink, so its hint names the brain host operator.
+ */
+export async function remoteUnlinkedFactsCheck(engine: BrainEngine, opts: { sourceIds?: string[]; remote?: boolean }): Promise<Check> {
+ try {
+ return { name: 'unlinked_facts', ...unlinkedFactsVerdict(await unlinkedFactsStats(engine, opts.sourceIds), { thinClient: opts.remote !== false }) };
+ } catch (err) {
+ return { name: 'unlinked_facts', status: 'warn', message: `Unlinked facts could not be counted: ${err instanceof Error ? err.message : String(err)}. Health is unknown.` };
+ }
+}
+
+async function runUnlinkedFacts(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ ctx.progress.heartbeat('unlinked_facts');
+ try {
+ const stats = await unlinkedFactsStats(engine, ctx.orphanRatioSourceId ? [ctx.orphanRatioSourceId] : undefined);
+ checks.push({ name: 'unlinked_facts', ...unlinkedFactsVerdict(stats) });
+ } catch (err) {
+ checks.push({ name: 'unlinked_facts', status: 'warn', message: `Unlinked facts could not be counted: ${err instanceof Error ? err.message : String(err)}. Health is unknown.` });
+ }
+ return checks;
+}
+
+export const unlinkedFactsEntry: DoctorEntry = { name: 'unlinked_facts', emits: ['unlinked_facts'], run: runUnlinkedFacts };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 69f53a3da9..ee99f4414a 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -81,6 +81,7 @@ import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/qu
import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { decideHealthEntry } from './checks/decide.ts';
+import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
@@ -137,6 +138,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
imageAssetsEntry,
syncFreshnessEntry,
decideHealthEntry,
+ unlinkedFactsEntry,
searchModeEntry,
];
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index d682e2240e..c439b72a2c 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -17,6 +17,7 @@ import { compareVersions } from '../migrations/index.ts';
import { resolveHoursEnv } from '../../core/env-number.ts';
import { schemaVersionHealth } from '../../core/schema-version-health.ts';
import { checkProjectionReadiness } from './checks/projection-readiness.ts';
+import { remoteUnlinkedFactsCheck } from './checks/unlinked-facts.ts';
import { resolveExcludePrivatePages } from '../../core/search/private-visibility.ts';
import {
type Check,
@@ -471,8 +472,8 @@ export async function doctorReportRemote(
checks.push(await checkFederationHealth(engine));
// 13. v0.42 self_upgrade_health: mode, whether behind, recent failures.
- // File-plane only (no engine) — works on thin clients too.
- checks.push(checkSelfUpgradeHealth());
+ // File-plane only (no engine) — works on thin clients too. Then #5836 unlinked_facts inside the caller's grant.
+ checks.push(checkSelfUpgradeHealth(), await remoteUnlinkedFactsCheck(engine, opts));
// 14. Wave checks as sanitized host-action lines (doctor/wave-checks.ts):
// stable check id, a count-free impact summary and the on-host preview
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ad12770464..890a4f0bc0 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -138,6 +138,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'sync_freshness',
'takes_count',
'takes_weight_grid',
+ // #5836: active facts with no entity (invisible to entity recall and the conflict sweep).
+ 'unlinked_facts',
'text_projection_readiness',
'timeline_coverage',
'timeline_orphans',
diff --git a/test/doctor-unlinked-facts.test.ts b/test/doctor-unlinked-facts.test.ts
new file mode 100644
index 0000000000..ba664ee00d
--- /dev/null
+++ b/test/doctor-unlinked-facts.test.ts
@@ -0,0 +1,180 @@
+/**
+ * unlinked_facts doctor check (#5836): the unlinked share of active facts and
+ * of the last 7 days' new facts, no_subject exclusion, fence-owned rows,
+ * origins, 7-day inferred links (both context shapes) and relink links by
+ * tier, the thin-client hint, and the degrade path for a brain without
+ * fact_relink_attempts.
+ *
+ * PGLite in-memory ($0).
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { remoteUnlinkedFactsCheck, unlinkedFactsEntry, unlinkedFactsStats, unlinkedFactsVerdict } from '../src/commands/doctor/checks/unlinked-facts.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+interface Seed { entity?: string | null; source?: string; context?: string | null; daysOld?: number; rowNum?: number | null; mdSlug?: string | null; sourceId?: string; expired?: boolean }
+
+/** Insert `count` facts; returns their ids. */
+async function seed(count: number, s: Seed = {}): Promise<number[]> {
+ const rows = await engine.executeRaw<{ id: string }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, source, context, row_num, source_markdown_slug, created_at, valid_from, expired_at)
+ SELECT $1, $2, 'fact ' || g, $3, $4, CASE WHEN $5::int IS NULL THEN NULL ELSE $5::int * 1000 + g END, $6, now() - ($7::int * interval '1 day'), now() - ($7::int * interval '1 day'),
+ CASE WHEN $8::boolean THEN now() END
+ FROM generate_series(1, $9::int) AS g RETURNING id`,
+ [s.sourceId ?? 'default', s.entity === undefined ? 'people/alice-example' : s.entity, s.source ?? 'cli:remember', s.context ?? null,
+ s.rowNum ?? null, s.mdSlug ?? null, s.daysOld ?? 0, s.expired === true, count]);
+ return rows.map((r) => Number(r.id));
+}
+
+async function attempt(ids: number[], outcome: string, tier: string | null = null, daysAgo = 0) {
+ for (const id of ids) {
+ await engine.executeRaw(
+ `INSERT INTO fact_relink_attempts (source_id, fact_id, outcome, tier, attempted_at) VALUES ('default', $1, $2, $3, now() - ($4::int * interval '1 day'))`,
+ [id, outcome, tier, daysAgo]);
+ }
+}
+
+async function check(sourceIds?: string[]) {
+ return unlinkedFactsVerdict(await unlinkedFactsStats(engine, sourceIds));
+}
+
+describe('unlinked_facts doctor check', () => {
+ test('is a brain check and ok on an empty brain', async () => {
+ expect(categorizeCheck('unlinked_facts')).toBe('brain');
+ const ctx = { engine, orphanRatioSourceId: undefined, progress: { heartbeat() {} } } as unknown as DoctorContext;
+ const [c] = await unlinkedFactsEntry.run(ctx) as Array<{ name: string; status: string }>;
+ expect(c).toMatchObject({ name: 'unlinked_facts', status: 'ok' });
+ });
+
+ test('warns when over 25% of at least 20 new facts are unlinked, with the relink hint', async () => {
+ await seed(14);
+ await seed(6, { entity: null });
+ const c = await check();
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('30.0% of 20 new facts unlinked');
+ expect(c.message).toContain('gbrain facts relink --dry-run');
+ expect((c.details as any).window).toMatchObject({ active: 20, unlinked: 6, capped: false });
+ });
+
+ test('ok at exactly 25%, below 20 new facts, and when only old facts are unlinked', async () => {
+ await seed(15);
+ await seed(5, { entity: null });
+ expect((await check()).status).toBe('ok');
+ await resetPgliteState(engine);
+ await seed(5);
+ await seed(10, { entity: null });
+ expect((await check()).status).toBe('ok');
+ await resetPgliteState(engine);
+ await seed(20);
+ await seed(30, { entity: null, daysOld: 30 });
+ const c = await check();
+ expect(c.status).toBe('ok');
+ expect((c.details as any).window).toMatchObject({ active: 50, unlinked: 30 });
+ expect(c.message).toContain('60.0% of 50 active facts have no entity');
+ });
+
+ test('facts judged no_subject are excluded from the 7-day share and counted', async () => {
+ await seed(15);
+ const unlinked = await seed(10, { entity: null });
+ expect((await check()).status).toBe('warn');
+ await attempt(unlinked.slice(0, 6), 'no_subject');
+ const c = await check();
+ expect(c.status).toBe('ok');
+ expect((c.details as any).new_7d).toMatchObject({ facts: 25, unlinked: 10, no_subject: 6, eligible: 19, unlinked_eligible: 4 });
+ expect((c.details as any).no_subject).toBe(6);
+ expect(c.message).toContain('6 judged no_subject');
+ });
+
+ test('expired, superseded-by-time and audit rows do not count', async () => {
+ await seed(20);
+ await seed(10, { entity: null, expired: true });
+ await engine.executeRaw(`UPDATE facts SET valid_until = now() - interval '1 hour' WHERE id IN (SELECT id FROM facts WHERE entity_slug IS NOT NULL LIMIT 2)`);
+ await seed(10, { entity: null, source: 'cli:extract-conversation-facts:terminal:v2' });
+ const s = await unlinkedFactsStats(engine);
+ expect(s!.window).toMatchObject({ active: 18, unlinked: 0 });
+ });
+
+ test('fence_owned counts unlinked rows with row_num or source_markdown_slug; origins bucket the source', async () => {
+ await seed(3, { entity: null, source: 'mcp:put_page', rowNum: 1, mdSlug: 'notes/acme-example' });
+ await seed(2, { entity: null, source: 'sync:import', mdSlug: 'notes/acme-example' });
+ await seed(1, { entity: null, source: 'hook:writeback' });
+ await seed(1, { entity: null, source: 'file_upload' });
+ await seed(4, { entity: null, source: 'cli:remember' });
+ await seed(5, { source: 'mcp:put_page', rowNum: 2, mdSlug: 'notes/acme-example' });
+ const s = await unlinkedFactsStats(engine);
+ expect(s!.window).toMatchObject({ active: 16, unlinked: 11, fence_owned: 5 });
+ expect(s!.origins).toEqual([{ origin: 'extraction', unlinked: 4 }, { origin: 'remember', unlinked: 4 }, { origin: 'mcp:put_page', unlinked: 3 }]);
+ });
+
+ test('7-day inferred links by tier for both context shapes, and relink links by tier', async () => {
+ await seed(2, { context: 'entity inferred from page' });
+ await seed(3, { context: 'notes/acme-example — entity inferred from mention' });
+ await seed(1, { context: 'notes/acme-example — entity inferred from page' });
+ await seed(4, { context: 'entity inferred from mention', daysOld: 10 });
+ await seed(1, { context: 'notes/acme-example' });
+ const linked = await seed(3);
+ await attempt(linked.slice(0, 2), 'linked', 'page');
+ await attempt(linked.slice(2), 'linked', 'model');
+ const old = await seed(1);
+ await attempt(old, 'linked', 'page', 9);
+ const s = await unlinkedFactsStats(engine);
+ expect(s!.inferred_7d).toEqual({ page: 3, mention: 3 });
+ expect(s!.relinked_7d).toEqual({ page: 2, model: 1 });
+ const c = unlinkedFactsVerdict(s);
+ expect(c.message).toContain('7-day links: inferred page 3, mention 3; relink page 2, model 1');
+ });
+
+ test('scopes to the requested sources', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`);
+ await seed(20, { entity: null, sourceId: 'other' });
+ await seed(20);
+ expect((await check(['default'])).status).toBe('ok');
+ expect((await check(['other'])).status).toBe('warn');
+ expect((await unlinkedFactsStats(engine))!.window.unlinked).toBe(20);
+ });
+
+ test('thin client: the hint asks the brain host operator to run relink', async () => {
+ await seed(10);
+ await seed(10, { entity: null });
+ const c = unlinkedFactsVerdict(await unlinkedFactsStats(engine), { thinClient: true });
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('ask the brain host operator to run: gbrain facts relink --dry-run');
+ const remote = await remoteUnlinkedFactsCheck(engine, { sourceIds: ['default'], remote: true });
+ expect(remote).toMatchObject({ name: 'unlinked_facts', status: 'warn' });
+ expect(remote.message).toContain('ask the brain host operator');
+ expect((await remoteUnlinkedFactsCheck(engine, {})).message).toContain('ask the brain host operator');
+ expect((await remoteUnlinkedFactsCheck(engine, { remote: false })).message).toContain('preview links: gbrain facts relink --dry-run');
+ });
+
+ test('degrades without fact_relink_attempts: relink figures omitted, nothing excluded', async () => {
+ await seed(10);
+ await seed(10, { entity: null });
+ await engine.executeRaw('ALTER TABLE fact_relink_attempts RENAME TO fact_relink_attempts_hidden');
+ let s: Awaited<ReturnType<typeof unlinkedFactsStats>>;
+ try { s = await unlinkedFactsStats(engine); } finally { await engine.executeRaw('ALTER TABLE fact_relink_attempts_hidden RENAME TO fact_relink_attempts'); }
+ expect(s!.no_subject).toBeNull();
+ expect(s!.relinked_7d).toBeNull();
+ const c = unlinkedFactsVerdict(s);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('relink history unavailable');
+ });
+});
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index f2d51150a4..a7ce3464b5 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -381,13 +381,13 @@
},
{
"category": "meta",
- "message": "Version 186 (latest: 186)",
+ "message": "Version 187 (latest: 187)",
"name": "schema_version",
"status": "ok"
},
{
"category": "meta",
- "message": "801 column(s) verified against live schema",
+ "message": "812 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
@@ -963,6 +963,34 @@
"name": "decide_health",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "fix": "preview links: gbrain facts relink --dry-run",
+ "inferred_7d": {
+ "mention": 0,
+ "page": 0
+ },
+ "new_7d": {
+ "facts": 0,
+ "no_subject": 0,
+ "unlinked": 0
+ },
+ "no_subject": 0,
+ "origins": [],
+ "relinked_7d": {},
+ "sources": 1,
+ "window": {
+ "active": 0,
+ "capped": false,
+ "fence_owned": 0,
+ "unlinked": 0
+ }
+ },
+ "message": "No active facts yet; nothing to link.",
+ "name": "unlinked_facts",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index d3975d0980..7648b3a9ef 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -381,13 +381,13 @@
},
{
"category": "meta",
- "message": "Version 186 (latest: 186)",
+ "message": "Version 187 (latest: 187)",
"name": "schema_version",
"status": "ok"
},
{
"category": "meta",
- "message": "801 column(s) verified against live schema",
+ "message": "812 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
@@ -963,6 +963,34 @@
"name": "decide_health",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "fix": "preview links: gbrain facts relink --dry-run",
+ "inferred_7d": {
+ "mention": 0,
+ "page": 0
+ },
+ "new_7d": {
+ "facts": 0,
+ "no_subject": 0,
+ "unlinked": 0
+ },
+ "no_subject": 0,
+ "origins": [],
+ "relinked_7d": {},
+ "sources": 1,
+ "window": {
+ "active": 0,
+ "capped": false,
+ "fence_owned": 0,
+ "unlinked": 0
+ }
+ },
+ "message": "No active facts yet; nothing to link.",
+ "name": "unlinked_facts",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index cf14433975..1567cbcadb 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -537,6 +537,10 @@
"category": "ops",
"name": "decide_health"
},
+ {
+ "category": "brain",
+ "name": "unlinked_facts"
+ },
{
"category": "ops",
"name": "chat_fallback_chain_inert"
diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.json
index 0a4fb8f93e..cf404a5111 100644
--- a/test/fixtures/goldens/doctor/registry-report-remote.json
+++ b/test/fixtures/goldens/doctor/registry-report-remote.json
@@ -185,6 +185,10 @@
"category": "ops",
"name": "self_upgrade_health"
},
+ {
+ "category": "brain",
+ "name": "unlinked_facts"
+ },
{
"category": "brain",
"name": "timeline_history"