Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): adopt legacy rows with NULL notability/confidence; duplicate-facts repair keeps the fenced copy (G4)

garrytana5b7064be729
diff --git a/docs/architecture/key-files/core-persistence-facts.md b/docs/architecture/key-files/core-persistence-facts.md
index 86da216372..39d4dd0fed 100644
--- a/docs/architecture/key-files/core-persistence-facts.md
+++ b/docs/architecture/key-files/core-persistence-facts.md
@@ -15,7 +15,7 @@ Managed facts extraction: the entity-intent preparer and publisher, conversation
- `src/core/facts/conversation-memo.ts` — #6764 what makes free relink, then paid re-extraction, then linking by hand converge, all in `fact_relink_attempts`: `conversationTriedSql` (a `conversation_unresolved` memo, re-armed for the free relink by any page created in the source after it unless `RELINK_REASONS` memoizes the reason), `conversationPaidSql` and `recordReextractMemo` (tier `paid_reextract`, `target_slug` the page, `reason` its `content_hash`, keyed on the page's completion outcome row; written when an extraction of the page completes, unmanaged in `extract-conversation-facts.ts` and managed in `conversation-publication.ts` `applyEntry`). No schema change. Test: `test/conversation-memo-6764.test.ts`.
- `src/core/facts/conversation-relink-carry.ts` — #6764 how a free conversation relink survives a batch replacement: `clearConversationFacts` (conversation-publication.ts) expires the page's relinked rows (`RELINKED_DERIVED_ROW`: entity set and `entity relinked from` in the context) instead of deleting them, after deleting the previous clear's expired copies, and `inheritRelinkedEntities` gives each inserted row with no entity whose claim matches one of them that entity (live page only) and the relink note, in every insert `publishConversationFacts` makes (managed and unmanaged, replacement or addition) and in `insertGatedFacts`. One active copy, link kept. Test: `test/conversation-relink-6764.test.ts`.
-- `src/core/repair/duplicate-facts.ts` — `gbrain repair duplicate-facts` (#7043), explicit-only and preview-bound (consent `destructive`). `findDuplicateFacts` (read-only) groups active facts by source, visibility, `attributed_to` and `gbrain_fact_fingerprint(fact)`, keeps the oldest row (created_at, id) and classes each group `same_entity` or `cross_entity` (retired only with `--include-cross-entity`). The apply sets `expired_at` and `superseded_by` on database-only copies (`coordinatedDatabaseWrite` with the `relink_facts` operation on a managed brain, one `maintenanceTransaction` per group otherwise) and strikes a fenced copy as `superseded by #N` through a revision-bound `put_page` when the kept row shares its fence; a copy whose kept row is elsewhere is listed as `fence_kept_elsewhere`, one on a segmented page as `segmented_page` (preview and apply). Near duplicates are never touched; a row changed since the preview reports `changed_since_preview`. Tests: `test/repair-duplicate-facts-7043.test.ts` (PGLite and Postgres).
+- `src/core/repair/duplicate-facts.ts` — `gbrain repair duplicate-facts` (#7043), explicit-only and preview-bound (consent `destructive`). `findDuplicateFacts` (read-only) groups active facts by source, visibility, `attributed_to` and `gbrain_fact_fingerprint(fact)`, keeps the oldest fenced row, else the oldest row (created_at, id; G4: a database-only legacy copy of a fenced claim is retired onto the fence row, so the unfenced copy no longer holds its page out of fact reconciliation) and classes each group `same_entity` or `cross_entity` (retired only with `--include-cross-entity`). The apply sets `expired_at` and `superseded_by` on database-only copies (`coordinatedDatabaseWrite` with the `relink_facts` operation on a managed brain, one `maintenanceTransaction` per group otherwise) and strikes a fenced copy as `superseded by #N` through a revision-bound `put_page` when the kept row shares its fence; a copy whose kept row is elsewhere is listed as `fence_kept_elsewhere`, one on a segmented page as `segmented_page` (preview and apply). Near duplicates are never touched; a row changed since the preview reports `changed_since_preview`. Tests: `test/repair-duplicate-facts-7043.test.ts` (PGLite and Postgres).
- `src/commands/doctor/checks/fact-bulk-dates.ts` — `fact_bulk_dates` (wave check, #7247): `findBulkFactDays` over the scoped sources (remote callers: their permitted sources); warns per day with fact and entity counts, top source tags and `dated_claims`, says the dates record loading, not occurrence, and names the `gbrain repair fact-claim-dates --source <id>` preview. Read-only.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 2564b9525c..28ea569fdb 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -25,7 +25,7 @@
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. `partialFenceRuns` finds the fence runs a forced segment cut splits. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6712 PR 1: the wire still validates an older CLI's `explicitProcessing` list by shape, then ignores it (`WIRE_SKEW_WINDOWS.explicitProcessing` in `src/core/wire-skew.ts`, floor 0.60.255.0, accepted until 2026-11-14); the cursor's opt-outs are inherited (`test/sync-owner-lane-processing-6696.test.ts`). #6712 PR 2: the owner lane's flag tables are views of `SYNC_FLAGS` (`src/core/sync-flags.ts`); `--lanes N`/`--no-lanes` are accepted and not sent, and a dropped retired field prints `retiredWireNotice`.
- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`. #6946: `fence-write.ts` returns `legacyFallback: true, databaseOnlyReason: 'url_clone'` for a gbrain-owned `--url` clone on an unmanaged brain, and the backstop does not warn `facts:fence-write-unexpected-fallback` for it.
-- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain is never fenced (`skipped_url_clone`); its rows stay database-only.
+- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. G4: `fenceRowOf` (exported, narrow `FenceRowInput`) is the one fact-to-fence-row renderer; NULL notability/confidence render as column defaults (`medium`, 1). Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`. #6946: a gbrain-owned `--url` clone on an unmanaged brain is never fenced (`skipped_url_clone`); its rows stay database-only.
- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. `seedLoopRechecks` (#5012) seeds spec-less due holds for unmute re-checks and once for the newest thread of the top 500 senders with open reply-owed loops; `recordWithheldVerdict` keeps `loop_withheld_senders` (cap 2,000). Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).
- `src/core/cycle/connector-extract.ts` — the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without `--dir`; #5875): `runPhaseExtractDatabaseOnly` runs the bounded, source-scoped `extractStaleFromDB` drain (`CYCLE_STALE_DRAIN_BUDGET_MS`; brain-wide when the cycle has no source id; managed brains route to `extractManagedStaleLinks`) and reports `extract: ok` with `database_only: true` and the stale counters, or `warn` naming the first failed page, its code and fix (`staleDrainFailures`, shared with `cycle.ts`); a dry run reports `skipped`. Tests: `test/connector-cycle-extract.test.ts` (+ Postgres twin), no `runCycle` mock.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 9ef6834267..effe6f4aa4 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2061,7 +2061,8 @@ gbrain repair duplicate-facts --apply --expect <hash> --yes
A group is the active facts of one source, visibility and speaker whose text
normalizes to the same fingerprint (the rule `forget` uses: case, punctuation
-and runs of whitespace do not matter). The oldest row is kept; every other copy gets
+and runs of whitespace do not matter). The row in a page's Facts table is kept (the
+oldest one if several are), else the oldest row; every other copy gets
`expired_at` and `superseded_by` pointing at it, so it leaves recall but is not
deleted or withdrawn, and the claim can be saved again. Groups whose copies all
sit on one entity are `same_entity`. Groups spread over several entities are
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index ec83bdc3d2..a4b16cd8a2 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1237,6 +1237,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.433.0', text: 'Hermes transcript import keeps the answers a user gave in a `clarify` form (answered responses of a submitted form, or the answers a timed-out form had already locked) as user turns, each after its question as the assistant\'s turn. A Hermes session imported before re-renders on its next import scan when it holds such answers, which can run fact extraction for that page again (#7396).' },
{ since: '0.60.433.0', text: 'Fact subject inference links more facts and fewer wrong ones: a currency code next to an amount (`CHF 80`) and a record label opening a sentence (`Invoice ...`, `Work session ...`) no longer block a fact that names one person or company, and an entity introduced only as an example (`including X notes`, `for example, X`) is never chosen as the subject. A page named like the code or label still competes. A sentence that opens with `For example, X ...` no longer takes X as its subject (#7405).' },
{ since: '0.60.433.0', text: '`gbrain think` gives reasoning models from gpt-5 on 16,000 output tokens behind any provider or router prefix, as it already did for gpt-5 and the o-series on their own provider; gpt-6 ids get it too. Before, those got 4,000 and long answers came back truncated (`LLM_OUTPUT_TRUNCATED`). Providers bill the tokens used, not the cap (#7421).' },
+ // GBRA-190 G4 (fact fences). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A legacy fact row whose `notability` or `confidence` is empty (a long-lived database whose column lost its NOT NULL) is now adopted into its page\'s `## Facts` table with the column default (notability `medium`, confidence 1) instead of being refused as unadoptable (`parse`) on every run, which held its page out of fact reconciliation and booked an `integrity_guard` halt each cycle. The fence cell is written first and the row derives its values from it. A row with no kind or visibility is still refused.' },
+ { since: 'TBD', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index c08df9986c..231aae29d8 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -155,9 +155,23 @@ export interface UnadoptableFactRecord {
request_id?: string;
}
-function fenceRowOf(row: UnfencedFactRow, rowNum: number, claim: string): ParsedFact {
- // Full timestamps survive the fence (date-only at midnight UTC), so the
- // canonical projection writes back the value the row already holds.
+/**
+ * The fact columns a fence row is rendered from. notability and confidence may be NULL as read: a long-lived brain's
+ * columns can lack the NOT NULL a fresh schema declares.
+ */
+export type FenceRowInput = Pick<UnfencedFactRow, 'kind' | 'visibility' | 'context' | 'valid_from' | 'valid_until'
+ | 'source' | 'claim_metric' | 'claim_value' | 'claim_unit' | 'claim_period' | 'attributed_to'>
+ & { notability: UnfencedFactRow['notability'] | null; confidence: number | null };
+
+/**
+ * The one renderer from a `facts` row to its `## Facts` fence row at `rowNum` with `claim` (active). Columns a long-lived
+ * brain may hold as NULL render as their column default, the value a fresh row gets: notability `medium`, confidence 1.
+ * kind and visibility are never defaulted: a NULL renders as is, the fence refuses the row, and `adoptableClaim` reports
+ * it. Timestamps render as `formatFenceDate` writes them (date-only at midnight UTC, else the full instant), so the
+ * projection derives back the value the row holds; optional columns (context, valid_until, the typed claim columns,
+ * attributed_to) render only when present.
+ */
+export function fenceRowOf(row: FenceRowInput, rowNum: number, claim: string): ParsedFact {
const validFromStr = formatFenceDate(row.valid_from instanceof Date ? row.valid_from : new Date(row.valid_from));
const validUntilStr = row.valid_until
? formatFenceDate(row.valid_until instanceof Date ? row.valid_until : new Date(row.valid_until))
@@ -167,9 +181,9 @@ function fenceRowOf(row: UnfencedFactRow, rowNum: number, claim: string): Parsed
active: true,
claim,
kind: row.kind,
- confidence: Number(row.confidence),
+ confidence: row.confidence == null ? 1 : Number(row.confidence),
visibility: row.visibility,
- notability: row.notability,
+ notability: row.notability ?? 'medium',
validFrom: validFromStr,
validUntil: validUntilStr,
source: row.source,
@@ -191,7 +205,7 @@ function fenceRowOf(row: UnfencedFactRow, rowNum: number, claim: string): Parsed
*/
export function adoptableClaim(row: Pick<UnfencedFactRow, 'fact' | 'kind' | 'visibility' | 'notability' | 'confidence' | 'context'
| 'valid_from' | 'valid_until' | 'source' | 'claim_metric' | 'claim_value' | 'claim_unit' | 'claim_period'>): { claim: string } | { rejected: UnrenderableClass } {
- const desired = fenceRowOf(row as UnfencedFactRow, 1, row.fact);
+ const desired = fenceRowOf(row, 1, row.fact);
const once = parseFactsFence(renderFactsTable([desired]));
const back = once.facts[0];
if (once.warnings.length > 0 || once.facts.length !== 1 || !back) return { rejected: 'parse' };
diff --git a/src/core/repair/duplicate-facts.ts b/src/core/repair/duplicate-facts.ts
index 372d04a699..f03801fffa 100644
--- a/src/core/repair/duplicate-facts.ts
+++ b/src/core/repair/duplicate-facts.ts
@@ -1,10 +1,14 @@
/**
* `gbrain repair duplicate-facts` (#7043): retire exact copies of one active
- * fact, keeping the oldest.
+ * fact, keeping a fenced copy when there is one, else the oldest.
*
* A group is the active facts of one source and visibility (and one speaker)
* that share `gbrain_fact_fingerprint`; near duplicates (rewordings) are never
- * grouped. The oldest row (created_at, then id) is kept; every other row is
+ * grouped. The oldest fenced row is kept, or the oldest row (created_at, then
+ * id) when none is fenced (G4: the page file is the record, so a database-only
+ * legacy copy of a fenced claim is the one retired; keeping it instead held
+ * the fenced copy and left the legacy row unfenced, which kept its page out of
+ * fact reconciliation for good); every other row is
* superseded by it: `expired_at` set and `superseded_by` pointing at the kept
* row. It is a supersession, never a withdrawal, so the claim stays
* rememberable and the kept row keeps its entity.
@@ -77,7 +81,7 @@ export async function findDuplicateFacts(engine: BrainEngine, sourceIds: string[
WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
AND f.superseded_by IS NULL AND COALESCE(f.source, '') <> ALL($2::text[])
) d WHERE d.n > 1
- ORDER BY d.source_id, d.visibility, d.fp, d.speaker, d.created_at, d.id`, [sourceIds, [...AUDIT_ROW_SOURCES]]);
+ ORDER BY d.source_id, d.visibility, d.fp, d.speaker, d.fenced DESC, d.created_at, d.id`, [sourceIds, [...AUDIT_ROW_SOURCES]]);
const groups: DuplicateGroup[] = [];
let key = '';
for (const row of rows) {
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index 13207f11e1..37b76a93f3 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -279,14 +279,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
'duplicate-facts': {
handler: duplicateFactsRepair, embeds: 'effect', checks: [], explicit_only: true, preview_bound: true, consent: 'destructive',
consentText: {
- what: 'Retire the previewed copies of duplicate facts, keeping the oldest row of each claim',
+ what: 'Retire the previewed copies of duplicate facts, keeping a fenced row of each claim, else its oldest row',
why: 'The preview listed each group of active facts that state one claim (same fingerprint, source and visibility) with the row it keeps; applying it supersedes exactly the listed copies.',
risk: 'Copies are expired with superseded_by pointing at the kept row, never deleted or withdrawn, so the claim stays in recall and can be saved again. '
+ 'Fenced copies are struck in their page as "superseded by #N" through a revision-bound page write. A row that changed since the preview is kept.',
- user_message: 'Retire the previewed duplicate fact copies? Each claim keeps its oldest row; the copies are marked superseded by it, not deleted.',
+ user_message: 'Retire the previewed duplicate fact copies? Each claim keeps the row in its page\'s Facts table, else its oldest row; the copies are marked superseded by it, not deleted.',
},
summary: 'Retire exact copies of one active fact (#7043): in each group of active facts of one source and visibility that share their fingerprint, the '
- + 'oldest row is kept and every other row is superseded by it (expired_at set, superseded_by the kept row; never a withdrawal, so the claim stays '
+ + 'oldest fenced row (else the oldest row) is kept and every other row is superseded by it (expired_at set, superseded_by the kept row; never a withdrawal, so the claim stays '
+ 'rememberable). Groups whose copies sit on other entities are listed as cross_entity and retired only with --include-cross-entity; the kept row keeps '
+ 'its entity. Near duplicates are never touched. Fenced copies are struck in their page through a revision-bound put_page when the kept row is in the '
+ 'same fence, listed as fence_kept_elsewhere otherwise, and kept as segmented_page on a segmented page. Preview-bound: --apply --expect <hash> --yes retires exactly the previewed set; a row that '
diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.ts
index cc395b2117..e678355bbf 100644
--- a/test/fact-fence-adoption-exits.test.ts
+++ b/test/fact-fence-adoption-exits.test.ts
@@ -17,6 +17,18 @@
* that will submit are checked before the fence step admits anything.
* - One unadoptable legacy row no longer stops the phantom-redirect pass for
* the whole source; only a phantom that owns legacy rows is held.
+ * - G4: a legacy row with a NULL `notability` (a brain whose column lost its
+ * NOT NULL, as some long-lived brains have it) adopts into its page's fence
+ * with the column default `medium`, on the managed and the unmanaged path,
+ * and the fence row reads back as the row. Before, the fence row rendered
+ * `null` in the notability cell, the codec oracle refused it as `parse`,
+ * and the row stayed unfenced on every run, keeping its page out of
+ * reconciliation and booking the source's facts fence as an
+ * `integrity_guard` halt.
+ * - G4: a legacy row that copies a fenced claim of its page (`duplicate_claim`)
+ * is never adopted; `gbrain repair duplicate-facts` keeps the fence row and
+ * retires the legacy copy onto it, and the page then leaves the guard.
+ * Before, the repair kept an older legacy copy and held the fence row.
* Seams: planFence against an engine stub, the managed-brain helper for the
* coordinator path, PGLite for the extract_facts cycle, and an unmanaged
* brain with a source checkout (PGLite and Postgres) for the file path.
@@ -27,7 +39,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { fenceCellReadBackProblem, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../src/core/facts-fence.ts';
-import { fenceUnfencedFacts, planFence, planUnfencedFacts, type UnfencedFactRow } from '../src/core/facts/unfenced-facts.ts';
+import { adoptableClaim, fenceRowOf, fenceUnfencedFacts, planFence, planUnfencedFacts, type UnfencedFactRow } from '../src/core/facts/unfenced-facts.ts';
import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
import { serializePageToMarkdown } from '../src/core/markdown.ts';
import { FACT_FENCE_PLANNER, maintenancePreflight, planFactFenceAdoption, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';
@@ -39,6 +51,7 @@ import { LEGACY_FILE_SLUG, seedLegacyManagedContent, type LegacySeed } from './h
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';
import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
@@ -102,6 +115,25 @@ describe('planFence reuses a leftover cell without widening or overwriting it (#
});
});
+describe('fenceRowOf renders an absent column as its column default (G4)', () => {
+ test('NULL notability and confidence render as medium and 1, and the row reads back exactly', () => {
+ const row = { ...legacyRow(), notability: null, confidence: null };
+ const cell = fenceRowOf(row, 7, row.fact);
+ expect(cell).toMatchObject({ rowNum: 7, active: true, claim: row.fact, notability: 'medium', confidence: 1 });
+ const back = parseFactsFence(renderFactsTable([cell]));
+ expect(back.warnings).toEqual([]);
+ expect(back.facts).toHaveLength(1);
+ expect(back.facts[0]).toMatchObject(cell);
+ expect(renderFactsTable(back.facts)).toBe(renderFactsTable([cell]));
+ expect(adoptableClaim(row as unknown as UnfencedFactRow)).toEqual({ claim: row.fact });
+ });
+
+ test('kind and visibility are never defaulted: a NULL one is refused, not guessed', () => {
+ expect(adoptableClaim(legacyRow({ kind: null as unknown as UnfencedFactRow['kind'] }))).toEqual({ rejected: 'parse' });
+ expect(adoptableClaim(legacyRow({ visibility: null as unknown as UnfencedFactRow['visibility'] }))).toEqual({ rejected: 'parse' });
+ });
+});
+
for (const backend of testBackends()) {
const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
@@ -324,3 +356,120 @@ for (const backend of testBackends()) {
} finally { fs.rmSync(home, { recursive: true, force: true }); }
}, 120_000);
}
+
+/** G4: the column shape of a brain whose `facts.notability` lost its NOT NULL, and one legacy row on it with no notability. */
+async function nullNotabilityRow(engine: BrainEngine, slug: string, claim: string): Promise<number> {
+ await engine.executeRaw('ALTER TABLE facts ALTER COLUMN notability DROP NOT NULL');
+ const [row] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', $1, $2, 'fact', 'world', NULL, '2026-03-01', 'mcp:remember', 0.8) RETURNING id`, [slug, claim]);
+ return Number(row.id);
+}
+
+/** The adopted row keeps its id and text, its fence row reads back as it, and the fence carries the column default. */
+async function expectAdoptedWithDefaultNotability(engine: BrainEngine, file: string, id: number, claim: string): Promise<void> {
+ const [row] = await engine.executeRaw<{ id: number; fact: string; row_num: number | null; source_markdown_slug: string | null; expired: boolean; notability: string | null }>(
+ 'SELECT id, fact, row_num, source_markdown_slug, expired_at IS NOT NULL AS expired, notability FROM facts WHERE id = $1', [id]);
+ expect(row).toMatchObject({ fact: claim, source_markdown_slug: SLUG, expired: false });
+ expect(row.row_num).not.toBeNull();
+ const cell = parseFactsFence(fs.readFileSync(file, 'utf8')).facts.find(f => f.rowNum === Number(row.row_num));
+ expect(cell).toMatchObject({ claim, active: true, visibility: 'world', notability: 'medium', kind: 'fact', source: 'mcp:remember' });
+ expect(fenceCellReadBackProblem(cell, { fact: row.fact, visibility: 'world' })).toBeNull();
+ // The fence is the record: the reconcile derives the cell's notability into the row; nothing else wrote it.
+ expect(row.notability).toBe('medium');
+ expect((await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id = $1 AND fact = $2 ORDER BY id', ['default', claim])).map(r => Number(r.id))).toEqual([id]);
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const claim = 'Alice example mentors founders';
+
+ test(`${backend}: managed: a legacy row with NULL notability adopts through the coordinator with the default notability (G4)`, async () => {
+ let id!: number;
+ await managedBrain(async ({ engine, root }) => {
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir: root });
+ expect(result.warnings.filter(w => w.startsWith('FACTS_FENCE_FAILED'))).toEqual([]);
+ expect(result).toMatchObject({ legacyRowsPending: 0, guardTriggered: false });
+ await expectAdoptedWithDefaultNotability(engine, path.join(root, `${LEGACY_FILE_SLUG}.md`), id, claim);
+ const again = await runExtractFacts(engine, { sourceId: 'default', brainDir: root });
+ expect(again).toMatchObject({ unfencedRowsFenced: 0, legacyRowsPending: 0, guardTriggered: false });
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ await seedLegacyManagedContent(engine, root);
+ id = await nullNotabilityRow(engine, LEGACY_FILE_SLUG, claim);
+ } });
+ }, 120_000);
+
+ test(`${backend}: unmanaged: a legacy row with NULL notability adopts onto the page file with the default notability (G4)`, async () => {
+ await unmanagedFilePage(databaseUrl, '# Alice Example\n\nProse.\n', async ({ engine, brainDir, file }) => {
+ const id = await nullNotabilityRow(engine, SLUG, claim);
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.warnings.filter(w => w.startsWith('FACTS_FENCE_FAILED'))).toEqual([]);
+ expect(result).toMatchObject({ unfencedRowsFenced: 1, legacyRowsPending: 0, guardTriggered: false });
+ await expectAdoptedWithDefaultNotability(engine, file, id, claim);
+ const written = fs.readFileSync(file, 'utf8');
+ const again = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(again).toMatchObject({ unfencedRowsFenced: 0, legacyRowsPending: 0, guardTriggered: false, factsInserted: 0, factsDeleted: 0 });
+ expect(fs.readFileSync(file, 'utf8')).toBe(written);
+ });
+ }, 120_000);
+
+ test(`${backend}: unmanaged: an older legacy copy of a fenced claim is retired by repair duplicate-facts and its page leaves the guard (G4)`, async () => {
+ const fence = replaceOrInsertFactsFence('# Alice Example\n\nProse.\n', renderFactsTable([{ rowNum: 1, active: true, claim, kind: 'fact', confidence: 0.8,
+ visibility: 'world', notability: 'medium', validFrom: '2026-03-01', source: 'mcp:remember' }]));
+ await unmanagedFilePage(databaseUrl, fence, async ({ engine, brainDir, file, home }) => {
+ const [legacy] = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, created_at)
+ VALUES ('default', $1, $2, 'fact', 'world', 'medium', '2026-03-01', 'mcp:remember', 0.8, '2026-01-01T00:00:00Z') RETURNING id`, [SLUG, claim]);
+ const first = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(first.warnings).toContain(`FACTS_FENCE_FAILED: ${SLUG} (duplicate_claim: 1 row(s))`);
+ expect(first).toMatchObject({ legacyRowsPending: 1, guardTriggered: true });
+ const [fenced] = await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_markdown_slug = $1 AND row_num = 1 AND expired_at IS NULL', [SLUG]);
+
+ const repair = async (args: string[]) => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['duplicate-facts', ...args, '--json'])); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')).results[0] as { preview_hash: string; residuals: Record<string, number> };
+ };
+ const preview = await repair([]);
+ expect(preview.residuals).toMatchObject({ copies_to_retire: 1, fence_kept_elsewhere: 0 });
+ await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+ const state = async (id: number) => (await engine.executeRaw<{ active: boolean; superseded_by: number | null }>(
+ 'SELECT expired_at IS NULL AS active, superseded_by FROM facts WHERE id = $1', [id])).map(r => [r.active, r.superseded_by === null ? null : Number(r.superseded_by)]);
+ expect(await state(legacy.id)).toEqual([[false, Number(fenced.id)]]);
+ expect(await state(fenced.id)).toEqual([[true, null]]);
+ const written = fs.readFileSync(file, 'utf8');
+
+ const next = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(next.warnings.filter(w => w.startsWith('FACTS_FENCE_FAILED'))).toEqual([]);
+ expect(next).toMatchObject({ legacyRowsPending: 0, guardTriggered: false });
+ expect(fs.readFileSync(file, 'utf8')).toBe(written);
+ });
+ }, 120_000);
+}
+
+/** An unmanaged brain whose default source checkout holds `SLUG` as a file-backed page with `body`, its fence rows indexed. */
+async function unmanagedFilePage(databaseUrl: string | undefined, body: string,
+ run: (brain: { engine: BrainEngine; brainDir: string; file: string; home: string }) => Promise<void>): Promise<void> {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'fence-adoption-g4-'));
+ 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 brainDir = path.join(home, 'brain');
+ fs.mkdirSync(brainDir, { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [brainDir]);
+ const page = await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: body });
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${SLUG}.md`, page.id]);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const file = path.join(brainDir, `${SLUG}.md`);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, serializePageToMarkdown(snapshot.page, snapshot.tags));
+ await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ await run({ engine, brainDir, file, home });
+ } finally { await close(); }
+ });
+ } finally { fs.rmSync(home, { recursive: true, force: true }); }
+}
diff --git a/test/repair-duplicate-facts-7043.test.ts b/test/repair-duplicate-facts-7043.test.ts
index 26e787ad12..7b90b13661 100644
--- a/test/repair-duplicate-facts-7043.test.ts
+++ b/test/repair-duplicate-facts-7043.test.ts
@@ -1,12 +1,14 @@
/**
* #7043 (reported by @mikez93): `gbrain repair duplicate-facts` retires exact
* copies of one active fact. In each group of active facts of one source and
- * visibility with one fingerprint, the oldest row is kept and the others are
+ * visibility with one fingerprint, the oldest fenced row (else the oldest row) is kept and the others are
* superseded by it (expired_at set, superseded_by the kept row; never a
* withdrawal). Copies on other entities are listed apart and retired only
* with --include-cross-entity; near duplicates are never touched; a fenced
* copy is struck in its page as "superseded by #N" when the kept row is in the
- * same fence and kept otherwise. Explicit-only and preview-bound.
+ * same fence and kept otherwise. G4: a fenced copy is kept over an older
+ * database-only one, so a legacy copy of a fenced claim is retired instead of
+ * holding the fence row. Explicit-only and preview-bound.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
@@ -160,13 +162,19 @@ for (const backend of testBackends()) {
const carol = (await engine.executeRaw<{ id: number; row_num: number }>(
"SELECT id, row_num FROM facts WHERE source_markdown_slug='people/carol-example' AND expired_at IS NULL ORDER BY row_num")).map(r => ({ id: Number(r.id), row: Number(r.row_num) }));
expect(carol.map(r => r.row)).toEqual([1, 2]);
+ // G4: an older database-only legacy copy of a fenced claim is retired onto the fence row, never kept over it.
const dana = await fact('Dana Example plays chess.', 'people/dana-example', '2020-01-01');
await call('put_page', { slug: 'people/dana-example', content: fencePage('Dana Example', 'Dana Example plays chess.').replace(/\n\| 2 \|[^\n]*/, '') });
+ const [danaFenced] = (await engine.executeRaw<{ id: number }>(
+ "SELECT id FROM facts WHERE source_markdown_slug='people/dana-example' AND row_num=1 AND expired_at IS NULL")).map(r => Number(r.id));
+ // A fenced copy on another page cannot name the kept row, so it is kept.
+ await call('put_page', { slug: 'people/erin-example', content: fencePage('Erin Example', 'Dana Example plays chess.').replace(/\n\| 2 \|[^\n]*/, '') });
- const preview = await repair([]);
+ const preview = await repair(['--include-cross-entity']);
expect(preview.residuals.fence_kept_elsewhere).toBe(1);
- expect(preview.listing.some((l: { class: string; item: string }) => l.class === 'fence_kept_elsewhere' && l.item.endsWith(`fact#${dana}`))).toBe(true);
- await repair(['--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(preview.listing.some((l: { class: string; item: string }) => l.class === 'fence_kept_elsewhere' && l.item.endsWith(`fact#${danaFenced}`))).toBe(true);
+ await repair(['--include-cross-entity', '--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(await state([dana, danaFenced!])).toEqual([{ id: dana, active: false, superseded_by: danaFenced }, { id: danaFenced, active: true, superseded_by: null }]);
expect(await state(carol.map(r => r.id))).toEqual([{ id: carol[0]!.id, active: true, superseded_by: null }, { id: carol[1]!.id, active: false, superseded_by: carol[0]!.id }]);
const page = await call('get_page', { slug: 'people/carol-example', include_content: true });