Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): fence classic unfenced facts of a database-only page into its database body (#6610)
time-attack9558f1cbb041
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 1a1405a70a..014ff473e5 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.- `src/commands/doctor/checks/extraction-input.ts` — `extraction_input_truncated` (large pages A7, BRAIN, registered after `fence_integrity`, before `search_mode`). Groups the live pages with an `input_truncated` receipt in `page_extraction_state` by pipeline and kind (`facts_backstop/head|tail_window`, `extract_atoms/head|tail_window`, `conversation_facts/skipped_too_large`) with three recent `source:slug` samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is `gbrain config set cycle.extract_atoms.max_input_chars <n>` (`ask_user`, consent `paid`), otherwise `fix_unavailable_reason: operator_judgement`. Facts-only receipts are `ok` with `severity: info`, `readiness_state: degraded` (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`, `test/conversation-facts-oversized-sidecar.test.ts`.-- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.+- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. #6610: `unbound_legacy_facts` lists, from the same plan, unfenced rows of classic database-only pages that `persistence.unbound_write` keeps unfenced; when it is the only finding the fix is `gbrain config set persistence.unbound_write database_only` with `ask_user`. Test: `test/doctor-fence-integrity.test.ts`, `test/extract-facts-unfenced-rows.test.ts`.- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.mdindex adf53b5122..f71b270a6a 100644--- a/docs/architecture/key-files/google-and-loops-continued.md+++ b/docs/architecture/key-files/google-and-loops-continued.md@@ -25,7 +25,7 @@- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open. #6696: the wire accepts an `explicitProcessing` list (processing keys only, no duplicates) and the owner keeps a supplied list exactly; a payload without one counts only its true-valued processing keys as typed (`typedSyncProcessing`), so a flagless resume adopts the cursor's stored options (`test/sync-owner-lane-processing-6696.test.ts`).- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`.-- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.+- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (a recorded canonical file absent on this host is also listed in `missing_files`), never materialized as stubs. #6610: an unmanaged database-only page (no `source_path`/`source_uri`, no file at its slug path) is fenced in its database body through the coordinator (`fenceDatabaseOnlyPage`, no file target) when `resolveFactWriteTarget` makes the write database-only; an unbound source without `persistence.unbound_write=database_only` leaves its rows in `unbound_refused`, which `extract_facts` holds out of reconciliation without gating and doctor `fence_integrity` reports as `unbound_legacy_facts` with the opt-in (`ask_user`). The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).- `src/core/cycle/connector-extract.ts` — the extract phase of a cycle with no on-disk checkout (connector sources, Postgres brains without `--dir`; #5875): `runPhaseExtractDatabaseOnly` runs the bounded, source-scoped `extractStaleFromDB` drain (`CYCLE_STALE_DRAIN_BUDGET_MS`; brain-wide when the cycle has no source id; managed brains route to `extractManagedStaleLinks`) and reports `extract: ok` with `database_only: true` and the stale counters; a dry run reports `skipped`. Tests: `test/connector-cycle-extract.test.ts` (+ Postgres twin), no `runCycle` mock.diff --git a/skills/migrations/v0.32.2.md b/skills/migrations/v0.32.2.mdindex f8848fe0ff..2e824c7981 100644--- a/skills/migrations/v0.32.2.md+++ b/skills/migrations/v0.32.2.md@@ -33,8 +33,12 @@ restorable database backup as well as source files.all of its fenced rows expired is reported as `skipped_expired_no_page`,not as drift, while a missing page with a live row still fails). Only live legacyrows with an existing source-scoped page and canonical file are- eligible. Missing targets are reported as `skipped_no_page`; no stub is- created. Existing fence and database row numbers remain reserved.+ eligible; on a brain without managed persistence, a database-only page+ (no recorded origin and no file at its slug path) is fenced in its+ database body when that write is database-only, and a source with a+ checkout but no owner and `persistence.unbound_write` unset leaves its+ rows as `skipped_unbound_source`. Missing targets are reported as+ `skipped_no_page`; no stub is created. Existing fence and database row numbers remain reserved.Row-number verification is not full content parity.`--dry-run` previews the migration plan; there is no `--write` flag.3. Dirty-tree refusal applies only to the source subtrees receiving writes.diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.tsindex 59d30910b3..ee19f42ab7 100644--- a/src/commands/doctor/checks/fence-integrity.ts+++ b/src/commands/doctor/checks/fence-integrity.ts@@ -25,11 +25,17 @@* classes, never the claim. Those rows stay active and searchable and* nothing is lost, so the finding has no command (`next: report`) and never* suggests `forget_fact`; its verify re-counts the rows.+ *+ * #6610: it also lists `unbound_legacy_facts`, the unfenced rows of a classic+ * database-only page that stay unfenced because the source has a checkout but+ * no canonical owner and `persistence.unbound_write` is not `database_only`;+ * the fix asks the user about that opt-in.*/import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { agentFix, doctorVerify } from '../check-fix.ts';-import { auditUnadoptableFacts, planUnfencedFacts, type UnadoptableFactRecord } from '../../../core/facts/unfenced-facts.ts';+import { auditUnadoptableFacts, planUnfencedFacts, unboundRefusedSentence, type UnadoptableFactRecord, type UnfencedFactsOutcome } from '../../../core/facts/unfenced-facts.ts';+import { UNBOUND_SOURCE_DOCS, UNBOUND_WRITE_KEY } from '../../../core/persistence/unbound-source.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { runFenceCensus, summarizeFenceCensus, type SourceCensus, type TierCounts } from '../../../core/fence-repair/census.ts';import { readTrend, type TrendEntry } from '../../../core/fence-repair/census-store.ts';@@ -105,14 +111,17 @@ function modelRepairSentence(caps: { perPageUsd: number; perDayUsd: number }, to}interface UnrenderablePage { source_id: string; slug: string; rows: Array<{ fact_id: number; reason: UnadoptableFactRecord['reason']; class: UnadoptableFactRecord['class'] }> }-interface UnrenderableLegacyFacts { total: number; complete: boolean; pages: UnrenderablePage[] }+interface UnrenderableLegacyFacts { total: number; complete: boolean; pages: UnrenderablePage[]; unbound: UnfencedFactsOutcome['unbound_refused'] }/** Legacy rows the fence step would leave unadopted, planned read-only per source within `deadline`; location only. */async function unrenderableLegacyFacts(engine: BrainEngine, sourceIds: string[] | undefined, deadline: number): Promise<UnrenderableLegacyFacts> {const byPage = new Map<string, UnrenderablePage>();let complete = true;+ const unbound: UnfencedFactsOutcome['unbound_refused'] = [];for (const sourceId of sourceIds ?? [undefined]) {- const audit = await auditUnadoptableFacts(engine, await planUnfencedFacts(engine, sourceId === undefined ? {} : { sourceId }), { deadline });+ const plan = await planUnfencedFacts(engine, sourceId === undefined ? {} : { sourceId });+ unbound.push(...plan.outcome.unbound_refused);+ const audit = await auditUnadoptableFacts(engine, plan, { deadline });complete &&= audit.complete;for (const record of audit.records) {const key = `${record.source_id}\0${record.slug}`;@@ -121,10 +130,10 @@ async function unrenderableLegacyFacts(engine: BrainEngine, sourceIds: string[]}}const pages = [...byPage.values()];- return { total: pages.reduce((sum, page) => sum + page.rows.length, 0), complete, pages };+ return { total: pages.reduce((sum, page) => sum + page.rows.length, 0), complete, pages, unbound };}-function unrenderableSentence(found: UnrenderableLegacyFacts): string {+function unrenderableSentence(found: Omit<UnrenderableLegacyFacts, 'unbound'>): string {const pages = found.pages.slice(0, 5).map(page => `${page.slug} (${page.source_id}): ${[...new Set(page.rows.map(row => row.class))].sort().join(', ')}`).join('; ');return `${found.total} legacy fact row(s) on ${found.pages.length} page(s) cannot be adopted into their facts fence: ${pages}${found.pages.length > 5 ? '; …' : ''}. `+ 'They stay active and searchable and nothing is lost: the fence codec would change their text (or the page already carries the claim), so gbrain leaves them as legacy rows '@@ -150,7 +159,8 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM// T2: legacy fence repairs written and imported but not committed yet (counts for a scoped remote caller, paths locally).const uncommitted = await readUncommittedFenceRepairs(engine, opts.sourceIds ?? census.map(c => c.source_id)).catch(() => []);// The audit's deadline is on the wall clock (it bounds real work; the census's `now` is for dates).- const unrenderable = await unrenderableLegacyFacts(engine, opts.sourceIds, Date.now() + timeoutMs).catch((): UnrenderableLegacyFacts => ({ total: 0, complete: false, pages: [] }));+ const { unbound, ...unrenderable } = await unrenderableLegacyFacts(engine, opts.sourceIds, Date.now() + timeoutMs)+ .catch((): UnrenderableLegacyFacts => ({ total: 0, complete: false, pages: [], unbound: [] }));const details = {total, partial: partial.length > 0, partial_sources: partial.map(c => c.source_id), sources: census, trend, warn_at_normalized_7d: FENCE_NORMALIZATION_WARN_7D,model_repair: { max_usd_per_page: caps.perPageUsd, max_usd_per_day: caps.perDayUsd, spent_today_usd: today?.committedUsd ?? null, reserved_today_usd: today?.reservedUsd ?? null },@@ -158,8 +168,9 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMuncommitted_repairs: uncommitted.length,...(uncommitted.length && !opts.sourceIds ? { uncommitted: uncommitted.map(n => ({ source_id: n.source_id, path: n.path, commit_step: n.commit_step })) } : {}),unrenderable_legacy_facts: unrenderable,+ unbound_legacy_facts: { total: unbound.reduce((sum, page) => sum + page.rows, 0), pages: unbound },};- if (!total && !partial.length && !noisy.length && !uncommitted.length && !unrenderable.total && unrenderable.complete) {+ if (!total && !partial.length && !noisy.length && !uncommitted.length && !unrenderable.total && unrenderable.complete && !unbound.length) {return { status: 'ok', details, message: census.length ? `No malformed facts or takes fence is held, stored or waiting in a checkout (${census.length} source(s) scanned).` : 'No sources to scan.' };}const auto = await readFenceAutoRepair(engine, now());@@ -189,6 +200,7 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM}if (unrenderable.total || !unrenderable.complete) sentences.push(unrenderable.total ? unrenderableSentence(unrenderable): 'The scan for legacy fact rows the fence cannot render did not finish within its time budget; run gbrain doctor --only fence_integrity again.');+ if (unbound.length) sentences.push(unboundRefusedSentence(unbound));const first = waiting[0];const fix = first ? sourceFix(first, auto): partial.length || (!unrenderable.total && !unrenderable.complete) ? agentFix(['gbrain', 'doctor', '--only', 'fence_integrity', '--json'], 'Resumes the fence census where the last scan stopped and reports what it found.', 'fence_integrity', { docs: DOCS })@@ -196,6 +208,10 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM'fence_integrity', { docs: DOCS }): uncommitted.length ? agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact git add and git commit step for each file.','fence_integrity', { docs: DOCS })+ : unbound.length && !unrenderable.total ? agentFix(['gbrain', 'config', 'set', UNBOUND_WRITE_KEY, 'database_only'],+ `Allows database-only writes to sources with a checkout but no canonical owner, so the next extract_facts run fences these rows into their database pages. It is brain-wide (every database-only page of such a source stays database-only after binding), so ask the user first.`,+ 'fence_integrity', { ask_user: true, docs: UNBOUND_SOURCE_DOCS,+ user_message: `Some saved facts sit on database-only pages of an unbound source and are not in those pages' facts tables yet. I can allow database-only writes to unbound sources (gbrain config set ${UNBOUND_WRITE_KEY} database_only) so the next maintenance run adds them; those pages then stay database-only even after the source is bound.` })// No command to run: the rows stay as they are, so the fix is a report; verify re-counts them.: { consent: [], actor: 'agent' as const, requires_exclusive: false, docs: UNRENDERABLE_DOCS, verify: doctorVerify('fence_integrity'),why: `Nothing to run: ${unrenderable.total} legacy fact row(s) stay active and searchable because their text cannot be written into a facts fence unchanged. Tell the user which pages are listed under unrenderable_legacy_facts and report them with the gbrain version; the verify re-counts the rows.` };diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.tsindex 823bc8f6ed..f046c38417 100644--- a/src/commands/migrations/v0_32_2.ts+++ b/src/commands/migrations/v0_32_2.ts@@ -154,7 +154,8 @@ async function phaseBFenceFacts(return {name: 'fence_facts', status: 'skipped',detail: `dry-run: would fence ${fenceableRowCount(plan)} rows; ${outcome.skipped_no_entity} unfenceable (NULL entity_slug); ` +- `skipped_no_page=${outcome.skipped_no_page} skipped_no_local_path=${outcome.skipped_no_local_path}`,+ `skipped_no_page=${outcome.skipped_no_page} skipped_no_local_path=${outcome.skipped_no_local_path}` ++ (outcome.unbound_refused.length > 0 ? ` skipped_unbound_source=${outcome.unbound_refused.reduce((n, page) => n + page.rows, 0)}` : ''),};}@@ -191,6 +192,7 @@ function fenceFactsResult(outcome: UnfencedFactsOutcome): OrchestratorPhaseResul`pages=${outcome.pages_touched} skipped_no_entity=${outcome.skipped_no_entity} ` +`skipped_no_local_path=${outcome.skipped_no_local_path} skipped_no_page=${outcome.skipped_no_page}` +(outcome.skipped_archived > 0 ? ` skipped_archived=${outcome.skipped_archived}` : '') ++ (outcome.unbound_refused.length > 0 ? ` skipped_unbound_source=${outcome.unbound_refused.reduce((n, page) => n + page.rows, 0)}` : '') +(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_factsdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 9d92b63af8..027761ca91 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -633,6 +633,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.243.0', text: 'A page whose only `## Facts` fence sits below the timeline sentinel keeps it there: `remember` and `extract_facts` now add their rows to that fence (and strike a replaced row where it lives) instead of adding a second fence above the sentinel, and `extract_facts` reconciles such a fence instead of warning `FACTS_FENCE_BELOW_SENTINEL` and freezing its facts. A page that already has a fence on each side of the sentinel still warns, now naming `gbrain repair split-facts --source <id>`, an explicit preview-then-apply repair that merges the two fences under their own row numbers and refuses a page whose fences share a row number.' },// #6608: fact writers onto a page of an unbound source.{ since: '0.0.0-wave17', text: 'On Postgres, `remember` about an existing page of a source that has a checkout but no canonical owner now follows the same rule as `put_page`: with `persistence.unbound_write=database_only` a page without a canonical file gets the fact fenced into its database body (database-only, `write_through.skipped: unbound_source`), and otherwise the refusal (still `unavailable` with `write_error: owner_unavailable`) carries `detail: unbound_source`, the opt-in or classic file path, and an ask-the-user fix instead of the generic writer hint. `loops_close` fact retirement and `gbrain facts relink` fence such pages the same way.' },+ // #6610: classic unfenced facts on database-only pages.+ { since: '0.0.0-wave17', text: 'On a brain without managed persistence, `extract_facts` (and the v0.32.2 fence step) now fences unfenced facts of a database-only page (no recorded file and none at its slug path) into the page\'s database body when such a write is database-only (`sync.write_through` off, or on Postgres an unbound source with `persistence.unbound_write=database_only`, which stamps the page `unbound_source`), instead of reporting a missing canonical file and halting the facts fence every run. Without that opt-in the rows stay unfenced and their page skips reconciliation, but they no longer count as pending (`legacyRowsPending`) or trigger the guard; doctor `fence_integrity` lists them under `unbound_legacy_facts` and asks the user about the opt-in, and the migration reports them as `skipped_unbound_source`.' },];/** 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.tsindex 306637d3bf..4bf746c052 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -762,7 +762,7 @@ function timelineHasGenuineFactsFenceMarker(timeline: string): boolean {* slugify-floor / stub-guard-blocked slugs) are structurally unfenceable and* never gate.*/-async function pendingLegacyRows(engine: BrainEngine, sourceId: string): Promise<{ count: number; slugs: Set<string> }> {+async function pendingLegacyRows(engine: BrainEngine, sourceId: string): Promise<Map<string, number>> {const legacy = await engine.executeRaw<{ entity_slug: string; n: string }>(`SELECT f.entity_slug, COUNT(*) AS nFROM facts f@@ -785,7 +785,7 @@ async function pendingLegacyRows(engine: BrainEngine, sourceId: string): PromiseGROUP BY f.entity_slug`,[sourceId],);- return { count: legacy.reduce((sum, row) => sum + parseInt(row.n ?? '0', 10), 0), slugs: new Set(legacy.map(row => row.entity_slug)) };+ return new Map(legacy.map(row => [row.entity_slug, parseInt(row.n ?? '0', 10)]));}/**@@ -835,11 +835,13 @@ export async function runExtractFacts(// managed brain, the page file + maintenance transaction otherwise. The// fenced pages join this run's reconcile below.let fencedSlugs: string[] = [];+ let unboundRefused = new Set<string>();if (!opts.dryRun) {try {const fence = await fenceUnfencedFacts(engine, await planUnfencedFacts(engine, { sourceId }), { pageLockRoot: opts.pageLockRoot });result.unfencedRowsFenced = fence.fenced;fencedSlugs = fence.fenced_slugs;+ unboundRefused = new Set(fence.unbound_refused.map(page => page.slug));for (const page of [...fence.failed_pages, ...fence.missing_files]) result.warnings.push(`FACTS_FENCE_FAILED: ${page}`);} catch (e) {result.warnings.push(`FACTS_FENCE_FAILED: ${(e instanceof Error ? e.message : String(e)).slice(0, 300)}`);@@ -849,18 +851,23 @@ export async function runExtractFacts(// ── Empty-fence guard (per page, #6278) ─────────────────────────// Rows the fence step could not fence this run keep their own page out of// the destructive reconciliation pass; the other pages reconcile.- const { count: legacyCount, slugs: legacySlugs } = await pendingLegacyRows(engine, sourceId);+ // #6610: rows the unbound-source policy keeps unfenced on database-only pages stay held out of reconciliation+ // but never gate the run; doctor fence_integrity names the opt-in that fences them.+ const pending = await pendingLegacyRows(engine, sourceId);+ const legacySlugs = new Set(pending.keys());+ const gating = [...pending].filter(([slug]) => !unboundRefused.has(slug));+ const legacyCount = gating.reduce((sum, [, n]) => sum + n, 0);result.legacyRowsPending = legacyCount;- result.legacyPages = [...legacySlugs].sort();+ result.legacyPages = gating.map(([slug]) => slug).sort();if (legacyCount > 0) {result.guardTriggered = true;result.warnings.push(- `extract_facts: ${legacyCount} unfenced fact row(s) on ${legacySlugs.size} page(s) in source "${sourceId}" (entity page present, row_num NULL) ` ++ `extract_facts: ${legacyCount} unfenced fact row(s) on ${gating.length} page(s) in source "${sourceId}" (entity page present, row_num NULL) ` +(opts.dryRun? 'would be fenced by this phase; a dry run writes nothing, so those pages skip reconciliation.': '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 page whose recorded 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 holds only the phantoms that own such rows. ' +'Individual rows can instead be drained via `forget_fact`.'),);diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.tsindex 057dad1cec..d154f9e60b 100644--- a/src/core/facts/unfenced-facts.ts+++ b/src/core/facts/unfenced-facts.ts@@ -63,9 +63,15 @@ import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesyimport { withPageLock } from '../page-lock.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { assertLifetimeIdHeadroom } from '../persistence/journal.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, type OperationContext } from '../ops/contract.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';-import { maintenancePreflight, planFactFenceAdoption, submitPlannedFactFenceAdoption, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { maintenancePreflight, planFactFenceAdoption, submitFactFenceAdoption, submitPlannedFactFenceAdoption, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { resolveFactWriteTarget } from '../persistence/fact-write-target.ts';+import { submissionAuthority } from '../persistence/authority.ts';+import { currentVerifiedLocalWriter, registerLocalWriter } from '../persistence/identity.ts';+import { assertPersistenceAccepting } from '../persistence/service.ts';+import type { WriteAuthority } from '../persistence/model.ts';+import { UNBOUND_WRITE_KEY } from '../persistence/unbound-source.ts';import { contentHash } from '../utils.ts';import { resolvePageWriteTarget } from '../write-through.ts';import { commitFactFenceFile, gitPathState } from './fence-write.ts';@@ -104,8 +110,14 @@ export interface UnfencedFactsOutcome {failed_pages: string[];/** Slugs whose fence this run wrote. */fenced_slugs: string[];- /** Unmanaged: `<slug> (<reason>)` per live page whose canonical file is not on this host (counted in skipped_no_page). */+ /** Unmanaged: `<slug> (<reason>)` per live page whose recorded canonical file is not on this host (counted in skipped_no_page). */missing_files: string[];+ /**+ * Unmanaged (#6610): database-only pages (no recorded origin, no file at the slug path) of a source with a checkout+ * but no canonical owner, whose rows stay unfenced because `persistence.unbound_write` is not `database_only`.+ * Their rows never gate the run (they are held out of reconciliation only); doctor `fence_integrity` names the opt-in.+ */+ unbound_refused: Array<{ source_id: string; slug: string; rows: number }>;/** 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[];}@@ -206,6 +218,8 @@ export interface UnfencedFactsPlan {groups: Map<string, UnfencedFactRow[]>;/** Unmanaged: the canonical file per group key. */filePaths: Map<string, string>;+ /** Unmanaged (#6610): groups whose page is database-only, fenced into its database body under this reason. */+ databaseOnly: Map<string, NonNullable<WriteAuthority['databaseOnlyReason']>>;localPathById: Map<string, string | null>;outcome: UnfencedFactsOutcome;}@@ -215,6 +229,37 @@ export function fenceableRowCount(plan: UnfencedFactsPlan): number {return [...plan.groups.values()].reduce((n, group) => n + group.length, 0);}+/**+ * #6610: where an unmanaged page with no canonical file on this host gets its fence. A page that records an origin+ * (`source_path` or `source_uri`) has a file on some host: `missing`. A page with no recorded origin and no file at its+ * slug path is database-only, and follows the fact writers' rule (`resolveFactWriteTarget`, #6608): fenced into its+ * database body when that write is database-only (`fence`), `refused` when the source has a checkout but no owner and+ * `persistence.unbound_write` is not `database_only`; a bound source, or one PGLite would claim, stays `missing`.+ */+async function databaseOnlyPlacement(engine: BrainEngine, sourceId: string, slug: string):+ Promise<{ kind: 'fence'; reason: NonNullable<WriteAuthority['databaseOnlyReason']> } | { kind: 'refused' } | { kind: 'missing' }> {+ const [page] = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(+ 'SELECT source_path, source_uri FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);+ if (!page || page.source_path?.trim() || page.source_uri?.trim()) return { kind: 'missing' };+ const [source] = await engine.executeRaw<{ local_path: string | null; kind: string | null }>(+ "SELECT local_path, config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);+ try {+ const target = await resolveFactWriteTarget(engine, sourceId, source!, { fileBacked: false, remote: false });+ return target.kind === 'publish' && !target.binding ? { kind: 'fence', reason: target.databaseOnlyReason ?? 'no_repo_configured' } : { kind: 'missing' };+ } catch (error) {+ if (error instanceof OperationError && error.detail === 'unbound_source') return { kind: 'refused' };+ throw error;+ }+}++/** `<slug> (<source>): N row(s)` per page the unbound-source policy keeps unfenced, and the opt-in that fences them. */+export function unboundRefusedSentence(pages: UnfencedFactsOutcome['unbound_refused']): string {+ return `${pages.reduce((n, page) => n + page.rows, 0)} unfenced fact row(s) on ${pages.length} database-only page(s) of a source with a checkout but no canonical owner stay unfenced: `+ + `${pages.slice(0, 5).map(page => `${page.slug} (${page.source_id}): ${page.rows} row(s)`).join('; ')}${pages.length > 5 ? '; …' : ''}. `+ + `They stay active and searchable and those pages skip destructive fact reconciliation. To fence them into the database page, the user can allow database-only writes to unbound sources `+ + `with gbrain config set ${UNBOUND_WRITE_KEY} database_only (a brain-wide choice: such pages stay database-only after binding).`;+}+/** Read the unfenced active rows of one source (or every source) and group the fenceable ones per page. */export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?: string } = {}): Promise<UnfencedFactsPlan> {const managed = await managedPersistenceEnabled(engine);@@ -237,7 +282,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: [], unadoptable_rows: [],+ skipped_archived: 0, pages_touched: 0, failed_pages: [], fenced_slugs: [], missing_files: [], unbound_refused: [], unadoptable_rows: [],};const groups = new Map<string, UnfencedFactRow[]>();for (const row of rows) {@@ -251,18 +296,19 @@ export async function planUnfencedFacts(engine: BrainEngine, opts: { sourceId?:groups.set(key, [...groups.get(key) ?? [], row]);}const filePaths = new Map<string, string>();+ const databaseOnly = new Map<string, NonNullable<WriteAuthority['databaseOnlyReason']>>();for (const [key, group] of managed ? [] : [...groups]) {const [sourceId, entitySlug] = key.split('\0');const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);- if (!target.ok || !existsSync(target.filePath)) {- outcome.skipped_no_page += group.length;- outcome.missing_files.push(`${entitySlug} (${target.ok ? `canonical file ${target.filePath} does not exist on this host` : `no canonical file: ${target.skipped}`})`);- groups.delete(key);- continue;- }- filePaths.set(key, target.filePath);+ if (target.ok && existsSync(target.filePath)) { filePaths.set(key, target.filePath); continue; }+ const placement = await databaseOnlyPlacement(engine, sourceId, entitySlug);+ if (placement.kind === 'fence') { databaseOnly.set(key, placement.reason); continue; }+ groups.delete(key);+ if (placement.kind === 'refused') { outcome.unbound_refused.push({ source_id: sourceId, slug: entitySlug, rows: group.length }); continue; }+ outcome.skipped_no_page += group.length;+ outcome.missing_files.push(`${entitySlug} (${target.ok ? `canonical file ${target.filePath} does not exist on this host; the page records it, so the cycle on the host that holds the file fences these rows` : `no canonical file: ${target.skipped}`})`);}- return { managed, groups, filePaths, localPathById, outcome };+ return { managed, groups, filePaths, databaseOnly, localPathById, outcome };}/**@@ -457,6 +503,36 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi}}+/**+ * #6610: one unmanaged database-only page, fenced into its database body through the coordinator as one+ * `managed_maintenance_adopt_fact_fence` request with no file target, the publication path `remember` uses for the+ * same page (#6608): the receipt, page version and projection follow, and an `unbound_source` write rechecks at+ * publication that the source is still unbound and the page still has no canonical file.+ */+async function fenceDatabaseOnlyPage(engine: BrainEngine, sourceId: string, entitySlug: string, reason: NonNullable<WriteAuthority['databaseOnlyReason']>,+ group: UnfencedFactRow[], outcome: UnfencedFactsOutcome): Promise<void> {+ try {+ const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });+ if (!snapshot) { outcome.skipped_no_page += group.length; return; }+ const fence = await planFence(engine, sourceId, entitySlug, serializePageToMarkdown(snapshot.page, snapshot.tags), group);+ if ('warnings' in fence) { outcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`); return; }+ recordUnadoptable(outcome, entitySlug, fence.rejected);+ if (fence.assignments.length === 0) return;+ assertPersistenceAccepting(engine);+ if (!currentVerifiedLocalWriter()) await registerLocalWriter(engine, 'cli');+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]);+ const writer = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext, 'submit_job', sourceId, source!.incarnation, 'maintenance');+ writer.databaseOnlyReason = reason;+ await submitFactFenceAdoption(engine, { writer, binding: null }, entitySlug, { content: fence.body, expectedRevision: snapshot.revision,+ assignments: fence.assignments.map(a => ({ id: Number(a.id), row_num: a.row_num })), file: false });+ outcome.fenced += fence.assignments.length;+ outcome.pages_touched += 1;+ outcome.fenced_slugs.push(entitySlug);+ } catch (err) {+ outcome.failed_pages.push(`${entitySlug} (${err instanceof Error ? err.message : String(err)})`);+ }+}+/** One unmanaged page: file first (atomic), then the page mirror and row stamps in one maintenance transaction. */async function fenceFilePage(engine: BrainEngine, sourceId: string, entitySlug: string, filePath: string,group: UnfencedFactRow[], outcome: UnfencedFactsOutcome, lockRoot?: string): Promise<void> {@@ -531,7 +607,7 @@ export async function auditUnadoptableFacts(engine: BrainEngine, plan: UnfencedFif (opts.deadline !== undefined && Date.now() > opts.deadline) return { records, complete: false };const [sourceId, entitySlug] = key.split('\0');let body: string;- if (plan.managed) {+ if (plan.managed || plan.databaseOnly.has(key)) {const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });if (!snapshot) continue;body = serializePageToMarkdown(snapshot.page, snapshot.tags);@@ -558,7 +634,9 @@ export async function fenceUnfencedFacts(engine: BrainEngine, plan: UnfencedFact}for (const [key, group] of plan.groups) {const [sourceId, entitySlug] = key.split('\0');- await fenceFilePage(engine, sourceId, entitySlug, plan.filePaths.get(key)!, group, plan.outcome, opts.pageLockRoot);+ const databaseOnly = plan.databaseOnly.get(key);+ if (databaseOnly) await fenceDatabaseOnlyPage(engine, sourceId, entitySlug, databaseOnly, group, plan.outcome);+ else await fenceFilePage(engine, sourceId, entitySlug, plan.filePaths.get(key)!, group, plan.outcome, opts.pageLockRoot);}return plan.outcome;}diff --git a/test/extract-facts-unfenced-rows.test.ts b/test/extract-facts-unfenced-rows.test.tsindex 6435d224ba..a0ab5fd87c 100644--- a/test/extract-facts-unfenced-rows.test.ts+++ b/test/extract-facts-unfenced-rows.test.ts@@ -37,9 +37,19 @@* the write-back is missing (the projection expires the adopted row and* inserts a new id), a rejected row is deleted, expired or rewritten, or the* source-wide guard skips every page.+ *+ * #6610: on an unmanaged brain, a database-only page (no recorded origin, no+ * file at its slug path) gets its unfenced rows fenced into its database body+ * through the coordinator when the fact writers' rule makes that write+ * database-only (`sync.write_through` off; on Postgres, an unbound source with+ * `persistence.unbound_write=database_only`). Without the opt-in its rows stay+ * unfenced and held out of reconciliation but never gate the run, and doctor+ * `fence_integrity` names the opt-in. Fails when: such a page is reported as a+ * missing file every run (`FACTS_FENCE_FAILED ... does not exist on this+ * host`) and halts the facts fence for good.*/import { expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { runCycle } from '../src/core/cycle.ts';@@ -47,6 +57,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { parseFactsFence } from '../src/core/facts-fence.ts';import { serializePageToMarkdown } from '../src/core/markdown.ts';import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';+import { fenceIntegrityResult } from '../src/commands/doctor/checks/fence-integrity.ts';import { managedBrain } from './helpers/managed-brain.ts';import { LEGACY_DB_ONLY_SLUG, LEGACY_FILE_SLUG, seedLegacyManagedContent, type LegacySeed } from './helpers/managed-legacy-fixture.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';@@ -326,6 +337,71 @@ for (const backend of testBackends()) {});}, 120_000);+ /** Turn the fixture's page into a database-only page: no recorded origin and no file at its slug path. */+ async function makeDatabaseOnly(engine: BrainEngine, root: string): Promise<void> {+ await engine.executeRaw("UPDATE pages SET source_path = NULL, source_uri = NULL WHERE source_id = 'default' AND slug = $1", [SLUG]);+ rmSync(join(root, `${SLUG}.md`));+ }+ async function databaseFence(engine: BrainEngine) {+ return parseFactsFence((await engine.getPage(SLUG, { sourceId: 'default' }))!.compiled_truth).facts.map(f => [f.rowNum, f.claim]);+ }+ const FENCED = [[1, 'Alice example joined Acme example'], [2, 'Alice example moved to Lisbon'], [3, 'Alice example prefers async updates']];++ test(`${backend}: unmanaged (#6610): a database-only page with sync.write_through off gets its rows fenced into its database body`, async () => {+ await unmanagedBrain(databaseUrl, async ({ engine, root }) => {+ await makeDatabaseOnly(engine, root);+ await engine.setConfig('sync.write_through', 'false');+ const first = await extractFactsPhase(engine, root);+ expect(first.status, JSON.stringify(first.details)).toBe('ok');+ expect(first.details).toMatchObject({ unfencedRowsFenced: 2, legacyRowsPending: 0, pagesFailed: 0 });+ expect(await pendingCount(engine)).toBe(0);+ expect(await databaseFence(engine)).toEqual(FENCED);+ const after = await factState(engine);+ expect(after.slice(0, 3).map(r => [r.row_num, r.source_markdown_slug, r.expired])).toEqual([[1, SLUG, false], [2, SLUG, false], [3, SLUG, false]]);+ const page = (await engine.getPage(SLUG, { sourceId: 'default' }))!;+ expect(page.source_path ?? null).toBeNull();+ expect(existsSync(join(root, `${SLUG}.md`))).toBe(false);+ const second = await extractFactsPhase(engine, root);+ expect(second.details).toMatchObject({ unfencedRowsFenced: 0, factsInserted: 0, factsDeleted: 0 });+ expect(await factState(engine)).toEqual(after);+ });+ }, 120_000);++ if (backend === 'postgres') {+ test('postgres: unmanaged (#6610): an unbound source with persistence.unbound_write=database_only fences a database-only page in its database body', async () => {+ await unmanagedBrain(databaseUrl, async ({ engine, root }) => {+ await makeDatabaseOnly(engine, root);+ await engine.setConfig('persistence.unbound_write', 'database_only');+ const result = await extractFactsPhase(engine, root);+ expect(result.status, JSON.stringify(result.details)).toBe('ok');+ expect(result.details).toMatchObject({ unfencedRowsFenced: 2, legacyRowsPending: 0 });+ expect(await databaseFence(engine)).toEqual(FENCED);+ const [page] = await engine.executeRaw<{ database_only_reason: string | null }>(+ "SELECT database_only_reason FROM pages WHERE source_id = 'default' AND slug = $1", [SLUG]);+ expect(page.database_only_reason).toBe('unbound_source');+ expect(existsSync(join(root, `${SLUG}.md`))).toBe(false);+ });+ }, 120_000);++ test('postgres: unmanaged (#6610): without the opt-in the rows stay unfenced, never gate the run, and fence_integrity names the opt-in', async () => {+ await unmanagedBrain(databaseUrl, async ({ engine, root }) => {+ await makeDatabaseOnly(engine, root);+ const before = await factState(engine);+ const result = await extractFactsPhase(engine, root);+ expect(result.status, JSON.stringify(result.details)).toBe('ok');+ expect(result.details).toMatchObject({ unfencedRowsFenced: 0, legacyRowsPending: 0, legacyPages: [] });+ expect((result.details as { warnings: string[] }).warnings.some(w => w.startsWith('FACTS_FENCE_FAILED'))).toBe(false);+ // Held out of reconciliation: nothing expired, detached or renumbered.+ expect(await factState(engine)).toEqual(before);+ const doctor = await fenceIntegrityResult(engine, { sourceIds: ['default'] });+ expect(doctor.status).toBe('warn');+ expect(doctor.details).toMatchObject({ unbound_legacy_facts: { total: 2, pages: [{ source_id: 'default', slug: SLUG, rows: 2 }] } });+ expect(doctor.message).toContain('gbrain config set persistence.unbound_write database_only');+ expect(doctor.fix).toMatchObject({ argv: ['gbrain', 'config', 'set', 'persistence.unbound_write', 'database_only'], ask_user: true });+ });+ }, 120_000);+ }+test(`${backend}: managed: one cycle fences row_num-NULL facts through the coordinator and a second cycle changes nothing`, async () => {let seed!: LegacySeed;await managedBrain(async ({ engine: managed, root: managedRoot }) => {