Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): the extract_facts fence step leaves ontology observations alone; repair ontology-facts restores the ones it moved (#6264)
garrytane0f22077f49d
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 89d34080d2..c7476f40ed 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -298,6 +298,7 @@ export const timelineHistoryEntry: DoctorEntry = {'extractor_facts_expired','captured_facts_active','loop_facts_drift',+ 'ontology_facts_fenced',],run: runTimelineHistory,};diff --git a/src/commands/doctor/checks/ontology-facts.ts b/src/commands/doctor/checks/ontology-facts.tsnew file mode 100644index 0000000000..25c26464ea--- /dev/null+++ b/src/commands/doctor/checks/ontology-facts.ts@@ -0,0 +1,32 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { classifyOntologyFacts } from '../../../core/repair/ontology-facts.ts';++/**+ * #6264: ontology observations the extract_facts fence step moved onto an+ * entity page's Facts table (fenced, or retired by a later page write).+ * Counts the restorable ones by state and names the explicit-only repair's+ * preview; excluded ones (withdrawn, consolidated, duplicated) are reported+ * but never count as a finding. Read-only.+ */+export async function ontologyFactsCheck(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 facts = await classifyOntologyFacts(engine, sources);+ const count = (reason: string) => facts.filter(f => f.class === 'restorable' && f.reason === reason).length;+ const details = { fenced: count('fenced'), retired: count('retired'), excluded: facts.filter(f => f.class === 'excluded').length,+ repair: 'ontology-facts', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' };+ if (!details.fenced && !details.retired) {+ return { name: 'ontology_facts_fenced', status: 'ok', details,+ message: `No ontology observation is held by a page's Facts table${details.excluded ? ` (${details.excluded} affected observation(s) are excluded and stay as they are)` : ''}.` };+ }+ return { name: 'ontology_facts_fenced', status: 'warn', details,+ message: `${details.fenced + details.retired} ontology observation(s) were moved onto an entity page's Facts table by the extract_facts fence step `+ + `(${details.retired} since retired by a page write, so ontology_get no longer returns them; ${details.fenced} still fenced under the page's provenance). `+ + 'Preview the restore on the brain host: gbrain repair ontology-facts — then run the apply command it prints after the user agrees.' };+ } catch (error) {+ return { name: 'ontology_facts_fenced', status: 'warn',+ message: `Fenced ontology observations could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,+ details: { count: 'unknown' } };+ }+}diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex b6e96cd85e..c15347dbf9 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -244,6 +244,13 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [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),},+ {+ id: 'ontology_facts_fenced', resolution: 'repair', registration: 'wave',+ hostOnly: 'Restoring fenced ontology observations is a host-side, explicit-only repair.',+ count: d => Number(d.fenced ?? 0) + Number(d.retired ?? 0),+ impact: 'Some ontology observations were moved onto an entity page\'s Facts table, and ontology_get no longer returns the ones a later page write retired',+ run: async (engine, scope) => (await import('./checks/ontology-facts.ts')).ontologyFactsCheck(engine, scope.sourceIds),+ },];/** A check that could not run reports unknown, never ok. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 835456f96b..072f24036b 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -498,15 +498,17 @@ export async function runExtractFacts(// reconciliation pass. A row counts only when `row_num IS NULL`, its// `entity_slug` resolves to a LIVE page in THIS run's source (#3526 source// isolation), it is not soft-expired (#2646: `forget_fact` drains rows by- // soft-expiring them), and the source has a `local_path` (#2763). Rows- // without a page or checkout (#2484: the inline writer's- // slugify-floor / stub-guard-blocked slugs) are structurally unfenceable- // and never gate.+ // soft-expiring them), the source has a `local_path` (#2763), and it is+ // not an ontology observation (`dimension IS NULL`, #6264: those are never+ // fenced, so they must not gate either). Rows without a page or checkout+ // (#2484: the inline writer's slugify-floor / stub-guard-blocked slugs)+ // are structurally unfenceable and never gate.const legacy = await engine.executeRaw<{ n: string }>(`SELECT COUNT(*) AS nFROM facts fWHERE f.source_id = $1AND f.row_num IS NULL+ AND f.dimension IS NULLAND f.entity_slug IS NOT NULLAND f.expired_at IS NULLAND EXISTS (diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex c59a5afc58..3554b2d299 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -66,6 +66,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['derived_visibility','extractor_facts_expired','loop_facts_drift',+ 'ontology_facts_fenced','orphan_persistence_bindings','safe_index_pending','self_capture',diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex 12f8962057..f49c836ed4 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -9,6 +9,13 @@* so the cycle fences them on every run instead of waiting for a manual* migration retry.*+ * Ontology observations (`dimension IS NOT NULL`, written by+ * `mergeOntologyFact`) are never candidates (#6264): they belong to the+ * entity's ontology, keyed by their own provenance in `source_markdown_slug`,+ * and have no row on any page's Facts table. Fencing one rewrote its+ * provenance to the page and handed it to the fence reconciler, which retired+ * it on the next page write that did not list it.+ ** Eligibility (`planUnfencedFacts`): the row names an `entity_slug`, its page* is live in the row's source, and either the brain is managed (the* coordinator publishes database-only pages too; archived sources are@@ -109,7 +116,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_idAND p.slug = f.entity_slug AND p.deleted_at IS NULL) AS page_existsFROM facts f- WHERE row_num IS NULL AND expired_at IS NULL+ WHERE row_num IS NULL AND expired_at IS NULL AND dimension IS NULL${opts.sourceId !== undefined ? 'AND source_id = $1' : ''}ORDER BY source_id, entity_slug, id`,opts.sourceId !== undefined ? [opts.sourceId] : [],diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex a7b1be6d49..370976d7ce 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' | 'captured-facts' | 'loop-facts' | 'failed-writes' | 'frontmatter' | 'fences';+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'frontmatter' | 'fences';export interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex a7006bd27e..116d1cb2a8 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -25,7 +25,7 @@ import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricinimport { shellQuote, type Action } from '../agent-output.ts';import type { RepairKindSpec } from './registry.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }diff --git a/src/core/repair/ontology-facts.ts b/src/core/repair/ontology-facts.tsnew file mode 100644index 0000000000..ebf3084be5--- /dev/null+++ b/src/core/repair/ontology-facts.ts@@ -0,0 +1,169 @@+/**+ * `gbrain repair ontology-facts` (#6264): give the ontology back the+ * observations the `extract_facts` fence step took from it.+ *+ * From v0.60.53.0 the fence step (`facts/unfenced-facts.ts`) fenced every+ * `row_num IS NULL` fact row onto its entity page, ontology observations+ * included: it gave the row a fence row number and rewrote its+ * `source_markdown_slug` (the observation's provenance, which+ * `mergeOntologyFact` writes equal to `source`) to the page slug. The next+ * write of that page that did not list the row retired it (expired, and+ * usually detached). The fix stopped new fencing; this kind restores the rows.+ *+ * Candidates: ontology rows (`dimension IS NOT NULL`) of the scoped sources+ * that carry the fence step's signature, a fence row number or a+ * `source_markdown_slug` that differs from `source`. Ontology writes never+ * produce either. Each is classified:+ * - excluded (listed, never restored): its claim was withdrawn+ * (`fact_withdrawals`, so `forget` won); it was consolidated into another+ * row; or restoring its provenance would duplicate an existing+ * observation (same entity, dimension, value, provenance and valid_from).+ * - restorable: everything else, active (still fenced) or retired.+ * Rows retired after their fence row left the page, whose provenance already+ * equalled the page slug, carry no signature and are not found.+ *+ * The apply sets `row_num` NULL, `source_markdown_slug` back to `source` and+ * clears `expired_at`; validity dates and supersession links are kept. On a+ * managed brain each row commits as one coordinated database-only write on+ * the entity's and the page's keys (the `ontology_propose` path); on an+ * unmanaged brain as one maintenance transaction. Each row is rechecked in+ * the same statement and restored only when its row number, page and expiry+ * are unchanged since the preview (`changed_since_preview` otherwise). Page+ * text is never rewritten: a row still fenced keeps its line in the page's+ * `## Facts` table, which the next reconcile indexes as an ordinary page fact.+ *+ * Explicit-only and preview-bound: the preview lists every candidate with its+ * class, prints a hash and saves the restorable set; `--apply --expect <hash>`+ * restores exactly that set.+ */+import type { BrainEngine } from '../engine.ts';+import { OperationError } from '../ops/contract.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';+import { coordinatedDatabaseWrite } from '../persistence/database-write.ts';+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';++/** The expiry instant as UTC text with microseconds; a bound timestamp parameter can lose them. */+const EXPIRY_TEXT = (column: string) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;++/** An observation with the same dedup key as `f` once its provenance is restored (the ontology unique index). */+const DUPLICATE_SQL = (f: string) => `EXISTS (SELECT 1 FROM facts d WHERE d.source_id=${f}.source_id AND d.entity_slug=${f}.entity_slug+ AND d.dimension=${f}.dimension AND d.value_hash=${f}.value_hash AND d.source_markdown_slug=${f}.source+ AND d.valid_from=${f}.valid_from AND d.id<>${f}.id)`;++export interface OntologyFactCandidate {+ id: number;+ source_id: string;+ entity_slug: string;+ dimension: string;+ /** The observation's own provenance. */+ source: string;+ /** The page the fence step moved it to (its current `source_markdown_slug`). */+ page: string | null;+ row_num: number | null;+ /** UTC, microseconds; null while the row is still active. */+ expired_at: string | null;+ class: 'restorable' | 'excluded';+ reason: string;+}++interface CandidateRow {+ id: number | string; source_id: string; entity_slug: string; dimension: string; source: string; page: string | null;+ row_num: number | string | null; expired_at: string | null; withdrawn: boolean; consolidated: boolean; duplicate: boolean;+}++/** Every candidate of these sources, classified, in id order. Read-only; also the doctor check's count. */+export async function classifyOntologyFacts(db: BrainEngine, sourceIds: string[]): Promise<OntologyFactCandidate[]> {+ const rows = await db.executeRaw<CandidateRow>(`+ SELECT f.id, f.source_id, f.entity_slug, f.dimension, f.source, f.source_markdown_slug AS page, f.row_num,+ ${EXPIRY_TEXT('f.expired_at')} AS expired_at,+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibility+ AND (w.subject='*' OR w.subject=f.entity_slug)+ AND w.fact_hash IN (gbrain_fact_fingerprint(f.fact), gbrain_fact_fingerprint_v1(f.fact))) AS withdrawn,+ f.consolidated_into IS NOT NULL AS consolidated,+ ${DUPLICATE_SQL('f')} AS duplicate+ FROM facts f+ WHERE f.source_id=ANY($1::text[]) AND f.dimension IS NOT NULL AND f.entity_slug IS NOT NULL AND f.source IS NOT NULL+ AND (f.row_num IS NOT NULL OR f.source_markdown_slug IS DISTINCT FROM f.source)+ ORDER BY f.id`, [sourceIds]);+ return rows.map(row => {+ const [klass, reason] = row.withdrawn ? ['excluded', 'withdrawn'] as const+ : row.consolidated ? ['excluded', 'consolidated'] as const+ : row.duplicate ? ['excluded', 'duplicate'] as const+ : ['restorable', row.expired_at ? 'retired' : 'fenced'] as const;+ return { id: Number(row.id), source_id: row.source_id, entity_slug: row.entity_slug, dimension: row.dimension, source: row.source,+ page: row.page, row_num: row.row_num == null ? null : Number(row.row_num), expired_at: row.expired_at, class: klass, reason };+ });+}++interface ApprovedFact extends OntologyFactCandidate { selection: string[] }+interface FactItem extends RepairItem { fact: OntologyFactCandidate; hash: string; last: boolean }++function previewCommand(scope: RepairScope): string {+ return `gbrain repair ontology-facts${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;+}++function item(fact: OntologyFactCandidate, hash: string, last: boolean): FactItem {+ return { cursor: { phase: 1, id: fact.id }, source_id: fact.source_id, slug: fact.entity_slug, chars: 0,+ action: `restore:${fact.reason}`, fact, hash, last };+}++function label(fact: OntologyFactCandidate): string {+ return fact.class === 'excluded' ? `excluded_${fact.reason}` : fact.reason;+}++function detail(fact: OntologyFactCandidate): string {+ const where = `${fact.page ?? 'no page'}${fact.row_num != null ? ` row #${fact.row_num}` : ''}`;+ const state = fact.class === 'excluded' ? `kept as is (${fact.reason})`+ : fact.expired_at ? `retired ${fact.expired_at}; restores to source ${fact.source}`+ : `still fenced; restores to source ${fact.source} (the page's Facts table keeps its line as page text)`;+ return `fact #${fact.id} ${fact.dimension} moved to ${where}: ${state}`;+}++export const ontologyFactsRepair: RepairHandler = {+ kind: 'ontology-facts',+ publication: 'projection',+ embeds: false,+ async plan(engine, scope, after, opts): Promise<RepairPlan> {+ const command = previewCommand(scope);+ if (!opts?.apply) {+ const facts = await classifyOntologyFacts(engine, scope.source_ids);+ const restorable = facts.filter(f => f.class === 'restorable');+ 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: 'ontology-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, facts });+ if (restorable.length) await saveApprovedSet<ApprovedFact>(engine, { command: 'ontology-facts', hash }, restorable.map(f => ({ ...f, selection: scope.source_ids })));+ const residuals: Record<string, number> = {};+ for (const f of facts) residuals[label(f)] = (residuals[label(f)] ?? 0) + 1;+ return { items: restorable.map((f, index) => item(f, hash, index === restorable.length - 1)), preview_hash: hash, residuals,+ listing: facts.map(f => ({ item: `${f.source_id}:${f.entity_slug}#${f.dimension}`, class: label(f), detail: detail(f) })) };+ }+ if (!opts.expect) {+ throw new OperationError('invalid_params', 'gbrain repair ontology-facts --apply restores 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<ApprovedFact>(engine, { command: 'ontology-facts', hash: opts.expect, previewCommand: command });+ if (approved.items.some(f => JSON.stringify(f.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);+ const items = approved.items.map(({ selection: _selection, ...f }, index) => item(f, 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 { fact, hash, last } = entry as FactItem;+ const restore = (tx: BrainEngine) => tx.executeRaw<{ id: number | string; expired: boolean }>(+ `UPDATE facts f SET row_num=NULL, source_markdown_slug=f.source, expired_at=NULL+ WHERE f.id=$1 AND f.source_id=$2 AND f.dimension IS NOT NULL+ AND f.row_num IS NOT DISTINCT FROM $3::integer AND f.source_markdown_slug IS NOT DISTINCT FROM $4::text+ AND ${EXPIRY_TEXT('f.expired_at')} IS NOT DISTINCT FROM $5::text AND NOT ${DUPLICATE_SQL('f')}+ RETURNING f.id, f.expired_at IS NOT NULL AS expired`,+ [fact.id, fact.source_id, fact.row_num, fact.page, fact.expired_at]);+ const keys = [...new Set([fact.entity_slug, ...(fact.page ? [fact.page] : [])])];+ const managed = await coordinatedDatabaseWrite(ctx, 'ontology_propose', fact.entity_slug, keys, restore);+ const [row] = managed ? managed.value : await maintenanceTransaction(ctx.engine, restore);+ if (last) await clearApprovedSet(ctx.engine, { command: 'ontology-facts', hash });+ if (!row) return { applied: false, outcome: 'changed_since_preview', reason: 'the row moved, was edited or now duplicates another observation' };+ // The withdrawal trigger re-expires a claim forgotten after the preview.+ if (row.expired) return { applied: false, outcome: 'withdrawn', reason: 'the claim was withdrawn after the preview' };+ return { applied: true, outcome: 'restored' };+ },+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex 862c3f51d5..317bf6ad27 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -48,6 +48,7 @@ import { staleAtomsRepair } from './stale-atoms.ts';import { extractorFactsRepair } from './extractor-facts.ts';import { capturedFactsRepair } from './captured-facts.ts';import { loopFactsRepair } from './loop-facts.ts';+import { ontologyFactsRepair } from './ontology-facts.ts';import { orphanChildrenRepair } from './orphan-children.ts';import { failedWritesRepair } from './failed-writes.ts';import { frontmatterRepair } from './frontmatter.ts';@@ -170,6 +171,13 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ '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.',},+ 'ontology-facts': {+ handler: ontologyFactsRepair, embeds: 'none', checks: ['ontology_facts_fenced'], explicit_only: true,+ summary: 'Restore ontology observations that the extract_facts fence step (v0.60.53.0 until this release, #6264) moved onto an entity page\'s Facts '+ + 'table: each gets its own provenance back, leaves the fence and, if a later page write retired it, becomes active again. Withdrawn, consolidated '+ + 'and duplicated observations are never restored. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a row that changed '+ + 'since reports changed_since_preview. Database-only; no page is rewritten.',+ },'orphan-children': {handler: orphanChildrenRepair, embeds: 'none', checks: ['child_table_orphans'], explicit_only: true,summary: 'Delete rows of page child tables (chunks, versions, tags, takes, raw data, timeline, links) whose page no longer exists, and clear dangling 'diff --git a/test/e2e/ontology-fence-sweep-postgres.test.ts b/test/e2e/ontology-fence-sweep-postgres.test.tsnew file mode 100644index 0000000000..878a7c5f36--- /dev/null+++ b/test/e2e/ontology-fence-sweep-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../ontology-fence-sweep.test.ts'));diff --git a/test/ontology-fence-sweep.test.ts b/test/ontology-fence-sweep.test.tsnew file mode 100644index 0000000000..78bdefba3d--- /dev/null+++ b/test/ontology-fence-sweep.test.ts@@ -0,0 +1,206 @@+/**+ * #6264: the maintenance sweep must not fence ontology observations onto an+ * entity page's Facts table, and `gbrain repair ontology-facts` restores the+ * ones it already moved.+ *+ * Protects: after an `ontology_propose`, a sweep, an ordinary rewrite of the+ * entity page and another sweep, `ontology_get` still returns the observation+ * with its own provenance; the row never gets a fence row number and the+ * sweep never republishes the page (which made a client's read-modify-write+ * of the page fail with revision_conflict, so the page kept serving its+ * previous Facts value). An ontology observation does not hold up the+ * extract_facts reconcile of its page either. The repair finds rows fenced+ * the old way (still fenced, or retired by a page write), restores exactly+ * the previewed set, and leaves withdrawn and duplicated observations alone.+ * Fails when: `planUnfencedFacts` selects rows with a `dimension` (the+ * v0.60.53.0 behavior: the observation's source becomes the page and the+ * second sweep retires it), or the empty-fence guard counts them.+ * Why existing coverage misses it: the unfenced-rows tests seed plain fact+ * rows only, and the ontology tests never run a sweep or a page rewrite.+ * Seams: none; real PGLite (and Postgres through the e2e registration), the+ * operations' handlers, `runMaintenanceSweep`, `runCycle` and the repair+ * command. The old fence behavior is reproduced by handing the ontology row+ * to `fenceUnfencedFacts` directly.+ */+import { expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runRepairCommand } from '../src/commands/repair.ts';+import { ontologyFactsCheck } from '../src/commands/doctor/checks/ontology-facts.ts';+import { runCycle } from '../src/core/cycle.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseFactsFence } from '../src/core/facts-fence.ts';+import { fenceUnfencedFacts, planUnfencedFacts } from '../src/core/facts/unfenced-facts.ts';+import { parseMarkdown, serializePageToMarkdown } from '../src/core/markdown.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';+import { runMaintenanceSweep } from '../src/core/sweep.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const SLUG = 'people/alder-example';+const page = (claim: string) => `---\ntitle: Alder Example\ntype: person\n---\nAlder Example is a fictional engineer.\n\n## Facts\n`+ + '<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + `|---|---|---|---|---|---|---|---|---|---|\n| 1 | ${claim} | preference | 1.0 | world | medium | 2026-01-01 | | manual | |\n<!--- gbrain:facts:end -->\n`;++const op = (ctx: OperationContext, name: string, params: Record<string, unknown>) => operationsByName[name].handler(ctx, params) as Promise<any>;+/** A managed page write: put_page bound to the revision just read, as a client makes it. */+async function put(ctx: OperationContext, content: string) {+ const current = await ctx.engine.readPageSnapshot(SLUG, { sourceId: 'default' });+ await op(ctx, 'put_page', { slug: SLUG, content, ...(current ? { expected_revision: current.revision } : {}) });+}+const propose = (ctx: OperationContext, dimension: string, value: string, valid_from: string) =>+ op(ctx, 'ontology_propose', { entity: SLUG, dimension, value, valid_from, source: 'manual', visibility: 'world', confidence: 0.9 });+const ontology = async (ctx: OperationContext) => (await op(ctx, 'ontology_get', { entity: SLUG }) as Array<{ dimension: string; value: string; source: string }>)+ .map(r => [r.dimension, r.value, r.source]);+const sweep = (engine: BrainEngine) => runMaintenanceSweep(engine, { sourceId: 'default', budgetMs: 60_000 });+const revision = async (engine: BrainEngine) => (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!.revision;+const ontologyRows = (engine: BrainEngine) => engine.executeRaw<{ id: number; dimension: string; row_num: number | null; page: string; expired: boolean }>(+ `SELECT id, dimension, row_num, source_markdown_slug AS page, expired_at IS NOT NULL AS expired FROM facts WHERE dimension IS NOT NULL ORDER BY id`);++interface Brain { engine: BrainEngine; ctx: OperationContext; write(content: string): Promise<void> }++/**+ * An unmanaged brain whose default source has a checkout; `write` updates the+ * page row and its canonical file together, as a sync of an edited file does.+ */+async function unmanagedBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-ontology-sweep-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(join(root, 'people'), { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const ctx: OperationContext = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, sourceId: 'default',+ remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+ const write = async (content: string) => {+ const parsed = parseMarkdown(content, `${SLUG}.md`);+ const row = await engine.putPage(SLUG, { type: parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth });+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${SLUG}.md`, row.id]);+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;+ writeFileSync(join(root, `${SLUG}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));+ };+ await run({ engine, ctx, write });+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++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, ['ontology-facts', ...args, '--json']); } finally { console.log = original; }+ return JSON.parse(lines.join('\n')).results[0] as { affected: number; applied: number; apply_command: string;+ listing?: Array<{ item: string; class: string }>; outcomes?: Record<string, number>; residuals: Record<string, number> };+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ const brains = [+ ['managed', (run: (b: Brain) => Promise<void>) => managedBrain(b => run({ ...b, write: content => put(b.ctx, content) }), { databaseUrl })],+ ['unmanaged', (run: (b: Brain) => Promise<void>) => unmanagedBrain(databaseUrl, run)],+ ] as const;++ for (const [mode, brain] of brains) {+ test(`${backend}: ${mode}: an ontology observation survives a sweep, a page rewrite and another sweep, and the sweep leaves the page alone`, async () => {+ await brain(async ({ engine, ctx, write }) => {+ await write(page('Alder Example likes example tea'));+ expect((await propose(ctx, 'location', 'Example City', '2026-02-01')).action).toBe('inserted');+ const before = await revision(engine);++ await sweep(engine);+ expect(await revision(engine)).toBe(before);+ expect(await ontology(ctx)).toEqual([['location', 'Example City', 'manual']]);++ await write(page('Alder Example likes example coffee'));+ await sweep(engine);+ expect(await ontology(ctx)).toEqual([['location', 'Example City', 'manual']]);+ expect((await ontologyRows(engine)).map(r => [r.row_num, r.page, r.expired])).toEqual([[null, 'manual', false]]);+ const fence = parseFactsFence((await engine.getPage(SLUG, { sourceId: 'default' }))!.compiled_truth).facts;+ expect(fence.map(f => f.claim)).toEqual(['Alder Example likes example coffee']);+ });+ }, 120_000);+ }++ test(`${backend}: unmanaged: an ontology observation does not hold up the extract_facts reconcile of its page`, async () => {+ await unmanagedBrain(databaseUrl, async ({ engine, ctx, write }) => {+ await write(page('Alder Example likes example tea'));+ await propose(ctx, 'location', 'Example City', '2026-02-01');+ // The page's fence row is not indexed yet (an edit synced from another host, never reconciled).+ await engine.executeRaw('DELETE FROM facts WHERE dimension IS NULL');+ const report = await runCycle(engine, { sourceId: 'default', phases: ['extract_facts'] });+ const phase = report.phases.find(p => p.phase === 'extract_facts')!;+ expect(phase.summary).not.toContain('skipped');+ expect(phase.details).toMatchObject({ factsInserted: 1, unfencedRowsFenced: 0 });+ const active = await engine.executeRaw<{ fact: string }>('SELECT fact FROM facts WHERE dimension IS NULL AND expired_at IS NULL ORDER BY id');+ expect(active.map(r => r.fact)).toEqual(['Alder Example likes example tea']);+ expect(await ontology(ctx)).toEqual([['location', 'Example City', 'manual']]);+ });+ }, 120_000);++ test(`${backend}: managed: repair ontology-facts restores observations the old fence step moved, and keeps withdrawn and duplicated ones`, async () => {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, page('Alder Example likes example tea'));+ await propose(ctx, 'location', 'Example City', '2026-02-01');+ await propose(ctx, 'role', 'engineer', '2026-02-01');+ await propose(ctx, 'employer', 'Acme Example', '2026-02-01');+ await propose(ctx, 'expertise', 'databases', '2026-02-01');+ const [location, role, employer, expertise] = (await ontologyRows(engine)).map(r => Number(r.id));++ // The pre-fix fence step: every ontology row of the page is fenced through the coordinator.+ const plan = await planUnfencedFacts(engine, { sourceId: 'default' });+ expect(plan.groups.size).toBe(0);+ const rows = await engine.executeRaw<any>(+ `SELECT id, source_id, entity_slug, fact, kind, visibility, notability, context, valid_from, valid_until, source, confidence,+ claim_metric, claim_value, claim_unit, claim_period, true AS page_exists FROM facts WHERE dimension IS NOT NULL ORDER BY id`);+ plan.groups.set(`default\0${SLUG}`, rows);+ expect((await fenceUnfencedFacts(engine, plan)).fenced).toBe(4);+ expect((await ontology(ctx)).map(r => r[2])).toEqual([SLUG, SLUG, SLUG, SLUG]);++ // The user forgets employer while it is fenced.+ await op(ctx, 'forget_fact', { id: employer });+ // A page rewrite from the client's own copy drops the fenced rows except role, and a sweep retires them.+ const fenced = parseFactsFence((await engine.getPage(SLUG, { sourceId: 'default' }))!.compiled_truth).facts;+ const roleRow = fenced.find(f => f.claim === 'role: engineer')!;+ await put(ctx, page('Alder Example likes example coffee').replace('<!--- gbrain:facts:end -->',+ `| ${roleRow.rowNum} | role: engineer | fact | 0.9 | world | medium | 2026-02-01 | | manual | |\n<!--- gbrain:facts:end -->`));+ await sweep(engine);+ expect((await ontology(ctx)).map(r => r[0])).toEqual(['role']);+ // The agent proposes expertise again after it went missing.+ expect((await propose(ctx, 'expertise', 'databases', '2026-02-01')).action).toBe('inserted');++ const check = await ontologyFactsCheck(engine, ['default']);+ expect(check).toMatchObject({ name: 'ontology_facts_fenced', status: 'warn', details: { fenced: 1, retired: 1, excluded: 2 } });+ expect(check.message).toContain('gbrain repair ontology-facts');++ const preview = await repair(engine, ['--source', 'default']);+ expect(preview).toMatchObject({ affected: 2, applied: 0, residuals: { fenced: 1, retired: 1, excluded_withdrawn: 1, excluded_duplicate: 1 } });+ expect(preview.listing!.map(l => [l.item, l.class])).toEqual([+ [`default:${SLUG}#location`, 'retired'], [`default:${SLUG}#role`, 'fenced'],+ [`default:${SLUG}#employer`, 'excluded_withdrawn'], [`default:${SLUG}#expertise`, 'excluded_duplicate'],+ ]);+ await expect(runRepairCommand(engine, ['ontology-facts', '--source', 'default', '--apply', '--json'])).rejects.toThrow(/restores only the set a preview printed/);++ const hash = preview.apply_command.match(/--expect ([0-9a-f]+)/)![1];+ const applied = await repair(engine, ['--source', 'default', '--apply', '--expect', hash]);+ expect(applied).toMatchObject({ applied: 2, outcomes: { restored: 2 } });++ const after = new Map((await ontologyRows(engine)).map(r => [Number(r.id), [r.row_num, r.page, r.expired]]));+ expect(after.get(location)).toEqual([null, 'manual', false]);+ expect(after.get(role)).toEqual([null, 'manual', false]);+ expect(after.get(employer)![2]).toBe(true);+ expect(after.get(expertise)).toEqual([null, SLUG, true]);+ expect((await ontology(ctx)).sort()).toEqual([+ ['expertise', 'databases', 'manual'], ['location', 'Example City', 'manual'], ['role', 'engineer', 'manual']]);+ expect(await ontologyFactsCheck(engine, ['default'])).toMatchObject({ status: 'ok', details: { fenced: 0, retired: 0, excluded: 2 } });+ expect((await repair(engine, ['--source', 'default'])).affected).toBe(0);+ }, { databaseUrl });+ }, 180_000);+}