Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): automatic facts drain on PGLite in serve, serve --http and the cycle

garrytan1c3667532aef
diff --git a/TODOS.md b/TODOS.md
index 47d9c605e6..301fa06314 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -62,8 +62,8 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro
## auto_chronicle wave follow-ups (filed 2026-10-04, follow-up from v0.60.45.0, #5876)
-- [ ] **P1 — facts-backstop jobs have no executor on PGLite.**
- **What:** `facts_backstop` effects enqueue jobs that `gbrain jobs work` refuses to run on PGLite (`commands/jobs/work.ts`), the same root cause the chronicle cycle phase fixed for events. **Fix:** run them from a cycle phase or the inline drain, bounded per run. **Effort:** M. **Priority:** P1.
+- [x] **P1 — facts-backstop jobs have no executor on PGLite.** **Completed:** the automatic facts drain (`src/core/facts/drain.ts`) runs them inside `gbrain serve`, `serve --http` and the `facts_drain` cycle phase, bounded per run and per day; doctor `facts_drain` reports it.
+ **What:** `facts_backstop` effects enqueue jobs that nothing ran on PGLite unless someone typed `gbrain jobs work`.
- [ ] **P2 — Drop future-dated events extracted from past pages.**
**What:** the measured run wrote 2 not-yet-happened events per 24 judged pages (a planned offsite date and a leave start date mentioned in past meetings) and 2 events for a launch plan stated in a chat. **Fix:** refuse proposals dated after the extraction time (or after the page's own date plus a margin) before publication, and tell the judge prompt to emit only what already happened; re-measure on the labeled fixture described in `docs/fix-wave-notes/capy-fix-wave-chronicle.md`. **Effort:** S. **Priority:** P2.
- [ ] **P2 — Event slug identity collapses distinct same-day proposals.**
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index d6cea2fee8..3e9c78ac03 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -85,6 +85,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
+- `src/core/facts/drain.ts` + `drain-scheduler.ts` + `src/core/cycle/facts-drain.ts` + `src/commands/doctor/checks/facts-drain.ts` — the automatic facts drain on PGLite (no job worker there). `runFactsDrain(engine, { owner, signal, wallClockMs })` runs queued `facts-absorb` jobs one at a time through the real handler (`withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler)`), with `authorizeJobExecution`/`withSubmissionAuthority`, lock renewal, a 25 ms yield between jobs and the owner's AbortSignal forwarded into the handler. Spend runs inside one `BudgetTracker` (`facts:drain`) capped at min(`facts.drain_budget_usd` 1.00, the rest of `facts.drain_daily_budget_usd` 5.00 over a rolling 24 h); `capSource` is `user` once either cap is set, so an unpriced model warns and runs under the defaults and refuses with the `gbrain pricing set` fix under a user cap. Before each claim the job's worst case (8,000-char turn + `facts.extraction_max_tokens`) must fit; `facts.drain_max_jobs` (50) bounds a run. Every stop other than an empty queue is a deferral that leaves jobs queued with no attempt counted (`queue.deferJob`): `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, shutdown. Run records (newest 20, 48 h) and the first-run marker live in config `facts.drain_state`; `readFactsDrainStatus` feeds doctor `facts_drain` and the readiness capability `facts_drain`. The first run prints the backlog, estimated spend, caps and opt-out on stderr and queues a `facts_drain_first_run` notice; deferrals raise one `facts_drain_deferred` notice per reason per process (`takeFactsDrainNotice`, taken by stdio `dispatch.ts`). Never writes stdout. `startFactsDrainScheduler` owns one unref'd 10-minute timer: it runs when the owner saw no activity since the previous tick or 30 minutes passed since the last run, one run in flight, an owner veto per tick (`canRun`), and `stop()` aborts and waits up to 5 s. Owners: stdio `serve` (`installFactsDrain`, stdin-data activity, delegated-sync veto, stopped first in the shutdown chain), `serve --http` (every tick; stopped before engine disconnect) and the cycle phase `facts_drain` (PGLite only; Postgres skips `not_applicable`). Opt-out: `facts.extraction_enabled false`. Tests: `test/facts-drain.test.ts`, `test/facts-drain-scheduler.test.ts`, `test/facts-absorb-keyless-deferral.test.ts`, the `facts_drain` row of `test/managed-phase-matrix.test.ts`.
- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes keep the 0.95 drop; capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).
- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 13f925c9a0..6cf6320b72 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -735,6 +735,28 @@ More: [docs/guides/write-refusals.md#embedding_auth_failed](../../docs/guides/wr
More: [docs/guides/write-refusals.md#facts_absorb_write_refused](../../docs/guides/write-refusals.md#facts_absorb_write_refused)
+### facts_drain_deferred
+
+<a id="facts_drain_deferred"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The automatic facts drain left queued facts-absorb jobs waiting; `reason` says why and `fix`, when present, is the next step. Nothing is dropped: the jobs run on a later drain. | A capability this request needs is not configured or not reachable on this brain. | Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first). Run: gbrain doctor --only facts_drain --json | agent | `gbrain doctor --json` | 1 | no |
+
+Reasons: `no_key`, `extraction_unavailable`, `budget_exhausted`, `daily_budget_exhausted`, `job_over_budget`, `no_pricing`, `provider_halted`, `drain_error`.
+
+More: [docs/guides/facts-drain.md#deferrals](../../docs/guides/facts-drain.md#deferrals)
+
+### facts_drain_job_failed
+
+<a id="facts_drain_job_failed"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A facts-absorb job failed inside the automatic facts drain; it retries with backoff until its attempts run out. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/facts-drain.md#deferrals](../../docs/guides/facts-drain.md#deferrals)
+
### facts_payload_expired
<a id="facts_payload_expired"></a>
diff --git a/docs/guides/facts-drain.md b/docs/guides/facts-drain.md
new file mode 100644
index 0000000000..ead63299e4
--- /dev/null
+++ b/docs/guides/facts-drain.md
@@ -0,0 +1,101 @@
+# Automatic facts drain (PGLite)
+
+**Say to your agent:** *"Are my notes being turned into facts automatically?"*
+
+**Say to your agent:** *"Turn off automatic fact extraction."*
+
+**Say to your agent:** *"Why are pages waiting for fact extraction?"*
+
+Every eligible page write (`put_page`, capture, sync) queues one `facts-absorb`
+job that extracts the page's facts with a chat model. A Postgres brain runs
+those jobs on its job worker (`gbrain jobs supervisor`). A PGLite brain has no
+background worker, so gbrain runs them inside the processes that already own
+the brain:
+
+- a resident `gbrain serve` (stdio, the recommended PGLite lifecycle);
+- `gbrain serve --http`;
+- the dream/autopilot cycle, as the `facts_drain` phase.
+
+No command is needed. This is **on by default**. Each extracted page is one
+paid chat call to the configured facts model (`facts.extraction_model`).
+
+To turn it off:
+
+```bash
+gbrain config set facts.extraction_enabled false
+```
+
+That key is the brain-wide facts-extraction switch, so it also stops the
+write-time extraction that queues the jobs.
+
+## When it runs
+
+`gbrain serve` (stdio and `--http`) checks every 10 minutes on its own timer.
+Stdio serve runs a drain on a check that saw no MCP traffic since the previous
+one, and at least every 30 minutes under sustained traffic, so a page written
+to a quiet serve is extracted within about 20 minutes. `serve --http` runs a
+drain on every check. A check that falls while a delegated sync owns the
+serve is skipped, so the 30-minute bound does not hold during an uninterrupted
+delegated sync. The cycle phase runs once per cycle. Each run takes one job at
+a time with a short pause between jobs, so foreground MCP calls interleave
+with it.
+
+On shutdown the in-flight job is stopped and returned to the queue without
+counting an attempt.
+
+## Spend caps
+
+| Key | Default | Bounds |
+|---|---|---|
+| `facts.drain_budget_usd` | `1.00` | priced spend of one run |
+| `facts.drain_daily_budget_usd` | `5.00` | priced spend of all runs in the last 24 hours |
+| `facts.drain_max_jobs` | `50` | jobs one run takes |
+
+Before each job the drain checks that the job's worst case (the page text, at
+most 8,000 characters, plus the output-token cap) fits the remaining run and
+daily budget; it stops the run otherwise. The first run on a brain prints the
+queued page count, the estimated spend, the caps and the opt-out command, on
+stderr and as a `facts_drain_first_run` notice on the next MCP call:
+
+```
+[gbrain notice facts_drain] Automatic fact extraction is on: 12 queued page(s), about $0.21 with anthropic:claude-sonnet-4-6, at most $1.00 per run and $5.00 per day. To opt out: gbrain config set facts.extraction_enabled false
+```
+
+A model with no known price runs under the default caps with a warning. Once
+you set either spend cap, an unpriced model refuses instead, and the fix tells
+the agent to look up the model's rate and register it with `gbrain pricing set`.
+
+## Deferrals
+
+The drain never drops work. Every stop other than an empty queue leaves the
+remaining jobs queued with no attempt counted, records the reason, and raises
+one `facts_drain_deferred` notice per reason per process:
+
+| Reason | Meaning | Next step |
+|---|---|---|
+| `no_key` | No chat provider key (OpenAI or Anthropic) | The user adds a key; `gbrain providers list` shows what each provider needs |
+| `extraction_unavailable` | The facts model's provider is not configured | Point `facts.extraction_model` at a model with a key |
+| `budget_exhausted` | The per-run cap was reached | Nothing (the next run continues), or raise `facts.drain_budget_usd` after asking the user |
+| `daily_budget_exhausted` | The 24-hour cap was reached | Nothing (budget frees as the window moves), or raise `facts.drain_daily_budget_usd` |
+| `job_over_budget` | One job's worst case is above the per-run cap | Raise `facts.drain_budget_usd` |
+| `no_pricing` | Unpriced model under a cap you set | Register the rate with `gbrain pricing set` |
+| `provider_halted` | The provider refused calls (auth, billing, rate limit) | Wait for the cooldown, or fix the key |
+
+A keyless brain stays silent while nothing is queued. A worker that runs a
+`facts-absorb` job without a key (for example a keyless `gbrain jobs work` on
+Postgres) also returns it to the queue for 30 minutes instead of completing it
+empty, so the backlog is extracted once a key exists.
+
+## Status
+
+```bash
+gbrain doctor --only facts_drain --json
+```
+
+The `facts_drain` check reports whether extraction is on, the queued backlog,
+the last run (owner, outcome, pages extracted, spend), the 24-hour spend, and
+the last deferral with its fix. It warns when jobs wait on a deferral, or when
+jobs are queued and no drain ran in the last 45 minutes (no serve or cycle owns
+the brain); the fix then is `gbrain dream --phase facts_drain`. The same status
+is the `facts_drain` entry of the MCP readiness resource
+(`gbrain://capabilities`).
diff --git a/llms.txt b/llms.txt
index 15a9d7e9c0..0ef8c568cf 100644
--- a/llms.txt
+++ b/llms.txt
@@ -40,6 +40,7 @@ Repo: https://github.com/garrytan/gbrain
- [docs/guides/quiet-hours.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/quiet-hours.md): Notification hold + timezone-aware delivery.
- [docs/guides/scaling-skills.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/scaling-skills.md): Three-tier architecture for agents with 300+ skills: always-loaded, resolver-routed, and dormant. Per-turn token math, the v0.41.7.0 compact list-format resolver, and the `gbrain doctor` safety net. 306 skills, ~21K tokens freed per turn, zero capability loss.
- [docs/guides/life-chronicle.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/life-chronicle.md): Life Chronicle automatic event extraction (on by default): what qualifies, per-page cost and daily ceiling, privacy, the receipt -> `gbrain dream --phase chronicle` -> `gbrain day` check, skip/failure codes with fixes, opt-out `gbrain config set auto_chronicle false`, history backfill.
+- [docs/guides/facts-drain.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/facts-drain.md): Automatic facts drain on PGLite (on by default): queued facts-absorb jobs run inside gbrain serve, serve --http and the facts_drain cycle phase with no command; per-run, daily and job-count caps, deferrals that never drop work, doctor facts_drain, opt-out `gbrain config set facts.extraction_enabled false`.
- [docs/guides/push-context.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/push-context.md): Push-based context: the brain volunteers confidence-gated pages from the rolling conversation window. Three channels (ambient reflex, volunteer_context op, gbrain watch), config knobs, and the volunteered-vs-used feedback loop.
- [docs/evidence-delivery.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/evidence-delivery.md): Evidence delivery (`return_unit`): window / section / page / auto evidence instead of chunks on search, query, recall and think, packed into a token budget; response fields, fallback codes, authorization guarantees, latency, and the frozen-hit `assemble_evidence` interface for evals.
- [docs/guides/github-source.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/github-source.md): Mirror GitHub issues, PRs, comments, reviews and CI checks as brain pages. One key + one registration command to a searchable mirror; webhook-driven instant refresh, poll-sweep fallback, daily reconcile, App-credential option.
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index e1d00035bd..13956a087f 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -22,7 +22,7 @@ src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decom
src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)
src/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/serve.ts installStdioLifecycle 315 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/commands/serve.ts installStdioLifecycle 322 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain)
src/commands/sources.ts runAdd 365 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 4 #5673: connector sources print that autopilot keeps them synced after the first sync
src/core/ai/gateway.ts chat 311 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/bootstrap/harness.ts applyHarness 1167 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
@@ -31,7 +31,7 @@ src/core/check-resolvable.ts checkResolvable 419 seed: W5 baseline, refactor wav
src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5824: search.vector_legacy_guard DB-plane merge
src/core/context-engine.ts createGBrainContextEngine 520 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #4618: seat sidecar call before the segment spool (helper recordOpenclawSeat)
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle.ts runCycle 1255 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block
+src/core/cycle.ts runCycle 1261 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder; +1 #4578: a lock steal during the last selected phase reports lock_stolen (one phase per runCycle call); +4 GBRA-40 F4b: planner-stats refresh after the freshness phases; +14 #5876: Life Chronicle phase dispatch block; +6 GBRA-40 Lane D: facts_drain phase dispatch
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stop
src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
@@ -48,7 +48,7 @@ src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 8
src/core/minions/handlers/subagent.ts runSubagentViaGateway 328 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/minions/worker.ts MinionWorker.executeJob 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
+src/core/minions/worker.ts MinionWorker.executeJob 304 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 GBRA-40 Lane D: JobDeferredError routes to deferJob
src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ops/facts.ts recall.handler 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ops/search.ts query.handler 330 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index bd4c9b4f40..b7e1c70120 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -182,6 +182,13 @@ export const SECTIONS: DocSection[] = [
path: "docs/guides/life-chronicle.md",
includeInFull: false,
},
+ {
+ title: "docs/guides/facts-drain.md",
+ description:
+ "Automatic facts drain on PGLite (on by default): queued facts-absorb jobs run inside gbrain serve, serve --http and the facts_drain cycle phase with no command; per-run, daily and job-count caps, deferrals that never drop work, doctor facts_drain, opt-out `gbrain config set facts.extraction_enabled false`.",
+ path: "docs/guides/facts-drain.md",
+ includeInFull: false,
+ },
{
title: "docs/guides/push-context.md",
description:
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..81f8ae9917 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -10,10 +10,10 @@ src/commands/embed.ts 2219 ratchet +2 agent operator wave D2: --json failure env
src/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)
src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)
src/commands/jobs.ts 660 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5)
-src/commands/serve-http.ts 919 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)
+src/commands/serve-http.ts 924 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)
src/core/ai/gateway.ts 4393 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)
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 3224 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)
+src/core/cycle.ts 3236 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); +12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts)
src/core/cycle/synthesize.ts 3297 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)
src/core/cycle/extract-atoms.ts 1808 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)
src/core/engine.ts 2678 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)
@@ -24,19 +24,19 @@ src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-fail
src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)
-src/core/minions/queue.ts 2522 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys
+src/core/minions/queue.ts 2523 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack
src/commands/init.ts 1869 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
-src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
+src/core/minions/worker.ts 1773 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper)
src/commands/sources.ts 2031 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured)
src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note
src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1838 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured)
+src/core/config.ts 1840 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts)
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index c761e7aaa1..f5ba8578fd 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -291,6 +291,11 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
if (key === 'auto_chronicle' || key.startsWith('chronicle.')) await refuseInvalidChronicleValue(key, value, force);
+ if (key.startsWith('facts.drain_')) {
+ const { validateFactsDrainConfigValue } = await import('../core/facts/drain.ts');
+ const err = validateFactsDrainConfigValue(key, value);
+ if (err) { console.error(`[config] ${err}`); process.exit(1); }
+ }
await engine.setConfig(key, value);
if (key === 'auto_chronicle') await acknowledgeAutoChronicle(engine, value);
if (!key.startsWith('decide.slots.')) return;
diff --git a/src/commands/doctor/checks/facts-drain.ts b/src/commands/doctor/checks/facts-drain.ts
new file mode 100644
index 0000000000..f104f95ce9
--- /dev/null
+++ b/src/commands/doctor/checks/facts-drain.ts
@@ -0,0 +1,30 @@
+/**
+ * facts_drain (Lane D): the automatic facts drain on PGLite (src/core/facts/drain.ts).
+ * Reports on/off, the queued facts-absorb backlog, the last run and its spend, and a
+ * deferral (no key, budget used up, unpriced model under a user cap) with its fix,
+ * so a background failure reaches the agent. Reads the database only.
+ */
+import { FACTS_DRAIN_DOCS, readFactsDrainStatus } from '../../../core/facts/drain.ts';
+import type { Check } from '../../doctor.ts';
+import { infoCheck } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+async function runFactsDrainCheck(ctx: DoctorContext): Promise<Check[]> {
+ const status = await readFactsDrainStatus(connectedEngine(ctx));
+ const details = {
+ health: status.health, backlog: status.backlog, last_run: status.last_run, daily_spent_usd: status.daily_spent_usd,
+ ...(status.settings ? { enabled: status.settings.enabled, budget_usd: status.settings.budgetUsd, daily_budget_usd: status.settings.dailyBudgetUsd, max_jobs: status.settings.maxJobs } : {}),
+ docs: FACTS_DRAIN_DOCS,
+ };
+ switch (status.health) {
+ case 'not_applicable': return [infoCheck('facts_drain', status.message, 'not_applicable', undefined, details)];
+ case 'disabled': return [infoCheck('facts_drain', status.message, 'disabled_by_choice', status.fix, details)];
+ case 'deferred':
+ case 'no_owner':
+ return [{ name: 'facts_drain', status: 'warn', message: status.message, ...(status.fix ? { fix: status.fix } : {}), readiness_state: 'degraded', details }];
+ default:
+ return [{ name: 'facts_drain', status: 'ok', message: status.message, details }];
+ }
+}
+
+export const factsDrainEntry: DoctorEntry = { name: 'facts_drain', emits: ['facts_drain'], run: runFactsDrainCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index c20b98d777..1c00a016da 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -83,6 +83,7 @@ import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';
import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { autoChronicleEntry } from './checks/auto-chronicle.ts';
+import { factsDrainEntry } from './checks/facts-drain.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';
@@ -152,6 +153,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
decideHealthEntry,
unlinkedFactsEntry,
autoChronicleEntry,
+ factsDrainEntry,
factTakeVectorsEntry,
plannerStatsEntry,
searchModeEntry,
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 1626e23160..7064cf841a 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -904,12 +904,17 @@ ${bootstrapFromEnv
const deregisterIpcCleanup = registerCleanup('resolve-ipc-close', async () => {
ipcBinding.close();
});
- const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', () =>
- engine.disconnect(),
- );
+ // Automatic facts drain (Lane D): the resident HTTP serve owns a PGLite brain the way stdio serve does.
+ const { startFactsDrainScheduler } = await import('../core/facts/drain-scheduler.ts');
+ const factsDrain = startFactsDrainScheduler(engine, { owner: 'serve_http', log: (line) => console.error(line) });
+ const deregisterEngineCleanup = registerCleanup('pglite-engine-disconnect', async () => {
+ await factsDrain.stop();
+ await engine.disconnect();
+ });
try {
await waitForHttpServerLifecycle(httpServer);
} finally {
+ await factsDrain.stop();
// Close the IPC listener + reap the socket file on orderly shutdown
// (abnormal termination goes through the registered cleanup above).
ipcBinding.close();
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 3dd36fd4b8..bbc560696d 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -7,6 +7,7 @@ import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } fr
import { VERB_NAMES } from '../core/verbs.ts';
import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
+import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
import { onForwardProgress } from '../core/forward-progress.ts';
import {
installLoopStallWatchdog,
@@ -146,6 +147,9 @@ export interface ServeOptions {
// (pre-#4409 behavior). Defaults to GBRAIN_SERVE_EOF_DRAIN_MS (30s when
// unset; lenient parse).
eofDrainMs?: number;
+ // Test seam for the automatic facts drain (src/core/facts/drain-scheduler.ts):
+ // false disables it; an object overrides its timer and run body.
+ factsDrain?: false | Pick<FactsDrainSchedulerOpts, 'run' | 'tickMs' | 'maxGapMs' | 'now'>;
}
/**
@@ -480,6 +484,34 @@ interface StdioLifecycleDeps {
probeWatchdog: () => boolean;
}
+/**
+ * Automatic facts drain (Foundations 2, Lane D): PGLite has no job worker, so
+ * the resident serve runs queued facts-absorb jobs on its own unref'd timer,
+ * bounded per run and per day. Activity is read from stdin 'data' chunks
+ * through a listener attached on the first tick (same reason as the idle
+ * sweep: never before the SDK transport attaches). Opt out with
+ * `gbrain config set facts.extraction_enabled false`.
+ */
+function installFactsDrain(engine: BrainEngine, opts: ServeOptions, deps: StdioLifecycleDeps, shuttingDown: () => boolean): FactsDrainScheduler | null {
+ if (opts.factsDrain === false || engine.kind !== 'pglite') return null;
+ let lastStdinDataAt = 0;
+ let listenerAttached = false;
+ return startFactsDrainScheduler(engine, {
+ owner: 'serve',
+ ...(opts.factsDrain ?? {}),
+ setInterval: deps.setInterval,
+ clearInterval: deps.clearInterval,
+ log: (line) => deps.log(line),
+ lastActivityAt: () => {
+ if (listenerAttached) return lastStdinDataAt;
+ listenerAttached = true;
+ deps.stdin.on('data', () => { lastStdinDataAt = Date.now(); });
+ return Number.MAX_SAFE_INTEGER;
+ },
+ canRun: async () => !shuttingDown() && !isEngineDegradedForServe(engine) && !(await loadSyncRunner()).isDelegatedSyncRunning(),
+ });
+}
+
function installStdioLifecycle(
engine: BrainEngine,
args: string[],
@@ -500,6 +532,7 @@ function installStdioLifecycle(
let parentWatchdog: unknown = null;
let idleSweepTimer: unknown = null;
let activateIdleActivityTracking = (): void => {};
+ let factsDrain: FactsDrainScheduler | null = null;
const beginShutdown = (reason: string): void => {
if (shuttingDown) return;
shuttingDown = true;
@@ -548,6 +581,9 @@ function installStdioLifecycle(
armDeadline(CLEANUP_DEADLINE_MS);
Promise.resolve()
+ // The facts drain aborts its in-flight job (left queued, no attempt
+ // counted) before the engine goes away.
+ .then(() => factsDrain?.stop())
// Idempotent shared promise — mcp/server.ts's shutdown races here on
// the same signals; whichever runs first does the abort+settle, the
// other awaits it. Must precede disconnect (settle writes need the
@@ -756,6 +792,9 @@ function installStdioLifecycle(
(idleSweepTimer as { unref?: () => void } | null)?.unref?.();
}
+ // Automatic facts drain (Lane D): see installFactsDrain.
+ factsDrain = installFactsDrain(engine, opts, deps, () => shuttingDown);
+
// Optional idle-timeout safety net. Default OFF; opt-in via
// `--stdio-idle-timeout <seconds>`. The flag is for the rare case where
// the parent leaks the stdin pipe but never closes it (so 'end' never
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..f5b61f5d30 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1409,6 +1409,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'loops.extraction_enabled',
// #2113: output-token cap for the per-turn facts extractor (default 4000).
'facts.extraction_max_tokens',
+ // Automatic facts drain caps (src/core/facts/drain.ts FACTS_DRAIN_KEYS).
+ 'facts.drain_budget_usd', 'facts.drain_daily_budget_usd', 'facts.drain_max_jobs',
// #3852: operator-set system-prompt appendix for the facts extractor (e.g.
// a durable-vs-ephemeral rubric for agent work-session transcripts).
// Composes with BOTH honest-notability prompt variants.
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 4ae8dad37a..45a88fc92e 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -82,6 +82,8 @@ export type CyclePhase =
| 'drift'
// #5876 — Life Chronicle events from meeting/conversation/calendar pages (default ON).
| 'chronicle'
+ // Lane D — runs queued facts-absorb jobs on PGLite (no job worker there); bounded per run and per day.
+ | 'facts_drain'
| 'embed' | 'orphans' | 'purge'
// v0.39 T12: schema-suggest passive trigger (D3 + D4 plan-eng-review).
// Wraps runSuggest() — same library the CLI verb + EIIRP call.
@@ -173,6 +175,8 @@ export const ALL_PHASES: CyclePhase[] = [
'drift',
// #5876 — Life Chronicle events (global). BEFORE embed so event pages embed same-cycle.
'chronicle',
+ // Lane D — automatic facts drain (PGLite). BEFORE embed so new facts embed same-cycle.
+ 'facts_drain',
// v0.41.11.0 — opt-in conversation-facts backfill. Default OFF; reads
// cycle.conversation_facts_backfill.enabled gate inside the wrapper.
// Ordered AFTER calibration_profile (matches the runCycle dispatch
@@ -333,6 +337,8 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set([
'drift',
// #5876 — writes event pages, projections and the chronicle ledger.
'chronicle',
+ // Lane D — writes facts (fence + index) through facts-absorb jobs.
+ 'facts_drain',
// v0.41 T9 — extract_atoms writes atom-typed pages via put_page;
// synthesize_concepts writes concept-typed pages + tier updates. Both
// mutate DB state and need the lock.
@@ -2754,6 +2760,12 @@ export async function runCycle(
await safeYield(opts.yieldBetweenPhases);
}
+ if (phases.includes('facts_drain')) { // Lane D: queued facts-absorb jobs on PGLite (src/core/cycle/facts-drain.ts)
+ checkAborted(cycleSignal);
+ const { result, duration_ms } = await timePhase(async () => (await import('./cycle/facts-drain.ts')).runPhaseFactsDrain(engine, { dryRun, signal: cycleSignal, deadlineAtMs: opts.deadlineAtMs ?? null }), 'facts_drain');
+ phaseResults.push({ ...result, duration_ms }); await safeYield(opts.yieldBetweenPhases);
+ }
+
// ── v0.41.11.0: conversation_facts_backfill ─────────────────
// Opt-in (default OFF). Walks long-form conversation/meeting/slack/
// email pages, segments by 30-min gap, runs facts extractor with a
diff --git a/src/core/cycle/facts-drain.ts b/src/core/cycle/facts-drain.ts
new file mode 100644
index 0000000000..c14a93f5f1
--- /dev/null
+++ b/src/core/cycle/facts-drain.ts
@@ -0,0 +1,34 @@
+/**
+ * `facts_drain` cycle phase (Lane D): one bounded run of the automatic facts
+ * drain (src/core/facts/drain.ts) inside the cycle, so a PGLite brain run by
+ * autopilot or `gbrain dream` extracts queued `facts-absorb` jobs without
+ * `gbrain jobs work`. Postgres brains have a job worker and skip the phase.
+ * The phase never fails the cycle: deferrals (no key, budget) report `warn`
+ * with the fix; an internal error reports `warn` with the doctor command.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
+import { FACTS_DRAIN_DEFERRALS, FACTS_DRAIN_WALL_MS, runFactsDrain } from '../facts/drain.ts';
+import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';
+
+export async function runPhaseFactsDrain(engine: BrainEngine | null, opts: { dryRun: boolean; signal?: AbortSignal; deadlineAtMs?: number | null }): Promise<PhaseResult> {
+ const base = { phase: 'facts_drain' as const, duration_ms: 0 };
+ if (!engine) return { ...base, status: 'skipped', summary: 'no database connected', details: { reason: 'no_database' } };
+ if (engine.kind !== 'pglite') {
+ return { ...base, status: 'skipped', summary: 'Postgres brains run facts-absorb jobs on the job worker', details: { reason: 'not_applicable' } };
+ }
+ if (opts.dryRun) return { ...base, status: 'skipped', summary: 'dry run: no facts extracted', details: { reason: 'dry_run' } };
+ const remaining = opts.deadlineAtMs != null ? opts.deadlineAtMs - CYCLE_DEADLINE_RESERVE_MS - Date.now() : FACTS_DRAIN_WALL_MS;
+ if (remaining <= 0) return { ...base, status: 'skipped', summary: 'no cycle time left for the facts drain', details: { reason: 'deadline' } };
+ const r = await runFactsDrain(engine, { owner: 'cycle', signal: opts.signal, wallClockMs: Math.min(FACTS_DRAIN_WALL_MS, remaining) });
+ const details: Record<string, unknown> = {
+ outcome: r.outcome, completed: r.completed, failed: r.failed, deferred: r.deferred, facts_inserted: r.facts_inserted,
+ spent_usd: r.spent_usd, unpriced_calls: r.unpriced_calls, backlog_before: r.backlog_before, backlog_after: r.backlog_after, model: r.model,
+ ...(r.error ? { code: r.error.code, reason: r.error.reason, fix: r.error.fix } : {}),
+ };
+ if (r.outcome === 'disabled') return { ...base, status: 'skipped', summary: 'facts extraction is off (facts.extraction_enabled false)', details };
+ if (r.outcome === 'idle' || r.outcome === 'not_applicable') return { ...base, status: 'ok', summary: 'no queued facts-absorb jobs', details };
+ const summary = `${r.completed} page(s) extracted (${r.facts_inserted} facts, $${r.spent_usd.toFixed(3)}), ${r.backlog_after ?? '?'} still queued` +
+ (r.error ? `: ${r.error.message}` : '');
+ return { ...base, status: FACTS_DRAIN_DEFERRALS.has(r.outcome) || r.failed > 0 ? 'warn' : 'ok', summary, details };
+}
diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.ts
index 5728acd454..454f8f0741 100644
--- a/src/core/cycle/phase-scope.ts
+++ b/src/core/cycle/phase-scope.ts
@@ -28,6 +28,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {
calibration_profile: 'global',
drift: 'global',
chronicle: 'global',
+ facts_drain: 'global',
embed: 'global',
orphans: 'global',
purge: 'global',
diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.ts
index 65ed1f87b6..7c9139e629 100644
--- a/src/core/cycle/phase-table.ts
+++ b/src/core/cycle/phase-table.ts
@@ -37,6 +37,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>
calibration_profile: { class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },
drift: { class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },
chronicle: { class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },
+ facts_drain: { class: 'writes', reason: 'Queued facts-absorb jobs publish facts through the same coordinated write path as the job worker.' },
conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },
enrich_thin: { class: 'writes', reason: 'Enriched pages publish through the maintenance coordinator.' },
skillopt: { class: 'no_coordinated_write', reason: 'Writes skill files and proposals outside the brain database.' },
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index a3d3ec27b3..053875ed9b 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -75,6 +75,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'auto_chronicle',
'auto_chronicle_default_on',
'chronicle_config_invalid',
+ 'facts_drain',
'fact_take_vectors',
'code_chunk_metadata',
'content_hash_duplicates',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 1ff419a60e..64c877f005 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -130,6 +130,8 @@ export const CODES = {
fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },
fact_not_found: { class: 'caller', summary: "Fact not found." },
facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },
+ facts_drain_deferred: { class: 'unavailable', summary: "The automatic facts drain left queued facts-absorb jobs waiting; `reason` says why and `fix`, when present, is the next step. Nothing is dropped: the jobs run on a later drain.", reasons: ['no_key', 'extraction_unavailable', 'budget_exhausted', 'daily_budget_exhausted', 'job_over_budget', 'no_pricing', 'provider_halted', 'drain_error'], docs: 'docs/guides/facts-drain.md#deferrals', suggestion: 'Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first).', fix: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', why: 'Shows the drain status, the backlog and the last error with its fix.', requires_exclusive: false } },
+ facts_drain_job_failed: { class: 'server', summary: "A facts-absorb job failed inside the automatic facts drain; it retries with backoff until its attempts run out.", docs: 'docs/guides/facts-drain.md#deferrals' },
facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },
fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
file_too_large: { class: 'caller', summary: "The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported.", why: "Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry.", suggestion: 'Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again.' },
@@ -328,6 +330,8 @@ export const NOTICE_CODES = {
onboard_opportunities: { kind: 'coaching', summary: 'Onboarding checks found work that would improve this brain (gbrain onboard --check lists it).' },
features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },
post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
+ facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },
+ facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },
held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },
recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/src/core/facts/drain-scheduler.ts b/src/core/facts/drain-scheduler.ts
new file mode 100644
index 0000000000..547f01e69a
--- /dev/null
+++ b/src/core/facts/drain-scheduler.ts
@@ -0,0 +1,94 @@
+/**
+ * The one in-process scheduler for the automatic facts drain (drain.ts), used
+ * by stdio `gbrain serve` and `gbrain serve --http`. Its own unref'd timer
+ * (never the 3-second idle maintenance sweep) ticks every 10 minutes; a tick
+ * runs one bounded drain when the owner saw no foreground activity since the
+ * previous tick, or when 30 minutes passed since the last run, so sustained
+ * MCP traffic still gets a run at least every 30 minutes. At most one run is
+ * in flight; `stop()` aborts it (the signal reaches the job handler) and
+ * waits a bounded time for it to settle. A tick the owner vetoes (`canRun`,
+ * e.g. while a delegated sync owns the event loop) is skipped, so the
+ * 30-minute bound excludes an uninterrupted delegated sync.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { runFactsDrain, type FactsDrainOwner, type FactsDrainRunResult } from './drain.ts';
+
+export const FACTS_DRAIN_TICK_MS = 10 * 60_000;
+export const FACTS_DRAIN_MAX_GAP_MS = 30 * 60_000;
+const STOP_SETTLE_MS = 5_000;
+
+export interface FactsDrainSchedulerOpts {
+ owner: FactsDrainOwner;
+ tickMs?: number;
+ maxGapMs?: number;
+ wallClockMs?: number;
+ /** Epoch ms of the owner's last foreground activity; omitted = always quiet. */
+ lastActivityAt?: () => number;
+ /** Owner veto for this tick (delegated sync running, engine degraded, shutting down). */
+ canRun?: () => boolean | Promise<boolean>;
+ setInterval?: (fn: () => void, ms: number) => unknown;
+ clearInterval?: (handle: unknown) => void;
+ now?: () => number;
+ log?: (line: string) => void;
+ /** Test seam: replaces runFactsDrain. */
+ run?: (engine: BrainEngine, opts: { owner: FactsDrainOwner; signal: AbortSignal; wallClockMs?: number; log?: (line: string) => void }) => Promise<FactsDrainRunResult>;
+}
+
+export interface FactsDrainScheduler {
+ /** Run one tick's decision now (tests and owners that want an early check). */
+ tick(): Promise<FactsDrainRunResult | null>;
+ stop(): Promise<void>;
+ readonly running: boolean;
+}
+
+export function startFactsDrainScheduler(engine: BrainEngine, opts: FactsDrainSchedulerOpts): FactsDrainScheduler {
+ const tickMs = opts.tickMs ?? FACTS_DRAIN_TICK_MS;
+ const maxGapMs = opts.maxGapMs ?? FACTS_DRAIN_MAX_GAP_MS;
+ const now = opts.now ?? Date.now;
+ const run = opts.run ?? runFactsDrain;
+ const abort = new AbortController();
+ let lastRunAt = now();
+ let lastTickAt = now();
+ let inflight: Promise<FactsDrainRunResult | null> | null = null;
+ let stopped = false;
+
+ const tick = async (): Promise<FactsDrainRunResult | null> => {
+ if (stopped || inflight || engine.kind !== 'pglite') return null;
+ const at = now();
+ const previousTick = lastTickAt;
+ lastTickAt = at;
+ const quiet = (opts.lastActivityAt?.() ?? 0) < previousTick;
+ if (!quiet && at - lastRunAt < maxGapMs) return null;
+ try {
+ if (opts.canRun && !(await opts.canRun())) return null;
+ } catch {
+ return null;
+ }
+ lastRunAt = at;
+ inflight = run(engine, { owner: opts.owner, signal: abort.signal, wallClockMs: opts.wallClockMs, ...(opts.log ? { log: opts.log } : {}) })
+ .catch(() => null)
+ .finally(() => { inflight = null; });
+ return inflight;
+ };
+
+ const set = opts.setInterval ?? ((fn: () => void, ms: number) => setInterval(fn, ms));
+ const clear = opts.clearInterval ?? ((h: unknown) => clearInterval(h as ReturnType<typeof setInterval>));
+ const handle = engine.kind === 'pglite' ? set(() => { void tick(); }, tickMs) : null;
+ (handle as { unref?: () => void } | null)?.unref?.();
+
+ return {
+ tick,
+ get running() { return inflight !== null; },
+ async stop() {
+ if (stopped) return;
+ stopped = true;
+ if (handle !== null) clear(handle);
+ abort.abort(new Error('shutdown'));
+ const current = inflight;
+ if (!current) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([current, new Promise(resolve => { timer = setTimeout(resolve, STOP_SETTLE_MS); timer.unref?.(); })]);
+ clearTimeout(timer);
+ },
+ };
+}
diff --git a/src/core/facts/drain.ts b/src/core/facts/drain.ts
new file mode 100644
index 0000000000..f37db307c3
--- /dev/null
+++ b/src/core/facts/drain.ts
@@ -0,0 +1,498 @@
+/**
+ * Automatic facts drain (Foundations 2, Lane D). PGLite has no background job
+ * worker, so `facts-absorb` jobs (one per eligible page write) wait until
+ * something runs them. This module runs them inside the processes that
+ * already own a PGLite brain: stdio `gbrain serve`, `gbrain serve --http` and
+ * the dream/autopilot cycle (`facts_drain` phase). One shared implementation:
+ *
+ * - one job at a time, with a yield between jobs, a wall-clock budget per
+ * run and an AbortSignal (shutdown) forwarded into the job handler;
+ * - spend bounded per run (`facts.drain_budget_usd`, default $1.00), per
+ * rolling 24 hours (`facts.drain_daily_budget_usd`, default $5.00) and by
+ * job count (`facts.drain_max_jobs`, default 50); unpriced models warn and
+ * run under the default caps, and refuse with the register-the-rate fix
+ * under a cap the user set;
+ * - every stop that is not "queue empty" is a deferral that keeps the jobs
+ * queued without counting an attempt (budget used up, no provider key,
+ * shutdown, provider halt);
+ * - status (last run, backlog, last error with its fix) lives in the config
+ * row `facts.drain_state`, read by doctor `facts_drain` and the MCP
+ * readiness entry `facts_drain`.
+ *
+ * Opt out with `gbrain config set facts.extraction_enabled false`. Logging goes
+ * to stderr only (stdio serve speaks JSON-RPC on stdout).
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { Action, Notice } from '../agent-output.ts';
+import type { MinionJob } from '../minions/types.ts';
+
+export const FACTS_DRAIN_JOB = 'facts-absorb';
+export const FACTS_DRAIN_QUEUE = 'default';
+export const FACTS_DRAIN_STATE_KEY = 'facts.drain_state';
+export const FACTS_DRAIN_OPT_OUT_ARGV = ['gbrain', 'config', 'set', 'facts.extraction_enabled', 'false'] as const;
+export const FACTS_DRAIN_DOCS = 'docs/guides/facts-drain.md';
+/** One run's default wall-clock budget. */
+export const FACTS_DRAIN_WALL_MS = 5 * 60_000;
+/** Tokens the extractor adds around the page text (system prompt + framing). */
+const PROMPT_OVERHEAD_TOKENS = 1_500;
+const RUN_HISTORY = 20;
+
+interface NumericKeySpec { fallback: number; min: number; max: number; integer: boolean; meaning: string }
+export const FACTS_DRAIN_KEYS = {
+ 'facts.drain_budget_usd': { fallback: 1, min: 0.01, max: 100, integer: false, meaning: 'USD cap for one automatic drain run' },
+ 'facts.drain_daily_budget_usd': { fallback: 5, min: 0.01, max: 1000, integer: false, meaning: 'USD cap for automatic drain runs per rolling 24 hours' },
+ 'facts.drain_max_jobs': { fallback: 50, min: 1, max: 1000, integer: true, meaning: 'jobs one automatic drain run takes at most' },
+} as const satisfies Record<string, NumericKeySpec>;
+export type FactsDrainKey = keyof typeof FACTS_DRAIN_KEYS;
+
+function parseKey(key: FactsDrainKey, raw: string): number | null {
+ const spec: NumericKeySpec = FACTS_DRAIN_KEYS[key];
+ const text = raw.trim();
+ if (!/^\d+(\.\d+)?$/.test(text)) return null;
+ const n = Number(text);
+ if (spec.integer && !Number.isInteger(n)) return null;
+ return n >= spec.min && n <= spec.max ? n : null;
+}
+
+/** `config set` validation for facts.drain_*; the refusal text, or null when valid. */
+export function validateFactsDrainConfigValue(key: string, value: string): string | null {
+ if (!(key in FACTS_DRAIN_KEYS)) return null;
+ const k = key as FactsDrainKey;
+ const spec: NumericKeySpec = FACTS_DRAIN_KEYS[k];
+ return parseKey(k, value) !== null ? null
+ : `${key} must be ${spec.integer ? 'a whole number' : 'a number'} from ${spec.min} to ${spec.max} (${spec.meaning}; default ${spec.fallback}) (got '${value}'). Nothing was written.`;
+}
+
+export interface FactsDrainSettings {
+ enabled: boolean;
+ budgetUsd: number;
+ dailyBudgetUsd: number;
+ maxJobs: number;
+ /** A spend cap was set by the user: an unpriced model then refuses instead of warn-and-run. */
+ explicitCap: boolean;
+}
+
+export async function factsDrainSettings(engine: BrainEngine): Promise<FactsDrainSettings> {
+ const { isFactsExtractionEnabled } = await import('./extract.ts');
+ const values = {} as Record<FactsDrainKey, number>;
+ let explicitCap = false;
+ for (const key of Object.keys(FACTS_DRAIN_KEYS) as FactsDrainKey[]) {
+ const raw = await engine.getConfig(key).catch(() => null);
+ const parsed = raw == null || raw.trim() === '' ? null : parseKey(key, raw);
+ values[key] = parsed ?? FACTS_DRAIN_KEYS[key].fallback;
+ if (parsed !== null && key !== 'facts.drain_max_jobs') explicitCap = true;
+ }
+ return {
+ enabled: await isFactsExtractionEnabled(engine),
+ budgetUsd: values['facts.drain_budget_usd'],
+ dailyBudgetUsd: values['facts.drain_daily_budget_usd'],
+ maxJobs: values['facts.drain_max_jobs'],
+ explicitCap,
+ };
+}
+
+export type FactsDrainOwner = 'serve' | 'serve_http' | 'cycle';
+export type FactsDrainOutcome =
+ | 'drained' | 'idle' | 'disabled' | 'not_applicable' | 'max_jobs' | 'deadline' | 'aborted'
+ | 'no_key' | 'extraction_unavailable' | 'budget_exhausted' | 'daily_budget_exhausted' | 'job_over_budget'
+ | 'no_pricing' | 'provider_halted' | 'error';
+/** Outcomes that leave work queued for a reason the agent can act on. */
+export const FACTS_DRAIN_DEFERRALS: ReadonlySet<FactsDrainOutcome> = new Set([
+ 'no_key', 'extraction_unavailable', 'budget_exhausted', 'daily_budget_exhausted', 'job_over_budget', 'no_pricing', 'provider_halted', 'error',
+]);
+
+export interface FactsDrainRunRecord {
+ owner: FactsDrainOwner;
+ started_at: string;
+ finished_at: string | null;
+ outcome: FactsDrainOutcome | 'running';
+ completed: number;
+ failed: number;
+ deferred: number;
+ facts_inserted: number;
+ spent_usd: number;
+ unpriced_calls: number;
+ backlog_before: number;
+ backlog_after: number | null;
+ model: string | null;
+ error?: { code: string; reason: string; message: string; fix?: Action };
+}
+
+interface FactsDrainState { version: 1; runs: FactsDrainRunRecord[]; first_run_reported_at?: string }
+
+export async function readFactsDrainState(engine: BrainEngine): Promise<FactsDrainState> {
+ try {
+ const raw = await engine.getConfig(FACTS_DRAIN_STATE_KEY);
+ const parsed = raw ? JSON.parse(raw) as Partial<FactsDrainState> : null;
+ if (parsed && Array.isArray(parsed.runs)) return { version: 1, runs: parsed.runs, first_run_reported_at: parsed.first_run_reported_at };
+ } catch { /* unreadable state starts fresh */ }
+ return { version: 1, runs: [] };
+}
+
+async function writeFactsDrainState(engine: BrainEngine, state: FactsDrainState): Promise<void> {
+ const cutoff = Date.now() - 48 * 3600_000;
+ const runs = state.runs.filter((r, i) => i === state.runs.length - 1 || Date.parse(r.started_at) >= cutoff).slice(-RUN_HISTORY);
+ await engine.setConfig(FACTS_DRAIN_STATE_KEY, JSON.stringify({ ...state, runs }));
+}
+
+/** Priced spend of drain runs that started in the last 24 hours. */
+export function dailySpentUsd(state: FactsDrainState, now = Date.now()): number {
+ return state.runs.filter(r => now - Date.parse(r.started_at) < 24 * 3600_000).reduce((sum, r) => sum + (r.spent_usd || 0), 0);
+}
+
+export interface FactsDrainBacklog { waiting: number; delayed: number; active: number }
+
+export async function factsDrainBacklog(engine: BrainEngine): Promise<FactsDrainBacklog> {
+ const rows = await engine.executeRaw<{ status: string; n: number }>(
+ `SELECT status, count(*)::int AS n FROM minion_jobs
+ WHERE name = $1 AND queue = $2 AND status IN ('waiting', 'delayed', 'active') GROUP BY status`,
+ [FACTS_DRAIN_JOB, FACTS_DRAIN_QUEUE]);
+ const out: FactsDrainBacklog = { waiting: 0, delayed: 0, active: 0 };
+ for (const r of rows) out[r.status as keyof FactsDrainBacklog] = Number(r.n);
+ return out;
+}
+
+const fmtUsd = (n: number) => `$${n < 0.1 ? n.toFixed(3) : n.toFixed(2)}`;
+const command = (argv: readonly string[]) => argv.join(' ');
+
+function keySetupFix(): Action {
+ return {
+ argv: ['gbrain', 'providers', 'list'], consent: ['credentials', 'paid'], actor: 'user', requires_exclusive: false,
+ why: 'Automatic fact extraction needs one chat provider key (for example ANTHROPIC_API_KEY or OPENAI_API_KEY, stored with `gbrain config set anthropic_api_key <key>`); `gbrain providers list` shows what each provider needs. Queued pages run on the next drain once a key exists.',
+ user_message: 'Pages are waiting for automatic fact extraction, which needs a chat model API key (Anthropic or OpenAI, for example). Want to add one? It costs a little per page processed.',
+ verify: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'] },
+ };
+}
+
+function budgetFix(key: 'facts.drain_budget_usd' | 'facts.drain_daily_budget_usd', suggested: number): Action {
+ return {
+ argv: ['gbrain', 'config', 'set', key, suggested.toFixed(2)], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: `Raises the cap so more queued pages are extracted per ${key === 'facts.drain_budget_usd' ? 'run' : 'day'}; each page is one paid chat call. Ask the user first. Doing nothing is also fine: the jobs wait and run when budget frees up.`,
+ user_message: `Automatic fact extraction reached its ${key === 'facts.drain_budget_usd' ? 'per-run' : 'daily'} spending cap and queued pages are waiting. Raise the cap to ${fmtUsd(suggested)}, or let them run as budget frees up?`,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'] },
+ };
+}
+
+export interface FactsDrainRunResult extends Omit<FactsDrainRunRecord, 'outcome'> { outcome: FactsDrainOutcome; notice?: Notice }
+
+export interface FactsDrainRunOpts {
+ owner: FactsDrainOwner;
+ signal?: AbortSignal;
+ wallClockMs?: number;
+ /** Stderr sink (default process.stderr). Never stdout. */
+ log?: (line: string) => void;
+ /** Pause between jobs so foreground work interleaves (default 25 ms). */
+ yieldMs?: number;
+}
+
+/** Pending notice for the next stdio MCP call (dispatch takes it); one per reason per process. */
+let pendingNotice: Notice | null = null;
+const noticedReasons = new Set<string>();
+export function takeFactsDrainNotice(): Notice | null {
+ const n = pendingNotice;
+ pendingNotice = null;
+ return n;
+}
+/** Test-only: reset the process-wide notice memo. */
+export function __resetFactsDrainNoticesForTests(): void { pendingNotice = null; noticedReasons.clear(); }
+
+function findError<T>(err: unknown, match: (e: unknown) => e is T): T | null {
+ let cur: unknown = err;
+ for (let i = 0; i < 6 && cur; i++) {
+ if (match(cur)) return cur;
+ cur = (cur as { cause?: unknown }).cause;
+ }
+ return null;
+}
+
+/** Estimated cost of extracting the queued pages, from their text length and the model price. */
+async function estimateBacklogUsd(engine: BrainEngine, model: string, backlog: number, maxTokens: number): Promise<number | null> {
+ const { reservationCostUsd } = await import('../budget/reservation-cost.ts');
+ const { MAX_TURN_TEXT_CHARS } = await import('./extract.ts');
+ const [row] = await engine.executeRaw<{ chars: number | null }>(
+ `SELECT avg(LEAST(length(p.compiled_truth), $3))::float AS chars FROM minion_jobs j
+ JOIN pages p ON p.slug = j.data->>'slug' AND p.source_id = COALESCE(j.data->>'sourceId', 'default')
+ WHERE j.name = $1 AND j.queue = $2 AND j.status IN ('waiting', 'delayed')`,
+ [FACTS_DRAIN_JOB, FACTS_DRAIN_QUEUE, MAX_TURN_TEXT_CHARS]).catch(() => [{ chars: null }]);
+ const inputTokens = Math.ceil((row?.chars ?? MAX_TURN_TEXT_CHARS / 2) / 4) + PROMPT_OVERHEAD_TOKENS;
+ const perJob = reservationCostUsd(model, 'chat', inputTokens, Math.min(maxTokens, 800));
+ return perJob === null ? null : perJob * backlog;
+}
+
+/**
+ * Run one bounded drain pass. Never throws: failures become the `error`
+ * outcome with the cause recorded in `facts.drain_state`.
+ */
+export async function runFactsDrain(engine: BrainEngine, opts: FactsDrainRunOpts): Promise<FactsDrainRunResult> {
+ const log = opts.log ?? ((line: string) => { process.stderr.write(`${line}\n`); });
+ const startedAt = new Date();
+ const result: FactsDrainRunResult = {
+ owner: opts.owner, started_at: startedAt.toISOString(), finished_at: null, outcome: 'idle',
+ completed: 0, failed: 0, deferred: 0, facts_inserted: 0, spent_usd: 0, unpriced_calls: 0,
+ backlog_before: 0, backlog_after: null, model: null,
+ };
+ const finish = (outcome: FactsDrainOutcome): FactsDrainRunResult => {
+ result.outcome = outcome;
+ result.finished_at = new Date().toISOString();
+ return result;
+ };
+ if (engine.kind !== 'pglite') return finish('not_applicable');
+ const { isEngineDegraded } = await import('../degraded-marker.ts');
+ if (isEngineDegraded(engine)) return finish('not_applicable');
+
+ let state: FactsDrainState | null = null;
+ let recorded = false;
+ const save = async () => {
+ if (!state) return;
+ const rec: FactsDrainRunRecord = { ...result, outcome: result.finished_at ? result.outcome : 'running' };
+ delete (rec as { notice?: unknown }).notice;
+ if (recorded) state.runs[state.runs.length - 1] = rec;
+ else { state.runs.push(rec); recorded = true; }
+ await writeFactsDrainState(engine, state).catch(() => undefined);
+ };
+ const defer = async (outcome: FactsDrainOutcome, reason: string, message: string, fix?: Action): Promise<FactsDrainRunResult> => {
+ result.error = { code: 'facts_drain_deferred', reason, message, ...(fix ? { fix } : {}) };
+ finish(outcome);
+ result.notice = { code: 'facts_drain_deferred', kind: 'degraded', why: message, ...(fix ? { fix } : {}) };
+ if (!noticedReasons.has(reason)) {
+ noticedReasons.add(reason);
+ log(`[gbrain notice facts_drain_deferred] ${message}${fix?.argv ? ` Next: ${command(fix.argv)}` : ''}`);
+ pendingNotice = result.notice;
+ }
+ await save();
+ return result;
+ };
+
+ try {
+ const settings = await factsDrainSettings(engine);
+ if (!settings.enabled) return finish('disabled');
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(engine);
+ await queue.promoteDelayed();
+ await queue.handleStalled();
+ const backlog = await factsDrainBacklog(engine);
+ result.backlog_before = backlog.waiting;
+ if (backlog.waiting === 0) { result.backlog_after = 0; return finish('idle'); }
+
+ const { refreshGatewayEnvFromFilePlane, reconfigureGatewayWithEngine, withBudgetTracker } = await import('../ai/gateway.ts');
+ refreshGatewayEnvFromFilePlane();
+ await reconfigureGatewayWithEngine(engine).catch(() => undefined);
+ const { resolveExtractionAvailability } = await import('./extraction-availability.ts');
+ const { getFactsExtractionMaxTokens } = await import('./extract.ts');
+ const { model, available } = await resolveExtractionAvailability(engine);
+ result.model = model;
+ state = await readFactsDrainState(engine);
+
+ if (!available) {
+ const { classifyUnavailable } = await import('./backstop.ts');
+ if ((await classifyUnavailable(model)) === 'keyless') {
+ return defer('no_key', 'no_key',
+ `${backlog.waiting} page(s) wait for automatic fact extraction, which needs a chat provider key (OpenAI or Anthropic). They stay queued and run on the next drain after a key is set.`,
+ keySetupFix());
+ }
+ return defer('extraction_unavailable', 'extraction_unavailable',
+ `The facts extraction model ${model} is not servable (its provider is not configured); ${backlog.waiting} page(s) stay queued.`,
+ { argv: ['gbrain', 'config', 'set', 'facts.extraction_model', '<provider:model>'], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'Points extraction at a model whose provider has a key, or set that provider\'s key instead.',
+ inputs: [{ name: 'provider:model', how: 'Pick a chat model whose provider key is configured (gbrain models doctor --json lists them).' }],
+ verify: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'] } });
+ }
+
+ const maxTokens = await getFactsExtractionMaxTokens(engine);
+ if (!state.first_run_reported_at) {
+ const est = await estimateBacklogUsd(engine, model, backlog.waiting, maxTokens);
+ const line = `[gbrain notice facts_drain] Automatic fact extraction is on: ${backlog.waiting} queued page(s), about ${est === null ? 'an unknown amount (unpriced model)' : fmtUsd(est)} with ${model}, ` +
+ `at most ${fmtUsd(settings.budgetUsd)} per run and ${fmtUsd(settings.dailyBudgetUsd)} per day. To opt out: ${command(FACTS_DRAIN_OPT_OUT_ARGV)}`;
+ log(line);
+ noticedReasons.add('first_run');
+ pendingNotice = { code: 'facts_drain_first_run', kind: 'info', why: line.replace('[gbrain notice facts_drain] ', ''),
+ fix: { argv: [...FACTS_DRAIN_OPT_OUT_ARGV], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Only if the user does not want automatic paid extraction; queued pages are then left unextracted.', verify: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'] } } };
+ state.first_run_reported_at = startedAt.toISOString();
+ }
+
+ const dailyRemaining = settings.dailyBudgetUsd - dailySpentUsd(state, startedAt.getTime());
+ if (dailyRemaining <= 0) {
+ return defer('daily_budget_exhausted', 'daily_budget_exhausted',
+ `Automatic fact extraction used its ${fmtUsd(settings.dailyBudgetUsd)} daily budget; ${backlog.waiting} page(s) stay queued and run as the 24-hour window frees budget.`,
+ budgetFix('facts.drain_daily_budget_usd', settings.dailyBudgetUsd * 2));
+ }
+ const runCap = Math.min(settings.budgetUsd, dailyRemaining);
+ const capIsDaily = dailyRemaining < settings.budgetUsd;
+ const { BudgetTracker, BudgetExhausted, loadPricingOverrides } = await import('../budget/budget-tracker.ts');
+ const { reservationCostUsd } = await import('../budget/reservation-cost.ts');
+ const { MAX_TURN_TEXT_CHARS } = await import('./extract.ts');
+ const pricingOverrides = await loadPricingOverrides(engine);
+ const ceiling = reservationCostUsd(model, 'chat', Math.ceil(MAX_TURN_TEXT_CHARS / 4) + PROMPT_OVERHEAD_TOKENS, maxTokens, pricingOverrides);
+ if (ceiling === null && settings.explicitCap) {
+ const { noPricingGuidance, noPricingFix, noPricingMessage } = await import('../budget/no-pricing.ts');
+ const guidance = noPricingGuidance(model, 'chat');
+ return defer('no_pricing', 'no_pricing', noPricingMessage(guidance, { label: 'facts drain', capUsd: runCap }), noPricingFix(guidance));
+ }
+ const tracker = new BudgetTracker({ maxCostUsd: runCap, capSource: settings.explicitCap ? 'user' : 'default', label: 'facts:drain', pricingOverrides });
+ await save();
+
+ const { makeFactsAbsorbHandler } = await import('../minions/handlers/facts-absorb.ts');
+ const { withFactsAbsorbHaltCooldown } = await import('../minions/llm-halt-cooldown.ts');
+ const { JobDeferredError, UnrecoverableError } = await import('../minions/errors.ts');
+ const { RateLeaseUnavailableError, leaseFullBackoffMs } = await import('../minions/rate-leases.ts');
+ const { buildJobContext } = await import('../minions/job-context.ts');
+ const { authorizeJobExecution, withSubmissionAuthority } = await import('../minions/submission-authority.ts');
+ const { withChatPhase } = await import('../ai/chat-usage.ts');
+ const { calculateBackoff } = await import('../minions/backoff.ts');
+ const { defaultLockDurationMsFor } = await import('../minions/handler-timeouts.ts');
+ const handler = withFactsAbsorbHaltCooldown(makeFactsAbsorbHandler(engine));
+ const lockMs = defaultLockDurationMsFor(FACTS_DRAIN_JOB) ?? 120_000;
+ const deadline = startedAt.getTime() + (opts.wallClockMs ?? FACTS_DRAIN_WALL_MS);
+ let outcome: FactsDrainOutcome = 'drained';
+ let stopReason: { reason: string; message: string; fix?: Action } | null = null;
+
+ while (true) {
+ if (opts.signal?.aborted) { outcome = 'aborted'; break; }
+ if (result.completed + result.failed >= settings.maxJobs) { outcome = 'max_jobs'; break; }
+ if (Date.now() >= deadline) { outcome = 'deadline'; break; }
+ const spent = tracker.totalSpent;
+ if (ceiling !== null && spent + ceiling > runCap) {
+ if (result.completed + result.failed === 0 && ceiling > settings.budgetUsd) {
+ outcome = 'job_over_budget';
+ stopReason = { reason: 'job_over_budget', message: `One queued page can cost up to ${fmtUsd(ceiling)} with ${model}, above the ${fmtUsd(settings.budgetUsd)} per-run cap, so automatic fact extraction cannot start it. The pages stay queued.`,
+ fix: budgetFix('facts.drain_budget_usd', Math.max(1, Math.ceil(ceiling * 2 * 100) / 100)) };
+ } else if (capIsDaily) {
+ outcome = 'daily_budget_exhausted';
+ stopReason = { reason: 'daily_budget_exhausted', message: `Automatic fact extraction reached its ${fmtUsd(settings.dailyBudgetUsd)} daily budget; the remaining pages stay queued and run as the 24-hour window frees budget.`, fix: budgetFix('facts.drain_daily_budget_usd', settings.dailyBudgetUsd * 2) };
+ } else {
+ outcome = 'budget_exhausted';
+ stopReason = { reason: 'budget_exhausted', message: `Automatic fact extraction reached its ${fmtUsd(settings.budgetUsd)} per-run budget; the remaining pages stay queued for the next run.`, fix: budgetFix('facts.drain_budget_usd', settings.budgetUsd * 2) };
+ }
+ break;
+ }
+ const lockToken = randomUUID();
+ const job: MinionJob | null = await queue.claim(lockToken, lockMs, FACTS_DRAIN_QUEUE, [FACTS_DRAIN_JOB]);
+ if (!job) { outcome = 'drained'; break; }
+
+ const abort = new AbortController();
+ const onShutdown = () => { if (!abort.signal.aborted) abort.abort(new Error('shutdown')); };
+ opts.signal?.addEventListener('abort', onShutdown, { once: true });
+ let renewing = false;
+ const renew = setInterval(() => {
+ if (renewing) return;
+ renewing = true;
+ queue.renewLock(job.id, lockToken, lockMs)
+ .then(ok => { if (!ok && !abort.signal.aborted) abort.abort(new Error('lock-lost')); }, () => undefined)
+ .finally(() => { renewing = false; });
+ }, Math.max(1000, Math.floor(lockMs / 3)));
+ let value: unknown;
+ let thrown: unknown = null;
+ try {
+ const authority = await authorizeJobExecution(engine, job);
+ const ctx = buildJobContext(engine, queue, job, lockToken, abort.signal, opts.signal ?? abort.signal);
+ value = await withBudgetTracker(tracker, () => withSubmissionAuthority(authority, () => withChatPhase(`job:${job.name}`, () => handler(ctx)), abort.signal));
+ } catch (e) {
+ thrown = e ?? new Error('facts-absorb failed');
+ } finally {
+ clearInterval(renew);
+ opts.signal?.removeEventListener('abort', onShutdown);
+ }
+
+ const budgetErr = thrown ? findError(thrown, (e): e is InstanceType<typeof BudgetExhausted> => e instanceof BudgetExhausted) : null;
+ if (!thrown) {
+ await queue.completeJob(job.id, lockToken, value != null && typeof value === 'object' ? value as Record<string, unknown> : undefined);
+ result.completed++;
+ result.facts_inserted += Number((value as { inserted?: number } | null)?.inserted ?? 0);
+ } else if (opts.signal?.aborted) {
+ await queue.deferJob(job.id, lockToken, 'deferred (shutdown): the owning process stopped mid-job', 0);
+ result.deferred++;
+ outcome = 'aborted';
+ } else if (thrown instanceof JobDeferredError) {
+ await queue.deferJob(job.id, lockToken, `deferred (${thrown.reason}): ${thrown.message}`, thrown.retryInMs);
+ result.deferred++;
+ if (thrown.reason === 'no_key') { outcome = 'no_key'; stopReason = { reason: 'no_key', message: thrown.message, fix: keySetupFix() }; }
+ } else if (thrown instanceof RateLeaseUnavailableError) {
+ await queue.deferJob(job.id, lockToken, `deferred (provider_halted): ${thrown.message}`, thrown.retryInMs ?? leaseFullBackoffMs());
+ result.deferred++;
+ outcome = 'provider_halted';
+ stopReason = { reason: 'provider_halted', message: `The chat provider for ${model} is refusing calls (${thrown.message}); queued pages wait for its cooldown.` };
+ } else if (budgetErr) {
+ await queue.deferJob(job.id, lockToken, `deferred (${budgetErr.reason === 'no_pricing' ? 'no_pricing' : 'budget_exhausted'}): ${budgetErr.message}`, 0);
+ result.deferred++;
+ outcome = budgetErr.reason === 'no_pricing' ? 'no_pricing' : capIsDaily ? 'daily_budget_exhausted' : 'budget_exhausted';
+ stopReason = { reason: outcome, message: budgetErr.message, ...(budgetErr.fix ? { fix: budgetErr.fix } : {}) };
+ } else if (abort.signal.aborted && String((abort.signal.reason as Error)?.message) === 'lock-lost') {
+ result.failed++;
+ } else {
+ const message = thrown instanceof Error ? thrown.message : String(thrown);
+ const dead = thrown instanceof UnrecoverableError || job.attempts_made + 1 >= job.max_attempts;
+ await queue.failJob(job.id, lockToken, message, dead ? 'dead' : 'delayed', dead ? 0 : calculateBackoff({ ...job, attempts_made: job.attempts_made + 1 }));
+ result.failed++;
+ result.error = { code: 'facts_drain_job_failed', reason: dead ? 'dead' : 'retrying', message: `facts-absorb job ${job.id} (${String(job.data.slug ?? '')}) failed: ${message}`,
+ fix: { argv: ['gbrain', 'jobs', 'get', String(job.id), '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the job\'s error and attempts; a retrying job runs again on a later drain.' } };
+ }
+ const snap = tracker.snapshot();
+ result.spent_usd = snap.cumulativeCostUsd;
+ result.unpriced_calls = snap.models.filter(m => m.cost_usd === null).reduce((n, m) => n + m.calls, 0);
+ await save();
+ if (outcome !== 'drained') break;
+ await new Promise(resolve => setTimeout(resolve, opts.yieldMs ?? 25));
+ }
+
+ result.backlog_after = (await factsDrainBacklog(engine)).waiting;
+ if (stopReason) return defer(outcome, stopReason.reason, stopReason.message, stopReason.fix);
+ finish(outcome);
+ await save();
+ return result;
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e);
+ state ??= await readFactsDrainState(engine).catch(() => ({ version: 1 as const, runs: [] }));
+ return defer('error', 'drain_error', `Automatic fact extraction failed before finishing its run: ${message}. Queued pages stay queued.`,
+ { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the drain status and the last error.' });
+ }
+}
+
+export const FACTS_DRAIN_RUN_NOW_ARGV = ['gbrain', 'dream', '--phase', 'facts_drain'] as const;
+/** A backlog older than this with no run means no owner is draining it. */
+const STALE_RUN_MS = 45 * 60_000;
+
+export type FactsDrainHealth = 'not_applicable' | 'disabled' | 'idle' | 'ok' | 'deferred' | 'no_owner';
+export interface FactsDrainStatus {
+ health: FactsDrainHealth;
+ message: string;
+ fix?: Action;
+ settings: FactsDrainSettings | null;
+ backlog: FactsDrainBacklog;
+ last_run: FactsDrainRunRecord | null;
+ daily_spent_usd: number;
+}
+
+/** The one status read for doctor `facts_drain` and the MCP readiness entry `facts_drain`. */
+export async function readFactsDrainStatus(engine: BrainEngine, now = Date.now()): Promise<FactsDrainStatus> {
+ const empty: FactsDrainBacklog = { waiting: 0, delayed: 0, active: 0 };
+ if (engine.kind !== 'pglite') {
+ return { health: 'not_applicable', message: 'Postgres brains run facts-absorb jobs on the job worker (gbrain jobs supervisor), not the automatic drain.', settings: null, backlog: empty, last_run: null, daily_spent_usd: 0 };
+ }
+ const settings = await factsDrainSettings(engine);
+ const backlog = await factsDrainBacklog(engine);
+ const state = await readFactsDrainState(engine);
+ const last = state.runs.at(-1) ?? null;
+ const daily = dailySpentUsd(state, now);
+ const base = { settings, backlog, last_run: last, daily_spent_usd: daily };
+ const queued = backlog.waiting + backlog.delayed;
+ const lastText = last ? `last run ${last.finished_at ?? last.started_at} by ${last.owner}: ${last.outcome}, ${last.completed} extracted, ${fmtUsd(last.spent_usd)}` : 'no run recorded yet';
+ if (!settings.enabled) {
+ return { ...base, health: 'disabled', message: `Facts extraction is off (facts.extraction_enabled false); ${queued} facts-absorb job(s) are queued and are skipped when they run.`,
+ fix: { argv: ['gbrain', 'config', 'set', 'facts.extraction_enabled', 'true'], consent: ['paid', 'egress'], actor: 'agent', requires_exclusive: false,
+ why: 'Turns automatic fact extraction back on: one paid chat call per eligible page write, bounded per run and per day.' } };
+ }
+ if (queued === 0) return { ...base, health: 'idle', message: `No facts-absorb jobs are queued (${lastText}).` };
+ if (last?.error && last.outcome !== 'running' && FACTS_DRAIN_DEFERRALS.has(last.outcome as FactsDrainOutcome)) {
+ return { ...base, health: 'deferred', message: `${queued} facts-absorb job(s) wait: ${last.error.message}`, ...(last.error.fix ? { fix: last.error.fix } : {}) };
+ }
+ const lastAt = last ? Date.parse(last.finished_at ?? last.started_at) : 0;
+ if (now - lastAt > STALE_RUN_MS) {
+ return { ...base, health: 'no_owner', message: `${queued} facts-absorb job(s) are queued and no drain ran in the last ${STALE_RUN_MS / 60_000} minutes (${lastText}). ` +
+ 'The drain runs inside a resident gbrain serve (stdio or --http) and the dream/autopilot cycle; with none running, run it now.',
+ fix: { argv: [...FACTS_DRAIN_RUN_NOW_ARGV], consent: ['paid'], actor: 'agent', requires_exclusive: true,
+ why: 'Runs one bounded drain (per-run and daily caps apply) in this process; each page is one paid chat call.', verify: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'] } } };
+ }
+ return { ...base, health: 'ok', message: `${queued} facts-absorb job(s) queued; the drain is running them (${lastText}; ${fmtUsd(daily)} of ${fmtUsd(settings.dailyBudgetUsd)} used in 24 h).` };
+}
diff --git a/src/core/readiness.ts b/src/core/readiness.ts
index 8af63b7742..9c319854ec 100644
--- a/src/core/readiness.ts
+++ b/src/core/readiness.ts
@@ -45,7 +45,7 @@ import { resolveWritebackConfigFromFile } from './facts/writeback-config.ts';
export type ReadinessState = 'ok' | 'disabled_by_choice' | 'not_applicable' | 'missing' | 'degraded' | 'unknown';
export type CapabilityId =
| 'embeddings' | 'chat_llm' | 'worker' | 'writeback' | 'backup' | 'tool_surface'
- | 'sync' | 'migrations' | 'harness_wiring' | 'local_transcripts';
+ | 'sync' | 'migrations' | 'harness_wiring' | 'local_transcripts' | 'facts_drain';
export interface ReadinessEntry {
capability: CapabilityId;
@@ -91,6 +91,8 @@ export const SYNC_REASONS = [
export const MIGRATIONS_REASONS = ['current', 'pending', 'engine_unreachable', 'probe_failed', 'probe_timeout'] as const;
/** Raw session transcripts on the brain host: present (read through the CLI) or none. */
export const LOCAL_TRANSCRIPTS_REASONS = ['transcripts_cli_only', 'no_transcripts', 'engine_unreachable', 'probe_failed', 'probe_timeout'] as const;
+/** Automatic facts drain on PGLite (src/core/facts/drain.ts). */
+export const FACTS_DRAIN_REASONS = ['not_applicable', 'disabled', 'idle', 'ok', 'deferred', 'no_owner', 'engine_unreachable', 'probe_failed', 'probe_timeout'] as const;
export const HARNESS_WIRING_REASONS = [
'wired_running', 'registration_unverified', 'http_serve_running', 'multiple_sessions', 'multiple_harnesses',
'no_harness_detected', 'binary_unresolved', 'remote_transport',
@@ -545,7 +547,10 @@ async function bounded(probe: Prober, engine: BrainEngine): Promise<ReadinessEnt
}
async function countWaitingJobs(engine: BrainEngine): Promise<number> {
- const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'waiting'`);
+ // PGLite facts-absorb jobs belong to the automatic facts drain (its own readiness entry), not a worker.
+ const [row] = await engine.executeRaw<{ n: number }>(engine.kind === 'pglite'
+ ? `SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'waiting' AND name <> 'facts-absorb'`
+ : `SELECT count(*)::int AS n FROM minion_jobs WHERE status = 'waiting'`);
return Number(row?.n ?? 0);
}
@@ -646,7 +651,18 @@ const transcriptsProbe: Prober = {
},
};
-const PROBERS: readonly Prober[] = [workerProbe, backupProbe, migrationsProbe, syncProbe, transcriptsProbe];
+const factsDrainProbe: Prober = {
+ capability: 'facts_drain',
+ async run(engine) {
+ const { readFactsDrainStatus } = await import('./facts/drain.ts');
+ const s = await readFactsDrainStatus(engine);
+ const state: ReadinessState = s.health === 'not_applicable' ? 'not_applicable' : s.health === 'disabled' ? 'disabled_by_choice'
+ : s.health === 'deferred' || s.health === 'no_owner' ? 'degraded' : 'ok';
+ return { capability: 'facts_drain', tier: 'probed', http_visible: false, state, reason: s.health, why: s.message, ...(s.fix ? { fix: s.fix } : {}) };
+ },
+};
+
+const PROBERS: readonly Prober[] = [workerProbe, backupProbe, migrationsProbe, syncProbe, transcriptsProbe, factsDrainProbe];
async function runProbes(engine: BrainEngine): Promise<ReadinessEntry[]> {
if (isEngineDegraded(engine)) return PROBERS.map(p => failedEntry(p.capability, 'engine_unreachable'));
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 11d9a2ba91..97c1756e93 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -22,6 +22,7 @@ import { logVerbUsage } from '../core/verbs/usage-log.ts';
import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';
import { hiddenToolHint } from './hidden-tool-hint.ts';
import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';
+import { takeFactsDrainNotice } from '../core/facts/drain.ts';
import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import {
@@ -903,6 +904,7 @@ export async function dispatchToolCall(
}
maybeBackupNotice(notices, opts);
if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
+ if (opts.transport === 'stdio' && opts.remote !== false) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drain
const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));
if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));
if (opts.transport === 'stdio') {
diff --git a/src/mcp/initialize-context.ts b/src/mcp/initialize-context.ts
index a8b0183ca1..0534b1beae 100644
--- a/src/mcp/initialize-context.ts
+++ b/src/mcp/initialize-context.ts
@@ -16,7 +16,7 @@ import { disabledOpsForPublishGates } from './publish-gates.ts';
import type { InstructionTools } from './instructions.ts';
/** Readiness entries the instructions tail may name, most limiting first. */
-const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker', 'local_transcripts'] as const;
+const TAIL_PRIORITY = ['embeddings', 'chat_llm', 'migrations', 'worker', 'facts_drain', 'local_transcripts'] as const;
/** Config plane + probed tier (≤ 250 ms), ordered by TAIL_PRIORITY; [] on any failure. */
export async function instructionReadiness(
diff --git a/test/facts-drain-scheduler.test.ts b/test/facts-drain-scheduler.test.ts
new file mode 100644
index 0000000000..81d1f52c9d
--- /dev/null
+++ b/test/facts-drain-scheduler.test.ts
@@ -0,0 +1,211 @@
+/**
+ * The facts drain scheduler and its stdio serve wiring (Foundations 2, Lane D).
+ * Protects: a quiet resident serve drains within two ticks with zero commands;
+ * sustained MCP traffic still drains every 30 minutes; shutdown aborts the
+ * in-flight run before the engine closes; the owner's veto (delegated sync,
+ * degraded engine) skips a tick; Postgres registers no timer; nothing is
+ * written to stdout. A real PGLite + stub chat case covers the acceptance
+ * path end to end (start serve, write after startup, restart with a backlog).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { EventEmitter } from 'node:events';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { runServe, type ServeOptions } from '../src/commands/serve.ts';
+import { _resetStdoutRedirectForTests } from '../src/core/console-prefix.ts';
+import { FACTS_DRAIN_MAX_GAP_MS, FACTS_DRAIN_TICK_MS, startFactsDrainScheduler } from '../src/core/facts/drain-scheduler.ts';
+import type { FactsDrainRunResult } from '../src/core/facts/drain.ts';
+import { __resetFactsDrainNoticesForTests } from '../src/core/facts/drain.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';
+
+const settle = () => new Promise<void>(r => setTimeout(r, 0));
+const fakeResult = (owner: FactsDrainRunResult['owner']) => ({ owner, outcome: 'drained' } as FactsDrainRunResult);
+
+function intervalStub() {
+ const registered: Array<{ fn: () => void; ms: number; handle: { unrefCalled: boolean; unref(): void } }> = [];
+ return {
+ registered,
+ setInterval: (fn: () => void, ms: number) => {
+ const handle = { unrefCalled: false, unref() { this.unrefCalled = true; } };
+ registered.push({ fn, ms, handle });
+ return handle;
+ },
+ clearInterval: (h: unknown) => {
+ const i = registered.findIndex(r => r.handle === h);
+ if (i >= 0) registered.splice(i, 1);
+ },
+ };
+}
+
+describe('startFactsDrainScheduler', () => {
+ test('quiet ticks run, busy ticks wait for the 30-minute gap, one run at a time', async () => {
+ let clock = 0;
+ let activity = 0;
+ const runs: number[] = [];
+ let release!: () => void;
+ const timers = intervalStub();
+ const s = startFactsDrainScheduler({ kind: 'pglite' } as BrainEngine, {
+ owner: 'serve', now: () => clock, lastActivityAt: () => activity, ...timers,
+ run: async () => { runs.push(clock); await new Promise<void>(r => { release = r; }); return fakeResult('serve'); },
+ });
+ expect(timers.registered.map(r => r.ms)).toEqual([FACTS_DRAIN_TICK_MS]);
+ expect(timers.registered[0].handle.unrefCalled).toBe(true);
+ clock = FACTS_DRAIN_TICK_MS; activity = clock - 1;
+ expect(await s.tick()).toBeNull();
+ clock += FACTS_DRAIN_TICK_MS;
+ void s.tick();
+ await settle();
+ expect(runs).toEqual([2 * FACTS_DRAIN_TICK_MS]);
+ expect(s.running).toBe(true);
+ clock += FACTS_DRAIN_TICK_MS;
+ expect(await s.tick()).toBeNull();
+ release();
+ await settle();
+ clock += FACTS_DRAIN_TICK_MS; activity = clock;
+ expect(await s.tick()).toBeNull();
+ clock += FACTS_DRAIN_TICK_MS; activity = clock;
+ void s.tick();
+ await settle();
+ expect(runs.length).toBe(2);
+ expect(runs[1] - runs[0]).toBeGreaterThanOrEqual(FACTS_DRAIN_MAX_GAP_MS);
+ release();
+ await s.stop();
+ expect(timers.registered).toEqual([]);
+ });
+
+ test('stop aborts the in-flight run; the owner veto skips a tick', async () => {
+ let signal: AbortSignal | undefined;
+ let veto = true;
+ const s = startFactsDrainScheduler({ kind: 'pglite' } as BrainEngine, {
+ owner: 'serve_http', ...intervalStub(), canRun: () => !veto,
+ run: async (_e, o) => { signal = o.signal; await new Promise(r => o.signal.addEventListener('abort', r, { once: true })); return fakeResult('serve_http'); },
+ });
+ expect(await s.tick()).toBeNull();
+ veto = false;
+ void s.tick();
+ await settle();
+ expect(signal?.aborted).toBe(false);
+ await s.stop();
+ expect(signal?.aborted).toBe(true);
+ });
+
+ test('a Postgres engine registers no timer and never runs', async () => {
+ const timers = intervalStub();
+ let ran = false;
+ const s = startFactsDrainScheduler({ kind: 'postgres' } as BrainEngine, { owner: 'serve', ...timers, run: async () => { ran = true; return fakeResult('serve'); } });
+ expect(timers.registered).toEqual([]);
+ expect(await s.tick()).toBeNull();
+ expect(ran).toBe(false);
+ });
+});
+
+describe('stdio serve wiring', () => {
+ function harness(engine: BrainEngine, factsDrain: ServeOptions['factsDrain']) {
+ const stdin = new EventEmitter() as EventEmitter & { isTTY?: boolean };
+ const timers = intervalStub();
+ const logs: string[] = [];
+ let resolveExit!: (code: number) => void;
+ const exited = new Promise<number>(r => { resolveExit = r; });
+ const opts: ServeOptions = {
+ stdin: stdin as never, signals: new EventEmitter() as never, exit: code => resolveExit(code ?? 0), log: m => { logs.push(m); },
+ startMcpServer: async () => {}, getParentPid: () => 1, probeWatchdog: () => true, mcpStdio: false, bootTimeoutMs: 0,
+ setInterval: timers.setInterval, clearInterval: timers.clearInterval, sweepEnabled: false, eofDrainMs: 0, factsDrain,
+ };
+ return { stdin, timers, logs, exited, opts };
+ }
+
+ test('serve registers the drain timer, drains on the second quiet tick, re-arms on stdin data, and aborts it on shutdown', async () => {
+ let calls = 0;
+ let signal: AbortSignal | undefined;
+ const engine = { kind: 'pglite', disconnect: async () => {} } as unknown as BrainEngine;
+ const h = harness(engine, { run: async (_e, o) => { calls++; signal = o.signal; expect(o.owner).toBe('serve'); return fakeResult('serve'); } });
+ await runServe(engine, [], h.opts);
+ _resetStdoutRedirectForTests();
+ expect(h.timers.registered.map(r => r.ms)).toEqual([FACTS_DRAIN_TICK_MS]);
+ const tick = h.timers.registered[0].fn;
+ const wait = () => new Promise(r => setTimeout(r, 100));
+ tick(); await wait();
+ expect(calls).toBe(0);
+ tick(); await wait();
+ expect(calls).toBe(1);
+ h.stdin.emit('data', Buffer.from('{}'));
+ tick(); await wait();
+ expect(calls).toBe(1);
+ h.stdin.emit('end');
+ expect(await h.exited).toBe(0);
+ expect(signal?.aborted).toBe(true);
+ expect(h.timers.registered).toEqual([]);
+ });
+
+ test('factsDrain: false and non-PGLite engines install nothing', async () => {
+ const off = harness({ kind: 'pglite', disconnect: async () => {} } as unknown as BrainEngine, false);
+ await runServe({ kind: 'pglite', disconnect: async () => {} } as unknown as BrainEngine, [], off.opts);
+ _resetStdoutRedirectForTests();
+ expect(off.timers.registered).toEqual([]);
+ off.stdin.emit('end'); await off.exited;
+ });
+});
+
+describe('acceptance: a resident serve on a real PGLite brain', () => {
+ let engine: PGLiteEngine;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-serve-drain-'));
+ const KEYS = { ANTHROPIC_API_KEY: 'sk-test-drain', OPENAI_API_KEY: 'sk-test-drain' };
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });
+ afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-sonnet-4-6');
+ __resetFactsDrainNoticesForTests();
+ configureGateway({ embedding_disabled: true, env: KEYS } as never);
+ __setChatTransportForTests(async () => ({ text: JSON.stringify({ facts: [{ fact: 'Acme Example shipped the beta in 2026', kind: 'fact', entity: 'companies/acme-example', confidence: 0.9, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ usage: { input_tokens: 900, output_tokens: 120, cache_read_tokens: 0, cache_creation_tokens: 0 } } as ChatResult));
+ });
+
+ async function write(slug: string) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Acme Example shipped the beta in 2026. ${'A substantive project record. '.repeat(6)}`, timeline: '', frontmatter: {} } as never);
+ await new MinionQueue(engine).add('facts-absorb', { slug, sourceId: 'default', source: 'mcp:put_page', notabilityFilter: 'all', visibility: 'private' });
+ }
+ const facts = async () => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts'))[0].n);
+
+ test('pages written after startup are extracted within two ticks; a restart drains the backlog', () => withEnv({ GBRAIN_HOME: home, ...KEYS }, async () => {
+ const view = Object.create(engine, { disconnect: { value: async () => {} } }) as BrainEngine;
+ const boot = async () => {
+ const stdin = new EventEmitter();
+ const timers = intervalStub();
+ let resolveExit!: (n: number) => void;
+ const exited = new Promise<number>(r => { resolveExit = r; });
+ await runServe(view, [], { stdin: stdin as never, signals: new EventEmitter() as never, exit: c => resolveExit(c ?? 0), log: () => {},
+ startMcpServer: async () => {}, getParentPid: () => 1, probeWatchdog: () => true, mcpStdio: false, bootTimeoutMs: 0,
+ setInterval: timers.setInterval, clearInterval: timers.clearInterval, sweepEnabled: false, eofDrainMs: 0 });
+ _resetStdoutRedirectForTests();
+ const tick = async () => { timers.registered.find(r => r.ms === FACTS_DRAIN_TICK_MS)!.fn(); for (let i = 0; i < 400 && (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name='facts-absorb' AND status IN ('waiting','active')"))[0].n > 0; i++) await new Promise(r => setTimeout(r, 10)); };
+ return { stdin, tick, exited };
+ };
+ const first = await boot();
+ await write('notes/after-startup-1');
+ await write('notes/after-startup-2');
+ expect(await facts()).toBe(0);
+ await first.tick();
+ await first.tick();
+ await new Promise(r => setTimeout(r, 50));
+ expect(await facts()).toBe(2);
+ await write('notes/backlog-1');
+ first.stdin.emit('end'); await first.exited;
+ const second = await boot();
+ await second.tick();
+ await second.tick();
+ await new Promise(r => setTimeout(r, 50));
+ expect(await facts()).toBe(3);
+ second.stdin.emit('end'); await second.exited;
+ }), 60_000);
+});
diff --git a/test/facts-drain.test.ts b/test/facts-drain.test.ts
new file mode 100644
index 0000000000..38e191b39a
--- /dev/null
+++ b/test/facts-drain.test.ts
@@ -0,0 +1,255 @@
+/**
+ * Automatic facts drain (Foundations 2, Lane D; src/core/facts/drain.ts).
+ * Protects: queued facts-absorb jobs on PGLite get extracted with no
+ * `gbrain jobs work`, within the per-run, daily and job-count caps, and every
+ * stop other than "queue empty" leaves the jobs queued with no attempt counted
+ * (budget, oversized job, no key, shutdown, unpriced model under a user cap).
+ * Stubs only the gateway chat transport (`__setChatTransportForTests`).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { LATEST_VERSION } from '../src/core/migrate.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';
+import {
+ FACTS_DRAIN_STATE_KEY, __resetFactsDrainNoticesForTests, readFactsDrainState, readFactsDrainStatus, runFactsDrain, takeFactsDrainNotice,
+ validateFactsDrainConfigValue,
+} from '../src/core/facts/drain.ts';
+
+let engine: PGLiteEngine;
+const KEYS = { ANTHROPIC_API_KEY: 'sk-test-drain', OPENAI_API_KEY: 'sk-test-drain' };
+const NO_KEYS = { ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined, GBRAIN_MODEL: undefined };
+const MODEL = 'anthropic:claude-sonnet-4-6';
+let home: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', String(LATEST_VERSION));
+ __resetFactsDrainNoticesForTests();
+ __setChatTransportForTests(null);
+ configureGateway({ embedding_disabled: true, env: KEYS } as never);
+ await engine.setConfig('facts.extraction_model', MODEL);
+ await engine.setConfig('embedding_disabled', 'true');
+});
+
+function reply(text: string, usage = { input_tokens: 10, output_tokens: 10 }): ChatResult {
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: MODEL, providerId: 'anthropic',
+ usage: { ...usage, cache_read_tokens: 0, cache_creation_tokens: 0 } } as ChatResult;
+}
+function factsReply(slug: string) {
+ return reply(JSON.stringify({ facts: [{ fact: `${slug} shipped the beta in 2026`, kind: 'fact', entity: 'companies/acme-example', confidence: 0.9, notability: 'high' }] }));
+}
+
+let seeded = 0;
+async function seed(n: number): Promise<string[]> {
+ const slugs: string[] = [];
+ const queue = new MinionQueue(engine);
+ for (let k = 0; k < n; k++) {
+ const i = seeded++;
+ const slug = `notes/drain-${i}`;
+ await engine.putPage(slug, { type: 'note', title: `Note ${i}`, compiled_truth: `Acme Example shipped the beta in 2026. Note ${i}. ${'A substantive project record. '.repeat(6)}`, timeline: '', frontmatter: {} } as never);
+ await queue.add('facts-absorb', { slug, sourceId: 'default', source: 'mcp:put_page', notabilityFilter: 'all', visibility: 'private' },
+ { queue: 'default', idempotency_key: `facts-absorb:test:${slug}`, max_attempts: 5, backoff_delay: 60_000 });
+ slugs.push(slug);
+ }
+ return slugs;
+}
+async function jobRows() {
+ return engine.executeRaw<{ status: string; attempts_made: number; attempts_started: number }>(
+ "SELECT status, attempts_made, attempts_started FROM minion_jobs WHERE name='facts-absorb' ORDER BY id");
+}
+async function factCount() {
+ const [row] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%shipped the beta%'");
+ return Number(row?.n ?? 0);
+}
+const run = (logs: string[], extra: Partial<Parameters<typeof runFactsDrain>[1]> = {}) =>
+ runFactsDrain(engine, { owner: 'serve', log: line => logs.push(line), yieldMs: 0, ...extra });
+const isolated = <T>(env: Record<string, string | undefined>, fn: () => Promise<T>) => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-facts-drain-'));
+ return withEnv({ GBRAIN_HOME: home, ...env }, fn).finally(() => rmSync(home, { recursive: true, force: true }));
+};
+
+describe('runFactsDrain', () => {
+ test('extracts every queued page with zero commands; before the drain they sit waiting', () => isolated(KEYS, async () => {
+ await seed(3);
+ expect((await jobRows()).map(j => j.status)).toEqual(['waiting', 'waiting', 'waiting']);
+ expect(await factCount()).toBe(0);
+ __setChatTransportForTests(async (opts: ChatOpts) => factsReply(String(opts.messages?.[0]?.content ?? '').match(/Note \d/)?.[0] ?? 'x'));
+ const logs: string[] = [];
+ const r = await run(logs);
+ expect(r).toMatchObject({ outcome: 'drained', completed: 3, failed: 0, deferred: 0, backlog_before: 3, backlog_after: 0 });
+ expect((await jobRows()).map(j => j.status)).toEqual(['completed', 'completed', 'completed']);
+ expect(await factCount()).toBe(3);
+ const status = await readFactsDrainStatus(engine);
+ expect(status.health).toBe('idle');
+ expect(status.last_run).toMatchObject({ owner: 'serve', outcome: 'drained', completed: 3 });
+ }));
+
+ test('first run reports backlog, estimated spend, caps and the opt-out (golden)', () => isolated(KEYS, async () => {
+ await seed(2);
+ __setChatTransportForTests(async () => factsReply('x'));
+ const logs: string[] = [];
+ await run(logs);
+ expect(logs[0]).toMatch(/^\[gbrain notice facts_drain\] Automatic fact extraction is on: 2 queued page\(s\), about \$0\.0\d\d with anthropic:claude-sonnet-4-6, at most \$1\.00 per run and \$5\.00 per day\. To opt out: gbrain config set facts\.extraction_enabled false$/);
+ expect(takeFactsDrainNotice()).toMatchObject({ code: 'facts_drain_first_run', kind: 'info', fix: { argv: ['gbrain', 'config', 'set', 'facts.extraction_enabled', 'false'] } });
+ await seed(1);
+ const again: string[] = [];
+ await run(again);
+ expect(again).toEqual([]);
+ }));
+
+ test('partial-batch budget exhaustion leaves the rest queued with no attempt counted', () => isolated(KEYS, async () => {
+ await seed(4);
+ await engine.setConfig('facts.drain_budget_usd', '0.15');
+ __setChatTransportForTests(async () => ({ ...factsReply('x'), usage: { input_tokens: 15_000, output_tokens: 1_000, cache_read_tokens: 0, cache_creation_tokens: 0 } }));
+ const logs: string[] = [];
+ const r = await run(logs);
+ expect(r.outcome).toBe('budget_exhausted');
+ expect(r.completed).toBeGreaterThanOrEqual(1);
+ expect(r.completed).toBeLessThan(4);
+ const rows = await jobRows();
+ const left = rows.filter(j => j.status !== 'completed');
+ expect(left.length).toBe(4 - r.completed);
+ for (const j of left) expect(j).toMatchObject({ status: 'waiting', attempts_made: 0 });
+ expect(r.error).toMatchObject({ code: 'facts_drain_deferred', reason: 'budget_exhausted', fix: { argv: ['gbrain', 'config', 'set', 'facts.drain_budget_usd', '0.30'], consent: ['paid'] } });
+ expect((await readFactsDrainStatus(engine)).health).toBe('deferred');
+ }));
+
+ test('an oversized single job is deferred unclaimed, never failed', () => isolated(KEYS, async () => {
+ await seed(1);
+ await engine.setConfig('facts.drain_budget_usd', '0.02');
+ let calls = 0;
+ __setChatTransportForTests(async () => { calls++; return factsReply('x'); });
+ const r = await run([]);
+ expect(r.outcome).toBe('job_over_budget');
+ expect(calls).toBe(0);
+ expect(await jobRows()).toEqual([{ status: 'waiting', attempts_made: 0, attempts_started: 0 }]);
+ expect(r.error?.fix?.argv?.slice(0, 4)).toEqual(['gbrain', 'config', 'set', 'facts.drain_budget_usd']);
+ }));
+
+ test('the rolling daily cap stops a run before any claim', () => isolated(KEYS, async () => {
+ await seed(2);
+ await engine.setConfig(FACTS_DRAIN_STATE_KEY, JSON.stringify({ version: 1, first_run_reported_at: new Date().toISOString(),
+ runs: [{ owner: 'cycle', started_at: new Date(Date.now() - 3600_000).toISOString(), finished_at: new Date().toISOString(), outcome: 'max_jobs',
+ completed: 50, failed: 0, deferred: 0, facts_inserted: 50, spent_usd: 5, unpriced_calls: 0, backlog_before: 60, backlog_after: 10, model: MODEL }] }));
+ const r = await run([]);
+ expect(r.outcome).toBe('daily_budget_exhausted');
+ expect((await jobRows()).map(j => j.attempts_started)).toEqual([0, 0]);
+ expect(r.error?.fix?.argv).toEqual(['gbrain', 'config', 'set', 'facts.drain_daily_budget_usd', '10.00']);
+ }));
+
+ test('keyless: jobs wait, one notice per process, and they run once a key exists', () => isolated(NO_KEYS, async () => {
+ configureGateway({ embedding_disabled: true, env: {} } as never);
+ await seed(2);
+ const logs: string[] = [];
+ const first = await run(logs);
+ expect(first.outcome).toBe('no_key');
+ expect(first.error).toMatchObject({ code: 'facts_drain_deferred', reason: 'no_key', fix: { argv: ['gbrain', 'providers', 'list'], actor: 'user' } });
+ expect(logs.filter(l => l.includes('facts_drain_deferred'))).toHaveLength(1);
+ expect(takeFactsDrainNotice()).toMatchObject({ code: 'facts_drain_deferred', kind: 'degraded' });
+ const second: string[] = [];
+ expect((await run(second)).outcome).toBe('no_key');
+ expect(second).toEqual([]);
+ expect(takeFactsDrainNotice()).toBeNull();
+ expect(await jobRows()).toEqual([{ status: 'waiting', attempts_made: 0, attempts_started: 0 }, { status: 'waiting', attempts_made: 0, attempts_started: 0 }]);
+ expect((await readFactsDrainStatus(engine)).health).toBe('deferred');
+
+ await withEnv(KEYS, async () => {
+ configureGateway({ embedding_disabled: true, env: KEYS } as never);
+ __setChatTransportForTests(async () => factsReply('x'));
+ const r = await run([]);
+ expect(r).toMatchObject({ outcome: 'drained', completed: 2 });
+ });
+ }));
+
+ test('a keyless queue with no backlog stays silent', () => isolated(NO_KEYS, async () => {
+ configureGateway({ embedding_disabled: true, env: {} } as never);
+ const logs: string[] = [];
+ expect((await run(logs)).outcome).toBe('idle');
+ expect(logs).toEqual([]);
+ expect(takeFactsDrainNotice()).toBeNull();
+ }));
+
+ test('shutdown mid-job returns the job to the queue with no attempt counted and no facts', () => isolated(KEYS, async () => {
+ await seed(1);
+ const abort = new AbortController();
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ abort.abort(new Error('shutdown'));
+ await new Promise((_, reject) => {
+ if (opts.abortSignal?.aborted) reject(opts.abortSignal.reason);
+ opts.abortSignal?.addEventListener('abort', () => reject(opts.abortSignal!.reason), { once: true });
+ });
+ return factsReply('x');
+ });
+ const r = await run([], { signal: abort.signal });
+ expect(r.outcome).toBe('aborted');
+ expect(r.deferred).toBe(1);
+ const [job] = await jobRows();
+ expect(job.attempts_made).toBe(0);
+ expect(['waiting', 'delayed']).toContain(job.status);
+ expect(await factCount()).toBe(0);
+ }));
+
+ test('max_jobs bounds one run', () => isolated(KEYS, async () => {
+ await seed(3);
+ await engine.setConfig('facts.drain_max_jobs', '2');
+ __setChatTransportForTests(async () => factsReply('x'));
+ const r = await run([]);
+ expect(r).toMatchObject({ outcome: 'max_jobs', completed: 2, backlog_after: 1 });
+ }));
+
+ test('an unpriced model warns and runs under the default caps, and refuses with the register-the-rate fix under a user cap', () => isolated(KEYS, async () => {
+ await engine.setConfig('facts.extraction_model', 'anthropic:claude-unpriced-example');
+ await seed(1);
+ __setChatTransportForTests(async () => factsReply('x'));
+ expect((await run([])).outcome).toBe('drained');
+ await seed(1);
+ await engine.setConfig('facts.drain_budget_usd', '1');
+ const r = await run([]);
+ expect(r.outcome).toBe('no_pricing');
+ expect(r.error?.fix?.argv?.slice(0, 3)).toEqual(['gbrain', 'pricing', 'set']);
+ expect((await jobRows()).at(-1)).toMatchObject({ status: 'waiting', attempts_made: 0 });
+ }));
+
+ test('facts.extraction_enabled false is the opt-out', () => isolated(KEYS, async () => {
+ await seed(1);
+ await engine.setConfig('facts.extraction_enabled', 'false');
+ expect((await run([])).outcome).toBe('disabled');
+ expect((await readFactsDrainStatus(engine)).health).toBe('disabled');
+ }));
+
+ test('state keeps the newest runs and never writes stdout', () => isolated(KEYS, async () => {
+ const write = process.stdout.write;
+ const out: string[] = [];
+ process.stdout.write = ((chunk: string) => { out.push(String(chunk)); return true; }) as typeof write;
+ try {
+ __setChatTransportForTests(async () => factsReply('x'));
+ for (let i = 0; i < 3; i++) { await seed(1); await runFactsDrain(engine, { owner: 'cycle', yieldMs: 0 }); }
+ } finally { process.stdout.write = write; }
+ expect(out.filter(s => s.includes('facts_drain'))).toEqual([]);
+ expect((await readFactsDrainState(engine)).runs.length).toBeGreaterThanOrEqual(1);
+ }));
+});
+
+test('config validation for facts.drain_* keys', () => {
+ expect(validateFactsDrainConfigValue('facts.drain_budget_usd', '2.5')).toBeNull();
+ expect(validateFactsDrainConfigValue('facts.drain_budget_usd', '-1')).toContain('must be a number from 0.01 to 100');
+ expect(validateFactsDrainConfigValue('facts.drain_max_jobs', '2.5')).toContain('whole number');
+ expect(validateFactsDrainConfigValue('facts.other', 'x')).toBeNull();
+});
diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.ts
index c5f0b9ec8b..3e609ac61a 100644
--- a/test/managed-phase-matrix.test.ts
+++ b/test/managed-phase-matrix.test.ts
@@ -31,6 +31,9 @@ import { runChronicleBackfill } from '../src/core/chronicle/backfill.ts';
import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { claimPersistenceEffect } from '../src/core/persistence/effect-journal.ts';
+import { dispatchFactsBackstopEffect } from '../src/core/persistence/effect-facts.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
@@ -286,6 +289,26 @@ const MATRIX: Record<CyclePhase, Entry> = {
expect(await engine.executeRaw("SELECT state FROM chronicle_page_state WHERE source_id=$1", [sourceId])).toEqual([{ state: 'extracted' }]);
},
},
+ facts_drain: {
+ config: { embedding_disabled: 'true' },
+ seed: async ({ engine, sourceId }) => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await put(engine, sourceId, 'notes/drain-example', page('note', 'Field notes', 'Carol Example founded Widget Co in 2019 and leads its design team. '.repeat(3)));
+ const held = await engine.executeRaw<{ id: number; next_attempt_at: string | null }>(
+ "SELECT id, next_attempt_at::text FROM persistence_effects WHERE kind<>'facts-backstop'");
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'facts-backstop'");
+ const effect = await claimPersistenceEffect(engine, localHostId());
+ for (const h of held) await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=$2::timestamptz WHERE id=$1', [h.id, h.next_attempt_at]);
+ expect(effect?.kind).toBe('facts-backstop');
+ await dispatchFactsBackstopEffect(engine, effect!, localHostId());
+ },
+ reply: () => JSON.stringify({ facts: [{ fact: 'Carol founded Widget Co in 2019', kind: 'fact', entity: 'people/carol-example', confidence: 0.9, notability: 'high' }] }),
+ assert: async ({ engine, sourceId, result }) => {
+ if (engine.kind !== 'pglite') { expect(result.details.reason).toBe('not_applicable'); return; }
+ expect(result.details).toMatchObject({ outcome: 'drained', completed: 1, backlog_after: 0 });
+ expect(await engine.executeRaw("SELECT fact FROM facts WHERE source_id=$1 AND fact LIKE '%Widget Co%'", [sourceId])).not.toHaveLength(0);
+ },
+ },
conversation_facts_backfill: {
config: { 'cycle.conversation_facts_backfill.enabled': 'true' },
seed: async ({ engine, sourceId }) => put(engine, sourceId, 'conversations/2026-09-20-example', page('conversation', 'Chat',