Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

PGLite: refresh planner statistics before and during stale link drains

garrytan19f25157cb2c
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 7f6ab3026e..5b6fd9ed26 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/brain-score-recommendations.ts` — pure data layer consumed by both `gbrain doctor --remediation-plan` / `--remediate` and `gbrain features`. Extraction-watermark staleness produces source-scoped `extract.stale` against database pages, including DB-only pages without a checkout; it does not imply a filesystem sync or block embedding on one. `RecommendationContext.staleExtractionBlocked` (probed by `staleExtractionBlocked()` in `remediation/context.ts`, shared with autopilot) withholds `extract.stale` and classifies `links_extraction_lag` as blocked while the remediated source, or any source with stale pages in an all-source sweep, cannot load its active schema pack, so no dispatch fails every cycle. `computeRecommendations(checks, opts)` returns `Remediation[]` with stable `id`, content-hash `idempotency_key`, `severity`, `est_seconds`, `est_usd_cost`, `depends_on` (references stable ids, not check names — so plan order is reproducible). `classifyChecks(report)` triages every doctor check three-state into `remediable | human_only | blocked` (`human_only` covers RLS warnings and other human-judgment gates; `blocked` covers dependency chains where a parent check failed). `maxReachableScore(checks)` computes the ceiling for empty/under-configured brains (no entity pages → graph_coverage caps at 70; no embedding key → embedding_coverage caps at 60). Cost estimates pull from `anthropic-pricing.ts` (synthesize/patterns/consolidate) and `embedding-pricing.ts` (embed jobs). Pinned by `test/brain-score-recommendations.test.ts` (~27 cases incl. determinism, content-hash idempotency, DB-backed checkpoint provenance, three-state triage).
- `src/core/orphan-policy.ts` — the shared orphan-reporting policy (`gbrain orphans`, doctor's orphan ratio, `get_health`): convention constants plus per-brain `orphans.exclude_prefixes` / `orphans.exclude_slugs` overrides. Two renderers over the same constants: `shouldExcludeFromOrphanReporting(slug, overrides, meta)` (TypeScript) and `orphanExclusionSql(alias, overrides)` (a never-NULL SQL predicate; every list value is a bound parameter, only the identifier-checked alias is spliced; regexes are spelled for Postgres's engine: ASCII digits, `.` stops at line terminators). Quarantine stays outside the SQL predicate. Parity pinned on a generated slug/type corpus by `test/orphan-policy-sql-parity.test.ts` and its Postgres arm in `test/e2e/engine-sql-health-parity.test.ts`.
-- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum; `n_mod_since_analyze` is never populated there). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts`, `test/e2e/planner-stats-postgres.test.ts`.
+- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum; `n_mod_since_analyze` is never populated there). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (before the first page, then on the same cadence; `link_transitions` and `link_relationships`, which carry no deltas, whenever `links` is analyzed), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables`) and repair kind `planner-stats` keep working. Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.
- `src/core/timeline-grading.ts` — `loadTimelineGradedPredicate(engine)`: which pages the 15-point brain_score timeline component grades (#5828). `engine-sql/health.ts` applies the predicate per page type to the linkable groups; `gradeTimelinePages` (re-exported by `orphan-policy.ts`) keeps the linkable (orphan-policy) pages whose active-pack primitive is `entity` or `temporal` (aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor and `get_health` output. Pinned by `test/brain-score-timeline-grading.test.ts`.
- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), and `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.
diff --git a/docs/guides/planner-stats.md b/docs/guides/planner-stats.md
index 964c0e4235..341ecb720d 100644
--- a/docs/guides/planner-stats.md
+++ b/docs/guides/planner-stats.md
@@ -22,6 +22,10 @@ default; Postgres brains are unaffected (autovacuum owns statistics there).
(at most one check every 2 seconds per process);
- every `import.analyze_every_pages` files (default 500) during
`gbrain import` and managed sync;
+ - before a stale link drain of at least 500 pages (`gbrain extract --stale`,
+ the dream cycle's extract phase, link extraction after a managed sync) and
+ every `import.analyze_every_pages` pages during it; `link_transitions` and
+ `link_relationships` are analyzed whenever `links` is;
- after the dream cycle's freshness phases, and when the resident write
consumer is idle;
- the full ANALYZE that import and sync already run at the end resets every
@@ -49,7 +53,7 @@ lock timeout.
|---|---|---|
| `planner.auto_analyze` (env `GBRAIN_PLANNER_AUTO_ANALYZE`, which wins) | `true` | `false` turns off every automatic ANALYZE, including the full ANALYZE at the end of import and sync (which falls back to the narrow `pages` refresh the search projection needs). Doctor still reports stale tables. |
| `planner.first_read_budget_ms` | `2000` | A stale table whose last ANALYZE took longer is analyzed after the read instead of before it. |
-| `import.analyze_every_pages` | `500` | Import and managed sync check statistics every N files; `0` disables that cadence. |
+| `import.analyze_every_pages` | `500` | Import, managed sync and stale link drains check statistics every N files or pages; `0` disables that cadence. |
To opt out: `gbrain config set planner.auto_analyze false`. To turn it back on:
`gbrain config set planner.auto_analyze true`.
diff --git a/scripts/bench/stale-drain.ts b/scripts/bench/stale-drain.ts
new file mode 100644
index 0000000000..d2fe7a1ffc
--- /dev/null
+++ b/scripts/bench/stale-drain.ts
@@ -0,0 +1,110 @@
+#!/usr/bin/env bun
+/**
+ * Stale link-extraction drain bench. Opt-in, never run in CI, not shipped in the CLI.
+ *
+ * bun scripts/bench/stale-drain.ts [--pages 3000] [--managed] [--analyze-seed] [--json]
+ * DATABASE_URL=postgresql://... bun scripts/bench/stale-drain.ts --postgres [--pages 3000]
+ *
+ * Seeds `--pages` pages through engine.putPage (each links to three other
+ * pages and carries two dated timeline bullets) without running any planner
+ * upkeep, so the brain looks like one that grew by single writes since its
+ * last ANALYZE. Every page is link-stale (never extracted). Then it drains
+ * them with `extractStaleFromDB` (catch-up, no time budget) and reports
+ * ms/page, plus the readPageSnapshot plan before and after the drain.
+ * `--managed` flips persistence_brain.enabled so the drain takes the managed
+ * `extractManagedStaleLinks` path; `--analyze-seed` runs a full ANALYZE after
+ * seeding (the shape a fresh `gbrain import` leaves). PGLite runs in a
+ * file-backed temp directory; `--postgres` creates and drops
+ * `gbrain_bench_stale_drain_<hex>` on the DATABASE_URL server.
+ */
+import { randomBytes } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import postgres from '#postgres';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { extractStaleFromDB } from '../../src/commands/extract.ts';
+import { configureGateway } from '../../src/core/ai/gateway.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+
+function flag(name: string, fallback: number): number {
+ const i = process.argv.indexOf(`--${name}`);
+ return i > 0 ? Number(process.argv[i + 1]) : fallback;
+}
+const PAGES = flag('pages', 3000);
+const MANAGED = process.argv.includes('--managed');
+const ANALYZE_SEED = process.argv.includes('--analyze-seed');
+const POSTGRES = process.argv.includes('--postgres');
+const JSON_OUT = process.argv.includes('--json');
+const log = (message: string) => console.error(`[stale-drain ${new Date().toISOString().slice(11, 19)}] ${message}`);
+
+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+
+let engine: BrainEngine;
+let cleanup: () => Promise<void>;
+if (POSTGRES) {
+ const adminUrl = process.env.DATABASE_URL;
+ if (!adminUrl) throw new Error('Set DATABASE_URL to a Postgres server where this role may CREATE DATABASE.');
+ const dbName = `gbrain_bench_stale_drain_${randomBytes(6).toString('hex')}`;
+ const admin = postgres(adminUrl, { max: 1, prepare: false });
+ await admin.unsafe(`CREATE DATABASE ${dbName}`);
+ const url = new URL(adminUrl);
+ url.pathname = `/${dbName}`;
+ const pg = new PostgresEngine();
+ await pg.connect({ database_url: url.toString(), poolSize: 2 });
+ engine = pg;
+ cleanup = async () => { await pg.disconnect(); await admin.unsafe(`DROP DATABASE IF EXISTS ${dbName} WITH (FORCE)`); await admin.end(); };
+} else {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-stale-drain-'));
+ const pglite = new PGLiteEngine();
+ await pglite.connect({ database_path: dir });
+ engine = pglite;
+ cleanup = async () => { await pglite.disconnect(); rmSync(dir, { recursive: true, force: true }); };
+}
+
+const SNAPSHOT_EXPLAIN = `EXPLAIN SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL
+ ORDER BY (p.slug=$1) DESC, (p.source_id=$3) DESC, p.source_id ASC LIMIT 1`;
+async function snapshotPlan(): Promise<string> {
+ const rows = await engine.executeRaw<{ 'QUERY PLAN': string }>(SNAPSHOT_EXPLAIN, ['notes/page-1', 'default', 'default']);
+ const plan = rows.map(r => r['QUERY PLAN']).join('\n');
+ return /pages_source_slug_key/.test(plan) ? 'pages_source_slug_key' : (plan.match(/(?:Index|Bitmap Index) Scan(?: Backward)? using (\w+)/)?.[1] ?? 'seq scan');
+}
+
+try {
+ await engine.initSchema();
+ const seedStart = performance.now();
+ const words = ['ledger', 'harbor', 'quartz', 'meadow', 'signal', 'lantern', 'orbit', 'canvas'];
+ for (let i = 0; i < PAGES; i++) {
+ const links = [1, 7, 31].map(k => `[[notes/page-${(i + k) % PAGES}]]`).join(', ');
+ await engine.putPage(`notes/page-${i}`, {
+ type: 'note', title: `Page ${i}`, frontmatter: {},
+ compiled_truth: `Page ${i} is about ${words[i % words.length]} and ${words[(i * 3) % words.length]}. Related: ${links}.`,
+ timeline: `- **2026-0${1 + (i % 9)}-1${i % 10}** | Met about ${words[i % words.length]}\n- **2026-0${1 + ((i + 4) % 9)}-2${i % 8}** | Follow-up on page ${i}`,
+ });
+ if ((i + 1) % 1000 === 0) log(`seeded ${i + 1}/${PAGES}`);
+ }
+ const seedMs = performance.now() - seedStart;
+ if (ANALYZE_SEED) await engine.executeRaw('ANALYZE');
+ if (MANAGED) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const planBefore = await snapshotPlan();
+ log(`seeded ${PAGES} pages in ${(seedMs / 1000).toFixed(1)} s; snapshot plan before drain: ${planBefore}`);
+
+ const start = performance.now();
+ const r = await extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });
+ const drainMs = performance.now() - start;
+ const planAfter = await snapshotPlan();
+ const [links] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM links');
+ const result = {
+ engine: engine.kind, pages: PAGES, managed: MANAGED, analyze_seed: ANALYZE_SEED,
+ processed: r.pagesProcessed, links: links!.n, stale_remaining: r.staleRemaining,
+ drain_s: +(drainMs / 1000).toFixed(2), ms_per_page: +(drainMs / Math.max(1, r.pagesProcessed)).toFixed(2),
+ plan_before: planBefore, plan_after: planAfter,
+ };
+ log(`drained ${r.pagesProcessed} pages in ${result.drain_s} s = ${result.ms_per_page} ms/page; links ${links!.n}; plan after: ${planAfter}`);
+ console.log(JSON_OUT ? JSON.stringify(result) : result);
+} finally {
+ await disposePersistenceConsumer(engine).catch(() => undefined);
+ await cleanup();
+}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 28fc737b55..d1b6b96a62 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilo
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2204 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); +22 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start)
-src/commands/extract.ts 2558 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); +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan
+src/commands/extract.ts 2561 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); +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain)
src/commands/jobs.ts 666 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); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)
src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index bccb12223f..918cee9e8f 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -94,6 +94,7 @@ import { runSlidingPool } from '../core/worker-pool.ts';
import { isAborted } from '../core/abort-check.ts';
import { parseWorkers, resolveWorkersWithClamp } from '../core/sync-concurrency.ts';
import { loadAllSources } from '../core/sources-load.ts';
+import { plannerStatsForLinkDrain } from '../core/planner-stats.ts';
// Batch size for addLinksBatch / addTimelineEntriesBatch.
// Postgres bind-parameter limit is 65535. Links use 4 cols/row → 16K hard ceiling;
@@ -2131,7 +2132,9 @@ export async function extractStaleFromDB(
let skippedCrossSource = 0;
const wantedEnabled = await isWantedPagesEnabled(engine);
+ const plannerTick = await plannerStatsForLinkDrain(engine, async () => totalStale);
for (;;) {
+ await plannerTick(pagesProcessed);
const rows = await engine.listStalePagesForExtraction({
batchSize: STALE_BATCH_SIZE, afterPageId, sourceId: sourceIdFilter, versionTs,
});
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index bbd83b7d06..7caad9507e 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -6,6 +6,7 @@ import { maintenanceAttribution } from './attribution.ts';
import { unrecordedCanonicalTimeline } from './canonical-projections.ts';
import { runMentionPass, type MentionPassResult } from '../mentions/pass.ts';
import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../mentions/stale.ts';
+import { plannerStatsForLinkDrain } from '../planner-stats.ts';
export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number;
/** The mention pass (absent when the caller ran links only, as sync does). */
@@ -100,8 +101,10 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
result.timeline += outcome.timeline;
};
const budget = () => result.pages + result.skipped < maxPages && Date.now() < deadline;
+ const plannerTick = await plannerStatsForLinkDrain(engine, async () =>
+ Math.min(maxPages, await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs })));
if (opts.slugs?.length && opts.sourceId) {
- for (const slug of new Set(opts.slugs)) { if (!budget()) break; await derive(slug, opts.sourceId); }
+ for (const slug of new Set(opts.slugs)) { if (!budget()) break; await plannerTick(result.pages + result.skipped); await derive(slug, opts.sourceId); }
}
let afterPageId = 0;
while (budget()) {
@@ -111,6 +114,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
if (!budget()) break;
afterPageId = row.id;
if (done.has(`${row.source_id}\0${row.slug}`)) continue;
+ await plannerTick(result.pages + result.skipped);
await derive(row.slug, row.source_id, row.updated_at.getTime() >= Date.parse(versionTs) ? row.updated_at_iso : versionTs);
}
}
diff --git a/src/core/planner-stats.ts b/src/core/planner-stats.ts
index e6a14585be..d16da7707e 100644
--- a/src/core/planner-stats.ts
+++ b/src/core/planner-stats.ts
@@ -14,7 +14,8 @@
*
* Call sites: the PGLite engine's planner-sensitive reads (first relevant
* read, `planner.first_read_budget_ms`), bulk import, managed sync and the
- * database timeline walk every `import.analyze_every_pages` pages, the cycle after its freshness phases,
+ * database timeline walk every `import.analyze_every_pages` pages, stale link
+ * drains (`plannerStatsForLinkDrain`), the cycle after its freshness phases,
* the resident consumer's idle tick, and `refreshProjectionStatistics` (full
* ANALYZE, then watermarks for every table). `planner.auto_analyze=false`
* (env GBRAIN_PLANNER_AUTO_ANALYZE) disables all of them; doctor
@@ -263,6 +264,42 @@ export async function maybeRefreshPlannerStats(engine: BrainEngine, reason: Plan
try { return await run; } finally { state.inflight = null; }
}
+/** A stale link drain at least this large checks planner statistics before its first page (PLANNER_STATS_MIN_PENDING's floor). */
+export const LINK_DRAIN_ANALYZE_MIN_STALE = 500;
+/** Link-graph tables the drain rewrites that carry no F4b deltas: analyzed whenever `links` is. */
+const LINK_DRAIN_UNTRACKED_TABLES = ['link_transitions', 'link_relationships'] as const;
+
+/**
+ * Planner upkeep for a stale link drain (`extractStaleFromDB` and
+ * `extractManagedStaleLinks`). The drain reads every page twice through
+ * readPageSnapshot and rewrites its links; on a brain that grew since its last
+ * ANALYZE the snapshot read scans the whole source instead of using
+ * pages_source_slug_key, so per-page cost grows with brain size. PGLite with at
+ * least LINK_DRAIN_ANALYZE_MIN_STALE stale pages (`countStale`, called only on
+ * PGLite): refresh stale tables now, then again every
+ * `import.analyze_every_pages` drained pages through the returned tick. Each
+ * refresh ANALYZEs only tables past the F4b threshold, plus link_transitions
+ * and link_relationships when `links` was analyzed. Postgres, small drains and
+ * `planner.auto_analyze=false`: a no-op. Never throws.
+ */
+export async function plannerStatsForLinkDrain(engine: BrainEngine, countStale: () => Promise<number>): Promise<(drained: number) => Promise<void>> {
+ const noop = async () => {};
+ const every = await importAnalyzeEveryPages(engine).catch(() => 0);
+ if (every <= 0 || await countStale().catch(() => 0) < LINK_DRAIN_ANALYZE_MIN_STALE) return noop;
+ const refresh = async () => {
+ const { analyzed } = await maybeRefreshPlannerStats(engine, 'extract', { throttle: false });
+ if (!analyzed.some(a => a.table === 'links')) return;
+ for (const table of LINK_DRAIN_UNTRACKED_TABLES) await engine.executeRaw(`ANALYZE ${table}`);
+ };
+ await refresh().catch(() => undefined);
+ let next = every;
+ return async drained => {
+ if (drained < next) return;
+ next = drained + every;
+ await refresh().catch(() => undefined);
+ };
+}
+
/**
* The first relevant read (O-ENG-12): refresh stale tables within
* `planner.first_read_budget_ms` before the read; the returned function, called
diff --git a/test/planner-stats-link-drain.test.ts b/test/planner-stats-link-drain.test.ts
new file mode 100644
index 0000000000..85ecb236d9
--- /dev/null
+++ b/test/planner-stats-link-drain.test.ts
@@ -0,0 +1,93 @@
+/**
+ * PGLite stale link drains refresh planner statistics before their first page
+ * (src/core/planner-stats.ts plannerStatsForLinkDrain). A brain that grew by
+ * single writes since its last ANALYZE plans readPageSnapshot's
+ * `slug = $1 AND source_id = $2` lookup as a scan of the whole source through
+ * pages_dedup_idx; the drain must read it through pages_source_slug_key. Both
+ * drains (unmanaged extractStaleFromDB, managed extractManagedStaleLinks) are
+ * checked by EXPLAINing the real snapshot statement at its first execution
+ * inside the drain; `planner.auto_analyze=false` keeps the drain from
+ * analyzing. In-memory PGLite ($0).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __testing, LINK_DRAIN_ANALYZE_MIN_STALE, type PlannerRefreshReason } from '../src/core/planner-stats.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const PAGES = LINK_DRAIN_ANALYZE_MIN_STALE + 100;
+const engines: PGLiteEngine[] = [];
+
+beforeAll(() => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+});
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ resetGateway();
+});
+
+async function grownBrain(): Promise<PGLiteEngine> {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push(engine);
+ for (let i = 0; i < PAGES; i++) {
+ await engine.putPage(`notes/page-${i}`, { type: 'note', title: `Page ${i}`,
+ compiled_truth: `Page ${i}. Related: [[notes/page-${(i + 1) % PAGES}]] and [[notes/page-${(i + 7) % PAGES}]].` });
+ }
+ return engine;
+}
+
+/** EXPLAIN the first readPageSnapshot statement the drain executes, with its own parameters. */
+async function snapshotPlanDuringDrain(engine: PGLiteEngine, drain: () => Promise<unknown>): Promise<string> {
+ let plan: string | null = null;
+ const executeRaw = engine.executeRaw;
+ engine.executeRaw = async function (this: PGLiteEngine, sql: string, params?: unknown[]) {
+ if (plan === null && sql.trimStart().startsWith('WITH chosen AS')) {
+ plan = (await executeRaw.call(this, `EXPLAIN ${sql}`, params) as Array<{ 'QUERY PLAN': string }>).map(r => r['QUERY PLAN']).join('\n');
+ }
+ return executeRaw.call(this, sql, params);
+ } as typeof engine.executeRaw;
+ try { await drain(); } finally { engine.executeRaw = executeRaw; }
+ if (plan === null) throw new Error('the drain never read a page snapshot');
+ return plan;
+}
+
+test('unmanaged extract --stale reads snapshots through pages_source_slug_key', async () => {
+ const engine = await grownBrain();
+ const analyzed: string[] = [];
+ __testing.hooks.onAnalyzed = async (_engine, event) => { if (event.reason === 'extract') analyzed.push(event.table); };
+ try {
+ const plan = await snapshotPlanDuringDrain(engine, () =>
+ extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true }));
+ expect(plan).toContain('pages_source_slug_key');
+ expect(plan).not.toContain('pages_dedup_idx');
+ expect(analyzed).toContain('pages');
+ } finally {
+ __testing.hooks.onAnalyzed = undefined;
+ }
+}, 120_000);
+
+test('managed extract --stale reads snapshots through pages_source_slug_key', async () => {
+ const engine = await grownBrain();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const plan = await snapshotPlanDuringDrain(engine, () =>
+ extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true }));
+ expect(plan).toContain('pages_source_slug_key');
+ expect(plan).not.toContain('pages_dedup_idx');
+}, 120_000);
+
+test('planner.auto_analyze=false: the drain runs no ANALYZE', async () => {
+ const engine = await grownBrain();
+ const reasons: PlannerRefreshReason[] = [];
+ __testing.hooks.onAnalyzed = async (_engine, event) => { reasons.push(event.reason); };
+ try {
+ await withEnv({ GBRAIN_PLANNER_AUTO_ANALYZE: 'false' }, () =>
+ extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true }));
+ expect(reasons).toEqual([]);
+ } finally {
+ __testing.hooks.onAnalyzed = undefined;
+ }
+}, 120_000);