Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): the extract_facts cycle phase fences row_num-NULL facts itself (#5299)

garrytan7007ba607941
diff --git a/TODOS.md b/TODOS.md
index eb6f664239..0a7eb3bf17 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -120,7 +120,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
**What:** wave 8's conformance gate (`test/fixtures/write-contract-conformance-cases.ts`) covers only the contracts this wave changed. **Fix:** every op × PGLite/Postgres/PgBouncer × stdio/HTTP, asserting the error-code taxonomy. **Effort:** L. **Priority:** P2 (Foundations 2).
- [ ] **P2 — Restore the `auto_chronicle` trigger (#5876).**
**What:** `auto_chronicle=true` still has no effect; doctor and the advisor say so. #5329's backfill idempotency landed in v0.60.32.0, so re-enabling the trigger no longer means duplicate event pages from repeat runs. **Fix:** call `runChronicleBackstop` from the import path behind the flag, with a cost note. **Effort:** M. **Priority:** P2 (Foundations 2).
-- [ ] **P2 — Cycle-side fence for `row_num IS NULL` facts (#5299).**
+- [x] **P2 — Cycle-side fence for `row_num IS NULL` facts (#5299).** **Completed** — the `extract_facts` phase fences them itself every cycle through the shared core pass (`src/core/facts/unfenced-facts.ts`) and reconciles those pages in the same run.
**What:** facts without a fence row number are invisible to the fence reconciler. **Fix:** the cycle fences them after GBRA-35's facts writeback (now on master). **Effort:** M. **Priority:** P2 (Foundations 2).
- [ ] **P2 — One-shot repair for supersession chains broken on managed brains (#5886).**
**What:** v0.60.36.0 writes the supersession pointer on the old take row; chains written before it keep `superseded_by` NULL on managed brains. **Fix:** a `gbrain repair` kind that rebuilds the pointers from the fence. **Effort:** S. **Priority:** P2.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 8389ad7bb7..43188f770c 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and still skip the destructive reconcile (the empty-fence guard, `legacyRowsPending`), while rows with no backing page or checkout never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index cab0f99526..6f5b59f4a4 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -28,7 +28,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. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.serial.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.
- `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`.
-- `src/commands/migrations/v0_32_2.ts` — fences live legacy facts only onto an existing source-scoped page and its recorded canonical file. Missing pages/files are counted as `skipped_no_page`, never materialized as stubs. Dirty-tree checks stay 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.
+- `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 its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included), 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.
- `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.serial.test.ts` (+ Postgres twin), no `runCycle` mock.
diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsv
index 42080cd462..67f592cc09 100644
--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv
+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv
@@ -38,7 +38,6 @@ src/core/backup/repository.ts 1
src/core/brainstorm/error-classify.ts 1
src/core/connectors/sync.ts 8
src/core/context/hook-heartbeat.ts 2
-src/core/cycle.ts 1
src/core/cycle/patterns.ts 1
src/core/cycle/synthesize.ts 1
src/core/error-catalogue.ts 2
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index dc98e5ee65..ae0cc2c252 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -384,7 +384,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/ops/links.ts": ["test/e2e/managed-writers-w3.test.ts", "test/e2e/federated-link-reads-postgres.test.ts"],
"src/core/cycle/extract-atoms-page-state.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],
"src/commands/migrations/v0_13_1.ts": ["test/e2e/grandfather-projection-postgres.test.ts", "test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],
- "src/commands/migrations/v0_32_2.ts": ["test/e2e/migrations-v0_32_2-managed.test.ts"],
+ "src/commands/migrations/v0_32_2.ts": ["test/e2e/migrations-v0_32_2-managed.test.ts", "test/e2e/extract-facts-unfenced-rows-postgres.test.ts"],
+ // #5299: the shared unfenced-facts fence pass (migration Phase B + extract_facts).
+ "src/core/facts/unfenced-facts.ts": ["test/e2e/extract-facts-unfenced-rows-postgres.test.ts", "test/e2e/migrations-v0_32_2-managed.test.ts"],
"src/core/facts/withdrawal.ts": ["test/e2e/facts-withdrawal-fingerprint-once.test.ts"],
"src/core/extract-takes-from-pages.ts": ["test/e2e/persistence-managed-takes-extract.test.ts", "test/e2e/extract-takes-from-pages-resolutions.test.ts"],
"src/core/persistence/prepared-maintenance.ts": ["test/e2e/migrations-v0_32_2-managed.test.ts", "test/e2e/fix-wave-4-integration.test.ts", "test/e2e/managed-connector-job-contract.test.ts", "test/e2e/maintenance-write-wait.test.ts"],
@@ -665,7 +667,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/serve-http-ingest-webhook.test.ts",
],
"src/core/embed-facts*.ts": ["test/e2e/fact-embedding-backfill-parity.test.ts"],
- "src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts", "test/e2e/write-attribution-postgres.test.ts"],
+ "src/core/cycle/extract-facts.ts": ["test/e2e/fact-vector-repair-parity.test.ts", "test/e2e/facts-fence-reconcile-postgres.test.ts", "test/e2e/write-attribution-postgres.test.ts", "test/e2e/extract-facts-unfenced-rows-postgres.test.ts"],
"src/core/cycle/phases/consolidate.ts": ["test/e2e/managed-maintenance.test.ts", "test/e2e/cycle.test.ts"],
"src/core/ops/facts.ts": ["test/e2e/managed-facts-backstop.test.ts"],
"src/core/facts/backstop.ts": ["test/e2e/capture-dedup-postgres.test.ts", "test/e2e/managed-facts-backstop.test.ts", "test/e2e/facts-worker-config.test.ts", "test/e2e/managed-facts-embedding.test.ts", "test/e2e/managed-facts-compaction.test.ts", "test/e2e/legacy-fact-extraction-dedup-postgres.test.ts"],
diff --git a/src/commands/migrations/v0_32_2.ts b/src/commands/migrations/v0_32_2.ts
index 6cb3391c21..6aa031c362 100644
--- a/src/commands/migrations/v0_32_2.ts
+++ b/src/commands/migrations/v0_32_2.ts
@@ -22,12 +22,13 @@
*
* Idempotency: phase B only touches rows with row_num IS NULL. Re-runs
* after a partial completion pick up where the previous run stopped.
- * Managed brains publish each page through the coordinator
- * (`managed_maintenance_adopt_fact_fence`) instead of writing files and
- * facts directly, and verify from the database.
- * Per-page atomic (.tmp + parse + rename, same primitive as
- * fence-write.ts). Dirty-tree refusal mirrors src/core/dry-fix.ts so
- * the user can review the diff before committing.
+ * Phase B is the shared core pass `src/core/facts/unfenced-facts.ts`, which
+ * the extract_facts cycle phase also runs: managed brains publish each page
+ * through the coordinator (`managed_maintenance_adopt_fact_fence`) and
+ * verify from the database; unmanaged pages are written per page atomically
+ * (.tmp + parse + rename under the page lock, same primitive as
+ * fence-write.ts). The migration adds a dirty-tree refusal that mirrors
+ * src/core/dry-fix.ts so the user can review the diff before committing.
*
* Facts with NULL entity_slug are structurally unfenceable (no page to
* fence onto). They're skipped with a warning; the operator decides
@@ -35,7 +36,7 @@
* forever; they live in the legacy keyspace permanently.
*/
-import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import type {
@@ -44,14 +45,13 @@ import type {
import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
-import { formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../../core/facts-fence.ts';
+import { parseFactsFence } from '../../core/facts-fence.ts';
import { duplicateActiveFenceRows } from '../../core/facts/extract-from-fence.ts';
import { resolvePageWriteTarget } from '../../core/write-through.ts';
import { serializePageToMarkdown } from '../../core/markdown.ts';
import { managedPersistenceEnabled } from '../../core/persistence/ownership.ts';
-import { assertLifetimeIdHeadroom } from '../../core/persistence/journal.ts';
import { OperationError } from '../../core/ops/contract.ts';
-import { maintenancePreflight, submitFactFenceAdoption, type MaintenanceAuthority } from '../../core/persistence/prepared-maintenance.ts';
+import { fenceableRowCount, fenceUnfencedFacts, planUnfencedFacts, type UnfencedFactsOutcome } from '../../core/facts/unfenced-facts.ts';
let testEngineOverride: BrainEngine | null = null;
export function __setTestEngineOverride(engine: BrainEngine | null): void {
@@ -112,43 +112,6 @@ async function phaseASchema(
// ── Phase B — Fence facts ──────────────────────────────────
-interface LegacyFactRow {
- id: string; // BIGSERIAL — string-typed on the wire for safety
- source_id: string;
- entity_slug: string | null;
- fact: string;
- kind: 'event' | 'preference' | 'commitment' | 'belief' | 'fact';
- visibility: 'private' | 'world';
- notability: 'high' | 'medium' | 'low';
- context: string | null;
- valid_from: Date;
- valid_until: Date | null;
- source: string;
- confidence: number;
- claim_metric: string | null;
- claim_value: number | null;
- claim_unit: string | null;
- claim_period: string | null;
- page_exists: boolean;
-}
-
-interface SourceLookup {
- id: string;
- local_path: string | null;
- archived?: boolean;
-}
-
-interface PhaseBOutcome {
- scanned: number;
- fenced: number;
- skipped_no_entity: number;
- skipped_no_local_path: number;
- skipped_no_page: number;
- skipped_archived: number;
- pages_touched: number;
- failed_pages: string[];
-}
-
/**
* Dirty-tree refusal: mirror src/core/dry-fix.ts behavior. Refuses to
* write if any source's local_path has uncommitted changes. Dry-run
@@ -170,112 +133,11 @@ function isLocalPathDirty(localPath: string): boolean {
}
/**
- * Append a page's legacy rows to its facts fence. Row numbering starts above
- * every occupied `row_num` on the page, conversation-extractor rows
- * included, so no fence row can take an extractor row's position. A fence
- * row left by a partial earlier run with the same claim and source and no
- * database owner is reused instead of appended again.
+ * Fence every unfenced row through the shared core pass
+ * (`src/core/facts/unfenced-facts.ts`, also run by the extract_facts cycle
+ * phase). The migration adds only its dirty-tree refusal on unmanaged
+ * sources, so the user can review the diff before committing.
*/
-async function planFence(engine: BrainEngine, sourceId: string, entitySlug: string, body: string, group: LegacyFactRow[]):
- Promise<{ body: string; assignments: Array<{ id: string; row_num: number }> } | { warnings: string[] }> {
- const existingFence = parseFactsFence(body);
- if (existingFence.warnings.length > 0) return { warnings: existingFence.warnings };
- const occupiedRows = await engine.executeRaw<{ row_num: number; fact: string; source: string | null }>(
- `SELECT row_num, fact, source FROM facts
- WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL`,
- [sourceId, entitySlug],
- );
- const occupied = new Map(occupiedRows.map(row => [Number(row.row_num), row]));
- let nextRowNum = Math.max(0, ...occupied.keys(), ...existingFence.facts.map(f => f.rowNum)) + 1;
- const claimed = new Set<number>();
- const assignments: Array<{ id: string; row_num: number }> = [];
- for (const row of group) {
- const existing = existingFence.facts.find(f => {
- const owner = occupied.get(f.rowNum);
- return f.active && !claimed.has(f.rowNum) && f.claim === row.fact &&
- (f.source ?? '') === (row.source ?? '') &&
- (!owner || owner.fact !== f.claim || (owner.source ?? '') !== (f.source ?? ''));
- });
- if (existing) {
- if (occupied.has(existing.rowNum)) existing.rowNum = nextRowNum++;
- assignments.push({ id: row.id, row_num: existing.rowNum });
- claimed.add(existing.rowNum);
- continue;
- }
- // Full timestamps survive the fence (date-only at midnight UTC), so the
- // canonical projection writes back the value the row already holds.
- const validFromStr = formatFenceDate(row.valid_from instanceof Date ? row.valid_from : new Date(row.valid_from));
- const validUntilStr = row.valid_until
- ? formatFenceDate(row.valid_until instanceof Date ? row.valid_until : new Date(row.valid_until))
- : undefined;
- const rowNum = nextRowNum++;
- existingFence.facts.push({
- rowNum,
- active: true,
- claim: row.fact,
- kind: row.kind,
- confidence: row.confidence,
- visibility: row.visibility,
- notability: row.notability,
- validFrom: validFromStr,
- validUntil: validUntilStr,
- source: row.source,
- context: row.context ?? undefined,
- ...(row.claim_metric ? { claimMetric: row.claim_metric } : {}),
- ...(row.claim_value != null ? { claimValue: Number(row.claim_value) } : {}),
- ...(row.claim_unit ? { claimUnit: row.claim_unit } : {}),
- ...(row.claim_period ? { claimPeriod: row.claim_period } : {}),
- });
- assignments.push({ id: row.id, row_num: rowNum });
- claimed.add(rowNum);
- }
- return { body: replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts)), assignments };
-}
-
-/**
- * Managed brains (#5728 class): the managed writer guard refuses direct fence
- * writes into the canonical worktree and any raw `UPDATE facts`. Each page
- * publishes its rendered fence through the coordinator as one
- * `managed_maintenance_adopt_fact_fence` request that adopts the legacy rows
- * in place. The page body comes from the database, so database-only pages
- * are included.
- */
-async function fenceFactsManaged(engine: BrainEngine, groups: Map<string, LegacyFactRow[]>, outcome: PhaseBOutcome): Promise<void> {
- const authorities = new Map<string, MaintenanceAuthority>();
- for (const key of groups.keys()) {
- const sourceId = key.split('\0')[0];
- if (!authorities.has(sourceId)) authorities.set(sourceId, (await maintenancePreflight(engine, sourceId))!);
- }
- // One admission per page: refuse up front, before any page publishes,
- // when the permanent request-ID caps cannot cover them all.
- const [first] = authorities.values();
- if (first) await assertLifetimeIdHeadroom(engine, first.writer.principal, groups.size);
- for (const [key, group] of groups) {
- const [sourceId, entitySlug] = key.split('\0');
- try {
- const authority = authorities.get(sourceId)!;
- const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });
- if (!snapshot) { outcome.skipped_no_page += group.length; continue; }
- const plan = await planFence(engine, sourceId, entitySlug, serializePageToMarkdown(snapshot.page, snapshot.tags), group);
- if ('warnings' in plan) {
- outcome.failed_pages.push(`${entitySlug} (${plan.warnings.join('; ')})`);
- continue;
- }
- const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
- await submitFactFenceAdoption(engine, authority, entitySlug, {
- content: plan.body, expectedRevision: snapshot.revision,
- assignments: plan.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)),
- });
- outcome.fenced += plan.assignments.length;
- outcome.pages_touched += 1;
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- outcome.failed_pages.push(`${entitySlug} (${msg})`);
- }
- }
-}
-
async function phaseBFenceFacts(
engine: BrainEngine | null,
opts: OrchestratorOpts,
@@ -285,162 +147,46 @@ async function phaseBFenceFacts(
}
try {
- const managed = await managedPersistenceEnabled(engine);
- // Look up all sources + their local_paths.
- const sources = await engine.executeRaw<SourceLookup>(
- `SELECT id, local_path, archived FROM sources`,
- );
- const localPathById = new Map<string, string | null>();
- for (const s of sources) localPathById.set(s.id, s.local_path);
- const archived = new Set(sources.filter(s => s.archived).map(s => s.id));
-
- // Walk legacy rows in (source_id, entity_slug) groups for per-page
- // atomic writes.
- const legacy = await engine.executeRaw<LegacyFactRow>(
- `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,
- 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
- WHERE row_num IS NULL AND expired_at IS NULL
- ORDER BY source_id, entity_slug, id`,
- );
-
- const outcome: PhaseBOutcome = {
- scanned: legacy.length,
- fenced: 0,
- skipped_no_entity: 0,
- skipped_no_local_path: 0,
- skipped_no_page: 0,
- skipped_archived: 0,
- pages_touched: 0,
- failed_pages: [],
- };
-
- // Group by (source_id, entity_slug) so each page's fence is updated
- // atomically with all its legacy rows.
- const groups = new Map<string, LegacyFactRow[]>();
- for (const row of legacy) {
- if (row.entity_slug === null) {
- outcome.skipped_no_entity += 1;
- continue;
- }
- // A managed brain publishes through the source's maintenance authority,
- // which an archived source does not grant; it never blocks the others.
- if (managed && archived.has(row.source_id)) {
- outcome.skipped_archived += 1;
- continue;
- }
- const localPath = localPathById.get(row.source_id);
- if (!localPath && !managed) {
- outcome.skipped_no_local_path += 1;
- continue;
- }
- if (!row.page_exists) {
- outcome.skipped_no_page += 1;
- continue;
- }
- const key = `${row.source_id}\0${row.entity_slug}`;
- const list = groups.get(key) ?? [];
- list.push(row);
- groups.set(key, list);
- }
-
- const filePaths = new Map<string, string>();
- 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;
- groups.delete(key);
- continue;
- }
- filePaths.set(key, target.filePath);
- }
+ const plan = await planUnfencedFacts(engine);
+ const { outcome } = plan;
if (opts.dryRun) {
- const fenceable = [...groups.values()].reduce((n, group) => n + group.length, 0);
return {
name: 'fence_facts', status: 'skipped',
- detail: `dry-run: would fence ${fenceable} rows; ${outcome.skipped_no_entity} unfenceable (NULL entity_slug); ` +
+ 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}`,
};
}
- if (managed) {
- try { await fenceFactsManaged(engine, groups, outcome); }
- catch (error) {
- if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;
- return { name: 'fence_facts', status: 'failed', detail: `queue_capacity: ${error.message} ${error.suggestion ?? ''}`.trim() };
- }
- return fenceFactsResult(outcome);
- }
-
- // Dirty-tree refusal: check ONLY the sources we are about to write
- // into. A dirty tree in an unrelated source (or zero fenceable rows
- // at all) must not block a no-op or a targeted backfill (#927).
- const targetSourceIds = new Set([...groups.keys()].map(k => k.split('\0')[0]));
- for (const id of targetSourceIds) {
- const localPath = localPathById.get(id);
- if (localPath && isLocalPathDirty(localPath)) {
- return {
- name: 'fence_facts',
- status: 'failed',
- detail: `source "${id}" has uncommitted changes in ${localPath}. Commit or stash, then re-run.`,
- };
- }
- }
-
- for (const [key, group] of groups) {
- const [sourceId, entitySlug] = key.split('\0');
- const filePath = filePaths.get(key)!;
- const tmpPath = `${filePath}.tmp`;
-
- try {
- let body = readFileSync(filePath, 'utf-8');
-
- const plan = await planFence(engine, sourceId, entitySlug, body, group);
- if ('warnings' in plan) {
- outcome.failed_pages.push(`${entitySlug} (${plan.warnings.join('; ')})`);
- continue;
- }
- const assignments = plan.assignments;
- body = plan.body;
-
- // Atomic write: .tmp + parse + rename.
- writeFileSync(tmpPath, body, 'utf-8');
- const tmpBody = readFileSync(tmpPath, 'utf-8');
- const parsed = parseFactsFence(tmpBody);
- if (parsed.warnings.length > 0) {
- outcome.failed_pages.push(`${entitySlug} (${parsed.warnings.join('; ')})`);
- // .tmp stays for inspection; do NOT rename.
- continue;
+ if (!plan.managed) {
+ // Dirty-tree refusal: check ONLY the sources we are about to write
+ // into. A dirty tree in an unrelated source (or zero fenceable rows
+ // at all) must not block a no-op or a targeted backfill (#927).
+ const targetSourceIds = new Set([...plan.groups.keys()].map(k => k.split('\0')[0]));
+ for (const id of targetSourceIds) {
+ const localPath = plan.localPathById.get(id);
+ if (localPath && isLocalPathDirty(localPath)) {
+ return {
+ name: 'fence_facts',
+ status: 'failed',
+ detail: `source "${id}" has uncommitted changes in ${localPath}. Commit or stash, then re-run.`,
+ };
}
- renameSync(tmpPath, filePath);
-
- // UPDATE the DB rows with their new row_nums + source_markdown_slug.
- for (const a of assignments) {
- await engine.executeRaw(
- `UPDATE facts SET row_num = $1, source_markdown_slug = $2 WHERE id = $3`,
- [a.row_num, entitySlug, a.id],
- );
- }
- outcome.fenced += assignments.length;
- outcome.pages_touched += 1;
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- outcome.failed_pages.push(`${entitySlug} (${msg})`);
}
}
+ try { await fenceUnfencedFacts(engine, plan); }
+ catch (error) {
+ if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;
+ return { name: 'fence_facts', status: 'failed', detail: `queue_capacity: ${error.message} ${error.suggestion ?? ''}`.trim() };
+ }
return fenceFactsResult(outcome);
} catch (e) {
return { name: 'fence_facts', status: 'failed', detail: e instanceof Error ? e.message : String(e) };
}
}
-function fenceFactsResult(outcome: PhaseBOutcome): OrchestratorPhaseResult {
+function fenceFactsResult(outcome: UnfencedFactsOutcome): OrchestratorPhaseResult {
const detail = `scanned=${outcome.scanned} fenced=${outcome.fenced} ` +
`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}` +
@@ -456,6 +202,11 @@ function fenceFactsResult(outcome: PhaseBOutcome): OrchestratorPhaseResult {
return { name: 'fence_facts', status: 'complete', detail };
}
+interface SourceLookup {
+ id: string;
+ local_path: string | null;
+}
+
// ── Phase C — Verify ────────────────────────────────────────
/** Row numbers a drift detail names per side before it summarizes the rest. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 742267af39..34733a9a74 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
- 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
+ 'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--query', '--quiet', '--save', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--add', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 45a88fc92e..cb700593ac 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1446,20 +1446,18 @@ async function runPhaseExtractFacts(
signal,
});
- // Empty-fence guard: pre-v51 legacy rows pending the v0_32_2 backfill.
- // Surface as 'warn' so doctor + the cycle report can see it; don't fail
- // the cycle because the workaround is well-defined (run apply-migrations).
+ // Empty-fence guard: unfenced rows the phase's own fence step could not
+ // fence this run. Surface as 'warn' so doctor + the cycle report can see
+ // it; the warnings name each page and why.
if (result.guardTriggered) {
return {
phase: 'extract_facts',
status: 'warn',
duration_ms: 0,
- summary: `extract_facts skipped: ${result.legacyRowsPending} legacy v0.31 facts pending fence backfill`,
+ summary: `extract_facts skipped: ${result.legacyRowsPending} unfenced fact row(s) could not be fenced`,
details: {
legacyRowsPending: result.legacyRowsPending,
- // A bare `apply-migrations --yes` no-ops once the v0.32.2 ledger
- // entry is complete; the retry marker is what re-runs Phase B.
- hint: 'gbrain apply-migrations --force-retry 0.32.2 && gbrain apply-migrations --yes',
+ unfencedRowsFenced: result.unfencedRowsFenced,
warnings: result.warnings,
},
};
@@ -1501,6 +1499,7 @@ async function runPhaseExtractFacts(
pagesWithFacts: result.pagesWithFacts,
factsInserted: result.factsInserted,
factsDeleted: result.factsDeleted,
+ unfencedRowsFenced: result.unfencedRowsFenced,
pagesFailed: result.pagesFailed,
warnings: result.warnings.slice(0, 5),
// v0.35.5: phantom counters surfaced so extractTotals() can lift
@@ -2301,9 +2300,9 @@ export async function runCycle(
// Reconcile DB facts index from the `## Facts` fence on every
// affected entity page. Runs AFTER extract (link/timeline
// materialization) and BEFORE patterns/recompute_emotional_weight
- // so downstream phases see fresh DB facts. Empty-fence guard
- // refuses to run while v0.31 legacy facts are pending the
- // v0_32_2 backfill (Codex R2-#7).
+ // so downstream phases see fresh DB facts. The phase first fences
+ // unfenced (`row_num IS NULL`) rows itself; rows it could not fence
+ // still skip reconciliation (Codex R2-#7, #5299).
if (phases.includes('extract_facts')) {
checkAborted(cycleSignal);
if (!engine) {
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 1ca31c4d81..b5a4b6f2b4 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -23,33 +23,23 @@
* fence-owned and are left alone. Active fence-owned rows of soft-deleted
* pages are expired at the start of each run.
*
- * Empty-fence guard (Codex R2-#7; #2484; #2646): the phase refuses to do
- * its destructive reconciliation pass when genuinely-backfillable legacy
- * rows still exist — in THIS run's source only (`source_id = sourceId`;
- * a pending row in source A must not jam extraction for source B — the
- * source-isolation invariant) — `row_num IS NULL` (never fenced) AND
- * `entity_slug` resolves to a live page in this source (so the v0_32_2
- * migration's Phase B could fence them) AND the row is not soft-expired
- * (`expired_at IS NULL`). Status returns `warn` with a hint to re-run
- * the v0.32.2 fence backfill (`apply-migrations --force-retry 0.32.2`
- * then `--yes` — a bare `--yes` is a no-op once the ledger says
- * complete). Without the guard, an interrupted upgrade where v0_32_2
- * hasn't run could leave the cycle silently misreporting "0 facts on
- * people/alice" while legacy rows linger.
+ * Unfenced rows (#5299): each run first fences the source's active
+ * `row_num IS NULL` rows onto their live entity pages through the shared
+ * core pass (`facts/unfenced-facts.ts`, also the v0.32.2 migration's Phase
+ * B) and reconciles those pages in the same run. The inline writer's
+ * DB-only fallback keeps producing such rows, so no manual migration retry
+ * is needed.
*
- * The live-page requirement (#2484) is load-bearing: the inline facts
- * writer keeps producing `row_num IS NULL, entity_slug IS NOT NULL`
- * rows AFTER the migration completes, whenever a resolved slug has no
- * fenceable page (slugify-floor / stub-guard-blocked unprefixed slugs).
- * Those are structurally unfenceable — no page to fence onto, and the
- * ledger-complete migration won't re-run — so they must NOT gate, or
- * the phase jams forever (~16/day observed). Requiring a backing page
- * keeps genuine pre-v0.32.2 rows (whose entity page exists) gating
- * while excluding the inline-writer's permanent-unfenceable rows.
- *
- * Soft-expired rows don't count either (#2646): they're what
- * `forget_fact` produces, so excluding them lets operators drain the
- * backlog through the sanctioned removal path instead of raw SQL.
+ * Empty-fence guard (Codex R2-#7; #2484; #2646): rows the fence step could
+ * not fence this run (a page whose file is not on this host, a malformed
+ * fence, a held page lock) still block the destructive reconciliation pass
+ * — in THIS run's source only (`source_id = sourceId`, the source-isolation
+ * invariant). A row counts when `row_num IS NULL`, its `entity_slug`
+ * resolves to a live page in this source, it is not soft-expired
+ * (`expired_at IS NULL`; `forget_fact` drains rows that way) and the source
+ * has a `local_path`. Status returns `warn` naming each failed page. Rows
+ * with no backing page or checkout (slugify-floor / stub-guard-blocked
+ * slugs from the inline writer) are structurally unfenceable and never gate.
*/
import { existsSync, readFileSync } from 'node:fs';
@@ -64,6 +54,7 @@ import {
type SupersessionChain,
} from '../facts/supersede-resolve.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
+import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';
import {
@@ -346,7 +337,10 @@ export interface ExtractFactsResult {
factsUpdated: number;
/** Fence-owned rows expired and detached because their row left the fence. */
factsDeleted: number;
+ /** Unfenced rows (`row_num IS NULL`, live entity page) still pending after this run's fence step. */
legacyRowsPending: number;
+ /** Unfenced rows this run appended to their page's fence and stamped with a row number (#5299). */
+ unfencedRowsFenced: number;
/** Active fence-owned rows expired because their page was soft-deleted. */
factsExpiredForDeletedPages: number;
guardTriggered: boolean;
@@ -453,6 +447,7 @@ export async function runExtractFacts(
factsUpdated: 0,
factsDeleted: 0,
legacyRowsPending: 0,
+ unfencedRowsFenced: 0,
factsExpiredForDeletedPages: 0,
pagesFailed: 0,
guardTriggered: false,
@@ -465,48 +460,34 @@ export async function runExtractFacts(
phantomsMorePending: false,
};
+ // ── Fence unfenced rows (#5299) ─────────────────────────────────
+ // The inline writer's DB-only fallback keeps producing `row_num IS NULL`
+ // rows on live entity pages (a write from a host without the checkout,
+ // `sync.write_through=off`). Each run fences them itself through the
+ // shared core pass (the v0.32.2 migration's Phase B): the coordinator on a
+ // managed brain, the page file + maintenance transaction otherwise. The
+ // fenced pages join this run's reconcile below.
+ let fencedSlugs: 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;
+ 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)}`);
+ }
+ }
+
// ── Empty-fence guard (Codex R2-#7; #2484; #2646) ──────────────
- // Pre-check: if any genuinely-backfillable legacy fact rows exist,
- // refuse to run the destructive reconciliation pass — the v0_32_2
- // orchestrator must fence them first.
- //
- // A row is a real backfill candidate only when `row_num IS NULL`
- // (never fenced) AND its `entity_slug` resolves to a LIVE page in
- // this source (the migration's Phase B only fences rows whose
- // entity_slug maps to a writable page) AND it is not soft-expired.
- // #2484: the original predicate was just `row_num IS NULL AND
- // entity_slug IS NOT NULL`, which ALSO matched
- // structurally-unfenceable hot-memory rows the inline writer keeps
- // producing post-migration: the legacy DB-only fallback
- // (backstop.ts) writes `entity_slug` (a resolved slug, e.g. a
- // slugify-floor or stub-guard-blocked unprefixed slug like
- // `people-jane-doe`) with `row_num` NULL whenever the slug has no
- // fenceable page. Those rows can never satisfy the migration's exit
- // condition (no page to fence onto, and `apply-migrations` is a
- // ledger-complete no-op for them), so they jammed the phase forever
- // — ~16/day, mislabeled "v0.31 pending backfill." We now require a
- // live backing page, which both genuine pre-v0.32.2 rows (their
- // entity page exists) satisfy and inline-writer unfenceable rows do
- // not. #2646: soft-expired rows (`expired_at IS NOT NULL`) are also
- // excluded — `forget_fact`, the officially sanctioned removal path,
- // soft-expires legacy rows rather than deleting them, so counting
- // expired rows would leave the guard permanently stuck with no
- // supported way to drain the backlog.
- //
- // Source isolation (#3526): the count is scoped to THIS run's
- // sourceId. The pre-fix query counted brain-wide, so a single pending
- // legacy row in any mounted source jammed extract_facts for every
- // source — a cross-source leak of one source's migration state into
- // another's cycle (CLAUDE.md source-isolation invariant).
- //
- // #2763: the count also requires the source to have a `local_path` —
- // mirroring the v0_32_2 Phase B fenceability rule (its backfill SKIPS
- // rows whose source has no local_path, `skipped_no_local_path`, yet
- // still returns complete). On a thin-client / DB-only source the
- // backstop writer keeps producing row_num-NULL rows whose entity_slug
- // maps to a LIVE page; without the local_path check those rows
- // tripped the guard forever with drain advice (`apply-migrations
- // --force-retry 0.32.2`) that is a structural no-op for them.
+ // Rows the fence step could not fence this run still block the destructive
+ // reconciliation pass. A row counts only when `row_num IS NULL`, its
+ // `entity_slug` resolves to a LIVE page in THIS run's source (#3526 source
+ // isolation), it is not soft-expired (#2646: `forget_fact` drains rows by
+ // soft-expiring them), and the source has a `local_path` (#2763). Rows
+ // without a page or checkout (#2484: the inline writer's
+ // slugify-floor / stub-guard-blocked slugs) are structurally unfenceable
+ // and never gate.
const legacy = await engine.executeRaw<{ n: string }>(
`SELECT COUNT(*) AS n
FROM facts f
@@ -531,25 +512,17 @@ export async function runExtractFacts(
result.legacyRowsPending = legacyCount;
if (legacyCount > 0) {
result.guardTriggered = true;
- // Drain advice must actually work: a bare `apply-migrations --yes`
- // is a no-op once the v0.32.2 ledger entry says complete (the
- // runner classifies it as already-applied), so the sanctioned
- // re-run path is the explicit retry marker first. Phase B is
- // idempotent — it only touches `row_num IS NULL` rows and de-dupes
- // against the existing fence — so the re-run is safe. Individual
- // rows can instead be drained through `forget_fact` (soft-expired
- // rows stop counting).
result.warnings.push(
- `extract_facts: ${legacyCount} legacy v0.31 fact rows in source "${sourceId}" ` +
- `(entity page present, not yet fenced) pending fence backfill. Re-run the v0.32.2 ` +
- `fence backfill: \`gbrain apply-migrations --force-retry 0.32.2\` then ` +
- `\`gbrain apply-migrations --yes\`. Or drain individual rows via \`forget_fact\`.`,
+ `extract_facts: ${legacyCount} unfenced fact row(s) in source "${sourceId}" (entity page present, row_num NULL) ` +
+ (opts.dryRun
+ ? 'would be fenced by this phase; a dry run writes nothing, so reconciliation is skipped.'
+ : 'could not be fenced this run, so reconciliation is skipped. 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. ' +
+ 'Individual rows can instead be drained via `forget_fact`.'),
);
// #3683: book the halt BEFORE the early return. The end-of-run rollup
- // write below is unreachable from this path, so pre-fix a guard-triggered
- // run recorded NOTHING in extract_rollup_7d — halt_count was structurally
- // 0 and doctor extract_health's `halt_rate > 10%` warning could never
- // fire for facts.fence no matter how long the phase stayed jammed.
+ // write below is unreachable from this path, so a guard-triggered run
+ // must record its halt here for doctor extract_health's halt_rate.
// upsertExtractRollup is best-effort internally (never throws).
if (!opts.dryRun) {
await upsertExtractRollup(engine, {
@@ -645,10 +618,8 @@ export async function runExtractFacts(
// Without this, an incremental-mode cycle with phantom-but-not-canonical
// in opts.slugs would leave canonical's DB facts stale until next full
// walk (codex A1 — the round-14 risk specialized to scenario B).
- if (phantomResult.touched_canonicals.length > 0) {
- const slugSet = new Set(slugs);
- for (const c of phantomResult.touched_canonicals) slugSet.add(c);
- slugs = Array.from(slugSet);
+ if (phantomResult.touched_canonicals.length > 0 || fencedSlugs.length > 0) {
+ slugs = Array.from(new Set([...slugs, ...phantomResult.touched_canonicals, ...fencedSlugs]));
}
// ── Reconcile each page ───────────────────────────────────────
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 921f421147..c18172b433 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -161,9 +161,9 @@ function recordWriteFailure(slug: string, sourceId: string, warnings: string[],
}
}
-type FactFenceGitPathState = 'clean' | 'self_dirty' | 'foreign_dirty' | 'unknown';
+export type FactFenceGitPathState = 'clean' | 'self_dirty' | 'foreign_dirty' | 'unknown';
-function gitPathState(repoPath: string, filePath: string): FactFenceGitPathState {
+export function gitPathState(repoPath: string, filePath: string): FactFenceGitPathState {
try {
const rel = relative(repoPath, filePath);
if (!rel || rel.startsWith('..') || isAbsolute(rel)) return 'unknown';
@@ -191,7 +191,7 @@ function gitPathState(repoPath: string, filePath: string): FactFenceGitPathState
}
}
-async function commitFactFenceFile(
+export async function commitFactFenceFile(
repoPath: string,
filePath: string,
slug: string,
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
new file mode 100644
index 0000000000..12f8962057
--- /dev/null
+++ b/src/core/facts/unfenced-facts.ts
@@ -0,0 +1,325 @@
+/**
+ * Fence unfenced fact rows (#5299): append every active fact row with
+ * `row_num IS NULL` to its entity page's `## Facts` fence and stamp the row
+ * with its fence row number, so the fence reconciler owns it.
+ *
+ * Shared by the v0.32.2 migration's Phase B and the `extract_facts` cycle
+ * phase. The inline writer's DB-only fallback keeps producing such rows (a
+ * write from a host without the source checkout, `sync.write_through=off`),
+ * so the cycle fences them on every run instead of waiting for a manual
+ * migration retry.
+ *
+ * Eligibility (`planUnfencedFacts`): the row names an `entity_slug`, its page
+ * is live in the row's source, and either the brain is managed (the
+ * coordinator publishes database-only pages too; archived sources are
+ * skipped) or the source has a `local_path` and the page's canonical file
+ * exists on this host. Everything else is counted and left alone: a NULL
+ * entity slug, a missing page or file, or a source without a checkout here.
+ *
+ * Write discipline (`fenceUnfencedFacts`):
+ * - Managed: one `managed_maintenance_adopt_fact_fence` request per page
+ * through the coordinator, which publishes the fence and adopts the rows
+ * in place (ids, vectors and provenance kept).
+ * - Unmanaged: under the source filesystem lock and the page lock, the same
+ * `.tmp` + parse + rename write as `fence-write.ts`, then one maintenance
+ * transaction mirrors the file body into `pages` and stamps the rows; a
+ * durability-hardened checkout commits the file.
+ * A page that fails is reported in `failed_pages`; the others still fence.
+ */
+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+
+import type { BrainEngine } from '../engine.ts';
+import { sanitizeText } from '../batch-rows.ts';
+import { isDurabilityHardened } from '../brain-repo-durability.ts';
+import { formatFenceDate, parseFactsFence, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';
+import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
+import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
+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 { contentHash } from '../utils.ts';
+import { resolvePageWriteTarget } from '../write-through.ts';
+import { commitFactFenceFile, gitPathState } from './fence-write.ts';
+
+interface UnfencedFactRow {
+ id: string;
+ source_id: string;
+ entity_slug: string | null;
+ fact: string;
+ kind: 'event' | 'preference' | 'commitment' | 'belief' | 'fact';
+ visibility: 'private' | 'world';
+ notability: 'high' | 'medium' | 'low';
+ context: string | null;
+ valid_from: Date;
+ valid_until: Date | null;
+ source: string;
+ confidence: number;
+ claim_metric: string | null;
+ claim_value: number | null;
+ claim_unit: string | null;
+ claim_period: string | null;
+ page_exists: boolean;
+}
+
+export interface UnfencedFactsOutcome {
+ scanned: number;
+ fenced: number;
+ skipped_no_entity: number;
+ skipped_no_local_path: number;
+ skipped_no_page: number;
+ skipped_archived: number;
+ pages_touched: number;
+ /** `<slug> (<reason>)` per page whose fence write failed; its rows stay unfenced. */
+ 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). */
+ missing_files: string[];
+}
+
+export interface UnfencedFactsPlan {
+ managed: boolean;
+ /** Fenceable rows grouped per page, keyed `<source_id>\0<entity_slug>`. */
+ groups: Map<string, UnfencedFactRow[]>;
+ /** Unmanaged: the canonical file per group key. */
+ filePaths: Map<string, string>;
+ localPathById: Map<string, string | null>;
+ outcome: UnfencedFactsOutcome;
+}
+
+/** Rows in the fenceable groups. */
+export function fenceableRowCount(plan: UnfencedFactsPlan): number {
+ return [...plan.groups.values()].reduce((n, group) => n + group.length, 0);
+}
+
+/** 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);
+ const sources = await engine.executeRaw<{ id: string; local_path: string | null; archived?: boolean }>(
+ 'SELECT id, local_path, archived FROM sources',
+ );
+ const localPathById = new Map(sources.map(s => [s.id, s.local_path] as const));
+ const archived = new Set(sources.filter(s => s.archived).map(s => s.id));
+ 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,
+ 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
+ WHERE row_num IS NULL AND expired_at IS NULL
+ ${opts.sourceId !== undefined ? 'AND source_id = $1' : ''}
+ ORDER BY source_id, entity_slug, id`,
+ opts.sourceId !== undefined ? [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: [],
+ };
+ const groups = new Map<string, UnfencedFactRow[]>();
+ for (const row of rows) {
+ if (row.entity_slug === null) { outcome.skipped_no_entity += 1; continue; }
+ // A managed brain publishes through the source's maintenance authority,
+ // which an archived source does not grant; it never blocks the others.
+ if (managed && archived.has(row.source_id)) { outcome.skipped_archived += 1; continue; }
+ if (!localPathById.get(row.source_id) && !managed) { outcome.skipped_no_local_path += 1; continue; }
+ if (!row.page_exists) { outcome.skipped_no_page += 1; continue; }
+ const key = `${row.source_id}\0${row.entity_slug}`;
+ groups.set(key, [...groups.get(key) ?? [], row]);
+ }
+ const filePaths = new Map<string, string>();
+ 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);
+ }
+ return { managed, groups, filePaths, localPathById, outcome };
+}
+
+/**
+ * Append a page's unfenced rows to its facts fence. Row numbering starts above
+ * every occupied `row_num` on the page, conversation-extractor rows included,
+ * so no fence row can take an extractor row's position. A fence row left by a
+ * partial earlier run with the same claim and source and no database owner is
+ * reused instead of appended again.
+ */
+async function planFence(engine: BrainEngine, sourceId: string, entitySlug: string, body: string, group: UnfencedFactRow[]):
+ Promise<{ body: string; assignments: Array<{ id: string; row_num: number }> } | { warnings: string[] }> {
+ const existingFence = parseFactsFence(body);
+ if (existingFence.warnings.length > 0) return { warnings: existingFence.warnings };
+ const occupiedRows = await engine.executeRaw<{ row_num: number; fact: string; source: string | null }>(
+ `SELECT row_num, fact, source FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num IS NOT NULL`,
+ [sourceId, entitySlug],
+ );
+ const occupied = new Map(occupiedRows.map(row => [Number(row.row_num), row]));
+ let nextRowNum = Math.max(0, ...occupied.keys(), ...existingFence.facts.map(f => f.rowNum)) + 1;
+ const claimed = new Set<number>();
+ const assignments: Array<{ id: string; row_num: number }> = [];
+ for (const row of group) {
+ const existing = existingFence.facts.find(f => {
+ const owner = occupied.get(f.rowNum);
+ return f.active && !claimed.has(f.rowNum) && f.claim === row.fact &&
+ (f.source ?? '') === (row.source ?? '') &&
+ (!owner || owner.fact !== f.claim || (owner.source ?? '') !== (f.source ?? ''));
+ });
+ if (existing) {
+ if (occupied.has(existing.rowNum)) existing.rowNum = nextRowNum++;
+ assignments.push({ id: row.id, row_num: existing.rowNum });
+ claimed.add(existing.rowNum);
+ continue;
+ }
+ // Full timestamps survive the fence (date-only at midnight UTC), so the
+ // canonical projection writes back the value the row already holds.
+ const validFromStr = formatFenceDate(row.valid_from instanceof Date ? row.valid_from : new Date(row.valid_from));
+ const validUntilStr = row.valid_until
+ ? formatFenceDate(row.valid_until instanceof Date ? row.valid_until : new Date(row.valid_until))
+ : undefined;
+ const rowNum = nextRowNum++;
+ existingFence.facts.push({
+ rowNum,
+ active: true,
+ claim: row.fact,
+ kind: row.kind,
+ confidence: row.confidence,
+ visibility: row.visibility,
+ notability: row.notability,
+ validFrom: validFromStr,
+ validUntil: validUntilStr,
+ source: row.source,
+ context: row.context ?? undefined,
+ ...(row.claim_metric ? { claimMetric: row.claim_metric } : {}),
+ ...(row.claim_value != null ? { claimValue: Number(row.claim_value) } : {}),
+ ...(row.claim_unit ? { claimUnit: row.claim_unit } : {}),
+ ...(row.claim_period ? { claimPeriod: row.claim_period } : {}),
+ });
+ assignments.push({ id: row.id, row_num: rowNum });
+ claimed.add(rowNum);
+ }
+ return { body: replaceOrInsertFactsFence(body, renderFactsTable(existingFence.facts)), assignments };
+}
+
+/**
+ * Managed brains (#5728 class): the managed writer guard refuses direct fence
+ * writes into the canonical worktree and any raw `UPDATE facts`. Each page
+ * publishes its rendered fence through the coordinator as one
+ * `managed_maintenance_adopt_fact_fence` request that adopts the rows in
+ * place. The page body comes from the database, so database-only pages are
+ * included. Preflight and capacity refusals throw before any page publishes.
+ */
+async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promise<void> {
+ const { groups, outcome } = plan;
+ const authorities = new Map<string, MaintenanceAuthority>();
+ for (const key of groups.keys()) {
+ const sourceId = key.split('\0')[0];
+ if (!authorities.has(sourceId)) authorities.set(sourceId, (await maintenancePreflight(engine, sourceId))!);
+ }
+ // One admission per page: refuse up front, before any page publishes,
+ // when the permanent request-ID caps cannot cover them all.
+ const [first] = authorities.values();
+ if (first) await assertLifetimeIdHeadroom(engine, first.writer.principal, groups.size);
+ for (const [key, group] of groups) {
+ const [sourceId, entitySlug] = key.split('\0');
+ try {
+ const authority = authorities.get(sourceId)!;
+ const snapshot = await engine.readPageSnapshot(entitySlug, { sourceId });
+ if (!snapshot) { outcome.skipped_no_page += group.length; continue; }
+ 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('; ')})`);
+ continue;
+ }
+ const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
+ await submitFactFenceAdoption(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)),
+ });
+ 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> {
+ const target = await resolvePageWriteTarget(engine, entitySlug, sourceId);
+ if (!target.ok) { outcome.skipped_no_page += group.length; return; }
+ const { writeRoot } = target;
+ const write = () => withPageLock(entitySlug, async () => {
+ const fence = await planFence(engine, sourceId, entitySlug, readFileSync(filePath, 'utf-8'), group);
+ if ('warnings' in fence) {
+ outcome.failed_pages.push(`${entitySlug} (${fence.warnings.join('; ')})`);
+ return;
+ }
+ const durable = isDurabilityHardened(writeRoot);
+ const prewrite = durable ? gitPathState(writeRoot, filePath) : 'clean';
+ const tmpPath = `${filePath}.tmp`;
+ assertSourceFilesystemActive();
+ writeFileSync(tmpPath, fence.body, 'utf-8');
+ const tmpBody = readFileSync(tmpPath, 'utf-8');
+ const parsed = parseFactsFence(tmpBody);
+ if (parsed.warnings.length > 0) {
+ // .tmp stays for inspection; the canonical file is untouched.
+ outcome.failed_pages.push(`${entitySlug} (${parsed.warnings.join('; ')})`);
+ return;
+ }
+ renameSync(tmpPath, filePath);
+ // Mirror the file into pages so this run's reconcile and get_page read the
+ // new fence (same body-only mirror as fence-write.ts: the row keeps its
+ // content_hash, so the next sync re-imports and re-chunks the page).
+ const reparsed = parseMarkdown(tmpBody, `${entitySlug}.md`);
+ await maintenanceTransaction(engine, async tx => {
+ const existing = await tx.getPage(entitySlug, { sourceId });
+ if (existing) {
+ await tx.refreshPageBody(entitySlug, sourceId, sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
+ existing.content_hash || contentHash(existing));
+ }
+ for (const a of fence.assignments) {
+ await tx.executeRaw(
+ `UPDATE facts SET row_num = $1, source_markdown_slug = $2
+ WHERE id = $3 AND source_id = $4 AND row_num IS NULL`,
+ [a.row_num, entitySlug, a.id, sourceId],
+ );
+ }
+ });
+ if (durable) await commitFactFenceFile(writeRoot, filePath, entitySlug, sourceId, prewrite);
+ outcome.fenced += fence.assignments.length;
+ outcome.pages_touched += 1;
+ outcome.fenced_slugs.push(entitySlug);
+ }, { timeoutMs: 5_000, ...(lockRoot ? { lockRoot } : {}) });
+ try {
+ await (hasSourceFilesystemLock(writeRoot) ? write() : withSourceFilesystemLock(engine, writeRoot, write));
+ } catch (err) {
+ outcome.failed_pages.push(`${entitySlug} (${err instanceof Error ? err.message : String(err)})`);
+ }
+}
+
+/**
+ * Fence every group of the plan through the brain's write path; fills
+ * `plan.outcome`. A managed preflight or capacity refusal throws before any
+ * page publishes; a per-page failure lands in `failed_pages`.
+ */
+export async function fenceUnfencedFacts(engine: BrainEngine, plan: UnfencedFactsPlan, opts: { pageLockRoot?: string } = {}): Promise<UnfencedFactsOutcome> {
+ if (plan.managed) {
+ await fenceManaged(engine, plan);
+ return plan.outcome;
+ }
+ 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);
+ }
+ return plan.outcome;
+}
diff --git a/test/e2e/extract-facts-unfenced-rows-postgres.test.ts b/test/e2e/extract-facts-unfenced-rows-postgres.test.ts
new file mode 100644
index 0000000000..3363a12e9e
--- /dev/null
+++ b/test/e2e/extract-facts-unfenced-rows-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extract-facts-unfenced-rows.test.ts'));
diff --git a/test/extract-facts-phase.test.ts b/test/extract-facts-phase.test.ts
index 0e56524c78..d803e736e2 100644
--- a/test/extract-facts-phase.test.ts
+++ b/test/extract-facts-phase.test.ts
@@ -3,7 +3,7 @@
*
* Covers the reconciliation contract: parse fence → deleteFactsForPage
* → insertFacts. Plus the empty-fence guard (Codex R2-#7) that refuses
- * to run when legacy v0.31 rows are pending the v0_32_2 backfill.
+ * to reconcile while unfenced rows the phase could not fence remain.
*
* Uses a real PGLite engine. Pages seeded via engine.putPage so
* compiled_truth + frontmatter are realistic.
@@ -1021,7 +1021,10 @@ describe('runExtractFacts — empty-fence guard (Codex R2-#7)', () => {
expect(r.legacyRowsPending).toBe(1);
expect(r.factsInserted).toBe(0);
expect(r.factsDeleted).toBe(0);
- expect(r.warnings.some(w => w.includes('apply-migrations'))).toBe(true);
+ // The page's canonical file is not on this host, so the phase's own fence
+ // step could not fence the row; the warning names the page and why.
+ expect(r.warnings.some(w => w.startsWith('FACTS_FENCE_FAILED: people/alice ('))).toBe(true);
+ expect(r.warnings.some(w => w.includes('unfenced fact row(s)') && !w.includes('v0.31'))).toBe(true);
// Legacy row was NOT touched.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1320,7 +1323,7 @@ describe('runExtractFacts — empty-fence guard (Codex R2-#7)', () => {
expect(r.legacyRowsPending).toBe(1);
expect(r.factsInserted).toBe(0);
expect(r.factsDeleted).toBe(0);
- expect(r.warnings.some(w => w.includes('apply-migrations'))).toBe(true);
+ expect(r.warnings.some(w => w.startsWith('FACTS_FENCE_FAILED: people/bob ('))).toBe(true);
});
test('#2484: a soft-deleted backing page makes its legacy row unfenceable (does NOT gate)', async () => {
@@ -1442,9 +1445,8 @@ describe('runExtractFacts — multi-source isolation', () => {
expect(rWork.guardTriggered).toBe(true);
expect(rWork.legacyRowsPending).toBe(1);
expect(rWork.factsInserted).toBe(0);
- // The drain advice must be one that actually re-runs Phase B — a bare
- // `apply-migrations --yes` no-ops once the ledger says complete.
- expect(rWork.warnings.some(w => w.includes('--force-retry 0.32.2'))).toBe(true);
+ // The advice names the page the phase's own fence step could not fence.
+ expect(rWork.warnings.some(w => w.startsWith('FACTS_FENCE_FAILED: people/alice ('))).toBe(true);
expect(rWork.warnings.some(w => w.includes('forget_fact'))).toBe(true);
expect(rWork.warnings.some(w => w.includes('source "work"'))).toBe(true);
});
diff --git a/test/extract-facts-unfenced-rows.test.ts b/test/extract-facts-unfenced-rows.test.ts
new file mode 100644
index 0000000000..3547118b2a
--- /dev/null
+++ b/test/extract-facts-unfenced-rows.test.ts
@@ -0,0 +1,188 @@
+/**
+ * #5299: the extract_facts cycle phase fences unfenced fact rows itself.
+ *
+ * Protects: after ONE cycle, every active `row_num IS NULL` fact on a live
+ * entity page is appended to that page's `## Facts` fence with a row number,
+ * the DB rows carry those row numbers, the guard count is 0 and the phase
+ * reconciles in the same run (status ok, no warning); a second cycle changes
+ * nothing. Rows that are structurally unfenceable (no backing page, NULL
+ * entity slug) are left exactly as they were. Unmanaged brains write the file
+ * and mirror it into `pages`; managed brains publish through the coordinator.
+ * Fails when: the phase only counts the rows and skips with a warn telling the
+ * operator to re-run the v0.32.2 migration (the pre-#5299 behavior), when a
+ * fenced row's number differs between the file and the DB, or when the fence
+ * step re-appends rows on a second run.
+ * Why existing coverage misses it: the migration tests exercise Phase B
+ * directly, and the extract_facts guard tests only cover rows that cannot be
+ * fenced (no canonical file).
+ * Seams: none; real PGLite (and Postgres through the e2e registration),
+ * `runCycle` with `phases: ['extract_facts']`, the shared `managedBrain` and
+ * legacy managed fixture.
+ */
+import { expect, test } from 'bun:test';
+import { 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';
+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 { 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';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUG = 'people/alice-example';
+
+/** The guard's own predicate: unfenced active rows on a live page of a source with a checkout. */
+async function pendingCount(engine: BrainEngine, sourceId = 'default'): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM facts f
+ WHERE f.source_id = $1 AND f.row_num IS NULL AND f.entity_slug IS NOT NULL AND f.expired_at IS NULL
+ AND 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)
+ AND EXISTS (SELECT 1 FROM sources s WHERE s.id = f.source_id AND s.local_path IS NOT NULL)`, [sourceId]);
+ return Number(row.n);
+}
+
+async function factState(engine: BrainEngine) {
+ return engine.executeRaw<{ id: number; entity_slug: string | null; fact: string; row_num: number | null; source_markdown_slug: string | null; expired: boolean }>(
+ `SELECT id, entity_slug, fact, row_num, source_markdown_slug, expired_at IS NOT NULL AS expired FROM facts ORDER BY id`);
+}
+
+async function extractFactsPhase(engine: BrainEngine, root: string) {
+ const report = await runCycle(engine, { brainDir: root, sourceId: 'default', phases: ['extract_facts'] });
+ return report.phases.find(p => p.phase === 'extract_facts')!;
+}
+
+const FENCE_ROW_1 = `## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | Alice example joined Acme example | fact | 1.0 | world | high | 2024-01-01 | | linkedin | |
+<!--- gbrain:facts:end -->
+`;
+
+/** An unmanaged brain whose default source checkout holds one entity page with one indexed fence row, plus unfenced rows. */
+async function unmanagedBrain(databaseUrl: string | undefined, run: (brain: { engine: BrainEngine; root: string }) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-unfenced-home-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ expect(await managedPersistenceEnabled(engine)).toBe(false);
+ const root = join(home, 'brain');
+ mkdirSync(root, { recursive: true });
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);
+ const page = await engine.putPage(SLUG, { type: 'person', title: 'Alice Example', compiled_truth: `# Alice Example\n\nProse.\n\n${FENCE_ROW_1}` });
+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', [`${SLUG}.md`, page.id]);
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId: 'default' }))!;
+ const path = join(root, `${SLUG}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, serializePageToMarkdown(snapshot.page, snapshot.tags));
+ // The fence row already indexed, as an earlier reconcile left it.
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Alice example joined Acme example', 'fact', 'world', 'high', '2024-01-01', 'linkedin', 1.0, 1, $1)`, [SLUG]);
+ // Rows the inline writer's DB-only fallback produced (row_num NULL).
+ await engine.executeRaw(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence)
+ VALUES ('default', $1, 'Alice example moved to Lisbon', 'fact', 'private', 'medium', '2026-02-05T13:45:12Z', 'mcp:remember', 0.9),
+ ('default', $1, 'Alice example prefers async updates', 'preference', 'private', 'medium', '2026-03-01', 'mcp:remember', 0.8),
+ ('default', 'people-jane-doe', 'Unfenceable: no backing page', 'fact', 'private', 'medium', now(), 'mcp:remember', 1.0),
+ ('default', NULL, 'Unfenceable: no entity', 'fact', 'private', 'medium', now(), 'mcp:remember', 1.0)`, [SLUG]);
+ await run({ engine, root });
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: unmanaged: one cycle fences row_num-NULL facts onto the page file, reconciles, and a second cycle changes nothing`, async () => {
+ await unmanagedBrain(databaseUrl, async ({ engine, root }) => {
+ expect(await pendingCount(engine)).toBe(2);
+
+ const first = await extractFactsPhase(engine, root);
+ expect(first.status).toBe('ok');
+ expect(first.details).toMatchObject({ unfencedRowsFenced: 2, pagesFailed: 0 });
+ expect(await pendingCount(engine)).toBe(0);
+
+ const file = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+ expect(parseFactsFence(file).facts.map(f => [f.rowNum, f.claim])).toEqual([
+ [1, 'Alice example joined Acme example'],
+ [2, 'Alice example moved to Lisbon'],
+ [3, 'Alice example prefers async updates'],
+ ]);
+ // The pages cache carries the same fence, so get_page and the reconcile agree with the file.
+ const cached = (await engine.getPage(SLUG, { sourceId: 'default' }))!;
+ expect(parseFactsFence(cached.compiled_truth).facts.map(f => f.rowNum)).toEqual([1, 2, 3]);
+
+ const after = await factState(engine);
+ expect(after.map(r => [r.fact, r.row_num, r.source_markdown_slug, r.expired])).toEqual([
+ ['Alice example joined Acme example', 1, SLUG, false],
+ ['Alice example moved to Lisbon', 2, SLUG, false],
+ ['Alice example prefers async updates', 3, SLUG, false],
+ ['Unfenceable: no backing page', null, null, false],
+ ['Unfenceable: no entity', null, null, false],
+ ]);
+
+ const second = await extractFactsPhase(engine, root);
+ expect(second.status).toBe('ok');
+ expect(second.details).toMatchObject({ unfencedRowsFenced: 0, factsInserted: 0, factsDeleted: 0 });
+ expect(readFileSync(join(root, `${SLUG}.md`), 'utf8')).toBe(file);
+ expect(await factState(engine)).toEqual(after);
+ });
+ }, 120_000);
+
+ test(`${backend}: unmanaged: a page whose canonical file is missing keeps its rows unfenced and is named in the warning`, async () => {
+ await unmanagedBrain(databaseUrl, async ({ engine, root }) => {
+ rmSync(join(root, `${SLUG}.md`));
+ const before = await factState(engine);
+ const result = await extractFactsPhase(engine, root);
+ expect(result.status).toBe('warn');
+ expect(result.summary).toBe('extract_facts skipped: 2 unfenced fact row(s) could not be fenced');
+ const warnings = (result.details as { warnings: string[] }).warnings;
+ expect(warnings.some(w => w.startsWith(`FACTS_FENCE_FAILED: ${SLUG} (canonical file `) && w.includes('does not exist on this host'))).toBe(true);
+ expect(warnings.some(w => w.includes('v0.31') || w.includes('force-retry'))).toBe(false);
+ expect(await factState(engine)).toEqual(before);
+ });
+ }, 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 }) => {
+ expect(await pendingCount(managed)).toBe(3);
+ const first = await extractFactsPhase(managed, managedRoot);
+ expect(first.status).toBe('ok');
+ expect(first.details).toMatchObject({ unfencedRowsFenced: 3, pagesFailed: 0 });
+ expect(await pendingCount(managed)).toBe(0);
+
+ const rows = await managed.executeRaw<{ id: number; row_num: number; source_markdown_slug: string; expired: boolean }>(
+ 'SELECT id, row_num, source_markdown_slug, expired_at IS NOT NULL AS expired FROM facts WHERE id = ANY($1::integer[]) ORDER BY id',
+ [[...seed.legacyFactIds, ...seed.dbOnlyFactIds]]);
+ expect(rows.map(r => [Number(r.id), r.row_num, r.source_markdown_slug, r.expired])).toEqual([
+ [seed.legacyFactIds[0], 2, LEGACY_FILE_SLUG, false],
+ [seed.legacyFactIds[1], 3, LEGACY_FILE_SLUG, false],
+ [seed.dbOnlyFactIds[0], 1, LEGACY_DB_ONLY_SLUG, false],
+ ]);
+ const file = readFileSync(join(managedRoot, `${LEGACY_FILE_SLUG}.md`), 'utf8');
+ expect(parseFactsFence(file).facts.map(f => [f.rowNum, f.claim])).toEqual([
+ [2, 'Alice example founded Acme example'], [3, 'Alice example moved to Lisbon']]);
+ const dbOnly = (await managed.readPageSnapshot(LEGACY_DB_ONLY_SLUG, { sourceId: 'default' }))!;
+ expect(parseFactsFence(dbOnly.page.compiled_truth).facts.map(f => [f.rowNum, f.claim])).toEqual([[1, 'Dana example advises Widget co']]);
+
+ const facts = await managed.executeRaw('SELECT id, row_num, fact, expired_at FROM facts ORDER BY id');
+ const [{ n: requests }] = await managed.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests');
+ const second = await extractFactsPhase(managed, managedRoot);
+ expect(second.status).toBe('ok');
+ expect(second.details).toMatchObject({ unfencedRowsFenced: 0, factsInserted: 0, factsDeleted: 0 });
+ expect(await managed.executeRaw('SELECT id, row_num, fact, expired_at FROM facts ORDER BY id')).toEqual(facts);
+ expect(readFileSync(join(managedRoot, `${LEGACY_FILE_SLUG}.md`), 'utf8')).toBe(file);
+ expect((await managed.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0].n).toBe(requests);
+ }, { databaseUrl, setup: async ({ engine: managed, root: managedRoot }) => { seed = await seedLegacyManagedContent(managed, managedRoot); } });
+ }, 120_000);
+}
diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.ts
index 8d6733aa74..ff1f5fc98f 100644
--- a/test/phantom-redirect.test.ts
+++ b/test/phantom-redirect.test.ts
@@ -593,9 +593,10 @@ describe('runExtractFacts — phantom-redirect integration', () => {
// Seed a legacy v0.31 fact row (row_num NULL, entity_slug NOT NULL).
// `source` is NOT NULL in the schema; the v0.31 path always set it.
// #2484: the guard only gates on rows whose entity_slug resolves to a
- // LIVE page (genuine backfill candidates), so seed the backing page too.
+ // LIVE page, so seed the backing page too. #5299: the phase fences a
+ // row whose canonical file exists, so the page has no file here and the
+ // row stays unfenced, which is what gates.
await putPage('people/legacy', '# legacy\n', { type: 'person' });
- writeMd(brainDir, 'people/legacy', '# legacy\n');
await engine.executeRaw(
`INSERT INTO facts (source_id, entity_slug, fact, kind, valid_from, source)
VALUES ('default', 'people/legacy', 'Legacy claim', 'fact', '2020-01-01'::date, 'legacy-import')`,