Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
facts: adopt legacy rows through the fence codec as the oracle, write the parsed claim back (#6278 C1, C2)
garrytan16e8a183c2c7
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 55b9ea3ecb..2e5c9b1a56 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -155,6 +155,7 @@ with each file and fix the ones that need no guessing."*| <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. A conflict no such request explains still blocks with `revision_conflict`. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. || <a id="parser_regression"></a>`parser_regression` | With `sync.parser_regression=hold`, a file whose exact bytes imported under an earlier gbrain is now refused. This is a gbrain bug. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version. After a fixed gbrain is installed, `gbrain sources retry-held <source>` and then `gbrain sync --source <source> --no-pull` re-screen it. || <a id="sync_parser_regression"></a>`sync_parser_regression` | Sync stopped without advancing because it would hold a file whose exact bytes imported before (default `sync.parser_regression=stop`). This is a gbrain bug, not a content problem. | Report it with the gbrain version, the file and the code; upgrade or pin the last good version, then `gbrain sync --source <source> --no-pull --retry-failed`. To keep syncing meanwhile, `gbrain config set sync.parser_regression hold` (ask the user). |+| <a id="fence_unrenderable"></a>`fence_unrenderable` | A legacy fact row (an active `facts` row with no fence row number) was not adopted into its page's `## Facts` fence because the fence codec reads the rendered row back as something other than the stored fact: a whitespace-only claim comes back empty, `~~x~~` comes back struck, a literal `<br>` comes back as a line break, or another column changes. Surrounding whitespace and CRLF line endings are the one accepted difference: such a row is adopted and `facts.fact` takes the fence's text. A second legacy row whose normalized claim and source the page already carries is left too (`duplicate_claim`). The cycle and the v0.32.2 migration print `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)`; doctor `fence_integrity` lists the pages, fact ids and reason classes under `unrenderable_legacy_facts` (never the claim text). The same code refuses a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input. | Nothing to fix in the page: the rows stay active and searchable, nothing is lost, and their pages skip destructive fact reconciliation until the rows are adopted. Report the pages and reason classes with the gbrain version. Never `forget_fact` a row to clear the count. || <a id="changed_since_preview"></a>`changed_since_preview` | A hash-bound repair apply (`gbrain repair frontmatter --apply --expect <hash>`, `gbrain repair fences --apply --expect <hash>`) found a file, its proposed change or its page different from what the preview showed, so that item was not written; the rest of the approved set still applied. | Preview again with the same selection and apply the new hash. For frontmatter, show the user the new diff first; a fence repair needs no extra consent ([fence reason](#fence-changed_since_preview)). |<a id="invalid_fence"></a>diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.tsindex 6aa031c362..5ffa08f8f1 100644--- a/src/commands/migrations/v0_32_2.ts+++ b/src/commands/migrations/v0_32_2.ts@@ -193,10 +193,13 @@ function fenceFactsResult(outcome: UnfencedFactsOutcome): OrchestratorPhaseResul(outcome.skipped_archived > 0 ? ` skipped_archived=${outcome.skipped_archived}` : '') +(outcome.failed_pages.length > 0 ? ` failed=${outcome.failed_pages.length}` : '');if (outcome.failed_pages.length > 0) {+ // The same `FACTS_FENCE_FAILED: <slug> (<reason>)` token the extract_facts+ // cycle phase prints, so an unadoptable row reads the same in both outputs.+ const failed = outcome.failed_pages.map(page => `FACTS_FENCE_FAILED: ${page}`);return {name: 'fence_facts',status: 'failed',- detail: `${detail} :: ${outcome.failed_pages.slice(0, 3).join(' | ')}${outcome.failed_pages.length > 3 ? '...' : ''}`,+ detail: `${detail} :: ${failed.slice(0, 3).join(' | ')}${failed.length > 3 ? '...' : ''}`,};}return { name: 'fence_facts', status: 'complete', detail };diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 73770f840c..e05d306848 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -306,6 +306,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.107.0', text: 'Search-hiding and other gate-owned frontmatter keys (`quarantine`, `content_flag`, `embed_skip`, `atoms_scan_hash`, `quarantine_override`) in a local `put_page`, a connector, an ingest event or any other non-owner write are now stripped instead of kept; sync and import of your own files, reindex, repair and `gbrain quarantine clear` keep them.' },{ since: '0.60.107.0', text: 'A quarantined page is no longer offered to automatic fact extraction (`facts_backstop.skipped: quarantined`) and its facts and takes fences are not projected; rows projected before it was quarantined stay.' },{ since: '0.60.107.0', text: '`get_page` and `fetch` of a quarantined page carry `quarantined` (fetch: `metadata.quarantined`) and a `page_quarantined` notice, and remote callers get no body or text unless an admin-scoped caller passes `include_quarantined: true`; a quarantined `put_page` now reports `quarantined: { reason, detail }`.' },+ { since: '0.60.107.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance), a claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one the page already carries stays a legacy row and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor fence_integrity `unrenderable_legacy_facts`, and only the pages still holding such rows skip destructive fact reconciliation instead of the whole source.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 7005abaf87..a653c248f6 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -152,6 +152,7 @@ export const CODES = {extraction_failed: { class: 'server', summary: "The accepted atom extraction failed (malformed output, or a response stopped before the end); a new attempt needs approval.", why: "A failed managed atom batch is recorded as a failure receipt instead of being retried automatically, so the same input is not paid for every cycle." },extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },+ fence_unrenderable: { class: 'server', summary: "A legacy fact row was not adopted into its page's facts fence because the fence codec reads the rendered row back as something other than the stored fact.", why: "The fence trims a claim, folds CRLF to LF, reads `~~x~~` as a struck row and `<br>` as a line break; a claim the codec would change by more than whitespace cannot be written into the fence without changing what it says, so the row stays a legacy row (active and searchable, nothing is lost) and is counted by doctor fence_integrity as unrenderable_legacy_facts. The same code names a planned adoption whose rendered fence does not read back as its facts; that is a gbrain planning defect, not caller input.", docs: 'docs/guides/write-refusals.md#fence_unrenderable', suggestion: 'Nothing to fix in the page: the rows stay active and searchable. Report the page slug and the reason class with the gbrain version; do not forget or expire a row to clear this count.', fix: { argv: ['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], consent: [], actor: 'agent', why: 'Lists the pages whose legacy fact rows cannot be adopted into their fence and why (by fact id and reason class, never the claim text), read-only.', requires_exclusive: false } },fact_not_found: { class: 'caller', summary: "Fact not found." },facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },facts_backstop_skipped: { class: 'unavailable', summary: "A page write queued no automatic fact extraction; the receipt's `facts_backstop.skipped` reason says why (a `kind:<type>` reason names a page type that is not extracted).", reasons: ['opted_out', 'quarantined', 'body_unchanged', 'extraction_disabled', 'dream_generated', 'subagent_namespace', 'too_short', 'no_parsed_page', 'slug_bound_client', 'operation_bound_client', 'not_imported', 'backstop_error'], docs: 'docs/guides/concurrent-writes.md#facts-backstop', suggestion: 'Nothing failed. `opted_out` means the page frontmatter sets `facts_backstop: false`; remove that line and save the page to extract it.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Shows the page frontmatter that decided the skip.', requires_exclusive: false } },diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.tsindex f575af3931..46f0358d32 100644--- a/src/core/facts-fence.ts+++ b/src/core/facts-fence.ts@@ -338,6 +338,17 @@ export function parseFactsFence(body: string): FactsFenceParseResult {return { facts, warnings };}+/**+ * The whitespace the codec changes about a claim, and nothing else: cells are+ * trimmed (JavaScript `trim`, Unicode whitespace including NBSP) and CRLF/CR+ * come back as LF. Two claims equal under this normalization render and parse+ * to the same fence row text; the fact adoption (#6278) accepts exactly this+ * difference between a stored legacy claim and its parsed fence cell.+ */+export function normalizeClaimWhitespace(text: string): string {+ return text.replace(/\r\n?/g, '\n').trim();+}+/*** Render an instant for a `valid_from` / `valid_until` cell. A UTC-midnight* value keeps the `YYYY-MM-DD` shape (date-only cells never churn); any otherdiff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex f49c836ed4..2163dbbedd 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -23,6 +23,23 @@* exists on this host. Everything else is counted and left alone: a NULL* entity slug, a missing page or file, or a source without a checkout here.*+ * Adoption oracle (#6278, `adoptableClaim`): the fence codec trims a claim,+ * folds CRLF/CR to LF, reads `~~x~~` as a struck row and `<br>` as a line+ * break, so a legacy claim is adopted only when `parseFactsFence(+ * renderFactsTable([row]))` hands it back active, non-empty, with the same+ * kind, visibility, validity and source, differing from the stored text by+ * whitespace and line endings alone. The parsed text is what the fence will+ * project, so it is written back into `facts.fact` with the row number (the+ * canonical projection expires any adopted row whose text differs from its+ * fence row). A row the codec would change further, or whose normalized+ * claim and source another active fence row or planned row already carries+ * (the reconciler indexes a duplicate once and would retire the second),+ * stays a legacy row exactly as it is: never deleted or expired, recorded as+ * an `UnadoptableFactRecord` (source, page, fact id, reason class; never the+ * claim text) and named in `failed_pages` with the stable token+ * `<slug> (fence_unrenderable: N row(s), <class>)`. The other rows of the+ * page still adopt; a page with no adoptable row submits nothing.+ ** Write discipline (`fenceUnfencedFacts`):* - Managed: one `managed_maintenance_adopt_fact_fence` request per page* through the coordinator, which publishes the fence and adopts the rows@@ -38,7 +55,8 @@ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import type { BrainEngine } from '../engine.ts';import { sanitizeText } from '../batch-rows.ts';import { isDurabilityHardened } from '../brain-repo-durability.ts';-import { formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';+import { formatFenceDate, normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';+import { FENCE_SOURCE_DEFAULT } from './extract-from-fence.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';import { withPageLock } from '../page-lock.ts';@@ -50,7 +68,7 @@ import { contentHash } from '../utils.ts';import { resolvePageWriteTarget } from '../write-through.ts';import { commitFactFenceFile, gitPathState } from './fence-write.ts';-interface UnfencedFactRow {+export interface UnfencedFactRow {id: string;source_id: string;entity_slug: string | null;@@ -84,6 +102,90 @@ export interface UnfencedFactsOutcome {fenced_slugs: string[];/** Unmanaged: `<slug> (<reason>)` per live page whose canonical file is not on this host (counted in skipped_no_page). */missing_files: string[];+ /** Legacy rows this run left as they are because the fence codec would change them or the page already carries the claim (#6278). */+ unadoptable_rows: UnadoptableFactRecord[];+}++/**+ * What the fence codec would change about a legacy claim, by column or+ * character class: `empty` (whitespace-only), `struck` (`~~x~~` reads back+ * inactive), `line_break_markup` (a literal `<br>` reads back as a newline),+ * `claim` (any other change to the text), `kind` / `visibility` /+ * `validity` / `source` (another column reads back different), `parse` (the+ * single-row fence does not parse at all).+ */+export type UnrenderableClass = 'empty' | 'struck' | 'line_break_markup' | 'claim' | 'kind' | 'visibility' | 'validity' | 'source' | 'parse';++/** One legacy row left unadopted, by location only: the claim text is never copied into a diagnostic. */+export interface UnadoptableFactRecord {+ source_id: string;+ slug: string;+ fact_id: number;+ reason: 'fence_unrenderable' | 'duplicate_claim';+ class: UnrenderableClass | 'duplicate_claim';+}++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.+ 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))+ : undefined;+ return {+ rowNum,+ active: true,+ claim,+ kind: row.kind,+ confidence: Number(row.confidence),+ visibility: row.visibility,+ notability: row.notability,+ validFrom: validFromStr,+ validUntil: validUntilStr,+ source: row.source,+ context: row.context ?? undefined,+ ...(row.claim_metric ? { claimMetric: row.claim_metric } : {}),+ ...(row.claim_value != null ? { claimValue: Number(row.claim_value) } : {}),+ ...(row.claim_unit ? { claimUnit: row.claim_unit } : {}),+ ...(row.claim_period ? { claimPeriod: row.claim_period } : {}),+ };+}++/**+ * The parser as the oracle (#6278): render the row as a one-row fence, parse+ * it back, and accept the parsed claim only when it is active, non-empty,+ * keeps the row's kind, visibility, validity and source, differs from the+ * stored text by whitespace and line endings alone, and survives a second+ * round trip unchanged (it is the text written back into `facts.fact`).+ */+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 once = parseFactsFence(renderFactsTable([desired]));+ const back = once.facts[0];+ if (once.warnings.length > 0 || once.facts.length !== 1 || !back) return { rejected: 'parse' };+ if (!back.active) return { rejected: 'struck' };+ if (back.claim === '') return { rejected: 'empty' };+ if (normalizeClaimWhitespace(back.claim) !== normalizeClaimWhitespace(row.fact)) {+ return { rejected: /<br\s*\/?>/i.test(row.fact) ? 'line_break_markup' : 'claim' };+ }+ if (back.kind !== desired.kind) return { rejected: 'kind' };+ if (back.visibility !== desired.visibility) return { rejected: 'visibility' };+ if ((back.validFrom ?? '') !== (desired.validFrom ?? '') || (back.validUntil ?? '') !== (desired.validUntil ?? '')) return { rejected: 'validity' };+ if ((back.source ?? '') !== (desired.source ?? '')) return { rejected: 'source' };+ const twice = parseFactsFence(renderFactsTable([{ ...desired, claim: back.claim }])).facts[0];+ if (!twice?.active || twice.claim !== back.claim) return { rejected: 'claim' };+ return { claim: back.claim };+}++/** The `failed_pages` entry for a page with unadoptable rows: `<slug> (fence_unrenderable: N row(s), <class>; duplicate_claim: N row(s))`. */+export function unadoptableRowsToken(slug: string, records: UnadoptableFactRecord[]): string {+ const parts: string[] = [];+ const unrenderable = records.filter(r => r.reason === 'fence_unrenderable');+ if (unrenderable.length) parts.push(`fence_unrenderable: ${unrenderable.length} row(s), ${[...new Set(unrenderable.map(r => r.class))].sort().join(', ')}`);+ const duplicates = records.filter(r => r.reason === 'duplicate_claim');+ if (duplicates.length) parts.push(`duplicate_claim: ${duplicates.length} row(s)`);+ return `${slug} (${parts.join('; ')})`;}export interface UnfencedFactsPlan {@@ -123,7 +225,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:);const outcome: UnfencedFactsOutcome = {scanned: rows.length, fenced: 0, skipped_no_entity: 0, skipped_no_local_path: 0, skipped_no_page: 0,- skipped_archived: 0, pages_touched: 0, failed_pages: [], fenced_slugs: [], missing_files: [],+ skipped_archived: 0, pages_touched: 0, failed_pages: [], fenced_slugs: [], missing_files: [], unadoptable_rows: [],};const groups = new Map<string, UnfencedFactRow[]>();for (const row of rows) {@@ -152,14 +254,18 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:}/**- * Append a page's unfenced rows to its facts fence. Row numbering starts above- * every occupied `row_num` on the page, conversation-extractor rows included,- * so no fence row can take an extractor row's position. A fence row left by a- * partial earlier run with the same claim and source and no database owner is- * reused instead of appended again.+ * Append a page's adoptable unfenced rows to its facts fence. Row numbering+ * starts above every occupied `row_num` on the page, conversation-extractor+ * rows included, so no fence row can take an extractor row's position. A+ * fence row left by a partial earlier run with the same claim and source and+ * no database owner is reused instead of appended again. Each assignment+ * carries the parsed claim the fence projects, to be written back into+ * `facts.fact` with the row number. Rows the codec would change further, and+ * a second row whose normalized claim and source the page already carries,+ * are returned in `rejected` and left alone.*/-async function planFence(engine: BrainEngine, sourceId: string, entitySlug: string, body: string, group: UnfencedFactRow[]):- Promise<{ body: string; assignments: Array<{ id: string; row_num: number }> } | { warnings: string[] }> {+export async function planFence(engine: BrainEngine, sourceId: string, entitySlug: string, body: string, group: UnfencedFactRow[]):+ Promise<{ body: string; assignments: Array<{ id: string; row_num: number; fact: string }>; rejected: UnadoptableFactRecord[] } | { warnings: string[] }> {const existingFence = parseFactsFence(body);if (existingFence.warnings.length > 0) return { warnings: existingFence.warnings };const occupiedRows = await engine.executeRaw<{ row_num: number; fact: string; source: string | null }>(@@ -170,48 +276,54 @@ async function planFence(engine: BrainEngine, sourceId: string, entitySlug: striconst occupied = new Map(occupiedRows.map(row => [Number(row.row_num), row]));let nextRowNum = Math.max(0, ...occupied.keys(), ...existingFence.facts.map(f => f.rowNum)) + 1;const claimed = new Set<number>();- const assignments: Array<{ id: string; row_num: number }> = [];+ const assignments: Array<{ id: string; row_num: number; fact: string }> = [];+ const rejected: UnadoptableFactRecord[] = [];+ // The reconciler indexes active rows with one claim and source once (#1781)+ // and retires the later copy, so a claim the page already carries, or that+ // an earlier row of this group plans, is not adopted a second time.+ const dupKey = (claim: string, source: string | undefined) => `${claim}\u0000${source || FENCE_SOURCE_DEFAULT}`;+ const planned = new Set<string>();+ const ownedKeys = new Set(existingFence.facts.filter(f => {+ const owner = occupied.get(f.rowNum);+ return f.active && owner !== undefined && owner.fact === f.claim && (owner.source ?? '') === (f.source ?? '');+ }).map(f => dupKey(f.claim, f.source)));for (const row of group) {+ const oracle = adoptableClaim(row);+ if ('rejected' in oracle) {+ rejected.push({ source_id: sourceId, slug: entitySlug, fact_id: Number(row.id), reason: 'fence_unrenderable', class: oracle.rejected });+ continue;+ }+ const key = dupKey(oracle.claim, row.source);+ if (planned.has(key) || ownedKeys.has(key)) {+ rejected.push({ source_id: sourceId, slug: entitySlug, fact_id: Number(row.id), reason: 'duplicate_claim', class: 'duplicate_claim' });+ continue;+ }+ planned.add(key);const existing = existingFence.facts.find(f => {const owner = occupied.get(f.rowNum);- return f.active && !claimed.has(f.rowNum) && f.claim === row.fact &&+ return f.active && !claimed.has(f.rowNum) && f.claim === oracle.claim &&(f.source ?? '') === (row.source ?? '') &&(!owner || owner.fact !== f.claim || (owner.source ?? '') !== (f.source ?? ''));});if (existing) {if (occupied.has(existing.rowNum)) existing.rowNum = nextRowNum++;- assignments.push({ id: row.id, row_num: existing.rowNum });+ assignments.push({ id: row.id, row_num: existing.rowNum, fact: oracle.claim });claimed.add(existing.rowNum);continue;}- // Full timestamps survive the fence (date-only at midnight UTC), so the- // canonical projection writes back the value the row already holds.- 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))- : undefined;const rowNum = nextRowNum++;- existingFence.facts.push({- rowNum,- active: true,- claim: row.fact,- kind: row.kind,- confidence: row.confidence,- visibility: row.visibility,- notability: row.notability,- validFrom: validFromStr,- validUntil: validUntilStr,- source: row.source,- context: row.context ?? undefined,- ...(row.claim_metric ? { claimMetric: row.claim_metric } : {}),- ...(row.claim_value != null ? { claimValue: Number(row.claim_value) } : {}),- ...(row.claim_unit ? { claimUnit: row.claim_unit } : {}),- ...(row.claim_period ? { claimPeriod: row.claim_period } : {}),- });- assignments.push({ id: row.id, row_num: rowNum });+ existingFence.facts.push(fenceRowOf(row, rowNum, oracle.claim));+ assignments.push({ id: row.id, row_num: rowNum, fact: oracle.claim });claimed.add(rowNum);}- return { body: replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts)), assignments };+ return { body: replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts)), assignments, rejected };+}++/** Keep the typed records and name the page once in `failed_pages` with the stable token; the rows stay as they are. */+function recordUnadoptable(outcome: UnfencedFactsOutcome, slug: string, records: UnadoptableFactRecord[]): void {+ if (records.length === 0) return;+ outcome.unadoptable_rows.push(...records);+ outcome.failed_pages.push(unadoptableRowsToken(slug, records));}/**@@ -244,6 +356,8 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promioutcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`);continue;}+ recordUnadoptable(outcome, entitySlug, fence.rejected);+ if (fence.assignments.length === 0) continue;const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);await submitFactFenceAdoption(engine, authority, entitySlug, {content: fence.body, expectedRevision: snapshot.revision,@@ -271,6 +385,8 @@ async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug:outcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`);return;}+ recordUnadoptable(outcome, entitySlug, fence.rejected);+ if (fence.assignments.length === 0) return;const durable = isDurabilityHardened(writeRoot);const prewrite = durable ? gitPathState(writeRoot, filePath) : 'clean';const tmpPath = `${filePath}.tmp`;@@ -294,11 +410,14 @@ async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug:await tx.refreshPageBody(entitySlug, sourceId, sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),existing.content_hash || contentHash(existing));}+ // The parsed claim is what the fence projects; the row keeps its id,+ // vectors and provenance (the reconcile would retire a row whose text+ // differs from its fence row).for (const a of fence.assignments) {await tx.executeRaw(- `UPDATE facts SET row_num = $1, source_markdown_slug = $2+ `UPDATE facts SET row_num = $1, source_markdown_slug = $2, fact = $5WHERE id = $3 AND source_id = $4 AND row_num IS NULL`,- [a.row_num, entitySlug, a.id, sourceId],+ [a.row_num, entitySlug, a.id, sourceId, a.fact],);}});@@ -314,6 +433,35 @@ async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug:}}+/**+ * Read-only (#6278): the rows of a plan the fence step would leave unadopted+ * and why, by location only, for doctor `fence_integrity`. Each page's body+ * is read the way the write path reads it (the database snapshot on a managed+ * brain, the canonical file otherwise) and planned without writing. A plan+ * the deadline cut short reports `complete: false`.+ */+export async function auditUnadoptableFacts(engine: BrainEngine, plan: UnfencedFactsPlan, opts: { deadline?: number } = {}):+ Promise<{ records: UnadoptableFactRecord[]; complete: boolean }> {+ const records: UnadoptableFactRecord[] = [];+ for (const [key, group] of plan.groups) {+ if (opts.deadline !== undefined && Date.now() > opts.deadline) return { records, complete: false };+ const [sourceId, entitySlug] = key.split('\0');+ let body: string;+ if (plan.managed) {+ const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });+ if (!snapshot) continue;+ body = serializePageToMarkdown(snapshot.page, snapshot.tags);+ } else {+ const filePath = plan.filePaths.get(key);+ if (!filePath || !existsSync(filePath)) continue;+ body = readFileSync(filePath, 'utf-8');+ }+ const fence = await planFence(engine, sourceId, entitySlug, body, group);+ if (!('warnings' in fence)) records.push(...fence.rejected);+ }+ return { records, complete: true };+}+/*** Fence every group of the plan through the brain's write path; fills* `plan.outcome`. A managed preflight or capacity refusal throws before anydiff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex d27d48fc07..57b05e0d82 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -7,7 +7,7 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { parseFactsFence } from '../facts-fence.ts';+import { normalizeClaimWhitespace, parseFactsFence } from '../facts-fence.ts';import { submissionAuthority, authorizeStoredRequest, authorizeWrite } from './authority.ts';import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';import { getWorktreeBinding, managedPersistenceEnabled, type WorktreeBinding } from './ownership.ts';@@ -288,10 +288,14 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,`A legacy fact on ${row.slug} in ${row.source_id} changed before fact-fence adoption request ${row.request_id} published; nothing was written. The next fact backfill run re-reads the facts and plans a fresh request.`,{ fix: receiptFix(row) });}+ // #6278: the fence codec trims and folds line endings, so the cell is+ // compared with the legacy text modulo that whitespace; the cell's text+ // is what the projection expects and is written back on apply.const cell = fence.get(assignment.row_num);- if (!cell?.active || cell.claim !== fact.value.fact || cell.visibility !== fact.value.visibility) {- throw opError('invalid_params', 'The adopted fence row does not render its legacy fact.',- `Fact-fence adoption request ${row.request_id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. The rendered fence does not match the facts it adopts, so report the request ID to the user rather than running the same backfill again.`,+ if (!cell?.active || cell.claim === '' || normalizeClaimWhitespace(cell.claim) !== normalizeClaimWhitespace(String(fact.value.fact))+ || cell.visibility !== fact.value.visibility) {+ throw opError('fence_unrenderable', 'The adopted fence row does not render its legacy fact.',+ `Fact-fence adoption request ${row.request_id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. Fence row ${assignment.row_num} does not read back as legacy fact ${assignment.id} (${!cell ? 'the row is missing from the rendered fence' : !cell.active ? 'it reads back struck' : cell.claim === '' ? 'it reads back empty' : cell.visibility !== fact.value.visibility ? 'its visibility differs' : 'its text differs by more than whitespace'}). This is a gbrain planning defect, not caller input: report the request ID with the gbrain version; the legacy fact stays active and searchable and nothing is lost.`,{ fix: receiptFix(row) });}}@@ -307,10 +311,13 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,return { ...prepared, validate: async tx => { await prepared.validate?.(tx); await check(tx, true); }, apply: async tx => {// Runs ahead of the page import and its canonical projection, so the// projection's expiry pass and insertFacts see the adopted positions.- const adopted = await tx.executeRaw(`UPDATE facts f SET row_num=a.row_num,source_markdown_slug=$2- FROM jsonb_to_recordset($3::text::jsonb) AS a(id integer,row_num integer)+ // The fence cell's parsed text is written back with the row number: the+ // projection expires any row whose (row_num, fact, visibility) differs from+ // its fence row and inserts a new one, which would lose the legacy id.+ const adopted = await tx.executeRaw(`UPDATE facts f SET row_num=a.row_num,source_markdown_slug=$2,fact=a.fact+ FROM jsonb_to_recordset($3::text::jsonb) AS a(id integer,row_num integer,fact text)WHERE f.source_id=$1 AND f.id=a.id AND f.row_num IS NULL RETURNING f.id`,- [row.source_id, row.slug, JSON.stringify(facts.map(({ id, row_num }) => ({ id, row_num })))]);+ [row.source_id, row.slug, JSON.stringify(facts.map(({ id, row_num }) => ({ id, row_num, fact: fence.get(row_num)!.claim })))]);if (adopted.length !== facts.length) throw opError('revision_conflict', 'A legacy fact was adopted by another run.',`Another run adopted a legacy fact on ${row.slug} in ${row.source_id} while request ${row.request_id} was publishing, so its transaction rolled back. Read the receipt with gbrain write-request -- ${row.request_id} for the final state before planning any new adoption.`,{ fix: receiptFix(row) });diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 7378d7435b..e08a5dfed3 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -19,6 +19,7 @@ export const WRITE_ERROR_CODES = ['invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline','core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only','timeline_rows_would_be_removed',+ 'fence_unrenderable',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/test/facts-fence-adoption-roundtrip.test.ts b/test/facts-fence-adoption-roundtrip.test.tsnew file mode 100644index 0000000000..9e791accc8--- /dev/null+++ b/test/facts-fence-adoption-roundtrip.test.ts@@ -0,0 +1,135 @@+/**+ * #6278 (2.1): the fence codec as the fact adoption's oracle.+ *+ * Protects: for 1,000 random fence rows, `adoptableClaim` either (a) accepts+ * the row and hands back a claim that equals the stored claim up to the+ * accepted whitespace normalization (trim at both ends, CRLF/CR → LF) and+ * that `renderFactsTable` → `parseFactsFence` reproduces exactly, together+ * with the row's kind, visibility, validity, source, notability, confidence+ * (as the fence writes it), context, typed-claim cells and active flag, or+ * (b) rejects it with the class that names what the codec changes; a row+ * whose stored claim already equals its parsed claim is always accepted, and+ * the known shapes (surrounding whitespace, whitespace-only, CRLF, lone CR,+ * NBSP, `~~x~~`, a literal `<br>`) land in their documented class.+ * Fails when: the oracle accepts a claim the fence would read back+ * differently (the projection would then expire the adopted row), rejects a+ * whitespace-only difference, mislabels a shape, or a column other than the+ * claim stops round-tripping.+ * Why existing coverage misses it: the fence tests round-trip hand-written+ * rows through the codec; nothing checks the adoption's acceptance rule+ * against the codec over random text.+ * Seams: none; pure functions.+ */+import { describe, expect, test } from 'bun:test';+import fc from 'fast-check';+import { normalizeClaimWhitespace, parseFactsFence, renderFactsTable, type ParsedFact } from '../src/core/facts-fence.ts';+import { adoptableClaim, type UnfencedFactRow, type UnrenderableClass } from '../src/core/facts/unfenced-facts.ts';++const NUM_RUNS = 1000;+const KINDS = ['event', 'preference', 'commitment', 'belief', 'fact'] as const;+const VISIBILITIES = ['private', 'world'] as const;+const NOTABILITIES = ['high', 'medium', 'low'] as const;++/** Claim text drawn from the characters the codec treats specially plus ordinary prose, unicode and emoji. */+const claimText = fc.array(fc.oneof(+ { weight: 6, arbitrary: fc.constantFrom(...'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,;:!?()[]{}"\'-_/#$%&*+=@') },+ { weight: 2, arbitrary: fc.constantFrom(' ', '\t', '\n', '\r\n', '\r', '\u00a0') },+ { weight: 1, arbitrary: fc.constantFrom('|', '\\', '`', '~~', '<br>', '<br/>', '<BR />', '~', '<', '>') },+ { weight: 1, arbitrary: fc.constantFrom('café', 'Zürich', '東京', 'мир', '🙂', '👩💻', '€1,200', '\u2028') },+), { minLength: 0, maxLength: 20 }).map(parts => parts.join(''));++const dateCell = fc.constantFrom('2024-01-01', '2026-02-05T13:45:12Z', '1999-12-31', '2026-10-07');+const sourceCell = fc.constantFrom('mcp:remember', 'linkedin', 'OH 2026-04-29', 'call notes', '', 'cli:think');+const contextCell = fc.option(fc.constantFrom('from a call', 'superseded later', 'note', 'a | pipe'), { nil: null });++const row = fc.record({+ fact: claimText,+ kind: fc.constantFrom(...KINDS),+ visibility: fc.constantFrom(...VISIBILITIES),+ notability: fc.constantFrom(...NOTABILITIES),+ confidence: fc.constantFrom(1, 0.9, 0.85, 0.5, 0.123, 0, 0.75),+ context: contextCell,+ valid_from: dateCell.map(d => new Date(d)),+ valid_until: fc.option(dateCell.map(d => new Date(d)), { nil: null }),+ source: sourceCell,+ claim_metric: fc.option(fc.constantFrom('mrr', 'team_size'), { nil: null }),+ claim_value: fc.option(fc.constantFrom(50000, 12, 2.5), { nil: null }),+ claim_unit: fc.option(fc.constantFrom('USD', 'people'), { nil: null }),+ claim_period: fc.option(fc.constantFrom('monthly', 'annual'), { nil: null }),+}) as fc.Arbitrary<Pick<UnfencedFactRow, 'fact' | 'kind' | 'visibility' | 'notability' | 'confidence' | 'context' | 'valid_from' | 'valid_until'+ | 'source' | 'claim_metric' | 'claim_value' | 'claim_unit' | 'claim_period'>>;++/** The fence row the adoption renders for a stored row, with the claim it decided on. */+function fenceRow(r: Parameters<typeof adoptableClaim>[0], claim: string): ParsedFact {+ const date = (d: Date) => d.toISOString().endsWith('T00:00:00.000Z') ? d.toISOString().slice(0, 10) : d.toISOString().replace(/\.\d{3}Z$/, 'Z');+ return { rowNum: 7, active: true, claim, kind: r.kind, confidence: r.confidence, visibility: r.visibility, notability: r.notability,+ validFrom: date(r.valid_from), validUntil: r.valid_until ? date(r.valid_until) : undefined, source: r.source, context: r.context ?? undefined,+ ...(r.claim_metric ? { claimMetric: r.claim_metric } : {}), ...(r.claim_value != null ? { claimValue: r.claim_value } : {}),+ ...(r.claim_unit ? { claimUnit: r.claim_unit } : {}), ...(r.claim_period ? { claimPeriod: r.claim_period } : {}) };+}++describe('fact adoption oracle over the fence codec (#6278)', () => {+ test(`${NUM_RUNS} random rows: an accepted claim round-trips every column exactly; a rejected one names what the codec changes`, () => {+ let accepted = 0, rejected = 0;+ fc.assert(fc.property(row, (r) => {+ const verdict = adoptableClaim(r);+ if ('rejected' in verdict) {+ rejected += 1;+ // Rejection is only ever about what the codec changes: the codec must indeed not hand the stored text back.+ const back = parseFactsFence(renderFactsTable([fenceRow(r, r.fact)])).facts[0];+ const unchanged = back !== undefined && back.active && back.claim !== '' && normalizeClaimWhitespace(back.claim) === normalizeClaimWhitespace(r.fact)+ && (back.source ?? '') === r.source;+ expect(unchanged).toBe(false);+ return;+ }+ accepted += 1;+ expect(normalizeClaimWhitespace(verdict.claim)).toBe(normalizeClaimWhitespace(r.fact));+ const desired = fenceRow(r, verdict.claim);+ const parsed = parseFactsFence(renderFactsTable([desired]));+ expect(parsed.warnings).toEqual([]);+ const back = parsed.facts[0]!;+ expect(back.claim).toBe(verdict.claim);+ expect(back.active).toBe(true);+ expect(back.kind).toBe(r.kind);+ expect(back.visibility).toBe(r.visibility);+ expect(back.notability).toBe(r.notability);+ expect(back.validFrom).toBe(desired.validFrom);+ expect(back.validUntil).toBe(desired.validUntil);+ expect(back.source ?? '').toBe(r.source);+ expect(back.context).toBe(desired.context);+ expect(back.confidence).toBe(Number(parseFloat(r.confidence.toFixed(2))));+ expect(back.claimMetric).toBe(desired.claimMetric);+ expect(back.claimValue).toBe(desired.claimValue);+ expect(back.claimUnit).toBe(desired.claimUnit);+ expect(back.claimPeriod).toBe(desired.claimPeriod);+ expect(back.rowNum).toBe(7);+ }), { numRuns: NUM_RUNS });+ // Both branches were exercised.+ expect(accepted).toBeGreaterThan(100);+ expect(rejected).toBeGreaterThan(20);+ });++ test('a stored claim the codec already hands back unchanged is always accepted as itself', () => {+ fc.assert(fc.property(row, (r) => {+ const back = parseFactsFence(renderFactsTable([fenceRow(r, r.fact)])).facts[0];+ fc.pre(back !== undefined && back.active && back.claim === r.fact && r.fact !== '');+ expect(adoptableClaim(r)).toEqual({ claim: r.fact });+ }), { numRuns: 300 });+ });++ test('the known shapes land in their documented class', () => {+ const base = { kind: 'fact' as const, visibility: 'world' as const, notability: 'high' as const, confidence: 0.9, context: null,+ valid_from: new Date('2024-01-01'), valid_until: null, source: 'linkedin', claim_metric: null, claim_value: null, claim_unit: null, claim_period: null };+ const cases: Array<[string, { claim: string } | { rejected: UnrenderableClass }]> = [+ ['x ', { claim: 'x' }], [' x', { claim: 'x' }], ['\tx', { claim: 'x' }], ['x\u00a0', { claim: 'x' }],+ ['a\r\nb', { claim: 'a\nb' }], ['a\rb', { claim: 'a\nb' }], ['a\nb', { claim: 'a\nb' }],+ ['a|b', { claim: 'a|b' }], ['a\\b', { claim: 'a\\b' }], ['`code`', { claim: '`code`' }], ['🙂 café', { claim: '🙂 café' }],+ [' ', { rejected: 'empty' }], ['', { rejected: 'empty' }],+ ['~~x~~', { rejected: 'struck' }], [' ~~x~~ ', { rejected: 'struck' }],+ ['a<br>b', { rejected: 'line_break_markup' }], ['a<BR />b', { rejected: 'line_break_markup' }],+ ];+ for (const [claim, expected] of cases) expect([claim, adoptableClaim({ ...base, fact: claim })]).toEqual([claim, expected]);+ // The one accepted difference between stored and parsed text is whitespace; a 1,200-character claim is fine.+ expect(adoptableClaim({ ...base, fact: 'y'.repeat(1200) })).toEqual({ claim: 'y'.repeat(1200) });+ });+});diff --git a/test/migrations-v0_32_2-managed.test.ts b/test/migrations-v0_32_2-managed.test.tsindex 9e263e691d..f941ddc265 100644--- a/test/migrations-v0_32_2-managed.test.ts+++ b/test/migrations-v0_32_2-managed.test.ts@@ -128,7 +128,8 @@ for (const backend of testBackends()) {const attempt = (assignments: Array<{ id: number; row_num: number }>) => submitFactFenceAdoption(engine, authority, LEGACY_FILE_SLUG,{ content, expectedRevision: snapshot.revision, assignments, file: true });await expect(attempt([{ id: seed.legacyFactIds[0], row_num: 1 }])).rejects.toMatchObject({ code: 'revision_conflict' });- await expect(attempt([{ id: seed.legacyFactIds[1], row_num: 1 }])).rejects.toMatchObject({ code: 'invalid_params' });+ // #6278: a fence row that does not read back as its legacy fact is a planning defect (class server), not caller input.+ await expect(attempt([{ id: seed.legacyFactIds[1], row_num: 1 }])).rejects.toMatchObject({ code: 'fence_unrenderable' });await expect(attempt([{ id: seed.legacyFactIds[0], row_num: 1 }, { id: seed.legacyFactIds[1], row_num: 1 }])).rejects.toMatchObject({ code: 'invalid_params' });expect(await factRows(engine, [...seed.legacyFactIds, seed.extractorFactId])).toEqual(before);