Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(graph): edge_validity doctor check, upgrade notice, temporal sweep and migrate-engine manual transitions (GBRA-49 P1)
garrytan14de098b94ec
diff --git a/src/commands/doctor/checks/edge-validity.ts b/src/commands/doctor/checks/edge-validity.tsnew file mode 100644index 0000000000..daecd9458b--- /dev/null+++ b/src/commands/doctor/checks/edge-validity.ts@@ -0,0 +1,97 @@+/**+ * edge_validity (temporal typed edges): how the brain's relationships stand in+ * time and what needs an agent's or the user's attention.+ *+ * Reports relationship state by status (live, ended, ended_unknown_date,+ * disputed, events), relationships whose state lags their evidence (the+ * extract cycle sweeps them), pages that still assert a relationship their+ * own timeline closed (stale compiled truth), open contradiction proposals+ * (and undated ones waiting for a date), plus the resolved read policy+ * (graph.edge_validity) and contradiction mode. Every figure is an indexed+ * count; nothing calls a model.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { edgeValidityEnabled } from '../../../core/link-validity.ts';+import { staleRelationshipKeys } from '../../../core/link-relationships.ts';++export interface EdgeValidityStats {+ read_policy: 'on' | 'off';+ contradiction_mode: string;+ relationships: Record<string, number>;+ lagging: number;+ stale_assertions: Array<{ slug: string; target: string; link_type: string; ended: string | null }>;+ proposals: { proposed: number; undated: number; applied: number };+}++export async function edgeValidityStats(engine: BrainEngine, sourceIds?: readonly string[]): Promise<EdgeValidityStats | null> {+ const [t] = await engine.executeRaw<{ lr: string | null }>(`SELECT to_regclass('link_relationships')::text AS lr`);+ if (!t?.lr) return null;+ const scope = sourceIds?.length ? [...sourceIds] : null;+ const byStatus = await engine.executeRaw<{ status: string; n: number }>(+ `SELECT CASE WHEN semantics = 'event' THEN 'event' WHEN disputed THEN 'disputed' ELSE status_now END AS status, COUNT(*)::int AS n+ FROM link_relationships WHERE scope = 'all' AND ($1::text[] IS NULL OR source_id = ANY($1::text[])) GROUP BY 1`, [scope]);+ const stale = await engine.executeRaw<{ slug: string; target: string; link_type: string; ended: string | null }>(+ `SELECT f.slug, t.slug AS target, lr.link_type, lr.last_end::text AS ended+ FROM link_relationships lr JOIN pages f ON f.id = lr.from_page_id JOIN pages t ON t.id = lr.to_page_id+ WHERE lr.scope = 'all' AND lr.semantics = 'state' AND lr.last_end IS NOT NULL AND lr.undated_present > 0+ AND NOT (lr.valid_ranges @> (now() AT TIME ZONE 'UTC')::date)+ AND ($1::text[] IS NULL OR lr.source_id = ANY($1::text[]))+ AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = lr.from_page_id AND l.to_page_id = lr.to_page_id+ AND l.link_type = lr.link_type AND COALESCE(l.origin_page_id, l.from_page_id) = lr.from_page_id+ AND COALESCE(l.assertion_tense, 'present') = 'present')+ ORDER BY lr.last_end DESC LIMIT 20`, [scope]);+ const [p] = await engine.executeRaw<{ proposed: number; undated: number; applied: number }>(+ `SELECT COUNT(*) FILTER (WHERE status = 'proposed')::int AS proposed, COUNT(*) FILTER (WHERE status = 'undated_unresolved')::int AS undated,+ COUNT(*) FILTER (WHERE status = 'applied')::int AS applied+ FROM link_edge_proposals WHERE $1::text[] IS NULL OR source_id = ANY($1::text[])`, [scope]);+ const lagging = (await staleRelationshipKeys(engine, 1000)).length;+ return {+ read_policy: (await edgeValidityEnabled(engine)) ? 'on' : 'off',+ contradiction_mode: (await engine.getConfig('dream.edge_contradictions.mode')) ?? 'propose (default)',+ relationships: Object.fromEntries(byStatus.map(r => [r.status, Number(r.n)])),+ lagging,+ stale_assertions: stale,+ proposals: { proposed: Number(p?.proposed ?? 0), undated: Number(p?.undated ?? 0), applied: Number(p?.applied ?? 0) },+ };+}++export function edgeValidityVerdict(stats: EdgeValidityStats | null, opts: { thinClient?: boolean } = {}): Omit<Check, 'name'> {+ if (!stats) return { status: 'ok', message: 'Relationship state tables not present yet (run gbrain apply-migrations).' };+ const host = (cmd: string) => opts.thinClient ? `ask the brain host operator to run: ${cmd}` : `run: ${cmd}`;+ const counts = Object.entries(stats.relationships).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${v} ${k}`).join(', ') || 'none yet';+ const parts = [`relationships: ${counts}`, `read policy ${stats.read_policy}`, `contradiction mode ${stats.contradiction_mode}`];+ const fixes: string[] = [];+ if (stats.lagging > 0) { parts.push(`${stats.lagging}${stats.lagging >= 1000 ? '+' : ''} lag their evidence`); fixes.push(host('gbrain extract --stale (the dream cycle also sweeps them)')); }+ if (stats.stale_assertions.length) {+ const first = stats.stale_assertions[0];+ parts.push(`${stats.stale_assertions.length} page(s) still state a relationship their timeline ended (e.g. ${first.slug}: ${first.link_type} ${first.target}, ended ${first.ended})`);+ fixes.push(`ask the user before rewriting: ${first.slug} still says ${first.link_type} ${first.target}; the timeline says it ended ${first.ended}`);+ }+ if (stats.proposals.proposed || stats.proposals.undated) {+ parts.push(`${stats.proposals.proposed} contradiction proposal(s) open, ${stats.proposals.undated} waiting for a date`);+ fixes.push(host('gbrain edge-proposals list --json'));+ }+ const warn = stats.stale_assertions.length > 0 || stats.proposals.proposed > 0;+ return {+ status: warn ? 'warn' : 'ok',+ message: `${parts.join('; ')}${fixes.length ? `. Next: ${fixes.join('; ')}` : ''}`,+ details: { ...stats, ...(fixes.length ? { fix: fixes } : {}) },+ };+}++async function runEdgeValidity(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ ctx.progress.heartbeat('edge_validity');+ try {+ const stats = await edgeValidityStats(engine, ctx.orphanRatioSourceId ? [ctx.orphanRatioSourceId] : undefined);+ checks.push({ name: 'edge_validity', ...edgeValidityVerdict(stats) });+ } catch (err) {+ checks.push({ name: 'edge_validity', status: 'warn', message: `Relationship state could not be read: ${err instanceof Error ? err.message : String(err)}. Health is unknown.` });+ }+ return checks;+}++export const edgeValidityEntry: DoctorEntry = { name: 'edge_validity', emits: ['edge_validity'], run: runEdgeValidity };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex c20b98d777..1e0986c413 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -86,6 +86,7 @@ import { autoChronicleEntry } from './checks/auto-chronicle.ts';import { factTakeVectorsEntry } from './checks/vector-coverage.ts';import { decideHealthEntry } from './checks/decide.ts';import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';+import { edgeValidityEntry } from './checks/edge-validity.ts';import { plannerStatsEntry } from './checks/planner-stats.ts';import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';import { agentContractEntry } from './checks/agent-contract.ts';@@ -151,6 +152,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [syncFreshnessEntry,decideHealthEntry,unlinkedFactsEntry,+ edgeValidityEntry,autoChronicleEntry,factTakeVectorsEntry,plannerStatsEntry,diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.tsindex 1166d64828..7838c2aae6 100644--- a/src/commands/migrate-engine.ts+++ b/src/commands/migrate-engine.ts@@ -423,6 +423,22 @@ export async function copyPageLinksToTarget();copied++;}+ // Temporal typed edges: manual dated statements (add_link valid_from /+ // valid_until) exist only in the database, so they travel with the page.+ // Statements derived from page content re-derive on the target's next+ // extract pass.+ const manual = await source.executeRaw<{ to_slug: string; to_source_id: string; link_type: string; kind: string; occurred_on: string }>(+ `SELECT t.slug AS to_slug, t.source_id AS to_source_id, lt.link_type, lt.kind, lt.occurred_on::text AS occurred_on+ FROM link_transitions lt JOIN pages f ON f.id = lt.from_page_id JOIN pages t ON t.id = lt.to_page_id+ WHERE f.slug = $1 AND f.source_id = $2 AND lt.producer = 'manual'`, [page.slug, page.source_id]).catch(() => []);+ if (manual.length) {+ const { writeManualTransitions } = await import('../core/link-temporal-apply.ts');+ for (const m of manual) {+ if (failedKeys.has(makeManifestKey(m.to_source_id, m.to_slug))) continue;+ await writeManualTransitions(target, { from: page.slug, to: m.to_slug, linkType: m.link_type, sourceId: page.source_id },+ m.kind === 'start' ? { validFrom: m.occurred_on.slice(0, 10) } : { validUntil: m.occurred_on.slice(0, 10) });+ }+ }return copied;}diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.tsindex 225fa5026b..b8e59482c0 100644--- a/src/commands/upgrade.ts+++ b/src/commands/upgrade.ts@@ -700,6 +700,9 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {// #5876: auto_chronicle now defaults on; one-shot [AGENT] cost + opt-out notice, best-effort.await (await import('../core/chronicle/upgrade-notice.ts')).printAutoChronicleUpgradeNotice(engine);+ // Temporal typed edges: one-shot [AGENT] notice (live-by-default graph reads + relationship check), best-effort.+ await (await import('../core/temporal-edges-upgrade-notice.ts')).printTemporalEdgesUpgradeNotice(engine);+// Ambient-writeback consent ask (WP8): one-shot for EXISTING installs// upgrading into the feature. Personal brains only; double-gated on// its own sentinel + the setting being unset; [AGENT]-relayed;diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex a3d3ec27b3..10e226527f 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -151,6 +151,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['takes_weight_grid',// #5836: active facts with no entity (invisible to entity recall and the conflict sweep).'unlinked_facts',+ 'edge_validity','text_projection_readiness','timeline_coverage','timeline_orphans',diff --git a/src/core/link-relationships.ts b/src/core/link-relationships.tsindex b348538ae7..57defc5dad 100644--- a/src/core/link-relationships.ts+++ b/src/core/link-relationships.ts@@ -209,6 +209,15 @@ export async function staleRelationshipKeys(exec: RawExec, limit = 500): PromiseGROUP BY from_page_id, to_page_id, link_typeORDER BY min(newest) LIMIT $2`,[[...TEMPORAL_LINK_TYPES], limit]);+ // Relationships whose evidence-owning page was deleted, restored or edited+ // after the last refresh (soft deletes change no evidence row).+ const originChanged = rows.length >= limit ? [] : await exec.executeRaw<RelationshipKey>(+ `SELECT DISTINCT lr.from_page_id, lr.to_page_id, lr.link_type FROM link_relationships lr+ JOIN links l ON l.from_page_id = lr.from_page_id AND l.to_page_id = lr.to_page_id AND l.link_type = lr.link_type+ JOIN pages o ON o.id = COALESCE(l.origin_page_id, l.from_page_id)+ WHERE lr.scope = 'all' AND GREATEST(o.updated_at, COALESCE(o.deleted_at, o.updated_at)) > lr.refreshed_at+ LIMIT $1`, [limit - rows.length]);+ rows.push(...originChanged.filter(k => !rows.some(r => r.from_page_id === k.from_page_id && r.to_page_id === k.to_page_id && r.link_type === k.link_type)));// State rows whose evidence is gone entirely (raw deletes) are refreshed away too.const orphans = rows.length >= limit ? [] : await exec.executeRaw<RelationshipKey>(`SELECT lr.from_page_id, lr.to_page_id, lr.link_type FROM link_relationships lrdiff --git a/src/core/temporal-edges-upgrade-notice.ts b/src/core/temporal-edges-upgrade-notice.tsnew file mode 100644index 0000000000..a8223b720c--- /dev/null+++ b/src/core/temporal-edges-upgrade-notice.ts@@ -0,0 +1,65 @@+// Temporal typed edges: one-shot post-upgrade notice. Graph reads now return+// relationships that are true today (history on request), and the+// edge_contradictions dream phase proposes closures for live relationships+// that cannot both hold (paid chat calls; proposals only unless the model is+// certified for automatic application). Printed by `gbrain post-upgrade` once.+import type { BrainEngine } from './engine.ts';+import { agentBlock } from './agent-markers.ts';++export const TEMPORAL_EDGES_NOTICE_SHOWN_KEY = 'graph.temporal_notice_shown';++export async function temporalEdgesUpgradeNotice(engine: BrainEngine): Promise<string[] | null> {+ const shown = await engine.getConfig(TEMPORAL_EDGES_NOTICE_SHOWN_KEY);+ if (shown != null && shown.trim() !== '') return null;+ let model: string | null = null;+ let chatAvailable = false;+ try {+ const { configureGatewayIfUninitialized, isAvailable } = await import('./ai/gateway.ts');+ const { resolveModel } = await import('./model-config.ts');+ configureGatewayIfUninitialized();+ model = await resolveModel(engine, { configKey: 'models.dream.edge_contradictions', tier: 'utility', fallback: 'haiku' });+ chatAvailable = isAvailable('chat', model);+ } catch { /* notice still prints without the model line */ }+ const { loadEdgeContradictionsConfig } = await import('./cycle/edge-contradictions.ts');+ const config = await loadEdgeContradictionsConfig(engine, model ?? '');+ const mode = !chatAvailable ? 'off (no chat model)' : config.mode;+ return [+ '',+ '═══════════════════════════════════════════════════════════════',+ '[gbrain] Relationships now have dates. Graph reads (get_links, get_backlinks,',+ '[gbrain] traverse_graph, the relational search arm) return what is true today;',+ '[gbrain] former relationships stay queryable with status "all", as_of or during.',+ '═══════════════════════════════════════════════════════════════',+ ...agentBlock({+ ask: 'Keep live-by-default graph reads and the nightly relationship check?',+ why: 'Pages are re-read without any model call to date relationships from timeline lines ("left Acme", "joined Widget"), ' ++ '"Ended works_at [[companies/x]]" lines and past-tense prose, so "who works at X" stops listing former employees. ' ++ `The dream cycle's relationship check (mode: ${mode}) sends a subject's competing relationships and their context lines to ` ++ `${model ?? 'the configured chat model'} once per changed subject (cap $${config.budgetUsd.toFixed(2)} per cycle). ` ++ 'In propose mode it writes nothing to pages until the user accepts a proposal (gbrain edge-proposals list).',+ consent: 'paid, egress',+ actor: 'user',+ next: 'ask_user',+ if_yes: 'Nothing to run; the defaults stay. Review proposals with gbrain edge-proposals list.',+ if_no: 'Run gbrain config set graph.edge_validity off (every edge, as before) and/or gbrain config set dream.edge_contradictions.mode off.',+ verify: 'gbrain doctor --only edge_validity --json',+ }, {+ showUser: 'GBrain now tracks when relationships started and ended, so it stops treating old jobs as current. A nightly check can also ' ++ 'suggest which of two conflicting relationships ended, using your chat model (a small paid call per changed person or company). Keep both on?',+ }).trimEnd().split('\n'),+ '',+ ];+}++/** Prints the notice once and stamps it. Best-effort: never blocks the upgrade. */+export async function printTemporalEdgesUpgradeNotice(engine: BrainEngine, log: (line: string) => void = console.log): Promise<boolean> {+ try {+ const lines = await temporalEdgesUpgradeNotice(engine);+ if (!lines) return false;+ for (const line of lines) log(line);+ await engine.setConfig(TEMPORAL_EDGES_NOTICE_SHOWN_KEY, new Date().toISOString());+ return true;+ } catch {+ return false;+ }+}diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex b72f8fcec2..a5f2e75422 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -1288,6 +1288,24 @@"name": "unlinked_facts","status": "ok"},+ {+ "category": "brain",+ "details": {+ "contradiction_mode": "propose (default)",+ "lagging": 0,+ "proposals": {+ "applied": 0,+ "proposed": 0,+ "undated": 0+ },+ "read_policy": "on",+ "relationships": {},+ "stale_assertions": []+ },+ "message": "relationships: none yet; read policy on; contradiction mode propose (default)",+ "name": "edge_validity",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex d7feca2855..f9c5a57981 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -1376,6 +1376,24 @@"name": "unlinked_facts","status": "ok"},+ {+ "category": "brain",+ "details": {+ "contradiction_mode": "propose (default)",+ "lagging": 0,+ "proposals": {+ "applied": 0,+ "proposed": 0,+ "undated": 0+ },+ "read_policy": "on",+ "relationships": {},+ "stale_assertions": []+ },+ "message": "relationships: none yet; read policy on; contradiction mode propose (default)",+ "name": "edge_validity",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex ff1428fea1..82154b5576 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -609,6 +609,10 @@"category": "brain","name": "unlinked_facts"},+ {+ "category": "brain",+ "name": "edge_validity"+ },{"category": "brain","name": "auto_chronicle"