Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): explicit repair loop-facts and doctor loop_facts_drift (#5869)
garrytand7e03154a5c0
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 84ca85f94f..90488d8d23 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -278,6 +278,7 @@ export const timelineHistoryEntry: DoctorEntry = {'stale_embedding_effects','google_file_modes','extractor_facts_expired',+ 'loop_facts_drift',],run: runTimelineHistory,};diff --git a/src/commands/doctor/checks/loop-facts.ts b/src/commands/doctor/checks/loop-facts.tsnew file mode 100644index 0000000000..67ffa03a93--- /dev/null+++ b/src/commands/doctor/checks/loop-facts.ts@@ -0,0 +1,23 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { loopFactDrift } from '../../../core/persistence/loop-fact-retirement.ts';++/**+ * #5869: closed commitment loops whose fact is still active (and retirable:+ * same source, no open loop shares it), left by `loops_close` before its+ * coordinated retirement. Names the explicit-only repair's preview. Read-only.+ */+export async function loopFactsDriftCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);+ const drifted = (await loopFactDrift(engine, sources)).length;+ const details = { drifted, repair: 'loop-facts', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' };+ if (!drifted) return { name: 'loop_facts_drift', status: 'ok', details, message: 'Every closed commitment loop has its fact retired.' };+ return { name: 'loop_facts_drift', status: 'warn', details,+ message: `${drifted} closed commitment loop(s) still have an active commitment fact, so entity cards and recall keep the finished promise. `+ + 'Preview the retirement on the brain host: gbrain repair loop-facts — then run the apply command it prints after the user agrees.' };+ } catch (error) {+ return { name: 'loop_facts_drift', status: 'warn', details: { count: 'unknown' },+ message: `Closed-loop commitment facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 9812aef570..202683e5b7 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -183,6 +183,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some conversation-extractor facts were expired by the pre-v0.60.11.0 canonical projection and recall no longer returns them',run: async (engine, scope) => (await import('./checks/extractor-facts.ts')).extractorFactsCheck(engine, scope.sourceIds),},+ {+ id: 'loop_facts_drift', resolution: 'repair', registration: 'wave',+ hostOnly: 'Retiring closed-loop commitment facts is a host-side, explicit-only repair.',+ count: d => Number(d.drifted ?? 0),+ impact: 'Some closed commitment loops still have an active commitment fact, so recall keeps the finished promise',+ run: async (engine, scope) => (await import('./checks/loop-facts.ts')).loopFactsDriftCheck(engine, scope.sourceIds),+ },];/** A check that could not run reports unknown, never ok. */diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 331e55f8ba..cdfdc9f8f5 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -62,6 +62,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['credential_projection_pending','derived_visibility','extractor_facts_expired',+ 'loop_facts_drift','orphan_persistence_bindings','safe_index_pending','self_capture',diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 582278a2e2..69fd528edf 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */export const APPROVAL_MAX_AGE_DAYS = 7;-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'loop-facts';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 79ec677b0a..f8d2dc073d 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'loop-facts'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/loop-facts.ts b/src/core/repair/loop-facts.tsnew file mode 100644index 0000000000..64c97fdc7d--- /dev/null+++ b/src/core/repair/loop-facts.ts@@ -0,0 +1,73 @@+/**+ * `gbrain repair loop-facts` (#5869): retires the commitment facts that+ * `loops_close` left active before this release (its raw expiry was refused+ * on managed brains and never struck the fence row anywhere).+ *+ * Candidates are closed (`done`/`dropped`) loops whose commitment fact is+ * still active, lives in the loop's source and is referenced by no open loop+ * (`loopFactDrift`, the same rule `loops_close` and doctor+ * `loop_facts_drift` use). The kind is explicit-only and preview-bound: the+ * preview lists every loop with its fact and saves the set under its hash;+ * `--apply --expect <hash>` retires exactly that set. Each item is rechecked+ * when it is applied (`changed_since_preview` when the loop or fact moved)+ * and retired through the same coordinated strike-plus-expire publication+ * as `loops_close`, so the fence row and the database row change together.+ */+import { OperationError } from '../ops/contract.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { loopFactDrift, retireLoopFact } from '../persistence/loop-fact-retirement.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++interface DriftedLoop { loop_id: number; source_id: string; fact_id: number; status: string; slug: string | null }+interface LoopFactItem extends RepairItem { loop: DriftedLoop; hash: string; last: boolean }+interface ApprovedLoop extends DriftedLoop { selection: string[] }++function previewCommand(scope: RepairScope): string {+ return `gbrain repair loop-facts${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++function item(loop: DriftedLoop, hash: string, last: boolean): LoopFactItem {+ return { cursor: { phase: 1, id: loop.loop_id }, source_id: loop.source_id, slug: loop.slug ?? `loops/${loop.loop_id}`,+ chars: 0, action: 'retire:closed_loop_fact', loop, hash, last };+}++export const loopFactsRepair: RepairHandler = {+ kind: 'loop-facts',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const loops = await loopFactDrift(engine, scope.source_ids);+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);+ const hash = previewHash({ kind: 'loop-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, loops });+ if (loops.length) await saveApprovedSet<ApprovedLoop>(engine, { command: 'loop-facts', hash }, loops.map(loop => ({ ...loop, selection: scope.source_ids })));+ return { items: loops.map((loop, index) => item(loop, hash, index === loops.length - 1)), preview_hash: hash,+ residuals: { closed_loop_facts: loops.length },+ listing: loops.map(loop => ({ item: `${loop.source_id}:loop#${loop.loop_id}`, class: 'closed_loop_fact',+ detail: `loop ${loop.status}; commitment fact #${loop.fact_id} still active${loop.slug ? ` on ${loop.slug}` : ''}` })) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair loop-facts --apply retires only the set a preview printed.',+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,+ 'docs/guides/repair.md#explicit-only-repair-kinds');+ }+ const approved = await loadApprovedSet<ApprovedLoop>(engine, { command: 'loop-facts', hash: opts.expect, previewCommand: command });+ if (approved.items.some(loop => JSON.stringify(loop.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, ...loop }, index) => item(loop, opts.expect!, index === approved.items.length - 1));+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };+ },+ async apply(ctx, entry): Promise<RepairItemOutcome> {+ const { loop, hash, last } = entry as LoopFactItem;+ const [live] = await loopFactDrift(ctx.engine, [loop.source_id], loop.loop_id);+ let outcome: RepairItemOutcome;+ if (!live || live.fact_id !== loop.fact_id) outcome = { applied: false, outcome: 'changed_since_preview', reason: 'the loop or its fact changed' };+ else {+ const retired = await retireLoopFact(ctx, loop.loop_id);+ outcome = retired.fact_expired ? { applied: true, outcome: 'retired' }+ : { applied: false, outcome: retired.retryable ? 'refused_retryable' : 'kept', ...(retired.reason ? { reason: retired.reason } : {}) };+ }+ if (last) await clearApprovedSet(ctx.engine, { command: 'loop-facts', hash });+ return outcome;+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 0db950fd6c..fe5d30877c 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -34,6 +34,7 @@ import { embeddingEffectsRepair } from './embedding-effects.ts';import { googleFileModesRepair } from './google-file-modes.ts';import { staleAtomsRepair } from './stale-atoms.ts';import { extractorFactsRepair } from './extractor-facts.ts';+import { loopFactsRepair } from './loop-facts.ts';import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';import type { OperationError } from '../ops/contract.ts';@@ -115,6 +116,12 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'without that evidence. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a fact that changed since reports '+ 'changed_since_preview and stays expired. Superseded, withdrawn and duplicated facts are never restored. Database-only; no page is rewritten.',},+ 'loop-facts': {+ handler: loopFactsRepair, embeds: 'effect', checks: ['loop_facts_drift'], explicit_only: true,+ summary: 'Retire the commitment facts of loops closed before this release (#5869): expires each fact and strikes its fence row in one coordinated write, '+ + 'only when no open loop shares the fact. Preview-bound: --apply --expect <hash> retires exactly the previewed set; a loop or fact that changed since '+ + 'reports changed_since_preview and is kept. Never writes a withdrawal, so the same promise made again is stored normally.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));diff --git a/test/loops-close-fact.serial.test.ts b/test/loops-close-fact.serial.test.tsindex 17746b5811..1658e1278e 100644--- a/test/loops-close-fact.serial.test.ts+++ b/test/loops-close-fact.serial.test.ts@@ -24,6 +24,8 @@ import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';import { parseFactsFence } from '../src/core/facts-fence.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { loopFactsDriftCheck } from '../src/commands/doctor/checks/loop-facts.ts';import { withEnv } from './helpers/with-env.ts';import { createConnectorFixture, googleConfig } from './helpers/connector-fixture.ts';@@ -173,3 +175,46 @@ describe('#5869 loops_close retires the commitment fact through the coordinator'}}), 180_000);});++describe('#5869 gbrain repair loop-facts and doctor loop_facts_drift', () => {+ async function repair(engine: BrainEngine, args: string[]) {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await runRepairCommand(engine, ['loop-facts', ...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n')) as { results: Array<{ affected: number; applied: number; apply_command: string; listing?: unknown[]; outcomes?: Record<string, number> }> };+ }++ for (const managed of [true, false]) {+ test(`${managed ? 'managed' : 'unmanaged'}: a loop closed before the fix is found, previewed, and retired by the explicit apply`, async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, loopId, factId } = await seedCommitment(engine, managed);+ // What the pre-fix loops_close left: the loop closed, its fact active and fenced.+ await engine.executeRaw("UPDATE open_loops SET status='done', closed_at=now(), closed_by='manual' WHERE id=$1", [loopId]);+ const before = await loopFactsDriftCheck(engine, [sourceId]);+ expect(before).toMatchObject({ name: 'loop_facts_drift', status: 'warn', details: { drifted: 1 } });+ expect(before.message).toContain('gbrain repair loop-facts');+ const preview = await repair(engine, ['--source', sourceId]);+ expect(preview.results[0]).toMatchObject({ affected: 1, applied: 0 });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: false, rowActive: true });+ const hash = preview.results[0].apply_command.match(/--expect ([0-9a-f]+)/)![1];+ const applied = await repair(engine, ['--source', sourceId, '--apply', '--expect', hash]);+ expect(applied.results[0]).toMatchObject({ applied: 1, outcomes: { retired: 1 } });+ expect(await factState(engine, sourceId, factId)).toMatchObject({ expired: true, rowActive: false });+ expect(await loopFactsDriftCheck(engine, [sourceId])).toMatchObject({ status: 'ok', details: { drifted: 0 } });+ await restore(engine);+ }+ }), 180_000);+ }++ test('the drift rule skips a fact still shared with an open loop', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const { sourceId, loopId, factId } = await seedCommitment(engine, true);+ await upsertOpenLoop(engine, { sourceId, dedupKey: 'commit:shared', loopType: 'commitment_owed_by_me',+ summary: 'Send the deck by Friday', evidence: [], threadId: 'example-3', pageSlug: 'emails/example', detector: 'llm_extract', factId });+ await engine.executeRaw("UPDATE open_loops SET status='done', closed_at=now(), closed_by='manual' WHERE id=$1", [loopId]);+ expect(await loopFactsDriftCheck(engine, [sourceId])).toMatchObject({ status: 'ok', details: { drifted: 0 } });+ await restore(engine);+ }+ }), 180_000);+});