Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): fact-fence adoption no longer leaks, loops or blocks the source (#6650)

garrytanf5bbf53ac947
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 3546a75fbe..2c6f381fe8 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -77,7 +77,7 @@ of making a duplicate.
| <a id="purge_lookup_timeout"></a>`purge_lookup_timeout` | `purge_lookup_timeout` | A page purge (`gbrain delete <slug> --purge`) ran one of the journal lookups that still execute inside its publication transaction (the lookup of stored intents for the slug, the re-check of requests admitted after its preparation scan or pending at that scan, the locking read of the requests to redact) and that statement hit the transaction's 5-second statement budget on a large `persistence_requests` table. The request failed terminally instead of being released as `database_contention` and claimed again: nothing of the page was removed or tombstoned, nothing in the journal was redacted, and later writes to the source move again. Do not assume the requested content was erased. The substring search for the page's claims no longer runs here: it runs at preparation in bounded keyset chunks under the preparation budget, and a sweep that outruns that budget twice ends [`preparation_stalled`](#preparation_stalled) instead. A committed purge's receipt reports `journal_sweep` (`scanned`, `ceiling`, `tail`, `pending_rechecked`, `complete`); `complete: false` means a cap was hit (the 10,000-match cap or the tail bound) and some requests were not tested. | If the receipt says the slug index `persistence_requests_slug_intent` is missing or INVALID, run `gbrain repair request-indexes --apply` (the `persistence_request_slug_intent_index` migration builds it online; the index serves the slug lookup, not the substring sweep), then submit the purge again with a new `request_id`. Otherwise submit it again with a new `request_id` (a retry with the same id returns this failure); if it times out again, report the request id with the `persistence_request_indexes` and `persistence_request_growth` entries of `gbrain doctor --json`. |
| <a id="preparation_stalled"></a>`preparation_stalled` | `preparation_stalled` | The write's owner could not finish *preparing* it. Every write has a preparation budget (`persistence.sync_preparation_ms` for a managed sync member, `persistence.maintenance_preparation_ms` for every other managed kind, 120 s each; `remember`, `put_page` and `edit_page` keep 30 s), the owner releases the claim at the budget and tries again, and a request cut off `persistence.max_preparation_attempts` times (default 2; a process killed mid-preparation counts too) is finished `failed` with this code instead of being claimed again and holding the rest of its root. The receipt names the last recorded step and what it was waiting on (`git`, `fs`, `db`, `pool` or `unknown`); while the write was still running, `gbrain sources writer status --json` showed the same on `claim.stall` (`preparation_overdue`). The rest of the root keeps publishing. A **managed sync member** (an import, delete or rename of a file) is also **held**: the sync turns the failed receipt into a `preparation_stalled` hold and carries on, so the file is not imported until it is retried. The file is fine; this is the write owner stalling (a database or pool wait, a hung step), never a frontmatter or fence problem, so no repair applies. The hold's `message` names the request and the step; a held deletion keeps its page. A stalled hold re-screens by itself only when the gbrain version changes; a run that stalls many files in a row stops with [`preparation_systemic`](#preparation_systemic) instead of holding them all. A **foreground write** (`put_page`, `edit_page`, `remember`) or a **maintenance write** (fact-fence adoption, maintenance page writes) gets the terminal receipt only. The deadlines sit behind `persistence.preparation_deadlines` (`false` restores the old behaviour, where only `remember`, `put_page` and `edit_page` had a 30 s budget). | Run `gbrain sources writer status --source <source> --json` (read-only: the step, its wait cause, the owner process and its gbrain version), fix what it names (restart or upgrade an owner that predates deadlines, free the pool, let the lock holder finish), then for a sync hold run `gbrain sources retry-held <source>` and the same `gbrain sync` with the same options (the hold's `fix.then.then` and `retry-held` print it, for example `gbrain sync --source <source> --no-pull --no-embed`). When that sync still has a backlog to finish, it finishes it first and re-screens the scheduled files in the same invocation (the drain yields at the checkpoint and discovers again), so one run of the printed command clears the hold. A foreground write needs a new `request_id`; the next maintenance run submits its write again. Runbook: [catch-up stuck / held N files](troubleshooting.md#catch-up-stuck). |
| <a id="write_outcome_unknown"></a>`write_outcome_unknown` | `write_outcome_unknown` | The database session dropped while the write was being admitted (a pooler reap, a failover, `pg_terminate_backend`), and it kept dropping through the re-reads, so whether the write was accepted is unknown (#6355). A single drop never reaches you: the admission attempt is re-run after 100, 300 and 900 ms, and every attempt begins by reading the retained `request_id`, so a re-run replays an admitted row instead of admitting again. Before this code existed the raw socket error (`write CONNECTION_CLOSED …`, `57P01`) reached the caller while the write went on to commit, and a receipt oracle took it for a refusal. | Read the request first: `gbrain write-request -- <request_id>` or `get_write_request { request_id }` (the error's `fix` names it). A committed or pending row means the write was accepted: replay the same `request_id` to wait for it. No row means it was not: submit it again with the same `request_id`. Never resubmit under a new `request_id` without that read. |
-| <a id="fence_unrenderable"></a>`fence_unrenderable` | `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, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). 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="fence_unrenderable"></a>`fence_unrenderable` | `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, source and visibility the page already carries is left too (`duplicate_claim`; a private and a world row with one text are two facts and both adopt). 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. The planner runs the publisher's own read-back check on the whole rendered fence first, so such a page is reported as unadoptable (class `whole_fence`) instead of being submitted. A managed adoption this build already refused in the last day is not resubmitted (class `prior_refusal`; message `This gbrain build already refused the same fact-fence adoption.`); a different build, or this one a day later, retries it once. Unadopted rows hold only their own page: the phantom-redirect pass skips a phantom that owns one and redirects the others. To count what an older build left in the writer table, run `scripts/diagnose/fence-adoption-census.sql` (read-only). | 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="reconcile-private-facts"></a>reconcile private facts | `permission_denied` | `gbrain sources reconcile --apply` (and its preview) found a `## Facts` row that would edit, renumber or change the visibility of a stored private fact, copy a stored private claim into a row under another visibility, or copy a stored private row's context (24 characters or longer) verbatim into a world row. A row is identified by its row number and claim, so a world row that only shares a private row's claim is not a private row and publishes. The refusal names the row number, never its text. It guards against verbatim copies only; reworded text is not detected, so it is not a confidentiality proof. Sources are not compared, because rows share provenance such as "Slack import". Nothing was written. | Read the stored page with the printed `gbrain get --source <id> -- <slug>`, keep the named row as stored in the file (or remove the copied text), then run a fresh `gbrain sources reconcile <id> <slug> --preview` and apply it. Change private facts with `remember` and `forget`. |
| <a id="maintenance_backpressure"></a>`maintenance_backpressure` (exit 12) | `maintenance_backpressure` | A managed maintenance run (`gbrain extract-conversation-facts`, its cycle phase or job) publishes each page as its own request, under the same local CLI writer your own CLI writes use. Before the run it counts the requests the whole run plans; before each page's model work it checks again. It stops admitting once the writer's outstanding requests, reserved receipt bytes (`persistence.limits.principal_terminal_bytes`; each request reserves 16 KiB until its receipt compacts after the retention window) or permanent request ids (`persistence.limits.principal_lifetime_ids`; never freed) would pass 80% of their limit, so the last 20% stays free for your other writes. The message names the resource. Pages already published keep their facts and nothing is half-written. | Outstanding requests: read them with `gbrain sources writer status --source <id> --json`; a resident `gbrain serve`, or the next CLI run, publishes them, then rerun the same command. Receipt bytes or request ids: run the smaller batch the message prints (`gbrain extract-conversation-facts --source-id <id> --limit <n>`), or wait for receipts to compact; raising the named `persistence.limits.*` key is the user's call. |
diff --git a/scripts/diagnose/fence-adoption-census.sql b/scripts/diagnose/fence-adoption-census.sql
new file mode 100644
index 0000000000..2ffe655212
--- /dev/null
+++ b/scripts/diagnose/fence-adoption-census.sql
@@ -0,0 +1,54 @@
+-- #6650: read-only census of failed fact-fence adoptions in the writer table.
+--
+-- Answers: how many failed adoption requests exist, which gbrain builds
+-- admitted them, whether any are still being minted, and how many of their
+-- pages still hold legacy (unfenced) facts. It writes nothing.
+--
+-- Run on the brain host against the brain's database, for example:
+-- psql "$GBRAIN_DATABASE_URL" -v source=default -f scripts/diagnose/fence-adoption-census.sql
+--
+-- Compacted receipts (older than the receipt retention window) keep their
+-- code but lose their message and intent; they are counted as `compacted`
+-- and grouped by code only. The refusal sub-reason (missing / struck / empty /
+-- visibility / text) was never stored on the row, so this census cannot
+-- reconstruct it; re-run the facts backfill on the current build and read
+-- `gbrain doctor` fence_integrity for today's reasons.
+
+BEGIN READ ONLY;
+
+\echo 'Failed adoptions by build, code and message'
+SELECT r.admitter_version,
+ r.error_code,
+ CASE WHEN r.compacted THEN '(compacted)' ELSE r.error_message END AS message,
+ count(*) AS failed_requests,
+ count(DISTINCT r.slug) AS distinct_pages,
+ min(r.completed_at) AS first_seen,
+ max(r.completed_at) AS last_seen,
+ count(*) FILTER (WHERE r.completed_at > now() - interval '24 hours') AS last_24h
+ FROM persistence_requests r
+ WHERE r.source_id = :'source'
+ AND r.state = 'failed'
+ AND (r.intent->>'kind' = 'managed_maintenance_adopt_fact_fence'
+ OR r.error_message = 'The adopted fence row does not render its legacy fact.'
+ OR r.error_code = 'fence_unrenderable')
+ GROUP BY 1, 2, 3
+ ORDER BY last_seen DESC;
+
+\echo 'Pages with failed adoptions: how many still hold legacy (unfenced) facts'
+WITH failed AS (
+ SELECT DISTINCT r.slug
+ FROM persistence_requests r
+ WHERE r.source_id = :'source'
+ AND r.state = 'failed'
+ AND (r.intent->>'kind' = 'managed_maintenance_adopt_fact_fence'
+ OR r.error_message = 'The adopted fence row does not render its legacy fact.'
+ OR r.error_code = 'fence_unrenderable')
+)
+SELECT count(*) AS pages_with_failures,
+ count(*) FILTER (WHERE EXISTS (
+ SELECT 1 FROM facts f
+ WHERE f.source_id = :'source' AND f.entity_slug = failed.slug
+ AND f.row_num IS NULL AND f.expired_at IS NULL AND f.dimension IS NULL)) AS pages_still_holding_legacy_facts
+ FROM failed;
+
+ROLLBACK;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index af6a92d5ff..a16bdf54f0 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -541,6 +541,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// #6574 (publication round trips). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.209.0', text: 'Publishing a page now writes its timeline rows, fact rows, fact field refreshes and take resolutions in a few set-based statements (one per 500 rows) instead of one statement per row, and `insertFacts` inserts in multi-row chunks for every caller. A large page no longer needs thousands of round trips, so it publishes inside `persistence.publication_ceiling_ms` behind a transaction-mode pooler with pipelining off. A projection that takes 30 s or more logs `[persistence] phase=publication reason=slow_projection` with its row counts and per-step milliseconds.' },
{ since: '0.60.209.0', text: 'Before a publish opens its transaction, the consumer now commits one claim renewal that stamps the request `publishing` and leases it for the publication ceiling plus its grace, and stops renewing until the publish ends. A long publish no longer reads as a lapsed claim, so `gbrain sync` no longer stops `drain_stalled` with `owner_missing` while the publish is still working; a publish past the ceiling still reports `publication_overdue`. An owner that crashes mid-publish now holds its head until that lease runs out (the ceiling plus about 70 s) rather than 30 s.' },
+ // #6650 (fact-fence adoption exits). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.214.0', text: 'Fencing a legacy fact into a fence row a partial earlier run left behind now rebuilds that row from the stored fact: the published row carries the fact\'s own visibility, kind, validity, confidence and speaker attribution instead of the leftover cell\'s, a leftover private row is never reused for a world fact (the world fact gets its own row), and a newly fenced fact keeps its `attributed_to`. Before, a leftover world row could publish a private fact as world and a leftover row could overwrite the fact\'s kind and dates.' },
+ { since: '0.60.214.0', text: 'A managed fact-fence adoption refused as a planning defect (`fence_unrenderable`) is no longer resubmitted every cycle: for a day after the refusal the page is reported as unadoptable (`prior_refusal`), then it gets one more try, or right away once the adoption planner changes. The writer stops collecting one identical failed request per page per cycle.' },
+ { since: '0.60.214.0', text: 'The `extract_facts` phantom-redirect pass no longer waits for the whole source to have no unfenced legacy fact rows: it holds only the phantom pages that own such rows (`held_legacy_rows` in the pass result) and redirects the rest.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index ea8e923338..4338265771 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -847,7 +847,7 @@ export async function runExtractFacts(
: 'could not be fenced this run, so those pages keep their fact index and skip reconciliation while the other pages reconcile. ' +
'The FACTS_FENCE_FAILED warnings name each page and why; ' +
'a page whose canonical file does not exist on this host is fenced by the cycle on the host that holds the file; ' +
- 'a row the fence codec cannot render stays active and searchable (doctor fence_integrity lists it); the phantom-redirect pass waits until the source has no unfenced rows. ' +
+ 'a row the fence codec cannot render stays active and searchable (doctor fence_integrity lists it); the phantom-redirect pass holds only the phantoms that own such rows. ' +
'Individual rows can instead be drained via `forget_fact`.'),
);
// #3683: a guard-triggered run books its halt here for doctor
@@ -875,10 +875,11 @@ export async function runExtractFacts(
// IS NOT NULL` so a half-redirected page (soft-deleted, .md still on
// disk) won't be re-redirected.
// #6278: the pass moves rows by their fence position and would strand a
- // legacy row (no position) on a deleted phantom, so it still waits for the
- // whole source to be fenced; the reconcile walk below is per page.
+ // legacy row (no position) on a deleted phantom. #6650: only the phantoms
+ // that own legacy rows are held, so one unadoptable row no longer stops
+ // the pass for the whole source.
let phantomResult: PhantomPassResult = emptyPhantomPassResult();
- if (opts.brainDir && legacyCount === 0) {
+ if (opts.brainDir) {
try {
phantomResult = await runPhantomRedirectPass(
engine,
@@ -886,6 +887,7 @@ export async function runExtractFacts(
sourceId,
opts.dryRun ?? false,
opts.signal,
+ legacySlugs,
);
} catch (e) {
// The pass owns its own per-phantom try/catch; reaching this catch
diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.ts
index 1f81f3bb1c..afe33fa55c 100644
--- a/src/core/cycle/phantom-redirect.ts
+++ b/src/core/cycle/phantom-redirect.ts
@@ -85,6 +85,8 @@ export interface PhantomPassResult {
skipped_drift: number;
no_canonical: number;
not_phantom: number;
+ /** #6650: phantoms held this pass because they still own legacy (unfenced) fact rows. */
+ held_legacy_rows: number;
/** True iff the pass was skipped wholesale because the writer lock was busy. */
lock_busy: boolean;
/** True iff more phantoms exist than the per-cycle cap — caller surfaces to operator. */
@@ -119,6 +121,7 @@ export function emptyPhantomPassResult(): PhantomPassResult {
skipped_drift: 0,
no_canonical: 0,
not_phantom: 0,
+ held_legacy_rows: 0,
lock_busy: false,
more_pending: false,
touched_canonicals: [],
@@ -659,6 +662,7 @@ export async function runPhantomRedirectPass(
sourceId: string,
dryRun: boolean,
signal?: AbortSignal,
+ holdSlugs: ReadonlySet<string> = new Set(),
): Promise<PhantomPassResult> {
const result = emptyPhantomPassResult();
const limitRaw = process.env.GBRAIN_PHANTOM_REDIRECT_LIMIT;
@@ -698,6 +702,10 @@ export async function runPhantomRedirectPass(
// #1972: bail between phantoms on abort (each is independently committed).
if (isAborted(signal)) break;
const slug = rows[i].slug;
+ // #6650: a phantom that still owns legacy (unfenced) fact rows is held:
+ // the redirect moves rows by fence position and would strand them on
+ // the deleted phantom. Every other phantom of the source proceeds.
+ if (holdSlugs.has(slug)) { result.held_legacy_rows += 1; continue; }
const page = await engine.getPage(slug, { sourceId });
if (!page) continue;
result.scanned += 1;
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index b84f59b62a..aa2f6a7998 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -398,6 +398,22 @@ export function normalizeClaimWhitespace(text: string): string {
return text.replace(/\r\n?/g, '\n').trim();
}
+/**
+ * #6650: why a parsed fence cell does not read back as the legacy fact the
+ * fact-fence adoption assigns to it, or null when it does. The planner runs it
+ * on the whole fence it renders and the publisher re-checks it before
+ * adopting, so the two can never disagree.
+ */
+export function fenceCellReadBackProblem(cell: ParsedFact | undefined, fact: { fact: string; visibility: string }):
+ 'row_missing' | 'struck' | 'empty' | 'visibility' | 'text' | null {
+ if (!cell) return 'row_missing';
+ if (!cell.active) return 'struck';
+ if (cell.claim === '') return 'empty';
+ if (cell.visibility !== fact.visibility) return 'visibility';
+ if (normalizeClaimWhitespace(cell.claim) !== normalizeClaimWhitespace(fact.fact)) return 'text';
+ return null;
+}
+
/**
* 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 other
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index ec92eb30d4..40a0274940 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -56,7 +56,7 @@ 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, normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type ParsedFact } from '../facts-fence.ts';
+import { fenceCellReadBackProblem, formatFenceDate, normalizeClaimWhitespace, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, type FactAttribution, 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';
@@ -64,7 +64,7 @@ import { withPageLock } from '../page-lock.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { assertLifetimeIdHeadroom } from '../persistence/journal.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
-import { maintenancePreflight, submitFactFenceAdoption, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { maintenancePreflight, planFactFenceAdoption, submitPlannedFactFenceAdoption, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { contentHash } from '../utils.ts';
import { resolvePageWriteTarget } from '../write-through.ts';
import { commitFactFenceFile, gitPathState } from './fence-write.ts';
@@ -86,6 +86,8 @@ export interface UnfencedFactRow {
claim_value: number | null;
claim_unit: string | null;
claim_period: string | null;
+ /** Speaker attribution; the fence carries it in its 15th column, so adoption keeps it. */
+ attributed_to?: FactAttribution | null;
page_exists: boolean;
}
@@ -113,9 +115,13 @@ export interface UnfencedFactsOutcome {
* 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).
+ * single-row fence does not parse at all), `whole_fence` (the row passes alone
+ * but does not read back from the page's whole rendered fence; the page
+ * submits nothing), `prior_refusal` (a managed adoption of the same inputs was
+ * already refused by this gbrain build; a later build retries it once).
*/
-export type UnrenderableClass = 'empty' | 'struck' | 'line_break_markup' | 'claim' | 'kind' | 'visibility' | 'validity' | 'source' | 'parse';
+export type UnrenderableClass = 'empty' | 'struck' | 'line_break_markup' | 'claim' | 'kind' | 'visibility' | 'validity' | 'source' | 'parse'
+ | 'whole_fence' | 'prior_refusal';
/** One legacy row left unadopted, by location only: the claim text is never copied into a diagnostic. */
export interface UnadoptableFactRecord {
@@ -149,6 +155,7 @@ function fenceRowOf(row: UnfencedFactRow, rowNum: number, claim: string): Parsed
...(row.claim_value != null ? { claimValue: Number(row.claim_value) } : {}),
...(row.claim_unit ? { claimUnit: row.claim_unit } : {}),
...(row.claim_period ? { claimPeriod: row.claim_period } : {}),
+ ...(row.attributed_to ? { attributedTo: row.attributed_to } : {}),
};
}
@@ -215,7 +222,7 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:
const rows = await engine.executeRaw<UnfencedFactRow>(
`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,
+ claim_metric, claim_value, claim_unit, claim_period, attributed_to,
EXISTS (SELECT 1 FROM pages p WHERE p.source_id = f.source_id
AND p.slug = f.entity_slug AND p.deleted_at IS NULL) AS page_exists
FROM facts f
@@ -302,16 +309,23 @@ export async function planFence(engine: BrainEngine, sourceId: string, entitySlu
continue;
}
planned.add(key);
- const existing = existingFence.facts.find(f => {
+ // #6650: a leftover cell is reused only when re-rendering it from the
+ // legacy row cannot widen its visibility (a private cell never becomes
+ // world), and it is re-rendered from the row: publication refreshes the
+ // fact's kind, validity and metadata from its fence cell, so a stale
+ // cell would otherwise overwrite them.
+ const existingAt = existingFence.facts.findIndex(f => {
const owner = occupied.get(f.rowNum);
return f.active && !claimed.has(f.rowNum) && f.claim === oracle.claim &&
- (f.source ?? '') === (row.source ?? '') &&
+ (f.source ?? '') === (row.source ?? '') && (f.visibility === row.visibility || row.visibility === 'private') &&
(!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, fact: oracle.claim });
- claimed.add(existing.rowNum);
+ if (existingAt >= 0) {
+ const at = existingFence.facts[existingAt].rowNum;
+ const rowNum = occupied.has(at) ? nextRowNum++ : at;
+ existingFence.facts[existingAt] = fenceRowOf(row, rowNum, oracle.claim);
+ assignments.push({ id: row.id, row_num: rowNum, fact: oracle.claim });
+ claimed.add(rowNum);
continue;
}
const rowNum = nextRowNum++;
@@ -319,7 +333,18 @@ export async function planFence(engine: BrainEngine, sourceId: string, entitySlu
assignments.push({ id: row.id, row_num: rowNum, fact: oracle.claim });
claimed.add(rowNum);
}
- return { body: replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts)), assignments, rejected };
+ const rendered = replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts));
+ if (assignments.length === 0) return { body: rendered, assignments, rejected };
+ // #6650: the page is published only when every assignment reads back from
+ // the whole rendered fence the way the publisher will check it.
+ const readBack = parseFactsFence(rendered);
+ const cells = new Map(readBack.facts.map(f => [f.rowNum, f]));
+ const byId = new Map(group.map(row => [row.id, row]));
+ if (readBack.warnings.length > 0 || assignments.some(a => fenceCellReadBackProblem(cells.get(a.row_num), byId.get(a.id)!) !== null)) {
+ return { body, assignments: [], rejected: [...rejected, ...assignments.map(a => ({ source_id: sourceId, slug: entitySlug, fact_id: Number(a.id),
+ reason: 'fence_unrenderable' as const, class: 'whole_fence' as const }))] };
+ }
+ return { body: rendered, assignments, rejected };
}
/** Keep the typed records and name the page once in `failed_pages` with the stable token; the rows stay as they are. */
@@ -359,14 +384,20 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi
outcome.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, {
+ if (fence.assignments.length === 0) { recordUnadoptable(outcome, entitySlug, fence.rejected); continue; }
+ const request = await planFactFenceAdoption(engine, authority, entitySlug, {
content: fence.body, expectedRevision: snapshot.revision,
assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })),
- file: Boolean(snapshot.page.source_path) || snapshot.page.source_uri?.startsWith('file:') === true || (target.ok && existsSync(target.filePath)),
});
+ if (request.kind === 'suppressed') {
+ recordUnadoptable(outcome, entitySlug, [...fence.rejected, ...fence.assignments.map(a => ({ source_id: sourceId, slug: entitySlug,
+ fact_id: Number(a.id), reason: 'fence_unrenderable' as const, class: 'prior_refusal' as const }))]);
+ continue;
+ }
+ recordUnadoptable(outcome, entitySlug, fence.rejected);
+ const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
+ await submitPlannedFactFenceAdoption(engine, authority, entitySlug, request,
+ Boolean(snapshot.page.source_path) || snapshot.page.source_uri?.startsWith('file:') === true || (target.ok && existsSync(target.filePath)));
outcome.fenced += fence.assignments.length;
outcome.pages_touched += 1;
outcome.fenced_slugs.push(entitySlug);
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index 0a56a6a7e8..ff0fd0fcd2 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -10,7 +10,7 @@ import type { Action } from '../agent-output.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { fenceOperationError, scanCanonicalFences } from '../fence-repair/refusal.ts';
-import { normalizeClaimWhitespace, parseFactsFence } from '../facts-fence.ts';
+import { fenceCellReadBackProblem, 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';
@@ -41,7 +41,7 @@ function ownerStatusFix(sourceId: string): Action {
{ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
}
-function receiptFix(row: WriteRequest): Action {
+function receiptFix(row: Pick<WriteRequest, 'request_id'>): Action {
return readFix('The receipt is the record of what this maintenance request did; read it before planning another.',
{ argv: ['gbrain', 'write-request', '--', row.request_id] });
}
@@ -295,21 +295,72 @@ export interface FactFenceAssignment { id: number; row_num: number; hash: string
* and adopt the legacy rows in place, so the canonical projection matches
* them by (source, page, row_num) instead of inserting duplicates.
*/
-export async function submitFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
- options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; file: boolean }): Promise<Record<string, unknown>> {
+const MALFORMED_ADOPTION = 'A fact adoption assigns one fact or fence position twice.';
+/**
+ * The fact-fence adoption planner's revision, part of every adoption intent
+ * and so of its request identity: bump it when the planner or the publisher's
+ * read-back check changes, and every held-back page gets a fresh attempt.
+ */
+export const FACT_FENCE_PLANNER = 2;
+/** How long a refused adoption is held back; the owner that refused it may since have restarted onto code that adopts it. */
+const ADOPTION_REFUSAL_HOLD_MS = 24 * 60 * 60 * 1000;
+
+/** The refusals a fact-fence adoption gets again for the same inputs (#6650). */
+function deterministicAdoptionRefusal(prior: Pick<WriteRequest, 'error_code' | 'error_message'>): boolean {
+ return prior.error_code === 'fence_unrenderable' || (prior.error_code === 'invalid_params' && prior.error_message === MALFORMED_ADOPTION);
+}
+
+/** What `planFactFenceAdoption` decided: submit (or replay) `requestId`, or skip because this build already refused these inputs. */
+export type FactFenceAdoptionPlan =
+ | { kind: 'submit'; requestId: string; intent: Record<string, unknown> }
+ | { kind: 'suppressed'; prior: WriteRequest };
+
+/**
+ * Choose the request for one page's adoption. A pending or committed receipt
+ * for the same inputs is replayed. After a terminal refusal the same inputs
+ * get a fresh attempt identity (a drifted file, a conflict), except a
+ * deterministic refusal of the same intent (same planner revision) in the
+ * last day: retrying it would only mint another identical failed request
+ * every cycle, so the page waits a day or a planner change.
+ */
+export async function planFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
+ options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }> }): Promise<FactFenceAdoptionPlan> {
const current = await readFacts(engine, authority.writer.sourceId, options.assignments.map(a => a.id));
const facts: FactFenceAssignment[] = options.assignments.map(a => ({ ...a, hash: digest(current.find(f => f.id === a.id)?.value ?? null) }));
const intent = { kind: 'managed_maintenance_adopt_fact_fence', expected_revision: options.expectedRevision,
- source_incarnation: authority.writer.sourceIncarnation, content: options.content, facts };
- // A retry replays a pending or committed receipt; after a terminal refusal
- // (a drifted file, a conflict) the same inputs get a fresh attempt identity.
+ source_incarnation: authority.writer.sourceIncarnation, content: options.content, facts, planner: FACT_FENCE_PLANNER };
for (let attempt = 0; ; attempt++) {
const requestId = maintenanceRequestId({ authority: authority.writer, slug, intent, ...(attempt ? { attempt } : {}) });
const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
- if (!prior || prior.state === 'committed' || !isTerminal(prior)) return submitMaintenance(engine, authority, slug, intent, requestId, options.file);
+ if (!prior || prior.state === 'committed' || !isTerminal(prior)) return { kind: 'submit', requestId, intent };
+ if (prior.state === 'failed' && deterministicAdoptionRefusal(prior)
+ && Date.now() - new Date(prior.completed_at ?? prior.updated_at).getTime() < ADOPTION_REFUSAL_HOLD_MS) {
+ return { kind: 'suppressed', prior };
+ }
}
}
+export async function submitPlannedFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
+ plan: Extract<FactFenceAdoptionPlan, { kind: 'submit' }>, file: boolean): Promise<Record<string, unknown>> {
+ return submitMaintenance(engine, authority, slug, plan.intent, plan.requestId, file);
+}
+
+export async function submitFactFenceAdoption(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
+ options: { content: string; expectedRevision: string; assignments: Array<{ id: number; row_num: number }>; file: boolean }): Promise<Record<string, unknown>> {
+ const plan = await planFactFenceAdoption(engine, authority, slug, options);
+ if (plan.kind === 'suppressed') {
+ throw opError('fence_unrenderable', 'The same fact-fence adoption was already refused.',
+ `Fact-fence adoption request ${plan.prior.request_id} for ${slug} was refused with ${plan.prior.error_code} for the same inputs in the last day, so it was not submitted again; nothing changed. It is retried once a day has passed, or right away by a gbrain build whose adoption planner changed.`,
+ { fix: receiptFix(plan.prior) });
+ }
+ return submitPlannedFactFenceAdoption(engine, authority, slug, plan, options.file);
+}
+
+const READ_BACK_TEXT: Record<NonNullable<ReturnType<typeof fenceCellReadBackProblem>>, string> = {
+ row_missing: 'the row is missing from the rendered fence', struck: 'it reads back struck', empty: 'it reads back empty',
+ visibility: 'its visibility differs', text: 'its text differs by more than whitespace',
+};
+
/**
* `clock` (#6278): the claim's phase clock; the adoption's await boundaries (read facts, parse, occupied rows, the page) name
* their step, and its preparation reads of `facts` run bounded by the remaining budget (`boundedReads`).
@@ -322,7 +373,7 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
`Source ${row.source_id} was replaced after fact-fence adoption request ${row.request_id} for ${row.slug} was accepted, so nothing was published. Read the receipt with gbrain write-request -- ${row.request_id}; the next fact backfill run plans against the current source.`,
{ fix: receiptFix(row) });
if (new Set(facts.map(f => f.id)).size !== facts.length || new Set(facts.map(f => f.row_num)).size !== facts.length) {
- throw opError('invalid_params', 'A fact adoption assigns one fact or fence position twice.',
+ throw opError('invalid_params', MALFORMED_ADOPTION,
`Fact-fence adoption request ${row.request_id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. The plan itself is malformed, so report the request ID to the user rather than running the same backfill again.`,
{ fix: receiptFix(row) });
}
@@ -343,11 +394,10 @@ async function prepareFactFenceAdoption(unbounded: BrainEngine, row: WriteReques
// #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 === '' || normalizeClaimWhitespace(cell.claim) !== normalizeClaimWhitespace(String(fact.value.fact))
- || cell.visibility !== fact.value.visibility) {
+ const problem = fenceCellReadBackProblem(fence.get(assignment.row_num), { fact: String(fact.value.fact), visibility: String(fact.value.visibility) });
+ if (problem) {
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.`,
+ `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} (${READ_BACK_TEXT[problem]}). 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) });
}
}
diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.ts
new file mode 100644
index 0000000000..4c33020591
--- /dev/null
+++ b/test/fact-fence-adoption-exits.test.ts
@@ -0,0 +1,190 @@
+/**
+ * #6650: the fact-fence adoption no longer leaks, loops or blocks.
+ *
+ * Protects:
+ * - A leftover fence cell the adoption reuses is re-rendered from the legacy
+ * row, so a stale world cell never publishes a private legacy fact as world
+ * and a stale cell never overwrites the fact's kind or validity; a private
+ * cell is never widened to world (the world row appends instead).
+ * - Planner and publisher share one read-back predicate.
+ * - A deterministic refusal of the same intent is not resubmitted within a
+ * day, so cycles stop minting identical failed requests; a day later, or a
+ * changed adoption planner, retries once.
+ * - One unadoptable legacy row no longer stops the phantom-redirect pass for
+ * the whole source; only a phantom that owns legacy rows is held.
+ * Seams: planFence against an engine stub, the managed-brain helper for the
+ * coordinator path, PGLite for the extract_facts cycle.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+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 { planFence, 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, submitFactFenceAdoption } from '../src/core/persistence/prepared-maintenance.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { LEGACY_FILE_SLUG, seedLegacyManagedContent, type LegacySeed } from './helpers/managed-legacy-fixture.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUG = 'people/alice-example';
+const noOccupiedRows = { executeRaw: async () => [] } as unknown as BrainEngine;
+
+function legacyRow(overrides: Partial<UnfencedFactRow> = {}): UnfencedFactRow {
+ return { id: '41', source_id: 'default', entity_slug: SLUG, fact: 'Alice example moved to Lisbon', kind: 'fact', visibility: 'private',
+ notability: 'medium', context: null, valid_from: new Date('2026-02-05T00:00:00Z'), valid_until: null, source: 'mcp:remember',
+ confidence: 0.9, claim_metric: null, claim_value: null, claim_unit: null, claim_period: null, page_exists: true, ...overrides };
+}
+
+/** A page whose fence holds a leftover row (no database owner) with the legacy claim, as a partial earlier run leaves it. */
+function pageWithLeftover(cell: Partial<ParsedFact>): string {
+ return replaceOrInsertFactsFence('# Alice Example\n\nProse.\n', renderFactsTable([{ rowNum: 3, active: true, claim: 'Alice example moved to Lisbon',
+ kind: 'fact', confidence: 0.9, visibility: 'world', notability: 'medium', validFrom: '2026-02-05', source: 'mcp:remember', ...cell }]));
+}
+
+describe('planFence reuses a leftover cell without widening or overwriting it (#6650)', () => {
+ test('a stale world cell for a private legacy fact publishes exactly one private row at that position', async () => {
+ const plan = await planFence(noOccupiedRows, 'default', SLUG, pageWithLeftover({ visibility: 'world' }), [legacyRow()]);
+ if ('warnings' in plan) throw new Error(plan.warnings.join('; '));
+ expect(plan.assignments).toEqual([{ id: '41', row_num: 3, fact: 'Alice example moved to Lisbon' }]);
+ const rows = parseFactsFence(plan.body).facts;
+ expect(rows.map(f => [f.rowNum, f.claim, f.visibility])).toEqual([[3, 'Alice example moved to Lisbon', 'private']]);
+ });
+
+ test('a stale cell does not overwrite the legacy fact\'s kind, validity or confidence', async () => {
+ const plan = await planFence(noOccupiedRows, 'default', SLUG,
+ pageWithLeftover({ visibility: 'private', kind: 'belief', validFrom: '2020-01-01', confidence: 0.2 }), [legacyRow()]);
+ if ('warnings' in plan) throw new Error(plan.warnings.join('; '));
+ const [cell] = parseFactsFence(plan.body).facts;
+ expect(cell).toMatchObject({ rowNum: 3, kind: 'fact', validFrom: '2026-02-05', confidence: 0.9, visibility: 'private' });
+ });
+
+ test('a private cell is never reused for a world legacy fact: it stays private and the world row appends', async () => {
+ const plan = await planFence(noOccupiedRows, 'default', SLUG, pageWithLeftover({ visibility: 'private' }), [legacyRow({ visibility: 'world' })]);
+ if ('warnings' in plan) throw new Error(plan.warnings.join('; '));
+ expect(plan.assignments).toEqual([{ id: '41', row_num: 4, fact: 'Alice example moved to Lisbon' }]);
+ expect(parseFactsFence(plan.body).facts.map(f => [f.rowNum, f.visibility])).toEqual([[3, 'private'], [4, 'world']]);
+ });
+
+ test('a legacy fact keeps its speaker attribution through the fence (fresh and reused rows)', async () => {
+ const fresh = await planFence(noOccupiedRows, 'default', SLUG, '# Alice Example\n', [legacyRow({ attributed_to: 'user' })]);
+ const reused = await planFence(noOccupiedRows, 'default', SLUG, pageWithLeftover({ visibility: 'private' }), [legacyRow({ attributed_to: 'assistant' })]);
+ if ('warnings' in fresh || 'warnings' in reused) throw new Error('unexpected fence warnings');
+ expect(parseFactsFence(fresh.body).facts.map(f => f.attributedTo)).toEqual(['user']);
+ expect(parseFactsFence(reused.body).facts.map(f => f.attributedTo)).toEqual(['assistant']);
+ });
+
+ test('the shared read-back predicate names each mismatch', () => {
+ const cell: ParsedFact = { rowNum: 1, active: true, claim: ' a\r\nb ', kind: 'fact', confidence: 1, visibility: 'world', notability: 'high' };
+ expect(fenceCellReadBackProblem(cell, { fact: 'a\nb', visibility: 'world' })).toBeNull();
+ expect(fenceCellReadBackProblem(undefined, { fact: 'a', visibility: 'world' })).toBe('row_missing');
+ expect(fenceCellReadBackProblem({ ...cell, active: false }, { fact: 'a\nb', visibility: 'world' })).toBe('struck');
+ expect(fenceCellReadBackProblem({ ...cell, claim: '' }, { fact: '', visibility: 'world' })).toBe('empty');
+ expect(fenceCellReadBackProblem(cell, { fact: 'a\nb', visibility: 'private' })).toBe('visibility');
+ expect(fenceCellReadBackProblem(cell, { fact: 'a b', visibility: 'world' })).toBe('text');
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: a refused adoption is resubmitted once a day or on a planner change, not once per cycle`, async () => {
+ let seed!: LegacySeed;
+ await managedBrain(async ({ engine }) => {
+ const authority = (await maintenancePreflight(engine, 'default'))!;
+ const snapshot = (await engine.readPageSnapshot(LEGACY_FILE_SLUG, { sourceId: 'default' }))!;
+ // Fence row 1 does not read back as legacy fact 1: the publisher refuses it as a planning defect.
+ const content = replaceOrInsertFactsFence(serializePageToMarkdown(snapshot.page, snapshot.tags), renderFactsTable([
+ { rowNum: 1, claim: 'Alice example founded Acme example', kind: 'fact', confidence: 0.9, visibility: 'world', notability: 'high', active: true }]));
+ const attempt = () => submitFactFenceAdoption(engine, authority, LEGACY_FILE_SLUG,
+ { content, expectedRevision: snapshot.revision, assignments: [{ id: seed.legacyFactIds[1], row_num: 1 }], file: true });
+ const failed = async () => (await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM persistence_requests WHERE slug=$1 AND state='failed' AND error_code='fence_unrenderable'`, [LEGACY_FILE_SLUG]))[0].n;
+
+ await expect(attempt()).rejects.toMatchObject({ code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.' });
+ await expect(attempt()).rejects.toMatchObject({ code: 'fence_unrenderable', message: 'The same fact-fence adoption was already refused.' });
+ await expect(attempt()).rejects.toMatchObject({ code: 'fence_unrenderable', message: 'The same fact-fence adoption was already refused.' });
+ expect(await failed()).toBe(1);
+
+ // Once a day has passed it is retried once (the owner that refused it may have restarted onto newer code).
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw(`UPDATE persistence_requests SET completed_at=now()-interval '25 hours' WHERE slug=$1 AND state='failed'`, [LEGACY_FILE_SLUG]);
+ });
+ await expect(attempt()).rejects.toMatchObject({ code: 'fence_unrenderable', message: 'The adopted fence row does not render its legacy fact.' });
+ await expect(attempt()).rejects.toMatchObject({ code: 'fence_unrenderable', message: 'The same fact-fence adoption was already refused.' });
+ expect(await failed()).toBe(2);
+ // The planner revision is part of the intent, so a planner change gets a fresh identity rather than replaying the refusal.
+ expect(await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE slug=$1 AND (intent->>'planner')::int=$2`, [LEGACY_FILE_SLUG, FACT_FENCE_PLANNER])).toHaveLength(2);
+ }, { databaseUrl, setup: async ({ engine, root }) => { seed = await seedLegacyManagedContent(engine, root); } });
+ }, 120_000);
+}
+
+describe('extract_facts: an unadoptable row holds only its own phantom (#6650)', () => {
+ const STUB = '# alice\n';
+
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+ beforeEach(async () => { await resetPgliteState(engine); });
+
+ async function withBrain(run: (ctx: { engine: PGLiteEngine; brainDir: string }) => Promise<void>): Promise<void> {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fence-adoption-exits-'));
+ const brainDir = path.join(root, 'brain');
+ fs.mkdirSync(path.join(root, 'audit'), { recursive: true });
+ try {
+ await withEnv({ GBRAIN_AUDIT_DIR: path.join(root, 'audit') }, async () => {
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [brainDir]);
+ const write = (slug: string, body: string) => {
+ fs.mkdirSync(path.dirname(path.join(brainDir, `${slug}.md`)), { recursive: true });
+ fs.writeFileSync(path.join(brainDir, `${slug}.md`), body);
+ };
+ await engine.putPage(SLUG, { type: 'person', title: SLUG, compiled_truth: '# alice-example\n', frontmatter: {}, timeline: '' });
+ write(SLUG, '# alice-example\n');
+ await engine.putPage('alice', { type: 'person', title: 'alice', compiled_truth: STUB, frontmatter: {}, timeline: '' });
+ write('alice', STUB);
+ // A page whose legacy row cannot be fenced here: its canonical file is not on this host.
+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme', compiled_truth: '# Acme\n', frontmatter: {}, timeline: '' });
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', 'companies/acme-example', 'Acme example ships widgets', 'fact', 'world', 'medium', '2026-03-01', 'mcp:remember', 0.8)`);
+ await run({ engine, brainDir });
+ });
+ } finally {
+ await engine.executeRaw("UPDATE sources SET local_path = NULL WHERE id = 'default'");
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ }
+
+ const alive = async (engine: PGLiteEngine, slug: string) =>
+ (await engine.executeRaw('SELECT 1 FROM pages WHERE slug=$1 AND deleted_at IS NULL', [slug])).length === 1;
+
+ test('a legacy row on another page no longer stops the source\'s phantom redirects', async () => {
+ await withBrain(async ({ engine, brainDir }) => {
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.legacyRowsPending).toBe(1);
+ expect(result.phantomsRedirected).toBe(1);
+ expect(await alive(engine, 'alice')).toBe(false);
+ });
+ });
+
+ test('a phantom that owns a legacy row is held and keeps its row', async () => {
+ await withBrain(async ({ engine, brainDir }) => {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', 'alice', ' ', 'fact', 'world', 'medium', '2026-03-01', 'mcp:remember', 0.8)`);
+ const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
+ expect(result.phantomsRedirected).toBe(0);
+ expect(await alive(engine, 'alice')).toBe(true);
+ expect(await engine.executeRaw("SELECT 1 FROM facts WHERE entity_slug='alice' AND row_num IS NULL AND expired_at IS NULL")).toHaveLength(1);
+ });
+ });
+});
diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.ts
index ff1f5fc98f..c873f790a5 100644
--- a/test/phantom-redirect.test.ts
+++ b/test/phantom-redirect.test.ts
@@ -580,7 +580,7 @@ describe('runExtractFacts — phantom-redirect integration', () => {
});
});
- test('round 2 P1: legacy-row guard fires BEFORE phantom-redirect pass', async () => {
+ test('round 2 P1 (#6650): the legacy-row guard holds only the phantom that owns legacy rows', async () => {
await withTempDirs(async ({ brainDir }) => {
// #2763: the guard only gates on rows the v0_32_2 Phase B backfill
// could actually fence, which requires the source's local_path — set
@@ -607,11 +607,24 @@ describe('runExtractFacts — phantom-redirect integration', () => {
await putPage('alice', STUB_BODY);
writeMd(brainDir, 'alice', STUB_BODY);
+ // #6650: a phantom that owns a legacy row would strand it, so it is held.
+ await putPage('bob', STUB_BODY);
+ writeMd(brainDir, 'bob', STUB_BODY);
+ await putPage('people/bob-example', '# bob-example\n', { type: 'person' });
+ writeMd(brainDir, 'people/bob-example', '# bob-example\n');
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source)
+ VALUES ('default', 'bob', ' ', 'fact', '2020-01-01'::date, 'legacy-import')`,
+ );
+
const result = await runExtractFacts(engine, { sourceId: 'default', brainDir });
expect(result.guardTriggered).toBe(true);
- expect(result.phantomsRedirected).toBe(0);
- // Phantom .md still on disk (pass skipped)
- expect(mdExists(brainDir, 'alice')).toBe(true);
+ // A legacy row on another page no longer stops the pass for the source (#6650).
+ expect(result.phantomsRedirected).toBe(1);
+ expect(mdExists(brainDir, 'alice')).toBe(false);
+ // The phantom that owns a legacy row is held: its file and row stay.
+ expect(mdExists(brainDir, 'bob')).toBe(true);
+ expect(await engine.executeRaw(`SELECT 1 FROM facts WHERE entity_slug = 'bob' AND row_num IS NULL AND expired_at IS NULL`)).toHaveLength(1);
} finally {
await engine.executeRaw(`UPDATE sources SET local_path = NULL WHERE id = 'default'`);
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index e3884ae6b5..677b05d68b 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -39,6 +39,7 @@ test/extract-atoms-input-truncated-6503.test.ts
test/extract-endpoint-revision.serial.test.ts
test/extract-entities-managed.test.ts
test/extract-timeline-from-meetings-managed.test.ts
+test/fact-fence-adoption-exits.test.ts
test/fact-purge-lookup-timeout-6511.test.ts
test/fence-repair-receipts.test.ts
test/frontmatter-reserved-keys-6454.test.ts