Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): surface held phantoms and prior-refusal request ids; census counts compacted legacy rows (#6650)
garrytan813ecf436bb5
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 2c6f381fe8..f7328f614c 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. 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="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 refused in the last day is not resubmitted: the cycle reports it as class `prior_refusal` with the refused request id (`gbrain write-request -- <id>` reads it), and a direct `submitFactFenceAdoption` call refuses with `The same fact-fence adoption was already refused.`. It is retried a day after the refusal, or at once by a build whose adoption planner revision changed. 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 the read-only `scripts/diagnose/fence-adoption-census.sql` on the brain host against the brain's Postgres database (its header shows the `psql` command). | 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.sqlindex 2ffe655212..d9fe881dd1 100644--- a/scripts/diagnose/fence-adoption-census.sql+++ b/scripts/diagnose/fence-adoption-census.sql@@ -4,12 +4,21 @@-- 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+-- Postgres brains only (a PGLite brain has no managed writer table to census).+-- Run it with psql against the same database the brain uses: the URL is the+-- `database_url` in the brain host's gbrain config (`gbrain doctor --json`+-- names the config file; it prints the URL redacted, so read the file). From+-- a gbrain checkout:+-- psql "<database url>" -v source=default -f scripts/diagnose/fence-adoption-census.sql+-- Without a checkout, fetch the file from the gbrain repository first:+-- curl -fsSLO https://raw.githubusercontent.com/garrytan/gbrain/master/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 /+-- code but lose their message and intent. A compacted `fence_unrenderable`+-- row is still counted above; a compacted legacy `invalid_params` row can no+-- longer be told apart from other invalid_params refusals, so the first two+-- tables are a lower bound and the last one counts those rows separately as+-- unattributed. 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.@@ -51,4 +60,18 @@ SELECT count(*) AS pages_AND f.row_num IS NULL AND f.expired_at IS NULL AND f.dimension IS NULL)) AS pages_still_holding_legacy_factsFROM failed;+\echo 'Unattributed: compacted invalid_params failures (older builds wrote fence refusals with this code; not all of these are adoptions)'+SELECT r.admitter_version,+ count(*) AS compacted_invalid_params,+ count(DISTINCT r.slug) AS distinct_pages,+ min(r.completed_at) AS first_seen,+ max(r.completed_at) AS last_seen+ FROM persistence_requests r+ WHERE r.source_id = :'source'+ AND r.state = 'failed'+ AND r.compacted+ AND r.error_code = 'invalid_params'+ GROUP BY 1+ ORDER BY last_seen DESC;+ROLLBACK;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f76c9592ed..8590f9ca57 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -544,7 +544,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6650 (fact-fence adoption exits). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.215.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.215.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.215.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.' },+ { since: '0.60.215.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 (`phantoms_held_legacy_rows` in the cycle report) 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.ts b/src/core/cycle.tsindex 359fa81ecf..1784f1a3d6 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1489,8 +1489,9 @@ async function runPhaseExtractFacts(// so the daily cycle report makes the cleanup visible.const phantomSummary = (result.phantomsRedirected|| result.phantomsAmbiguous- || result.phantomsSkippedDrift)- ? `, ${result.phantomsRedirected} phantom(s) redirected (${result.phantomsAmbiguous} ambiguous, ${result.phantomsSkippedDrift} drift-skipped)`+ || result.phantomsSkippedDrift+ || result.phantomsHeldLegacyRows)+ ? `, ${result.phantomsRedirected} phantom(s) redirected (${result.phantomsAmbiguous} ambiguous, ${result.phantomsSkippedDrift} drift-skipped${result.phantomsHeldLegacyRows ? `, ${result.phantomsHeldLegacyRows} held for unfenced fact rows` : ''})`: '';// #1928: a reconcile that deletes far more facts than it reinserts is the// signature of the conversation-facts wipe (factsDeleted 1829, inserted 0@@ -1539,6 +1540,7 @@ async function runPhaseExtractFacts(phantoms_redirected: result.phantomsRedirected,phantoms_ambiguous: result.phantomsAmbiguous,phantoms_skipped_drift: result.phantomsSkippedDrift,+ phantoms_held_legacy_rows: result.phantomsHeldLegacyRows,phantoms_lock_busy: result.phantomsLockBusy,phantoms_more_pending: result.phantomsMorePending,...(decideConflict ? { decide_conflict: decideConflict } : {}),diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 4338265771..8238071424 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -664,6 +664,8 @@ export interface ExtractFactsResult {phantomsRedirected: number;phantomsAmbiguous: number;phantomsSkippedDrift: number;+ /** #6650: phantoms held because they own legacy (unfenced) fact rows. */+ phantomsHeldLegacyRows: number;phantomsLockBusy: boolean;phantomsMorePending: boolean;}@@ -809,6 +811,7 @@ export async function runExtractFacts(phantomsRedirected: 0,phantomsAmbiguous: 0,phantomsSkippedDrift: 0,+ phantomsHeldLegacyRows: 0,phantomsLockBusy: false,phantomsMorePending: false,};@@ -901,6 +904,7 @@ export async function runExtractFacts(result.phantomsRedirected = phantomResult.redirected;result.phantomsAmbiguous = phantomResult.ambiguous;result.phantomsSkippedDrift = phantomResult.skipped_drift;+ result.phantomsHeldLegacyRows = phantomResult.held_legacy_rows;result.phantomsLockBusy = phantomResult.lock_busy;result.phantomsMorePending = phantomResult.more_pending;diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex 40a0274940..76a7d523e3 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -117,8 +117,9 @@ export interface UnfencedFactsOutcome {* `validity` / `source` (another column reads back different), `parse` (the* 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).+ * submits nothing), `prior_refusal` (a managed adoption of the same intent was+ * refused in the last day; it is retried a day after the refusal, or at once+ * when `FACT_FENCE_PLANNER` changes).*/export type UnrenderableClass = 'empty' | 'struck' | 'line_break_markup' | 'claim' | 'kind' | 'visibility' | 'validity' | 'source' | 'parse'| 'whole_fence' | 'prior_refusal';@@ -130,6 +131,8 @@ export interface UnadoptableFactRecord {fact_id: number;reason: 'fence_unrenderable' | 'duplicate_claim';class: UnrenderableClass | 'duplicate_claim';+ /** `prior_refusal`: the refused request, readable with `gbrain write-request -- <id>`. */+ request_id?: string;}function fenceRowOf(row: UnfencedFactRow, rowNum: number, claim: string): ParsedFact {@@ -391,7 +394,7 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi});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 }))]);+ fact_id: Number(a.id), reason: 'fence_unrenderable' as const, class: 'prior_refusal' as const, request_id: request.prior.request_id }))]);continue;}recordUnadoptable(outcome, entitySlug, fence.rejected);diff --git a/test/fact-fence-adoption-exits.test.ts b/test/fact-fence-adoption-exits.test.tsindex 4c33020591..e53eae394a 100644--- a/test/fact-fence-adoption-exits.test.ts+++ b/test/fact-fence-adoption-exits.test.ts@@ -183,6 +183,7 @@ describe('extract_facts: an unadoptable row holds only its own phantom (#6650)',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(result.phantomsHeldLegacyRows).toBe(1);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);});