Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): extract_facts drains pages whose facts watermark is behind (#5151)

time-attack66d9e55e0522
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 43188f770c..d493571f06 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 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/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`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `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/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fe1ee6649d..4620a5c050 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -13,7 +13,7 @@ src/commands/jobs.ts 662 ratchet refactor wave 1 split target (W4 jobs, cut line
src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)
src/core/ai/gateway.ts 4408 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts)
src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)
-src/core/cycle.ts 3253 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge
+src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)
src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index 9a782cab99..455dbf3429 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -8,6 +8,8 @@
*/
import { applyExtractAtomsNoPricing, readExtractAtomsNoPricing } from '../../../core/cycle/extract-atoms-cost-gate.ts';
+import { applyFactsReconcileBacklog, readFactsReconcileBacklog } from '../../../core/facts/reconcile-watermark.ts';
+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';
import { join } from 'path';
import { gbrainPath } from '../../../core/config.ts';
import { multiSourceDriftCheck, multiSourceDriftNotVerified } from '../schema-pack-checks.ts';
@@ -200,6 +202,12 @@ async function runExtractionBacklogs(ctx: DoctorContext): Promise<Check[]> {
// expected limit in the rollup, not a halt; the overlay names the fix.
const check = await computeExtractHealthCheck(engine);
applyExtractAtomsNoPricing(check, await readExtractAtomsNoPricing(engine).catch(() => []));
+ // #5151: unmanaged brains reconcile fences in the cycle, so fence pages
+ // behind their facts watermark are facts not indexed yet.
+ if (!await managedPersistenceEnabled(engine).catch(() => true)) {
+ const backlog = await readFactsReconcileBacklog(engine).catch(() => null);
+ if (backlog) applyFactsReconcileBacklog(check, backlog);
+ }
checks.push(check);
} catch {
// Best-effort; rollup-table missing on pre-v106 brains is normal
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 7123d3f476..2759b35ddb 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1445,6 +1445,7 @@ async function runPhaseExtractFacts(
const { runExtractFacts } = await import('./cycle/extract-facts.ts');
const result = await runExtractFacts(engine, {
slugs: changedSlugs,
+ drain: {},
dryRun,
sourceId,
brainDir: brainDir ?? undefined,
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index e34be81b61..835456f96b 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -72,6 +72,14 @@ import { isAborted } from '../abort-check.ts';
import { parseMarkdown } from '../markdown.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';
import { acquirePageLock } from '../page-lock.ts';
+import {
+ lockReconcileRevision,
+ selectFactsReconcileDrain,
+ settleFactsReconcile,
+ FACTS_DRAIN_BUDGET_MS,
+ type FactsReconcileDrainOpts,
+ type FactsReconcileOutcome,
+} from '../facts/reconcile-watermark.ts';
interface ExistingPageFact {
id: number | string;
@@ -327,6 +335,12 @@ export interface ExtractFactsOpts {
signal?: AbortSignal;
/** Override the shared page-lock directory for deterministic tests. */
pageLockRoot?: string;
+ /**
+ * #5151: with an explicit slug list on an unmanaged brain, also reconcile
+ * a bounded batch of pages whose facts watermark is behind the page
+ * (src/core/facts/reconcile-watermark.ts). The dream cycle sets it.
+ */
+ drain?: FactsReconcileDrainOpts;
}
export interface ExtractFactsResult {
@@ -621,17 +635,28 @@ export async function runExtractFacts(
if (phantomResult.touched_canonicals.length > 0 || fencedSlugs.length > 0) {
slugs = Array.from(new Set([...slugs, ...phantomResult.touched_canonicals, ...fencedSlugs]));
}
+ const watermark = !managed && !opts.dryRun;
+ const explicit = new Set(slugs);
+ if (watermark && opts.drain && opts.slugs !== undefined) {
+ slugs = Array.from(new Set([...slugs, ...await selectFactsReconcileDrain(engine, sourceId, opts.drain)]));
+ }
+ const drainDeadline = Date.now() + (opts.drain?.budgetMs ?? FACTS_DRAIN_BUDGET_MS);
// ── Reconcile each page ───────────────────────────────────────
// Each page reconciles independently: 'stop' ends the walk (cancellation),
- // 'next' moves on. A thrown error is isolated to its page below.
- const reconcilePage = async (slug: string): Promise<'next' | 'stop'> => {
+ // every other outcome moves on. A thrown error is isolated to its page
+ // below. For the watermark, 'unchanged' is a complete no-op still to be
+ // stamped and 'complete' was stamped inside the write transaction.
+ type PageOutcome = FactsReconcileOutcome | 'unchanged' | 'skipped' | 'stop';
+ let revision: string | null | undefined;
+ const reconcilePage = async (slug: string): Promise<PageOutcome> => {
const page = await engine.getPage(slug, { sourceId });
if (!page) {
// Slug listed but not in DB — skip silently. The next cycle
// will pick it up if it exists.
- return 'next';
+ return 'skipped';
}
+ revision = page.knowledge_revision ?? null;
const body = page.compiled_truth ?? '';
const parsed = parseFactsFence(body);
@@ -643,7 +668,7 @@ export async function runExtractFacts(
// could still recover. That partial result is not authoritative: using
// it for reconciliation would interpret skipped rows as deletions.
// Preserve this page's existing index and continue with other pages.
- return 'next';
+ return 'invalid';
}
// #3625: splitBody() puts everything below the timeline sentinel into
@@ -673,7 +698,7 @@ export async function runExtractFacts(
`Move the fence above the sentinel and re-save — leaving it in place ` +
`preserves the existing indexed facts but they will not update.`,
);
- return 'next';
+ return 'invalid';
}
if (parsed.facts.length > 0) result.pagesWithFacts += 1;
@@ -689,7 +714,7 @@ export async function runExtractFacts(
const extracted = extractFactsFromFenceText(parsed.facts, slug, sourceId, { pageEffectiveDate })
.filter(f => !duplicates.has(f.row_num));
- if (opts.dryRun) return 'next';
+ if (opts.dryRun) return 'skipped';
// Reconcile by row number, the fence's own unique identity (the parser
// refuses duplicate row numbers). A DB row whose (row_num, claim) is still
@@ -723,7 +748,7 @@ export async function runExtractFacts(
const stored = matched.get(f.row_num)!.superseded_by;
return resolveSupersession(f, byRow, chain, slug).superseded_by === (stored == null ? null : Number(stored));
});
- if (inSync) return 'next';
+ if (inSync) return 'unchanged';
}
// v0.35.4 (D-CDX-3) — batch-embed new rows before insert so
@@ -787,6 +812,7 @@ export async function runExtractFacts(
try {
return await transact([slug], async tx => {
opts.signal?.throwIfAborted();
+ if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;
const current = await tx.getPage(slug, { sourceId });
if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;
for (const fact of expireInPlace) {
@@ -824,6 +850,7 @@ export async function runExtractFacts(
const linked = await syncSupersession(tx, sourceId, slug, extracted, chain, insertedRows);
opts.signal?.throwIfAborted();
const updated = new Set([...updates.map(f => f.row_num), ...linked.changed.filter(row => !insertedRows.has(row))]);
+ if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);
return { inserted: inserted.inserted, updated: updated.size, warnings: linked.warnings };
});
} catch (error) {
@@ -841,13 +868,13 @@ export async function runExtractFacts(
if (isAborted(opts.signal)) return null;
return apply();
}, opts, result.warnings);
- if (!outcome) return 'next';
+ if (!outcome) return isAborted(opts.signal) ? 'cancelled' : 'deferred';
result.factsInserted += outcome.inserted;
result.factsUpdated += outcome.updated;
result.factsDeleted += detach.length + expireInPlace.length;
// resolveSupersededByRow prefixes each message with the slug + row.
for (const w of outcome.warnings) result.warnings.push(w);
- return 'next';
+ return deferInserts ? 'deferred' : 'complete';
};
for (const slug of slugs) {
@@ -855,9 +882,13 @@ export async function runExtractFacts(
// independent delete-then-insert commit, so breaking leaves a consistent
// partial state; the receipt/rollup below still runs with partial counts.
if (isAborted(opts.signal)) break;
+ // Drained pages follow the explicit ones, so the drain budget ends the walk.
+ if (!explicit.has(slug) && Date.now() > drainDeadline) break;
result.pagesScanned += 1;
+ revision = undefined;
+ let outcome: PageOutcome;
try {
- if (await reconcilePage(slug) === 'stop') break;
+ outcome = await reconcilePage(slug);
} catch (error) {
if (isAborted(opts.signal)) throw error;
// One page the database rejects (CHECK/FK violation, malformed input the
@@ -865,7 +896,15 @@ export async function runExtractFacts(
// Its transaction rolled back, so the existing index is preserved.
result.pagesFailed += 1;
result.warnings.push(`${slug}: FACTS_RECONCILE_FAILED: ${(error instanceof Error ? error.message : String(error)).slice(0, 300)}`);
+ outcome = 'deferred';
+ }
+ if (watermark && outcome !== 'complete' && outcome !== 'skipped') {
+ const settled = outcome === 'unchanged' ? 'complete' : outcome === 'stop' ? 'cancelled' : outcome;
+ await settleFactsReconcile(engine, sourceId, slug, settled, revision).catch((error: unknown) => {
+ result.warnings.push(`${slug}: facts reconcile watermark not recorded: ${error instanceof Error ? error.message : String(error)}`);
+ });
}
+ if (outcome === 'stop') break;
}
// v0.42 Wave B3: receipt + rollup. extract_facts is deterministic
diff --git a/src/core/facts/reconcile-watermark.ts b/src/core/facts/reconcile-watermark.ts
new file mode 100644
index 0000000000..f4944eb86f
--- /dev/null
+++ b/src/core/facts/reconcile-watermark.ts
@@ -0,0 +1,178 @@
+/**
+ * Facts reconcile watermark (#5151) for unmanaged brains.
+ *
+ * `page_facts_reconcile` records, per page, the `knowledge_revision` the
+ * extract_facts phase last reconciled completely, plus the outcome of the
+ * latest attempt. It is a side table on purpose: any `UPDATE pages` fires the
+ * statement-level generation-clock trigger and the page row triggers, so
+ * stamping a watermark on `pages` would churn every reconcile.
+ *
+ * The cycle's extract_facts phase drains pages whose watermark is behind
+ * their revision, so a fence imported by a standalone `gbrain sync` (which
+ * the cycle's own no-op sync never reports as changed) still reaches the
+ * facts index, and a fence removed from a page still expires its rows.
+ *
+ * Outcomes: `complete` (the index matches the page, including a no-op),
+ * `deferred` (lock held, stale cache, embedding deferral, page changed,
+ * database error: retried next run), `invalid` (malformed or misplaced
+ * fence: retried only after the page changes) and `cancelled`. The drain
+ * orders by last attempt, never-attempted first, so pages that keep
+ * deferring rotate to the back and cannot starve the rest.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';
+
+export type FactsReconcileOutcome = 'complete' | 'deferred' | 'invalid' | 'cancelled';
+
+export interface FactsReconcileDrainOpts {
+ /** Most pages one run drains beyond its explicit slug list. */
+ pageLimit?: number;
+ /** Wall-clock budget for drained pages, in ms. */
+ budgetMs?: number;
+}
+
+export const FACTS_DRAIN_PAGE_LIMIT = 250;
+export const FACTS_DRAIN_BUDGET_MS = 60_000;
+/** Upper bound on pages one run settles in bulk as having no fence and no fence rows. */
+const FACTLESS_SETTLE_LIMIT = 10_000;
+
+const DUE = `(r.page_id IS NULL OR r.reconciled_revision IS DISTINCT FROM p.knowledge_revision)`;
+const OWNS_FENCE_ROWS = `EXISTS (SELECT 1 FROM facts f
+ WHERE f.source_id = p.source_id AND f.source_markdown_slug = p.slug AND f.row_num IS NOT NULL)`;
+const RETRYABLE = `NOT COALESCE(r.outcome = 'invalid' AND r.attempted_revision IS NOT DISTINCT FROM p.knowledge_revision, false)`;
+
+/**
+ * Record one page's reconcile outcome. `revision` is the `knowledge_revision`
+ * the reconcile read: nothing is recorded when the page has moved on since,
+ * so a stale result never marks newer content. `undefined` records against
+ * the current revision (an attempt that failed before or while reading).
+ */
+export async function settleFactsReconcile(
+ db: BrainEngine,
+ sourceId: string,
+ slug: string,
+ outcome: FactsReconcileOutcome,
+ revision?: string | null,
+): Promise<void> {
+ await db.executeRaw(
+ `INSERT INTO page_facts_reconcile AS r (page_id, reconciled_revision, reconciled_at, outcome, attempted_revision, attempted_at)
+ SELECT p.id, CASE WHEN $3 = 'complete' THEN p.knowledge_revision END, CASE WHEN $3 = 'complete' THEN now() END,
+ $3, p.knowledge_revision, now()
+ FROM pages p
+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL
+ AND ($5::boolean OR p.knowledge_revision IS NOT DISTINCT FROM $4::uuid)
+ ON CONFLICT (page_id) DO UPDATE SET
+ reconciled_revision = CASE WHEN EXCLUDED.outcome = 'complete' THEN EXCLUDED.reconciled_revision ELSE r.reconciled_revision END,
+ reconciled_at = CASE WHEN EXCLUDED.outcome = 'complete' THEN EXCLUDED.reconciled_at ELSE r.reconciled_at END,
+ outcome = EXCLUDED.outcome,
+ attempted_revision = EXCLUDED.attempted_revision,
+ attempted_at = EXCLUDED.attempted_at`,
+ [sourceId, slug, outcome, revision ?? null, revision === undefined],
+ );
+}
+
+/**
+ * Lock the page row against concurrent writers for the rest of the
+ * transaction and confirm it is still the revision the reconcile read.
+ * `SELECT … FOR SHARE` fires no trigger and changes nothing.
+ */
+export async function lockReconcileRevision(tx: BrainEngine, sourceId: string, slug: string, revision: string | null): Promise<boolean> {
+ const rows = await tx.executeRaw<{ knowledge_revision: string | null }>(
+ `SELECT knowledge_revision FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL FOR SHARE`,
+ [sourceId, slug],
+ );
+ return rows.length === 1 && (rows[0]!.knowledge_revision ?? null) === revision;
+}
+
+/**
+ * Pages of `sourceId` this run should reconcile beyond its explicit slugs.
+ * First settles, in one bounded statement, the due pages that have no fence
+ * marker and own no fence rows (their reconcile is a no-op), so the common
+ * case never reads those bodies again until they change. Returns the
+ * remaining due pages, never-attempted first, then by oldest attempt.
+ */
+export async function selectFactsReconcileDrain(
+ engine: BrainEngine,
+ sourceId: string,
+ opts: FactsReconcileDrainOpts,
+): Promise<string[]> {
+ const marker = `%${FACTS_FENCE_BEGIN}%`;
+ await engine.executeRaw(
+ `INSERT INTO page_facts_reconcile AS r (page_id, reconciled_revision, reconciled_at, outcome, attempted_revision, attempted_at)
+ SELECT p.id, p.knowledge_revision, now(), 'complete', p.knowledge_revision, now()
+ FROM pages p LEFT JOIN page_facts_reconcile r ON r.page_id = p.id
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND ${DUE}
+ AND p.compiled_truth NOT LIKE $2 AND p.timeline NOT LIKE $2
+ AND NOT ${OWNS_FENCE_ROWS}
+ ORDER BY p.id
+ LIMIT $3
+ ON CONFLICT (page_id) DO UPDATE SET
+ reconciled_revision = EXCLUDED.reconciled_revision, reconciled_at = EXCLUDED.reconciled_at,
+ outcome = EXCLUDED.outcome, attempted_revision = EXCLUDED.attempted_revision, attempted_at = EXCLUDED.attempted_at`,
+ [sourceId, marker, FACTLESS_SETTLE_LIMIT],
+ );
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT p.slug FROM pages p LEFT JOIN page_facts_reconcile r ON r.page_id = p.id
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND ${DUE} AND ${RETRYABLE}
+ ORDER BY r.attempted_at ASC NULLS FIRST, p.id ASC
+ LIMIT $2`,
+ [sourceId, opts.pageLimit ?? FACTS_DRAIN_PAGE_LIMIT],
+ );
+ return rows.map(r => r.slug);
+}
+
+export interface FactsReconcileBacklog {
+ /** Live pages with a fence or fence rows whose facts index is behind the page. */
+ pending: number;
+ /** Pages whose current revision holds a malformed or misplaced fence. */
+ invalid: Array<{ source_id: string; slug: string }>;
+}
+
+/**
+ * Doctor's read of the watermark, unmanaged brains only. The due set is
+ * materialized before the body match so a settled brain reads no page body.
+ */
+export async function readFactsReconcileBacklog(engine: BrainEngine): Promise<FactsReconcileBacklog> {
+ const rows = await engine.executeRaw<{ source_id: string; slug: string; invalid: boolean }>(
+ `WITH due AS MATERIALIZED (
+ SELECT p.id, p.source_id, p.slug, p.knowledge_revision, r.outcome, r.attempted_revision
+ FROM pages p LEFT JOIN page_facts_reconcile r ON r.page_id = p.id
+ WHERE p.deleted_at IS NULL AND ${DUE}
+ )
+ SELECT d.source_id, d.slug,
+ COALESCE(d.outcome = 'invalid' AND d.attempted_revision IS NOT DISTINCT FROM d.knowledge_revision, false) AS invalid
+ FROM due d JOIN pages p ON p.id = d.id
+ WHERE p.compiled_truth LIKE $1 OR p.timeline LIKE $1 OR ${OWNS_FENCE_ROWS}
+ ORDER BY d.source_id, d.slug`,
+ [`%${FACTS_FENCE_BEGIN}%`],
+ );
+ return {
+ pending: rows.filter(r => !r.invalid).length,
+ invalid: rows.filter(r => r.invalid).map(r => ({ source_id: r.source_id, slug: r.slug })),
+ };
+}
+
+/**
+ * Doctor's extract_health overlay, applied in place: fence pages whose facts
+ * are not indexed yet, and fences the phase cannot read, turn the check into
+ * a warning with the command that reconciles every page now.
+ */
+export function applyFactsReconcileBacklog(
+ check: { status: 'ok' | 'warn' | 'fail'; message: string; details?: Record<string, unknown> },
+ backlog: FactsReconcileBacklog,
+): void {
+ if (backlog.pending === 0 && backlog.invalid.length === 0) return;
+ const parts: string[] = [];
+ if (backlog.pending > 0) {
+ parts.push(`${backlog.pending} page(s) with a Facts fence are not reconciled into the facts index yet ` +
+ `(the dream cycle drains up to ${FACTS_DRAIN_PAGE_LIMIT} per run; to reconcile every page now run: gbrain dream --phase extract_facts)`);
+ }
+ if (backlog.invalid.length > 0) {
+ const names = backlog.invalid.slice(0, 3).map(p => p.slug).join(', ');
+ parts.push(`${backlog.invalid.length} page(s) have a Facts fence extract_facts cannot read (${names}); ` +
+ 'fix the fence table or move it above the timeline sentinel and save the page');
+ }
+ if (check.status !== 'fail') check.status = 'warn';
+ check.message = `${parts.join('; ')}; ${check.message}`;
+ check.details = { ...(check.details ?? {}), facts_reconcile: { pending: backlog.pending, invalid: backlog.invalid.slice(0, 20) } };
+}
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index dcc321b983..3bd7e1aec3 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -97,6 +97,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),
carry('open_loops', 'user_data', 'Open loops and their status.'),
carry('page_aliases', 'user_data', 'Page aliases.'),
+ carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),
carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),
carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),
carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index aadccdd67a..b8f6c92835 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -209,6 +209,7 @@ import { v205 } from './v205-minion-spend-authorization.ts';
import { v206 } from './v206-entity-mention-index.ts';
import { v207 } from './v207-retrieval-feedback.ts';
import { v208 } from './v208-delta-per-arm-cursor.ts';
+import { v209 } from './v209-w9-p-facts-reconcile.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -416,4 +417,5 @@ export const MIGRATIONS: Migration[] = [
v206,
v207,
v208,
+ v209,
];
diff --git a/src/core/schema-migrations/v209-w9-p-facts-reconcile.ts b/src/core/schema-migrations/v209-w9-p-facts-reconcile.ts
new file mode 100644
index 0000000000..c5a8127726
--- /dev/null
+++ b/src/core/schema-migrations/v209-w9-p-facts-reconcile.ts
@@ -0,0 +1,31 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Facts reconcile watermark (#5151, src/core/facts/reconcile-watermark.ts):
+// per page, the knowledge_revision extract_facts last reconciled completely
+// and the outcome of its latest attempt. A side table, not a pages column, so
+// stamping it never fires the pages triggers. Created empty: every page starts
+// due, and the cycle drains them in bounded batches. Migration-only like
+// page_mention_state. Placeholder number: the fix wave 9 integrator renumbers it.
+export const v209: Migration = {
+ version: 209,
+ name: 'w9_p_facts_reconcile',
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS page_facts_reconcile (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ reconciled_revision UUID,
+ reconciled_at TIMESTAMPTZ,
+ outcome TEXT NOT NULL CHECK (outcome IN ('complete','deferred','invalid','cancelled')),
+ attempted_revision UUID,
+ attempted_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THEN
+ ALTER TABLE page_facts_reconcile ENABLE ROW LEVEL SECURITY;
+ END IF;
+ END $rls$;
+ `,
+};
diff --git a/test/e2e/extract-facts-reconcile-drain-postgres.test.ts b/test/e2e/extract-facts-reconcile-drain-postgres.test.ts
new file mode 100644
index 0000000000..7912783312
--- /dev/null
+++ b/test/e2e/extract-facts-reconcile-drain-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extract-facts-reconcile-drain.test.ts'));
diff --git a/test/extract-facts-reconcile-drain.test.ts b/test/extract-facts-reconcile-drain.test.ts
new file mode 100644
index 0000000000..62028d33f3
--- /dev/null
+++ b/test/extract-facts-reconcile-drain.test.ts
@@ -0,0 +1,232 @@
+/**
+ * #5151: the extract_facts cycle phase drains pages whose facts watermark is
+ * behind the page (`page_facts_reconcile`, src/core/facts/reconcile-watermark.ts).
+ *
+ * Protects: on an unmanaged brain, a fence imported by a standalone
+ * `gbrain sync` reaches the facts index on the next dream cycle even though
+ * the cycle's own sync is a no-op; removing a page's whole fence expires its
+ * fence rows (`cli:` rows and withdrawals untouched); an edit to an already
+ * indexed fence is reconciled; a second run with nothing changed reconciles
+ * nothing and issues no `UPDATE pages`; malformed or lock-held pages at the
+ * head of the drain do not starve later pages; doctor names fence pages that
+ * are not reconciled yet.
+ * Fails when: extract_facts only visits the slugs the cycle's sync reported
+ * (the pre-#5151 behavior: `slugs: []` after a no-op sync reconciled nothing).
+ * Why existing coverage misses it: phase tests pass explicit slugs or a full
+ * walk; nothing ran a standalone sync before the cycle.
+ * Seams: none; real PGLite (and Postgres through the e2e registration),
+ * a real git checkout for the sync case, `runCycle` and `runExtractFacts`.
+ */
+import { expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { performSync } from '../src/commands/sync.ts';
+import { runCycle } from '../src/core/cycle.ts';
+import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { applyFactsReconcileBacklog, readFactsReconcileBacklog } from '../src/core/facts/reconcile-watermark.ts';
+import { acquirePageLock } from '../src/core/page-lock.ts';
+import { managedPersistenceEnabled } from '../src/core/persistence/ownership.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 fence = (rows: string): string => `## Facts
+
+<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows}
+<!--- gbrain:facts:end -->
+`;
+const row = (n: number, claim: string): string => `| ${n} | ${claim} | fact | 1.0 | world | high | 2024-01-01 | | notes | |`;
+const body = (rows: string): string => `# Page\n\nProse.\n\n${fence(rows)}`;
+
+async function brain(databaseUrl: string | undefined, run: (b: { engine: BrainEngine; home: string }) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-facts-drain-'));
+ 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);
+ await run({ engine, home });
+ } finally {
+ await close();
+ }
+ });
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+async function put(engine: BrainEngine, slug: string, compiled: string): Promise<void> {
+ await engine.putPage(slug, { type: 'person', title: slug, compiled_truth: compiled, timeline: '', frontmatter: {} });
+}
+
+async function activeFacts(engine: BrainEngine) {
+ return engine.executeRaw<{ slug: string; fact: string; row_num: number | null }>(
+ `SELECT source_markdown_slug AS slug, fact, row_num FROM facts WHERE expired_at IS NULL ORDER BY source_markdown_slug, row_num, fact`);
+}
+
+async function generationClock(engine: BrainEngine): Promise<string> {
+ const [r] = await engine.executeRaw<{ v: string }>('SELECT last_value::text AS v FROM page_generation_clock_seq');
+ return r!.v;
+}
+
+const drainRun = (engine: BrainEngine, extra: Parameters<typeof runExtractFacts>[1] = {}) =>
+ runExtractFacts(engine, { slugs: [], drain: {}, ...extra });
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ test(`${backend}: a standalone sync then a dream cycle reconciles the imported fence`, () => brain(databaseUrl, async ({ engine, home }) => {
+ const repo = join(home, 'repo');
+ mkdirSync(join(repo, 'people'), { recursive: true });
+ writeFileSync(join(repo, 'people', 'alice-example.md'),
+ `---\ntype: person\ntitle: Alice Example\n---\n${body(row(1, 'Alice example joined Acme example'))}`);
+ const git = (...args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=t', ...args], { cwd: repo, stdio: 'ignore' });
+ git('init', '-q');
+ git('add', '.');
+ git('commit', '-qm', 'seed');
+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [repo]);
+ await performSync(engine, { sourceId: 'default', noPull: true, noEmbed: true });
+ expect(await activeFacts(engine)).toEqual([]);
+
+ const report = await runCycle(engine, { brainDir: repo, sourceId: 'default', phases: ['sync', 'extract_facts'] });
+ const phase = report.phases.find(p => p.phase === 'extract_facts')!;
+ expect(phase.details).toMatchObject({ factsInserted: 1, pagesFailed: 0 });
+ expect(await activeFacts(engine)).toEqual([{ slug: 'people/alice-example', fact: 'Alice example joined Acme example', row_num: 1 }]);
+ }), 60_000);
+
+ test(`${backend}: a second run with nothing changed reconciles nothing and issues no UPDATE pages`, () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/alice-example', body(row(1, 'Claim one')));
+ await put(engine, 'notes/plain', '# Plain\n\nNo facts here.');
+ const first = await drainRun(engine);
+ expect(first.factsInserted).toBe(1);
+ const clock = await generationClock(engine);
+ const second = await drainRun(engine);
+ expect({ scanned: second.pagesScanned, inserted: second.factsInserted, clock: await generationClock(engine) })
+ .toEqual({ scanned: 0, inserted: 0, clock });
+ expect(await readFactsReconcileBacklog(engine)).toEqual({ pending: 0, invalid: [] });
+ }), 60_000);
+
+ test(`${backend}: an edit to an already indexed fence is reconciled by the drain`, () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/alice-example', body(row(1, 'Claim one')));
+ await drainRun(engine);
+ await put(engine, 'people/alice-example', body(`${row(1, 'Claim one')}\n${row(2, 'Claim two')}`));
+ const r = await drainRun(engine);
+ expect(r.factsInserted).toBe(1);
+ expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['Claim one', 'Claim two']);
+ }), 60_000);
+
+ test(`${backend}: removing the whole fence expires its rows; cli: facts and withdrawals survive`, () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/alice-example', body(`${row(1, 'Claim one')}\n${row(2, 'Claim two')}`));
+ await drainRun(engine);
+ await engine.insertFacts( // gbrain-allow-direct-insert: test fixture for a conversation-origin row
+ [{ fact: 'Said in a meeting', kind: 'fact', source: 'cli:session-1', row_num: 100, source_markdown_slug: 'people/alice-example' }],
+ { source_id: 'default' },
+ );
+ await engine.executeRaw(
+ `INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', 'people/alice-example', 'abc123')`);
+ await put(engine, 'people/alice-example', '# Page\n\nProse only now.');
+ const r = await drainRun(engine);
+ expect(r.factsDeleted).toBe(2);
+ expect(await activeFacts(engine)).toEqual([{ slug: 'people/alice-example', fact: 'Said in a meeting', row_num: 100 }]);
+ const [w] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM fact_withdrawals');
+ expect(Number(w!.n)).toBe(1);
+ }), 60_000);
+
+ test(`${backend}: malformed pages at the head of the drain do not starve later pages`, () => brain(databaseUrl, async ({ engine }) => {
+ for (const n of [1, 2, 3]) {
+ await put(engine, `people/broken-${n}`, `# Broken\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim |\n|---|---|\n| x | not a row |\n<!--- gbrain:facts:end -->\n`);
+ }
+ await put(engine, 'people/tail', body(row(1, 'Tail claim')));
+ const first = await drainRun(engine, { drain: { pageLimit: 2 } });
+ expect(first.factsInserted).toBe(0);
+ const second = await drainRun(engine, { drain: { pageLimit: 2 } });
+ expect(second.factsInserted).toBe(1);
+ expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['Tail claim']);
+ expect((await drainRun(engine, { drain: { pageLimit: 2 } })).pagesScanned).toBe(0);
+
+ const backlog = await readFactsReconcileBacklog(engine);
+ expect(backlog.invalid.map(p => p.slug)).toEqual(['people/broken-1', 'people/broken-2', 'people/broken-3']);
+ const check = { status: 'ok' as 'ok' | 'warn' | 'fail', message: 'all extractors healthy', details: {} as Record<string, unknown> };
+ applyFactsReconcileBacklog(check, backlog);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('3 page(s) have a Facts fence extract_facts cannot read (people/broken-1, people/broken-2, people/broken-3)');
+
+ await put(engine, 'people/broken-1', body(row(1, 'Fixed claim')));
+ expect((await drainRun(engine)).factsInserted).toBe(1);
+ }), 60_000);
+
+ test(`${backend}: a page whose reconcile keeps deferring rotates behind the rest`, () => brain(databaseUrl, async ({ engine, home }) => {
+ const lockRoot = join(home, '.locks');
+ await put(engine, 'people/head', body(`${row(1, 'Head one')}\n${row(2, 'Head two')}`));
+ await put(engine, 'people/tail', body(row(1, 'Tail one')));
+ await drainRun(engine);
+ await put(engine, 'people/head', body(row(1, 'Head one')));
+ await put(engine, 'people/tail', body(`${row(1, 'Tail one')}\n${row(2, 'Tail two')}`));
+ const held = await acquirePageLock('people/head', { lockRoot });
+ try {
+ const first = await drainRun(engine, { drain: { pageLimit: 1 }, pageLockRoot: lockRoot });
+ expect(first.warnings).toContainEqual(expect.stringContaining('people/head: FACTS_PAGE_LOCK_TIMEOUT'));
+ const second = await drainRun(engine, { drain: { pageLimit: 1 }, pageLockRoot: lockRoot });
+ expect(second.factsInserted).toBe(1);
+ } finally {
+ await held!.release();
+ }
+ expect((await readFactsReconcileBacklog(engine)).pending).toBe(1);
+ const third = await drainRun(engine, { pageLockRoot: lockRoot });
+ expect(third.factsDeleted).toBe(1);
+ expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['Head one', 'Tail one', 'Tail two']);
+ }), 60_000);
+
+ test(`${backend}: doctor names fence pages that are not reconciled yet, and a full run clears them`, () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/alice-example', body(row(1, 'Claim one')));
+ await put(engine, 'notes/plain', '# Plain\n\nNo facts here.');
+ const backlog = await readFactsReconcileBacklog(engine);
+ expect(backlog).toEqual({ pending: 1, invalid: [] });
+ const check = { status: 'ok' as 'ok' | 'warn' | 'fail', message: 'all extractors healthy', details: {} as Record<string, unknown> };
+ applyFactsReconcileBacklog(check, backlog);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('to reconcile every page now run: gbrain dream --phase extract_facts');
+ await runExtractFacts(engine, {});
+ expect(await readFactsReconcileBacklog(engine)).toEqual({ pending: 0, invalid: [] });
+ }), 60_000);
+
+ if (backend === 'postgres') {
+ test('postgres: a page rewritten on another connection while its reconcile waits is never committed stale', () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/race', body(row(1, 'Old claim')));
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const writer = engine.transaction(async tx => {
+ await tx.executeRaw(`SELECT 1 FROM pages WHERE slug = 'people/race' FOR UPDATE`);
+ await gate;
+ await tx.executeRaw(`UPDATE pages SET compiled_truth = $1 WHERE slug = 'people/race'`, [body(row(1, 'New claim'))]);
+ });
+ const run = drainRun(engine);
+ for (let i = 0; i < 200; i++) {
+ const [w] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock'`);
+ if (Number(w!.n) > 0) break;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ release();
+ await writer;
+ const raced = await run;
+ expect(raced.factsInserted).toBe(0);
+ expect(await activeFacts(engine)).toEqual([]);
+ expect((await readFactsReconcileBacklog(engine)).pending).toBe(1);
+ expect((await drainRun(engine)).factsInserted).toBe(1);
+ expect((await activeFacts(engine)).map(f => f.fact)).toEqual(['New claim']);
+ }), 60_000);
+ }
+
+ test(`${backend}: without the drain option an empty slug list still reconciles nothing`, () => brain(databaseUrl, async ({ engine }) => {
+ await put(engine, 'people/alice-example', body(row(1, 'Claim one')));
+ const r = await runExtractFacts(engine, { slugs: [] });
+ expect({ scanned: r.pagesScanned, inserted: r.factsInserted }).toEqual({ scanned: 0, inserted: 0 });
+ }), 60_000);
+}
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 86194ddbaa..edab1ffdaf 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -507,7 +507,7 @@
},
{
"category": "meta",
- "message": "Version 208 (latest: 208)",
+ "message": "Version 209 (latest: 209)",
"name": "schema_version",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 618bf92713..20733091ed 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -510,7 +510,7 @@
},
{
"category": "meta",
- "message": "Version 208 (latest: 208)",
+ "message": "Version 209 (latest: 209)",
"name": "schema_version",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 0d2d457e9a..53db9d19c1 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -497,13 +497,13 @@
},
{
"category": "ops",
- "message": "RLS enabled on 115/115 public tables",
+ "message": "RLS enabled on 116/116 public tables",
"name": "rls",
"status": "ok"
},
{
"category": "meta",
- "message": "Version 208 (latest: 208)",
+ "message": "Version 209 (latest: 209)",
"name": "schema_version",
"status": "ok"
},
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index cfe9cbf0b3..dc947a2b50 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 203,
+ "count": 204,
"gaps": [
17,
18,
@@ -29,7 +29,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 208,
+ "latest": 209,
"records": [
{
"handler": {
@@ -3081,6 +3081,19 @@
"transaction": "absent",
"verify": "absent",
"version": 208
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "w9_p_facts_reconcile",
+ "sql": {
+ "length": 588,
+ "sha256": "f29640b05b0676eaa08c2bb65e8bfd1525021b8548848247761233d8b309b93a"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 209
}
],
"versions": [
@@ -3286,7 +3299,8 @@
205,
206,
207,
- 208
+ 208,
+ 209
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index f487839ed4..3e22d3a397 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 105, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
+ expect(counts).toEqual({ carry: 106, rebind: 2, rebuild: 2, discard: 6, schema_owned: 3 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });