Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): the extraction nudge matches doctor and names the command that finishes (#6803 part 6)

garrytan889de2399697
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 37ebcbcd66..126d6a5e7b 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-contract/v1/`.
-- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain`/`--source` before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.
+- `src/core/fix-routing.ts` — A1 render-time routing pin: `pinRouting(argv, routing)` appends `--brain` and the command's source flag (`--source`; `--source-id` for a record declaring `routes_source: '--source-id'`, extract, whose `--source` is a mode selector and never blocks the pin) before a bare `--` for commands that route them (shared ops registered by `operations.ts`; CLI-only commands from the generated `CLI_ROUTING_FLAGS`, built from the command table's `phase`/`routes_source` and each command's code). Holds the CLI process's routing provider (`installCliRouting`, installed by `src/cli/fix-routing-provider.ts`; never for `serve`) and the first source the invocation resolved (`noteResolvedSource`, called by the source resolver). Never imports the command table (its lazy loaders would bundle every command). Tests: `test/fix-routing.test.ts`; journey proof in `test/agent-journey-recovery.serial.test.ts`.
- `src/core/agent-output.ts` — the contract v1 types and renderers every surface shares: `Action` (stored; never carries `next` or `command`; the escalation flag `ask_user: true` marks a refusal whose every way out is the user's decision) and `RenderedAction`, `Notice`/`RenderedNotice`, `AgentEnvelope`, `RenderContext`. `deriveNext` is the published decision table (a stored `ask_user: true` → `ask_user`; no runnable step → `report`; provider → `wait`; user/host_admin or a CLI-only fix on MCP → `tell_user_to_run`; unpreapproved consent, and `destructive` always → `ask_user`; else `run`). `renderAction` drops `mcp` unless `ctx.isCallable` (an MCP-only fix on the CLI, a thin client's remote fix, is kept as relay data with actor `user` and `tell_user_to_run`), pins `ctx.routing` (`--brain`/`--source`) into every gbrain argv via `src/core/fix-routing.ts`, renders `command` only from argv via `shellQuote`, rewrites a CLI-only agent fix to actor `user` (stdio) / `host_admin` (http). `inertText` flattens newlines and breaks marker tokens in every interpolated value. `docsUrl` pins `v<VERSION>` for a published package, `master` for a source checkout, `LLMS_REPO_BASE` for forks when `src/core/repo-base.ts` `parseRepoBase` accepts it (W4.12: a plain `https://host/path`, no credentials, query, fragment or whitespace, returned as the parser normalizes it (fix wave 13 P1.16); an invalid value is ignored with one stderr warning, and the build scripts refuse it through `repoBaseOrThrow`). `redactForTransport` is the one HTTP redaction pass (paths, PIDs, key names, posture keys). `toAgentError` is total and table-driven (OperationError incl. F0 refresh refusals → `fix.argv`, StructuredAgentError, BudgetExhausted/no_pricing with `inputs`, RemoteMcpError, CredentialError, AIConfig/AITransient, GBrainError, legacy PhaseError objects, the `GBRAIN_DB_ACCESS` classifier, unknown throws → `internal_error` naming the op); it applies the safe-recovery rule (an unknown-outcome mutation points at its receipt; `retryable` only for `idempotent` ops), adds the registry's diagnostic default fix for server/unavailable classes, logs internal faults and suggestion-less envelopes to E11, and redacts on http. `renderCliError`, `toolResultWithNotices` (content[0] byte-identical; notices as prefixed extra blocks + `_meta.gbrain_notices`), `toolErrorResult` (exactly one block), `withAgentSiblings`/`legacyNestedErrorDocument` (nested legacy shapes gain `code`/`fix`), `fallbackJsonDocument`. Tests: `test/agent-output.test.ts`, `test/agent-error.test.ts`, `test/agent-contract-goldens.test.ts`. `PageProjectionConflictError` has its own row (`page_projection_conflict`, `detail` names the changed fields, re-run suggestion naming the CLI command, read-only `gbrain get` fix) ahead of the unknown-throw fallback.
- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.
- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 5e5e050aa9..119a4b6aa6 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -33,4 +33,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); `extract --stale` replaces through `replaceDerivedLinks`, the db link walk through `replaceDerivedLinksBatch`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: a page's throw aborts the sweep after the batch's finished pages are flushed and stamped (S4), so the failing page and later ones stay stale and re-extract idempotently. `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + crash-contract), `test/sync-inline-extract-stamps.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0. W4.14: one basename index per slug set (rebuilt as it grows).
- `src/commands/extract-timeline-db.ts` — the `extract timeline --source db` walk (`extractTimelineFromDB`), also used by `runExtractCore` for a timeline-only pass on a managed brain. Managed brains (every fresh `gbrain init` brain) publish each page that needs a change as one database-only maintenance request (`managed_maintenance_timeline_extract`, owner-checked by `maintenancePreflight`, request id bound to the page revision; `prepareTimelineExtract` is dispatched from `prepareMaintenanceMutation`): under the page lock it retracts rows the current text no longer produces and inserts the canonical tuples with no stored row (`unrecordedCanonicalTimeline`); a page with nothing to change admits no request, and a page edited meanwhile is skipped. Unmanaged brains batch raw inserts. A refused write prints `refused: <code>; nothing written; existing timeline rows are untouched`, the summary counts written versus refused (a request still pending counts as not confirmed) with `gbrain extract --stale` and the `write-refusals.md#extract-timeline-refused` anchor, and the CLI exits 1 (the `extract` job throws). Pinned by `test/extract-timeline-db-managed.test.ts`, `test/e2e/extract-timeline-db-postgres.test.ts`, `test/fresh-init-db-extract.serial.test.ts`.
+- `src/commands/extract-stale-options.ts` — `gbrain extract --stale` source-option validation, run by `extract-stale-delegate.ts` before every `--stale` invocation connects (so before direct and owner dispatch alike): `--source` is the fs|db read mode, never a source id; `--source db` is accepted, `--source fs` and any other `--source <x>` refuse `invalid_params` (exit 2) with a fix naming `--source-id <x>`. `assertStaleSourceModeUnambiguous` refuses `--source db` as ambiguous when a registered source is named `db` (direct path in `runExtract`; owner path in `writer_extract_stale`, which also takes `catch_up`). Tests: `test/extraction-nudge-6803.test.ts`.
+- `src/core/extraction-lag.ts` — the extraction backlog as doctor `links_extraction_lag`, the end-of-sync nudge (`sync/report.ts` `maybeExtractionNudge`, which runs the doctor check) and `extract --stale` report it: `readExtractionLag` (one statement, `extractionLagStatement` in `engine-sql/pages.ts`: live pages, actionable stale pages without attendance-blocked ones, attendance-blocked pages, under a statement deadline; the mention-due read only when the mention pass is on), `extractionLagVerdict` (warn/fail thresholds and the vacuous-skip floor), `extractionRoutes` (the plain `gbrain extract --stale` fix verified by the scoped `--dry-run --json`, the plain and `--catch-up` routes with estimates at `EXTRACTION_PAGES_PER_SECOND`, actor `user`/`host_admin` past `AGENT_TOOL_LIMIT_MS`, option argv pinned to the selected brain), and `staleExtractionCounts`/`formatStaleCounts` (`actionable`, `attendance_blocked`, `mention_due`, `complete` in every `extract --stale` report). Owns `STALE_TIME_BUDGET_MS` (re-exported by `extract.ts`). Tests: `test/extraction-nudge-6803.test.ts`, `test/doctor-links-extraction-lag.test.ts`.
- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index b690c1d466..0bf9f73387 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -36,7 +36,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/persistence/terminal-failures.ts` — #6650: the bounded readers over that classifier. `readTerminalFailureSummary` is one set-based aggregate (GROUPING SETS per source; `TERMINAL_STATEMENT_MS` 5 s statement and `TERMINAL_ACQUIRE_MS` 2 s connection deadlines; past either it returns `status: 'unknown'`, never an empty pile) splitting active blockers (recovery records plus the passed-in `checkpoint_blockers` of `sync-status.ts`, read by `readCheckpointBlockerMap`), unresolved rows (count, distinct slugs and intents, oldest age), historical rows (a later write superseded them, or older than `TERMINAL_FIXED_IN` via the SQL twin `TERMINAL_HISTORICAL_SQL`), 24 h and 7-day daily counts, categories and defect classes; archived sources are skipped. Thresholds `persistence.terminal_failures.window_days` (clamped to `persistence.receipt_retention_days`), `spike_factor`, `spike_min` (`readTerminalThresholds`, `validateTerminalConfigValue`, refused at `config set` by `commands/config/preparation-keys.ts`); `isSpike` against `sevenDayMedian`. `readTerminalFailures` is the drill-down (batches of 200, at most 2,000 rows scanned per call, a sequence cursor, verdict filters, `--group-by category` groups with an exact `drill_down` argv each). Consumers: doctor `persistence_terminal_failures` (`commands/doctor/checks/persistence-requests.ts`), `sync status` `terminal_failures` (`sync-status.ts`, `next` falls back to a recovery blocker's action), the `writer_failures` administration operation, and the admin `/metrics` gauges (`serve-http-metrics.ts` `renderTerminalFailureMetrics`, one aggregate per engine shared by scrapes for `TERMINAL_METRICS_TTL_MS` = 60 s via `cachedTerminalSummary`; never `/health`). Each source also reports `new_last_24h_older_builds` (rows and builds older than their class's fix), and doctor's spike message says an older write owner is producing them when they are most of the spike. Tests: `test/terminal-failures-6650.test.ts`, `test/sync-status-terminal-6650.test.ts`, `test/terminal-failure-metrics-6650.test.ts`, the CLI journey `test/agent-journey-terminal-failures-6650.test.ts`.
- `src/commands/sources-writer-failures.ts` — #6650: output of `gbrain sources writer failures <source> [--state all] [--group-by category] [--since Nd] [--limit N] [--before <cursor>] [--category|--code|--origin] [--json]`, dispatched by `persistence-admin.ts` as `writer_failures` (validated in `administration.ts` `writerFailuresQuery`, locally or through the resident owner). A table by default, one JSON document with `--json`; row and group `fix` / `inspect` actions are rendered for the CLI; a full page prints `truncated` with the exact next command. The operation is advertised to clients in the owner's `administration_extensions` (`ipc.ts`, `admin-contract.ts` `PERSISTENCE_ADMIN_EXTENSIONS`), never in the `administration` list an older client validates strictly, and `local-client.ts` delegates it only to an owner that lists it (`ownerAdministers`). Tests: `test/writer-failures-cli-6650.test.ts`.
- `src/core/persistence/public-category.ts` — #6712 PR 2 (L5): `publicCategory({ category?, code })`, the closed public vocabulary (`drift`, `conflict`, `content_refused`, `file_missing`, `permission`, `storage`, `config`, `superseded`, `transient`, `defect`) that sits beside the unchanged diagnosis `category`. `PUBLIC_BY_TERMINAL` maps every `TerminalCategory`, `PUBLIC_BY_CODE` every `SYNC_FAULT_TABLE` code (a new fault code needs a row: `test/public-category.test.ts`), and anything else goes by its registry class (unknown codes are `defect`). `classifyTerminal` carries it as `public_category`; `classifyRecordedFault` (terminal-classify.ts) reads a hold, a managed-sync failure row or a run stop as the failed receipt it stands for, so the receipt diagnosis, `managedWrite`, sync status holds and `last_error`, the terminal summary and doctor `sync_failures` (`details.failures`) render one verdict.
-- `src/core/persistence/sync-tail.ts` + `sync-tail-record.ts` — #6712 PR 2 (L5): the tail of a committed checkpoint (projection statistics, then link extraction for the run's imported slugs read from its manifest). `recordSyncTail` runs inside the checkpoint's publication transaction (`applyManagedSyncCheckpoint`) and appends `{run_id, changed, extract}` to `op_checkpoints` `managed-sync-tail` / `<source>` (at most 16), so the tail is owed before anyone can read the run as synced. `withSyncTail` runs it after the outermost drain lease is released (`performManagedBranch`, and `performManagedSync` when it took the lease itself; a call still inside a lease, a dry run and a lease-held follower run none), bounded by `SYNC_TAIL_BUDGET_MS` (5 min) and the caller's deadline, and folds `tail` (`done` / `truncated` / `degraded` / `deferred` / `failed`) and `links` into the result. The obligation is cleared by compare-and-swap only when every step ran; a failed, deferred or truncated tail attaches a degraded `sync_tail_degraded` notice with its fix (the sync CLI prints it with the capacity notices). Fault point `sync:tail_started`. Tests: `test/sync-drain-finish-tail.test.ts`.
+- `src/core/persistence/sync-tail.ts` + `sync-tail-record.ts` — #6712 PR 2 (L5): the tail of a committed checkpoint (projection statistics, then link extraction for the run's imported slugs read from its manifest). `recordSyncTail` runs inside the checkpoint's publication transaction (`applyManagedSyncCheckpoint`) and appends `{run_id, changed, extract}` to `op_checkpoints` `managed-sync-tail` / `<source>` (at most 16), so the tail is owed before anyone can read the run as synced. `withSyncTail` runs it after the outermost drain lease is released (`performManagedBranch`, and `performManagedSync` when it took the lease itself; a call still inside a lease, a dry run and a lease-held follower run none), bounded by `SYNC_TAIL_BUDGET_MS` (5 min) and the caller's deadline, and folds `tail` (`done` / `truncated` / `degraded` / `deferred` / `failed`, with `underived`: the run's imports its link extraction left underived, which the per-source "still owe extraction" line prints) and `links` into the result. The obligation is cleared by compare-and-swap only when every step ran; a failed, deferred or truncated tail attaches a degraded `sync_tail_degraded` notice with its fix (the sync CLI prints it with the capacity notices). Fault point `sync:tail_started`. Tests: `test/sync-drain-finish-tail.test.ts`.
- `src/core/since.ts` — #6712 PR 2: `parseSince(input, flag, now)`, the one `--since` parser (`gbrain agent logs --since`, `gbrain repair file-drift --since`). An age (`90s`, `30m`, `12h`, `7d`) becomes one concrete UTC instant at parse time; an ISO-8601 date or timestamp is normalized; anything else throws `invalid_params` naming the flag. Callers print and hash the instant, never the age. Tests: `test/sync-exits-l4-6712.test.ts`, `test/agent-cli.test.ts`.
- `src/core/persistence/sync-ghosts.ts` — #6712 PR 2: `countSyncGhosts(engine, sourceId)`, the post-sync ghost count. It reuses `scanGhostSource` from `repair/ghost-pages.ts` (no second classifier) with a candidate bound of `SYNC_GHOST_CHECK_LIMIT` (50) stats, leaves out paths sync holds (a held file is the hold's to explain), and returns the count, samples and the `gbrain repair ghost-pages --source <id>` preview as its fix. Sync never deletes or tombstones a ghost; `commands/sync/perform.ts` prints one line and sets `SyncResult.ghostPages`. Test: `test/sync-exits-l4-6712.test.ts`.
- `src/core/persistence/soak-counters.ts` — #6712 PR 2: the soak counters doctor `sync_soak_counters` reports (one `op_checkpoints` row per UTC day under op `sync-soak-counters`). Interventions: `sync_non_plain` (`nonPlainSyncFlags`, from `sync/run.ts`), `repair_apply` (`repair.ts`), `unblock_apply` (`sync/operator.ts`), `retry_held` (`sources-retry-held.ts`) and `needs_human` (`sweepNeedsHumanHolds`, run after each managed sync: stamps `needs_human_at` on a hold the fault table now calls `needs_human` and counts it once; the stamp survives same-code re-holds). Content decisions: `file_drift_apply` and `file_drift_hold`. `readSoakCounters` sums the last seven days. Counting never fails the command that counts. Test: `test/sync-exits-l4-6712.test.ts`.
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index e52dec1db3..aa2534326e 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -19,6 +19,7 @@
| `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |
| A write (`add_timeline_entry`, `put_page`, `remember`, any `mutating` tool) refused `invalid_params` "unknown parameter … write operations always reject unknown parameters; nothing was written" | the call named a parameter the tool does not declare (for example `content` instead of `detail`); the `suggestion` names the submitted key and the declared one; resend with the declared name. Reads keep the `mcp.strict_params` warn grace period | agent | none | the resent call returns no `invalid_params` and no `unknown_param` warning |
| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): the fix text names the config key that selected the model when the gateway knows it ("Selected via models.tier.reasoning. Fix: gbrain config set …"; an env var or config.json pin says what to clear); otherwise check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` |
+| Doctor `links_extraction_lag` or the end-of-sync line says "N page(s) have un-extracted edges" (while `page_extraction_state` has 0 rows) | the count is the link-extraction watermark backlog (`page_extraction_state` is the facts pipeline's large-page table, unrelated); preview with `gbrain extract --stale --dry-run --json`, then on the brain host run `gbrain extract --stale --catch-up [--source-id <id>]` (finishes in one run, safe to interrupt) or repeat plain `gbrain extract --stale` (30 min per run, resumes); scope with `--source-id`, never `--source` (fs\|db) | user on the brain host when the estimate passes 120 s (the fix says `tell_user_to_run`); agent otherwise | none | `gbrain extract --stale --dry-run --json` shows `actionable: 0` (and `mention_due: 0` with mentions on) |
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index b09934cc90..1e85f2fa1c 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -625,7 +625,8 @@ interface RenderedAction {
`verify.argv`, `then`) names the brain and source the failing call acted on:
`--brain <id>` for commands that open a brain, `--source <id>` for commands that
resolve their source through the ambient chain (shared ops, and CLI commands the
-command table marks `routes_source`). gbrain appends them when it renders the
+command table marks `routes_source`; `gbrain extract`, whose `--source` picks the
+fs|db read mode, gets `--source-id <id>` instead). gbrain appends them when it renders the
fix, before any bare `--`, and keeps flags the fix already carries. So you can
run the fix later from another directory, or under a different `GBRAIN_BRAIN_ID`,
`GBRAIN_SOURCE`, `.gbrain-mount` or `.gbrain-source`, and it still acts on the
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.ts
index fb0863b449..42223de73c 100644
--- a/scripts/check-agent-contract.ts
+++ b/scripts/check-agent-contract.ts
@@ -271,7 +271,9 @@ const READ_ONLY_SUBCOMMANDS = new Set(['config get', 'sources list', 'sources st
// #6466: `--list` returns before the orchestration lock and never runs an orchestrator or writes the ledger.
'apply-migrations --list',
// #6661: [X12] --status takes no lock, makes no home dir and writes no receipt; it probes the serve over HTTP.
- 'bootstrap harness --status']);
+ 'bootstrap harness --status',
+ // #6803: the stale-extraction preview returns before any write and reports the terminal counts (actionable, mention_due).
+ 'extract --stale --dry-run']);
function tsFiles(dir: string): string[] {
if (!existsSync(dir)) return [];
diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.json
index 557e6df7ad..5b4cc31dd4 100644
--- a/scripts/e2e-weights.json
+++ b/scripts/e2e-weights.json
@@ -162,6 +162,7 @@
"test/e2e/extract-takes-managed.test.ts": 3680,
"test/e2e/extract-timeline-attendance-postgres.test.ts": 8660,
"test/e2e/extract-timeline-db-postgres.test.ts": 4140,
+ "test/e2e/extraction-nudge-6803-postgres.test.ts": 4200,
"test/e2e/extraction-review-postgres.test.ts": 8150,
"test/e2e/fact-embedding-backfill-parity.test.ts": 5810,
"test/e2e/fact-embedding-opt-out.test.ts": 4430,
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index 1ddeccb422..850a82901c 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -360,9 +360,10 @@ export function buildFlagRegistry(root: string = ROOT): Record<string, string[]>
* - `--brain` when the command opens its brain through the connect terminator
* (phase other than `pre-connect`), or its own code reads the global brain
* option;
- * - `--source` when the record declares `routes_source` (its source resolves
- * through the ambient chain). The declaration needs consumption evidence (the
- * tight-quoted `'--source'` literal in the command's own code, the
+ * - `--source` when the record declares `routes_source: true` (its source resolves
+ * through the ambient chain), or the flag it declares instead (`'--source-id'`
+ * for extract, whose `--source` selects fs|db). The declaration needs consumption
+ * evidence (the tight-quoted flag literal in the command's own code, the
* SAFETY_FLAGS rule); a declaration without it fails the generator.
*/
export function buildRoutingFlags(root: string = ROOT): Record<string, string[]> {
@@ -485,12 +486,12 @@ function buildFlagArtifacts(root: string): { registry: Record<string, string[]>;
}
registry[command] = [...flags].sort();
const record = records.find(r => r.name === command);
- if (record?.routesSource && !consumes(depthZeroText, '--source')) {
- throw new Error(`generate-flag-registry: ${command} declares routes_source but its code never reads '--source'`);
+ if (record?.routesSource && !consumes(depthZeroText, record.routesSource)) {
+ throw new Error(`generate-flag-registry: ${command} declares routes_source but its code never reads '${record.routesSource}'`);
}
const routed = [
...(record?.phase !== 'pre-connect' || /getCliOptions\(\)\.brain|cliOpts\.brain/.test(depthZeroText) ? ['--brain'] : []),
- ...(record?.routesSource ? ['--source'] : []),
+ ...(record?.routesSource ? [record.routesSource] : []),
];
if (routed.length) routing[command] = routed;
}
@@ -525,7 +526,8 @@ ${entries}
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
// src/core/fix-routing.ts): '--brain' when the command opens its brain (not a
// pre-connect command, or its code reads the global brain option); '--source'
-// when the command-table record declares routes_source (consumption-checked).
+// (or the declared '--source-id') when the command-table record declares
+// routes_source (consumption-checked).
export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
${render(routing)}
};
diff --git a/scripts/lib/cli-pipeline.ts b/scripts/lib/cli-pipeline.ts
index e2f2c7b324..465a032136 100644
--- a/scripts/lib/cli-pipeline.ts
+++ b/scripts/lib/cli-pipeline.ts
@@ -130,8 +130,8 @@ export interface TableRecordShape {
helpSpecifier?: string | null;
/** The record's `phase` string literal (A1 routing pin: pre-connect commands open no brain through the terminator). */
phase?: string;
- /** A1: `routes_source: true` on the record. */
- routesSource?: true;
+ /** A1: the flag naming the record's target source: `'--source'` for `routes_source: true`, else the declared flag (`'--source-id'`). */
+ routesSource?: '--source' | '--source-id';
}
/** Every record of CLI_COMMANDS in table order, read by AST (the EO13 literal-load contract). */
@@ -155,8 +155,10 @@ export function readTableRecords(root: string): TableRecordShape[] {
&& ts.isStringLiteral(init.body.arguments[0]!) ? init.body.arguments[0].text : null;
const help = prop('help');
const phase = prop('phase')?.initializer;
- const routesSource = prop('routes_source')?.initializer.kind === ts.SyntaxKind.TrueKeyword;
+ const routes = prop('routes_source')?.initializer;
+ const routesSource = routes?.kind === ts.SyntaxKind.TrueKeyword ? '--source' as const
+ : routes && ts.isStringLiteral(routes) && routes.text === '--source-id' ? '--source-id' as const : undefined;
return { name: name.text, loadSpecifier: literalImport(prop('load')?.initializer), ...(help ? { helpSpecifier: literalImport(help.initializer) } : {}),
- ...(phase && ts.isStringLiteral(phase) ? { phase: phase.text } : {}), ...(routesSource ? { routesSource: true as const } : {}) };
+ ...(phase && ts.isStringLiteral(phase) ? { phase: phase.text } : {}), ...(routesSource ? { routesSource } : {}) };
});
}
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 452e5103ac..670ac18b4a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -43,7 +43,7 @@ src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap a
src/core/ops/pages.ts 710 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); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts)
src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part)
src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)
-src/commands/doctor/checks/extraction-sync.ts 1543 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts)
+src/commands/doctor/checks/extraction-sync.ts 1492 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge)
src/core/search/evidence-delivery.ts 1673 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136)
src/commands/config.ts 1510 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig)
src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 55d73ee069..c133485b93 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -135,6 +135,7 @@
"e2e:test/e2e/extract-takes-managed.test.ts": 3170,
"e2e:test/e2e/extract-timeline-attendance-postgres.test.ts": 3183,
"e2e:test/e2e/extract-timeline-db-postgres.test.ts": 3581,
+ "e2e:test/e2e/extraction-nudge-6803-postgres.test.ts": 4200,
"e2e:test/e2e/extraction-review-postgres.test.ts": 1447,
"e2e:test/e2e/fact-embedding-backfill-parity.test.ts": 11979,
"e2e:test/e2e/fact-embedding-opt-out.test.ts": 2857,
@@ -1866,6 +1867,7 @@
"unit:test/extract/status.test.ts": 174,
"unit:test/extractable-pack.test.ts": 165,
"unit:test/extractable-spec-widening.test.ts": 165,
+ "unit:test/extraction-nudge-6803.test.ts": 3900,
"unit:test/extraction-review.test.ts": 5736,
"unit:test/fact-backfill-resident.test.ts": 6989,
"unit:test/fact-embedding-opt-out.test.ts": 2517,
@@ -2214,6 +2216,7 @@
"unit:test/link-extraction-pack-3190.test.ts": 1587,
"unit:test/link-extraction-relative-path.test.ts": 237,
"unit:test/link-extraction.test.ts": 218,
+ "unit:test/link-extractor-bump-notes.test.ts": 300,
"unit:test/link-inference-constraints.test.ts": 234,
"unit:test/link-inference-pack.test.ts": 207,
"unit:test/link-relationships.test.ts": 1353,
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 66f9ebf9cb..07a69a5e78 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -107,10 +107,12 @@ interface CliCommandBase {
/**
* A1: the command's target source resolves through the ambient chain
* (`--source` → GBRAIN_SOURCE → .gbrain-source → …), so a fix naming it
- * carries `--source <id>` (src/core/fix-routing.ts). Requires consumption
- * evidence in the generated registry (test/fix-routing.test.ts).
+ * carries `--source <id>` (src/core/fix-routing.ts). `'--source-id'` names that
+ * flag instead for a command whose `--source` is a mode selector (extract:
+ * fs|db). Requires consumption evidence in the generated registry
+ * (test/fix-routing.test.ts).
*/
- routes_source?: true;
+ routes_source?: true | '--source-id';
/** D3: lazy curated help module. */
help?: () => Promise<{ help: CliHelpSpec }>;
}
@@ -304,7 +306,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'sync', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', routes_source: true, load: () => import('./commands/sync.ts') },
// selfHelp: #3834: extract ships detailed help for its mode-specific flags. Keep the generic
// CLI-only stub from hiding that contract.
- { name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/extract.ts') },
+ { name: 'extract', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: '--source-id', load: () => import('./commands/extract.ts') },
// selfHelp: v0.41.11.0 — extract-conversation-facts ships its own detailed HELP describing segment
// splitting + checkpointing + budget caps + the unified types config story. Route around the
// generic short-circuit.
diff --git a/src/cli/fix-routing-provider.ts b/src/cli/fix-routing-provider.ts
index cb3c47b2ca..c748ea23cc 100644
--- a/src/cli/fix-routing-provider.ts
+++ b/src/cli/fix-routing-provider.ts
@@ -37,11 +37,12 @@ export function cliRoutingProvider(currentCommand: () => string | undefined, arg
if (!thin) {
try { brain = resolveBrainId(getCliOptions().brain); } catch { /* unresolvable: no brain pin */ }
const cmd = currentCommand();
- if (cmd && routingFlagsFor(cmd).source) {
+ const flag = cmd ? routingFlagsFor(cmd).source : false;
+ if (flag) {
const end = args.indexOf('--');
const head = end === -1 ? args : args.slice(0, end);
- const i = head.findIndex(a => a === '--source' || a.startsWith('--source='));
- const explicit = i === -1 ? null : head[i]!.startsWith('--source=') ? head[i]!.slice('--source='.length) : head[i + 1] ?? null;
+ const i = head.findIndex(a => a === flag || a.startsWith(`${flag}=`));
+ const explicit = i === -1 ? null : head[i]!.startsWith(`${flag}=`) ? head[i]!.slice(flag.length + 1) : head[i + 1] ?? null;
try { source = resolveSourceIdEngineFree(explicit) ?? undefined; } catch { /* invalid: no source pin */ }
}
}
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 9917e019de..ffbced31de 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -11,10 +11,10 @@ import { probeSourceGitState } from '../../../core/git-head.ts';
// v0.41.32.0: remote staleness reads the stored newest_content_at column via
// this pure comparator (no git subprocess on the HTTP MCP doctor path).
import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeconds } from '../../../core/source-health.ts';
-import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';
+import { resolveHoursEnv } from '../../../core/env-number.ts';
import { chunkerStamp } from '../../../core/chunkers/code.ts';
-import { effectiveLinkExtractorWatermark, smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';
-import { previewMentionPass } from '../../../core/mentions/stale.ts';
+import { smallBrainBacklogNote } from '../../../core/link-extraction-watermark.ts';
+import { extractionLagVerdict, extractionRoutes, readExtractionLag } from '../../../core/extraction-lag.ts';
import { isMissingSchemaObject } from '../../../core/utils.ts';
import {
loadStorageConfig,
@@ -38,21 +38,14 @@ import { checkError } from '../check-fix.ts';
import { checkpointMovedFix, firstSyncRunning, noSuccessfulSync, stoppedConnectorIssues, type SyncOutcomeEntry } from '../sync-outcome.ts';
import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';
-/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */
-const _resolveEnvNumber = resolveEnvNumber;
+/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */
const _resolveSyncFreshnessHours = resolveHoursEnv;
/**
- * v0.42.7 (#1696): single source of truth for the extraction-lag warn
- * threshold (percent). Both the `links_extraction_lag` doctor check AND the
- * end-of-sync nudge (`sync.ts:maybeExtractionNudge`) resolve through this +
- * `_resolveEnvNumber` so "the nudge fires iff doctor would warn" can't drift.
+ * The extraction-lag threshold and vacuous-skip floor live with the shared read and verdict
+ * (core/extraction-lag.ts), so "the sync nudge fires iff doctor would warn" can't drift.
*/
-export const EXTRACTION_LAG_WARN_PCT_DEFAULT = 20;
-/** Min non-deleted page count below which extraction-lag is vacuous-skipped
- * (unless an explicit --source scope is set). Shared by doctor + the sync
- * nudge (D6/C4) so their skip predicates match exactly. */
-export const EXTRACTION_LAG_MIN_PAGES = 100;
+export { EXTRACTION_LAG_WARN_PCT_DEFAULT, EXTRACTION_LAG_MIN_PAGES } from '../../../core/extraction-lag.ts';
/**
* Sync freshness check (v0.32.4) — verify that sources with local_path have
@@ -106,77 +99,39 @@ export const EXTRACTION_LAG_MIN_PAGES = 100;
*/
export async function checkLinksExtractionLag(
engine: BrainEngine,
- opts?: { sourceId?: string },
+ opts?: { sourceId?: string; remote?: boolean },
): Promise<Check> {
const name = 'links_extraction_lag';
const sourceId = opts?.sourceId;
- const fix = "Run: gbrain extract --stale";
try {
- const totalRows = await engine.executeRaw<{ count: number }>(
- sourceId
- ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND ${quarantineFilterFragment('pages')} AND source_id = $1`
- : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND ${quarantineFilterFragment('pages')}`,
- sourceId ? [sourceId] : [],
- );
- const total = Number(totalRows[0]?.count ?? 0);
+ // #6803 (D1): one statement and one verdict shared with the sync nudge; attendance-blocked pages (#5761: stale
+ // only by an unresolved attendee, `extract --stale` cannot clear them) are reported apart from lag.
+ const lag = await readExtractionLag(engine, { sourceId });
+ const { total, actionable: stale, attendance_blocked: attendanceBlocked } = lag;
if (total === 0) {
return { name, status: 'ok', message: 'Extraction lag not applicable (no pages)' };
}
- // Vacuous-skip tiny brains unless explicitly source-scoped. Shared floor
- // const so the sync nudge (D6/C4) skips on the exact same predicate.
- if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) {
+ const verdict = extractionLagVerdict(lag, sourceId);
+ if (verdict.skipped) {
return { name, status: 'ok', message: `Extraction lag not applicable (${total} pages — too few to assess)${await smallBrainBacklogNote(engine)}` };
}
-
- // #5761: a page left stale only by an unresolved attendee, and not edited
- // since, is attendance-blocked: `extract --stale` cannot clear it, so it
- // is reported apart from lag. Pre-v180 brains have no marker column.
- const versionTs = await effectiveLinkExtractorWatermark(engine);
- let stale: number;
- let attendanceBlocked = 0;
- try {
- stale = await engine.countStalePagesForExtraction({ sourceId, versionTs, attendance: 'exclude' });
- attendanceBlocked = await engine.countStalePagesForExtraction({ sourceId, versionTs, attendance: 'blocked' });
- } catch (e) {
- if (!isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) throw e;
- stale = await engine.countStalePagesForExtraction({ sourceId, versionTs });
- }
- const pct = (stale / total) * 100;
- const pctStr = pct.toFixed(0);
+ const pctStr = verdict.pct.toFixed(0);
const scope = sourceId ? ` in source '${sourceId}'` : '';
const blockedNote = attendanceBlocked
? `. ${attendanceBlocked} more page(s) wait on unresolved attendees; the next extraction clears each once its attendee's person page exists in the meeting's source (docs/guides/attendance-evidence.md)`
: '';
-
- const warnPct = _resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
- // Fail threshold is DISABLED unless explicitly set (warn-only default). A
- // bare unset env var → no hard-fail; invalid value → warn-once + disabled.
- let failPct: number | undefined;
- const failRaw = process.env.GBRAIN_EXTRACTION_LAG_FAIL_PCT;
- if (failRaw !== undefined && failRaw !== '') {
- const n = Number(failRaw);
- if (Number.isFinite(n) && n > 0) {
- failPct = n;
- } else {
- warnOnceForEnv(
- 'GBRAIN_EXTRACTION_LAG_FAIL_PCT',
- `[gbrain] Ignoring invalid GBRAIN_EXTRACTION_LAG_FAIL_PCT=${failRaw}; hard-fail stays disabled.`,
- );
- }
- }
-
- // Entity mention index: pages the mention pass has not scanned at their current content.
- const mention = await previewMentionPass(engine, sourceId).catch(() => null);
- const mentionNote = mention?.due ? `; ${mention.due} page(s) await the mention pass (last pass: ${mention.last_pass_at ?? 'never'})` : '';
- const details = { total, stale, attendance_blocked: attendanceBlocked, pct: Number(pctStr), warn_pct: warnPct, fail_pct: failPct ?? null, source_id: sourceId ?? null,
- mention_due: mention?.due ?? null, mention_last_pass_at: mention?.last_pass_at ?? null };
- if (failPct !== undefined && pct > failPct) {
- return { name, status: 'fail', message: `${stale}/${total} pages (${pctStr}%)${scope} need link/timeline extraction (> ${failPct}% fail threshold)${mentionNote}. ${fix}${blockedNote}`, details };
- }
- if (pct > warnPct) {
- return { name, status: 'warn', message: `${stale}/${total} pages (${pctStr}%)${scope} have un-extracted edges${mentionNote}. ${fix}${blockedNote}`, details };
+ const mentionNote = lag.mention_due ? `; ${lag.mention_due} page(s) await the mention pass (last pass: ${lag.mention_last_pass_at ?? 'never'})` : '';
+ const details: Record<string, unknown> = { total, stale, attendance_blocked: attendanceBlocked, pct: Number(pctStr), warn_pct: verdict.warn_pct, fail_pct: verdict.fail_pct,
+ source_id: sourceId ?? null, mention_due: lag.mention_due, mention_last_pass_at: lag.mention_last_pass_at };
+ if (verdict.status === 'ok') {
+ return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${mentionNote}${blockedNote}`, details };
}
- return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${mentionNote}${blockedNote}`, details };
+ const { fix, decision, routes } = extractionRoutes(lag, { sourceId, remote: opts?.remote });
+ details.routes = routes;
+ details.decision = decision;
+ const fixText = `Run: ${routes.map(route => `${route.argv.join(' ')} (${route.label})`).join(', or ')}`;
+ const what = verdict.status === 'fail' ? `need link/timeline extraction (> ${verdict.fail_pct}% fail threshold)` : 'have un-extracted edges';
+ return { name, status: verdict.status, message: `${stale}/${total} pages (${pctStr}%)${scope} ${what}${mentionNote}. ${fixText}${blockedNote}`, details, fix };
} catch (e) {
// Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK
// (migration/bootstrap adds it; nothing to assess until then).
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 1871f88c8d..229084ef84 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -374,7 +374,7 @@ export async function doctorReportRemote(
// safe on the thin-client/remote path — remote operators on checkout-less
// Postgres brains are exactly who can't otherwise see the extraction backlog.
// Brain-wide here (remote --source scoping is a separate TODO, like orphan_ratio).
- checks.push(await checkLinksExtractionLag(engine));
+ checks.push(await checkLinksExtractionLag(engine, { remote: true }));
// #4576 (related gap): extract_atoms_backlog was absent from the
// thin-client surface, so an MCP-only caller couldn't see the backlog at
diff --git a/src/commands/extract-stale-delegate.ts b/src/commands/extract-stale-delegate.ts
index 4073ab4f5d..eb7b7d5421 100644
--- a/src/commands/extract-stale-delegate.ts
+++ b/src/commands/extract-stale-delegate.ts
@@ -4,18 +4,31 @@ import { resolveBrainId } from '../core/brain-resolver.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { inspectLockHolder } from '../core/pglite-lock.ts';
-import { opError } from '../core/ops/contract.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { writeCliError } from '../cli/cli-error.ts';
import { readFix } from '../core/ops/op-fix.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import { writeStdoutFinal } from '../core/cli-force-exit.ts';
import { formatManagedStaleExtraction, type ManagedLinkExtraction } from '../core/persistence/links-maintenance.ts';
+import { parseStaleSourceArgs, type StaleSourceSelection } from './extract-stale-options.ts';
-/** A live PGLite owner holds the database; `extract --stale` runs inside it instead of failing on the lock. */
+/**
+ * A live PGLite owner holds the database; `extract --stale` runs inside it instead of failing on the lock. Every
+ * `extract --stale` passes through here before connecting, so the source options are validated (#6803 D2) before
+ * direct and owner dispatch alike.
+ */
export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null, args: string[]): Promise<boolean> {
+ const json = args.includes('--json');
+ let selection: StaleSourceSelection;
+ try { selection = parseStaleSourceArgs(args); } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ setCliExitVerdict(writeCliError(error, 'extract', { json }));
+ return true;
+ }
const brainId = resolveBrainId(getCliOptions().brain, process.cwd());
const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());
if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;
- const json = args.includes('--json');
const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion,
{ fix: readFix('Prints the gbrain extract forms and flags.', { argv: ['gbrain', 'extract', '--help'] }) });
try {
@@ -27,9 +40,11 @@ export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null,
const value = args[++i];
if (!value || value.startsWith('-')) throw invalid('--source-id requires a value.', 'Give --source-id the source to extract, e.g. gbrain extract --stale --source-id default, or omit it to extract every source.');
params.source_id = value;
- } else if (arg === '--source') {
- if (args[++i] !== 'db') throw invalid("extract --stale is DB-source only; drop '--source fs'.", 'Drop --source fs (or pass --source db); stale extraction reads pages from the database.');
- } else if (!['--stale', '--json', '--include-frontmatter', '--catch-up', 'all'].includes(arg)) {
+ } else if (arg === '--source' || arg === '--source=db') {
+ if (arg === '--source') i++;
+ params.source_mode = selection.mode;
+ } else if (arg === '--catch-up') params.catch_up = true;
+ else if (!['--stale', '--json', '--include-frontmatter', 'all'].includes(arg)) {
throw invalid(`Unsupported owner-delegated extract --stale option: ${arg.split('=')[0]}.`,
`Remove ${arg.split('=')[0]}; while the running serve holds the brain, extract --stale accepts --source-id, --dry-run, --json, --include-frontmatter and --catch-up. Stop the serve to use other extract options.`);
}
diff --git a/src/commands/extract-stale-options.ts b/src/commands/extract-stale-options.ts
new file mode 100644
index 0000000000..d0a264b207
--- /dev/null
+++ b/src/commands/extract-stale-options.ts
@@ -0,0 +1,65 @@
+/**
+ * #6803 (D2): `gbrain extract --stale` source-option validation, run before both direct dispatch and the PGLite-owner
+ * hand-off (`writer_extract_stale`). `--source fs|db` is extract's read-mode selector, never a source id: stale
+ * extraction reads the database, so `--source db` is accepted (refused as ambiguous when a registered source is named
+ * `db`), `--source fs` is refused, and any other `--source <x>` is refused with the `--source-id <x>` command that scopes
+ * the sweep, instead of silently running brain-wide.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { Action } from '../core/agent-output.ts';
+import { opError } from '../core/ops/contract.ts';
+import { SOURCE_ID_RE } from '../core/source-id.ts';
+
+export interface StaleSourceSelection { sourceId?: string; mode?: 'db' }
+
+const sourceArgAt = (args: readonly string[], i: number): { value: string | undefined; width: number } =>
+ args[i]!.startsWith('--source=') ? { value: args[i]!.slice('--source='.length), width: 1 } : { value: args[i + 1], width: 2 };
+
+/** `args` with the `--source <x>` at `i` replaced by `replacement` (dropped when empty). */
+function replaced(args: readonly string[], i: number, width: number, replacement: string[]): string[] {
+ return ['gbrain', 'extract', ...args.slice(0, i), ...replacement, ...args.slice(i + width)];
+}
+
+const corrected = (argv: string[], why: string): Action => ({ argv, consent: [], actor: 'agent', requires_exclusive: false, why });
+const invalid = (message: string, suggestion: string, fix?: Action) => opError('invalid_params', message, suggestion, fix ? { fix } : {});
+
+/** Engine-free half: `--source` must be `db` (or absent); `--source-id` names the source to scope to. */
+export function parseStaleSourceArgs(args: readonly string[]): StaleSourceSelection {
+ const selection: StaleSourceSelection = {};
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--source-id' || arg.startsWith('--source-id=')) {
+ const value = arg === '--source-id' ? args[i + 1] : arg.slice('--source-id='.length);
+ if (value && !value.startsWith('-')) selection.sourceId = value;
+ continue;
+ }
+ if (arg !== '--source' && !arg.startsWith('--source=')) continue;
+ const { value, width } = sourceArgAt(args, i);
+ if (value === 'db') { selection.mode = 'db'; continue; }
+ if (!value || value.startsWith('-')) {
+ throw invalid('--source requires a value; extract --stale only takes --source db.',
+ 'Drop --source (stale extraction always reads the database), or pass --source-id with a source id to scope the sweep to that source.',
+ corrected(replaced(args, i, 1, []), 'The same extraction without the empty --source; it reads the database.'));
+ }
+ if (value === 'fs') {
+ throw invalid("extract --stale is DB-source only (it reads pages from the database); '--source fs' is not a mode it takes.",
+ "Drop '--source fs' (stale extraction works on checkout-less brains). To scope the sweep to a source named fs, pass --source-id fs.",
+ corrected(replaced(args, i, width, []), "The same extraction without '--source fs'; it reads the database."));
+ }
+ throw invalid(`'--source ${value}' does not select a source for extract --stale: --source picks the read mode (fs|db), and without --source-id the sweep would run brain-wide.`,
+ `To scope the sweep to source ${value}, pass --source-id ${value}.`,
+ SOURCE_ID_RE.test(value) ? corrected(replaced(args, i, width, ['--source-id', value]), `The same extraction scoped to source ${value}.`) : undefined);
+ }
+ return selection;
+}
+
+/** Engine half: `--source db` is ambiguous when a registered source has that id. */
+export async function assertStaleSourceModeUnambiguous(engine: Pick<BrainEngine, 'executeRaw'>, args: readonly string[]): Promise<void> {
+ if (parseStaleSourceArgs(args).mode !== 'db') return;
+ const rows = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1', ['db']);
+ if (!rows.length) return;
+ const i = args.findIndex(arg => arg === '--source' || arg === '--source=db');
+ throw invalid("'--source db' is ambiguous: it is extract's read mode, and a registered source is named db.",
+ 'Pass --source-id db to scope the sweep to that source, or drop --source db (stale extraction always reads the database) to sweep every source.',
+ corrected(replaced(args, i, args[i] === '--source' ? 2 : 1, ['--source-id', 'db']), 'The same extraction scoped to the source named db.'));
+}
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 36eecca6e8..b431418bd1 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -101,6 +101,8 @@ 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';
+import { STALE_TIME_BUDGET_MS, formatStaleCounts, staleExtractionCounts } from '../core/extraction-lag.ts';
+import { assertStaleSourceModeUnambiguous } from './extract-stale-options.ts';
// Batch size for addLinksBatch / addTimelineEntriesBatch.
// Postgres bind-parameter limit is 65535. Links use 4 cols/row → 16K hard ceiling;
@@ -117,12 +119,10 @@ const BATCH_SIZE = 100;
// 25 caps the worst case at ~625MB even if every page is a 25MB transcript.
// Normal pages are KBs; raise via GBRAIN_EXTRACT_STALE_BATCH for throughput.
const STALE_BATCH_SIZE = Math.max(1, Number(process.env.GBRAIN_EXTRACT_STALE_BATCH) || 25);
-// v0.42.7: wall-clock budget for one `extract --stale` invocation (default
-// 30 min). `--catch-up` removes the cap (loops until 0 stale). Mirrors
-// embedAllStale's time-budget shape. Exported so the #2849 deferred-sweep
-// submitters (sync's size-gate defer branch + the jobs continuation chain)
-// derive their job timeout_ms from the SAME budget instead of hardcoding.
-export const STALE_TIME_BUDGET_MS = Math.max(1000, Number(process.env.GBRAIN_EXTRACT_TIME_BUDGET_MS) || 30 * 60 * 1000);
+// v0.42.7: wall-clock budget for one `extract --stale` invocation (default 30 min; `--catch-up` removes it). It lives
+// with the shared extraction-lag read (#6803) so doctor's and the sync nudge's estimates use it; re-exported for the
+// #2849 deferred-sweep submitters, which derive their job timeout_ms from it.
+export { STALE_TIME_BUDGET_MS };
/**
* v0.42.7 (#1696): best-effort extraction stamp for the source-correct write
@@ -879,11 +879,11 @@ Incremental sweep:
${ATTENDANCE_REPAIR_HELP}
gbrain extract --stale [--source-id <id>] [--include-frontmatter]
[--catch-up] [--dry-run] [--json]
- Re-extract links + timeline only for stale pages, then run the mention
- pass: refresh entity pages' declared aliases and title subjects and link
- every page that names an entity (link_source='mentions'). DB-source;
- safe to cron. --catch-up loops past the 30-minute budget until none
- remain. Off: gbrain config set mentions.auto_link false.
+ Re-extract links + timeline for stale pages, then the mention pass (entity
+ aliases and title subjects; link_source='mentions'; off: gbrain config set
+ mentions.auto_link false). DB-source; safe to cron; 30 min per run, the next
+ resumes; --catch-up runs until none remain. Scope with --source-id (--source
+ is fs|db). Done when --dry-run --json reports actionable 0 and mention_due 0.
Inspection:
gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]
@@ -962,15 +962,8 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?
// works with no subcommand (and `gbrain extract all --stale` too). DB-source
// only — reads page content from the DB so it runs on checkout-less brains.
if (args.includes('--stale')) {
- const sIdx = args.indexOf('--source');
- const src = (sIdx >= 0 && sIdx + 1 < args.length) ? args[sIdx + 1] : 'db';
- if (src === 'fs') {
- console.error(
- `extract --stale is DB-source only (reads page content from the database\n` +
- `so it works on checkout-less brains). Drop '--source fs' or pass '--source db'.`,
- );
- process.exit(1);
- }
+ // #6803 (D2): --source fs|<id> was refused before connecting (extract-stale-options.ts); --source db is ambiguous only when a source is named db.
+ await assertStaleSourceModeUnambiguous(engine, args);
const sidIdx = args.indexOf('--source-id');
const staleSourceId = (sidIdx >= 0 && sidIdx + 1 < args.length) ? args[sidIdx + 1] : undefined;
await extractStaleFromDB(engine, {
@@ -2112,11 +2105,11 @@ export async function extractStaleFromDB(
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
const totalStale = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
if (dryRun) {
- const m = await previewMentionPass(engine, sourceIdFilter);
+ const m = await previewMentionPass(engine, sourceIdFilter), counts = opts.quiet ? null : await staleExtractionCounts(engine, sourceIdFilter);
if (jsonMode && !opts.quiet) {
- process.stdout.write(JSON.stringify({ action: 'extract_stale_dry_run', stale_pages: totalStale, mention_due_pages: m.due, mention_last_pass_at: m.last_pass_at }) + '\n');
+ process.stdout.write(JSON.stringify({ action: 'extract_stale_dry_run', stale_pages: totalStale, mention_due_pages: m.due, mention_last_pass_at: m.last_pass_at, ...counts }) + '\n');
} else {
- log(`(dry run) ${totalStale} page(s) need link/timeline extraction; ${m.due} page(s) need a mention pass (last pass: ${m.last_pass_at ?? 'never'}). Run without --dry-run to extract.`);
+ log(`(dry run) ${totalStale} page(s) need link/timeline extraction; ${m.due} page(s) need a mention pass (last pass: ${m.last_pass_at ?? 'never'}). Run without --dry-run to extract.${counts ? `\n${formatStaleCounts(counts)}` : ''}`);
}
return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: totalStale + m.due };
}
@@ -2124,8 +2117,8 @@ export async function extractStaleFromDB(
// canonical timeline rows and the watermark publish on the one managed path
// (the mention pass runs inside it).
if (await managedPersistenceEnabled(engine)) {
- const { extractManagedStaleLinks, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');
- const r = await extractManagedStaleLinks(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { timeBudgetMs }) });
+ const { runManagedStaleExtraction, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');
+ const r = await runManagedStaleExtraction(engine, { sourceId: sourceIdFilter, catchUp, timeBudgetMs, counts: !opts.quiet });
if (!jsonMode) log(formatManagedStaleExtraction(r, false, false));
else if (!opts.quiet) process.stdout.write(formatManagedStaleExtraction(r, false, true) + '\n');
return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining + (r.mentions?.remaining ?? 0),
@@ -2314,6 +2307,7 @@ export async function extractStaleFromDB(
if (packUnavailable) throw new Error('Cannot extract links: active schema pack is unavailable.');
const mentions = await runMentionPass(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { deadline: startMs + timeBudgetMs }) });
const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs }) + mentions.remaining;
+ const counts = opts.quiet ? null : await staleExtractionCounts(engine, sourceIdFilter);
if (!jsonMode) {
const mentionLine = formatMentionSummary(mentions);
@@ -2332,13 +2326,14 @@ export async function extractStaleFromDB(
if (budgetHit && staleRemaining > 0) {
log(`Time budget reached — ${staleRemaining} page(s) still stale. Re-run 'gbrain extract --stale' (or pass --catch-up) to continue.`);
}
+ if (counts) log(formatStaleCounts(counts));
} else if (!opts.quiet) {
process.stdout.write(JSON.stringify({
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...(skippedChanged ? { skipped_changed: skippedChanged } : {}),
- ...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}), ...mentionJsonFields(mentions),
+ ...(skippedConcurrentWrite ? { skipped_concurrent_write: skippedConcurrentWrite } : {}), ...mentionJsonFields(mentions), ...counts,
}) + '\n');
}
return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index daf4046d3c..fd25ccbaef 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -75,9 +75,11 @@ export function printManagedSyncNotes(result: SyncResult, write: (line: string)
const skips = result.legacySkips;
if (skips?.contextualMode) write(` ${skips.contextualMode} legacy file(s) skipped because they parse to the same page but have no contextual retrieval mode, which a skipped import cannot stamp; to stamp it: gbrain repair contextual-mode`);
if (skips?.canonicalBytes) write(` ${skips.canonicalBytes} legacy file(s) skipped because they parse to the same page but their bytes are not what gbrain reads back (for example, not valid UTF-8); re-save them as UTF-8 to publish them exactly.`);
+ // #6803 (D4): the count is this sync's imports the tail left underived, never the source's whole stale backlog.
const links = result.links;
- if (links && (links.created || links.removed || links.remaining)) {
+ const underived = result.tail?.underived ?? 0;
+ if (links && (links.created || links.removed || underived)) {
write(` Links: ${links.created} created, ${links.removed} removed across ${links.pages} page(s)` +
- (links.remaining ? `; ${links.remaining} page(s) still owe extraction — run 'gbrain extract --stale'.` : '.'));
+ (underived ? `; ${underived} page(s) this sync imported still owe extraction — run 'gbrain extract --stale'.` : '.'));
}
}
diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.ts
index e635a82b23..9707ea03f5 100644
--- a/src/commands/sync/report.ts
+++ b/src/commands/sync/report.ts
@@ -50,37 +50,26 @@ export async function maybeBackupCoverageRefresh(engine: BrainEngine): Promise<v
}
/**
- * v0.42.7 (#1696): one-line end-of-sync nudge when the brain (or a source)
- * carries a meaningful link/timeline extraction backlog. Reuses the same warn
- * threshold (GBRAIN_EXTRACTION_LAG_WARN_PCT, default 20%) the doctor check uses
- * so the nudge fires iff doctor would warn — one source of truth. Always
- * stderr (never stdout — keeps `--json` clean), suppressible via
+ * v0.42.7 (#1696), #6803 (D1): end-of-sync nudge when the brain (or a source)
+ * carries a link/timeline extraction backlog. It IS doctor's
+ * `links_extraction_lag` (one statement and verdict, core/extraction-lag.ts),
+ * so it prints iff doctor would warn (attendance-blocked pages excluded), and
+ * names both routes: plain `gbrain extract --stale` (30 min per run, resumes)
+ * and `--catch-up` (finishes in one run), with an estimate at its stated basis.
+ * Always stderr (never stdout — keeps `--json` clean), suppressible via
* GBRAIN_SYNC_NO_EXTRACT_NUDGE, best-effort (never throws). Source-prefix-aware
* via serr when called inside a withSourcePrefix scope.
*/
export async function maybeExtractionNudge(engine: BrainEngine, sourceId?: string): Promise<void> {
if (process.env.GBRAIN_SYNC_NO_EXTRACT_NUDGE) return;
try {
- const { effectiveLinkExtractorWatermark } = await import('../../core/link-extraction-watermark.ts');
- // D3/C4: resolve the warn threshold + vacuous-skip floor through the SAME
- // helpers the doctor check uses (dynamic import keeps doctor.ts off sync's
- // eager-load path) so "the nudge fires iff doctor would warn" can't drift.
- const { _resolveEnvNumber, EXTRACTION_LAG_WARN_PCT_DEFAULT, EXTRACTION_LAG_MIN_PAGES } = await import('../doctor.ts');
- const totalRows = await engine.executeRaw<{ count: number }>(
- sourceId
- ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`
- : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,
- sourceId ? [sourceId] : [],
- );
- const total = Number(totalRows[0]?.count ?? 0);
- // Match doctor's predicate EXACTLY (C4): skip tiny brains only when NOT
- // source-scoped (a small explicit source IS assessed, like orphan_ratio).
- if (total < EXTRACTION_LAG_MIN_PAGES && !sourceId) return;
- const stale = await engine.countStalePagesForExtraction({ sourceId, versionTs: await effectiveLinkExtractorWatermark(engine) });
- const warnPct = _resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
- if ((stale / total) * 100 > warnPct) {
- serr(`[sync] ${stale} page(s) have un-extracted edges — run 'gbrain extract --stale'`);
- }
+ const { checkLinksExtractionLag } = await import('../doctor.ts');
+ const check = await checkLinksExtractionLag(engine, { sourceId });
+ const d = check.details as { total: number; stale: number; attendance_blocked: number; mention_due: number | null; mention_last_pass_at: string | null; routes?: unknown } | undefined;
+ if (check.status === 'ok' || !d?.routes) return;
+ const { extractionNudgeLines } = await import('../../core/extraction-lag.ts');
+ const lag = { total: d.total, actionable: d.stale, attendance_blocked: d.attendance_blocked, mention_due: d.mention_due, mention_last_pass_at: d.mention_last_pass_at };
+ for (const line of extractionNudgeLines(lag, { sourceId })) serr(line);
} catch { /* nudge is best-effort — never block sync on it */ }
}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 83ffa4ae98..902403f883 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -143,7 +143,8 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,
// src/core/fix-routing.ts): '--brain' when the command opens its brain (not a
// pre-connect command, or its code reads the global brain option); '--source'
-// when the command-table record declares routes_source (consumption-checked).
+// (or the declared '--source-id') when the command-table record declares
+// routes_source (consumption-checked).
export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'advisor': ['--brain'],
'agent': ['--brain'],
@@ -178,7 +179,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'enrich': ['--brain', '--source'],
'eval': ['--brain'],
'export': ['--brain', '--source'],
- 'extract': ['--brain', '--source'],
+ 'extract': ['--brain', '--source-id'],
'extract-conversation-facts': ['--brain'],
'facts': ['--brain', '--source'],
'features': ['--brain'],
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index b4087129a6..3cbead82e3 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -727,6 +727,19 @@ function stalePagesWhere(opts?: { sourceId?: string; versionTs?: string; attenda
return sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}`;
}
+/**
+ * #6803 (D1): the live page count, the stale count without attendance-blocked pages and the attendance-blocked count
+ * in one statement, so doctor's `links_extraction_lag` and the sync nudge share one predicate and one threshold input.
+ * `attendance: false` is the pre-v180 shape (no marker column: nothing is attendance-blocked).
+ */
+export function extractionLagStatement(opts: { sourceId?: string; versionTs: string; attendance: boolean }): { text: string; params: unknown[] } {
+ const source = opts.sourceId ? sqlFragment` AND source_id = ${opts.sourceId}` : sqlFragment``;
+ const stale = stalePagesWhere({ versionTs: opts.versionTs, ...(opts.attendance ? { attendance: 'exclude' as const } : {}) });
+ const blocked = opts.attendance ? sqlFragment`count(*) FILTER (WHERE ${stalePagesWhere({ versionTs: opts.versionTs, attendance: 'blocked' })})::int` : sqlFragment`0`;
+ return renderFragment(sqlFragment`SELECT count(*)::int AS total, count(*) FILTER (WHERE ${stale})::int AS stale, ${blocked} AS attendance_blocked
+ FROM pages WHERE deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))}${source}`);
+}
+
export async function countStalePagesForExtraction(exec: ScopedRead, opts?: { sourceId?: string; versionTs?: string; attendance?: 'exclude' | 'blocked' }): Promise<number> {
const { text, params } = renderFragment(sqlFragment`SELECT count(*)::int AS count FROM pages WHERE ${stalePagesWhere(opts)}`);
const { rows } = await exec.unsafe<{ count?: number }>(text, params);
diff --git a/src/core/extraction-lag.ts b/src/core/extraction-lag.ts
new file mode 100644
index 0000000000..794976568b
--- /dev/null
+++ b/src/core/extraction-lag.ts
@@ -0,0 +1,148 @@
+/**
+ * #6803 (D1, D3): the extraction backlog as doctor's `links_extraction_lag`, the end-of-sync nudge and
+ * `gbrain extract --stale` all report it. One statement reads the live page count, the actionable stale count
+ * (attendance-blocked pages excluded: extraction cannot clear them) and the attendance-blocked count under a short
+ * statement deadline; the mention-due read runs only when the mention pass is enabled. One verdict decides whether
+ * doctor warns and the nudge prints, and one builder renders the default fix (plain `gbrain extract --stale`, the
+ * cron default) plus the decision between both routes, with an estimate stated at its basis.
+ */
+import type { BrainEngine } from './engine.ts';
+import { AGENT_TOOL_LIMIT_MS, type Action, type Decision } from './agent-output.ts';
+import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';
+import { extractionLagStatement } from './engine-sql/pages.ts';
+import { effectiveLinkExtractorWatermark } from './link-extraction-watermark.ts';
+import { previewMentionPass } from './mentions/stale.ts';
+import { readMentionPolicy } from './mentions/policy.ts';
+import { resolveEnvNumber, warnOnceForEnv } from './env-number.ts';
+import { isMissingSchemaObject } from './utils.ts';
+
+/** Warn threshold (percent of live pages actionable-stale); `GBRAIN_EXTRACTION_LAG_WARN_PCT` overrides it. */
+export const EXTRACTION_LAG_WARN_PCT_DEFAULT = 20;
+/** Below this many live pages a brain-wide (unscoped) read is too small to grade. */
+export const EXTRACTION_LAG_MIN_PAGES = 100;
+/**
+ * Wall-clock budget of one plain `gbrain extract --stale` run (default 30 min); `--catch-up` removes it.
+ * The deferred-sweep submitters derive their job timeout from it.
+ */
+export const STALE_TIME_BUDGET_MS = Math.max(1000, Number(process.env.GBRAIN_EXTRACT_TIME_BUDGET_MS) || 30 * 60 * 1000);
+/** Measured managed extraction throughput at 10 ms round-trip time (part-6 investigation); the estimates' basis. */
+export const EXTRACTION_PAGES_PER_SECOND = 13.5;
+export const EXTRACTION_ESTIMATE_BASIS = 'estimate at 10 ms RTT; measure your pooler RTT';
+
+export interface ExtractionLag {
+ total: number;
+ /** Stale pages extraction can clear (attendance-blocked excluded). */
+ actionable: number;
+ attendance_blocked: number;
+ /** Pages due for the mention pass; null when the pass is off. */
+ mention_due: number | null;
+ mention_last_pass_at: string | null;
+}
+
+export async function readExtractionLag(engine: BrainEngine, opts: { sourceId?: string; timeoutMs?: number } = {}): Promise<ExtractionLag> {
+ const versionTs = await effectiveLinkExtractorWatermark(engine);
+ const read = async (attendance: boolean) => {
+ const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance });
+ return (await engine.executeRaw<{ total: number; stale: number; attendance_blocked: number }>(text, params, { timeoutMs: opts.timeoutMs ?? 10_000 }))[0];
+ };
+ let row;
+ try { row = await read(true); } catch (e) {
+ if (!isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) throw e;
+ row = await read(false);
+ }
+ const mention = (await readMentionPolicy(engine)).enabled ? await previewMentionPass(engine, opts.sourceId) : null;
+ return { total: Number(row?.total ?? 0), actionable: Number(row?.stale ?? 0), attendance_blocked: Number(row?.attendance_blocked ?? 0),
+ mention_due: mention ? mention.due : null, mention_last_pass_at: mention?.last_pass_at ?? null };
+}
+
+export interface ExtractionLagVerdict { status: 'ok' | 'warn' | 'fail'; skipped: boolean; pct: number; warn_pct: number; fail_pct: number | null }
+
+/** Doctor warns, and the sync nudge prints, exactly when this says warn or fail. */
+export function extractionLagVerdict(lag: Pick<ExtractionLag, 'total' | 'actionable'>, sourceId?: string): ExtractionLagVerdict {
+ const warnPct = resolveEnvNumber('GBRAIN_EXTRACTION_LAG_WARN_PCT', EXTRACTION_LAG_WARN_PCT_DEFAULT, { unit: '%' });
+ // Hard-fail is off unless GBRAIN_EXTRACTION_LAG_FAIL_PCT is set: a just-upgraded brain warns, it never breaks a cron gate.
+ let failPct: number | null = null;
+ const failRaw = process.env.GBRAIN_EXTRACTION_LAG_FAIL_PCT;
+ if (failRaw !== undefined && failRaw !== '') {
+ const n = Number(failRaw);
+ if (Number.isFinite(n) && n > 0) failPct = n;
+ else warnOnceForEnv('GBRAIN_EXTRACTION_LAG_FAIL_PCT', `[gbrain] Ignoring invalid GBRAIN_EXTRACTION_LAG_FAIL_PCT=${failRaw}; hard-fail stays disabled.`);
+ }
+ const skipped = lag.total === 0 || (lag.total < EXTRACTION_LAG_MIN_PAGES && !sourceId);
+ const pct = lag.total ? (lag.actionable / lag.total) * 100 : 0;
+ const status = skipped ? 'ok' : failPct !== null && pct > failPct ? 'fail' : pct > warnPct ? 'warn' : 'ok';
+ return { status, skipped, pct, warn_pct: warnPct, fail_pct: failPct };
+}
+
+function duration(seconds: number): string {
+ if (seconds < 90) return `${Math.max(1, Math.ceil(seconds))} s`;
+ if (seconds < 90 * 60) return `${Math.ceil(seconds / 60)} min`;
+ return `${(seconds / 3600).toFixed(1)} h`;
+}
+
+export interface ExtractionRoute { id: 'plain' | 'catch_up'; argv: string[]; label: string; estimate_seconds: number; runs: number }
+
+/**
+ * The default fix (plain `gbrain extract --stale`: 30 minutes per run, resumes; the cron default), verified by the
+ * scoped dry run, and one decision between both routes. A fix expected to outlast an agent tool call
+ * (`AGENT_TOOL_LIMIT_MS`) is the user's (`host_admin` on a remote brain): `tell_user_to_run`. Option argv are pinned to
+ * the selected brain (the CLI's routing unless given; none on a remote brain); a brain-wide run never gets a source
+ * pinned onto it.
+ */
+export function extractionRoutes(lag: Pick<ExtractionLag, 'actionable'>, opts: { sourceId?: string; remote?: boolean; routing?: FixRouting } = {}): { fix: Action; decision: Decision; routes: ExtractionRoute[] } {
+ const scope = opts.sourceId ? ['--source-id', opts.sourceId] : [];
+ const selected = opts.routing ?? (opts.remote ? undefined : cliRouting());
+ const routing = selected ? { ...(selected.brain ? { brain: selected.brain } : {}), ...(opts.sourceId ? { source: opts.sourceId } : {}) } : undefined;
+ const catchUpSeconds = lag.actionable / EXTRACTION_PAGES_PER_SECOND;
+ const runs = Math.max(1, Math.ceil((catchUpSeconds * 1000) / STALE_TIME_BUDGET_MS));
+ const runMinutes = Math.round(STALE_TIME_BUDGET_MS / 60_000);
+ const long = Math.min(catchUpSeconds * 1000, STALE_TIME_BUDGET_MS) > AGENT_TOOL_LIMIT_MS;
+ const plainArgv = ['gbrain', 'extract', '--stale', ...scope];
+ const catchUpArgv = ['gbrain', 'extract', '--stale', '--catch-up', ...scope];
+ const routes: ExtractionRoute[] = [
+ { id: 'plain', argv: pinRouting(plainArgv, routing), estimate_seconds: Math.ceil(catchUpSeconds), runs,
+ label: `${lag.actionable} page(s): about ${runs} run(s) of up to ${runMinutes} min (${EXTRACTION_ESTIMATE_BASIS}); each run resumes where the last stopped (the cron default)` },
+ { id: 'catch_up', argv: pinRouting(catchUpArgv, routing), estimate_seconds: Math.ceil(catchUpSeconds), runs: 1,
+ label: `${lag.actionable} page(s): about ${duration(catchUpSeconds)} in one run (${EXTRACTION_ESTIMATE_BASIS}); finishes, safe to interrupt, each page commits alone` },
+ ];
+ const fix: Action = {
+ argv: plainArgv, consent: [], actor: long ? (opts.remote ? 'host_admin' : 'user') : 'agent', requires_exclusive: false,
+ why: `Derives links and timeline entries for ${lag.actionable} stale page(s); each run stops after ${runMinutes} minutes and the next resumes where it stopped; it changes no page content.`,
+ ...(long ? { user_message: `Run on the brain host, in a terminal rather than an agent tool call: ${routes[0]!.argv.join(' ')} (${routes[0]!.label}), or ${routes[1]!.argv.join(' ')} (${routes[1]!.label}).` } : {}),
+ verify: { argv: ['gbrain', 'extract', '--stale', '--dry-run', '--json', ...scope] },
+ docs: 'docs/guides/troubleshooting.md#symptom-table',
+ };
+ const decision: Decision = {
+ id: 'extraction_route', question: 'How should the link-extraction backlog finish?',
+ options: routes.map(route => ({ id: route.id, label: `${route.argv.join(' ')}: ${route.label}`, argv: route.argv })),
+ default: 'plain', default_reason: `Bounded runs fit cron and never hold the brain longer than ${runMinutes} minutes; the catch-up run finishes in one go.`,
+ };
+ return { fix, decision, routes };
+}
+
+/** The end-of-sync nudge's lines: the count doctor reports, then both commands with duration and resume text. */
+export function extractionNudgeLines(lag: ExtractionLag, opts: { sourceId?: string; routing?: FixRouting } = {}): string[] {
+ const { fix, routes } = extractionRoutes(lag, opts);
+ const blocked = lag.attendance_blocked ? `; ${lag.attendance_blocked} more wait on unresolved attendees and are not counted` : '';
+ const mentions = lag.mention_due ? `; ${lag.mention_due} page(s) await the mention pass` : '';
+ const where = fix.actor === 'agent' ? '' : ' Run it on the brain host, not inside an agent tool call.';
+ return [`[sync] ${lag.actionable} page(s) have un-extracted edges (doctor: links_extraction_lag${blocked}${mentions}). Two ways to finish:${where}`,
+ ...routes.map(route => `[sync] ${route.argv.join(' ')} — ${route.label}`)];
+}
+
+export interface StaleExtractionCounts { actionable: number; attendance_blocked: number; mention_due: number | null; complete: boolean }
+
+/** The terminal counts `extract --stale` reports: done when `actionable` is 0 and, with mentions on, `mention_due` is 0. */
+export async function staleExtractionCounts(engine: BrainEngine, sourceId?: string): Promise<StaleExtractionCounts> {
+ const lag = await readExtractionLag(engine, { sourceId });
+ return { actionable: lag.actionable, attendance_blocked: lag.attendance_blocked, mention_due: lag.mention_due,
+ complete: lag.actionable === 0 && (lag.mention_due ?? 0) === 0 };
+}
+
+/** One human line for the counts; raw totals elsewhere in the report include blocked pages and are not a completion signal. */
+export function formatStaleCounts(c: StaleExtractionCounts): string {
+ return `Actionable: ${c.actionable} page(s) still need link/timeline extraction` +
+ (c.attendance_blocked ? `; ${c.attendance_blocked} attendance-blocked page(s) wait on unresolved attendees (extraction cannot clear them)` : '') +
+ (c.mention_due === null ? '' : `; ${c.mention_due} page(s) due for the mention pass`) +
+ (c.complete ? '. Extraction is complete (raw stale totals are not a completion signal).' : '. Raw stale totals include blocked pages; done when actionable is 0' + (c.mention_due === null ? '.' : ' and mention-due is 0.'));
+}
diff --git a/src/core/fix-routing.ts b/src/core/fix-routing.ts
index c762691e7b..80b6f4dd76 100644
--- a/src/core/fix-routing.ts
+++ b/src/core/fix-routing.ts
@@ -33,6 +33,9 @@ export interface FixRouting { brain?: string; source?: string }
const BRAIN_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
const pinnableSource = (s: string) => SOURCE_ID_RE.test(s) || s === ALL_SOURCES;
const SOURCE_SELECTORS = ['--source', '--source-id', '--all-sources', '--sources'];
+/** The flag a command's target source is routed through: `--source`, or `--source-id` where `--source` selects a mode (extract: fs|db). */
+type SourceFlag = '--source' | '--source-id';
+const SOURCE_FLAGS: readonly SourceFlag[] = ['--source', '--source-id'];
const opCommands = new Map<string, { ownsSource: boolean; scopesSourceId: boolean }>();
@@ -55,15 +58,16 @@ export function registerOpRoutes(ops: Iterable<{ params: Record<string, unknown>
* pinned there, and `--source` only where a thin client can send it (an op with a
* `source_id` scope, or a CLI command the brain host's operator runs).
*/
-export function routingFlagsFor(command: string, opts: { remote?: boolean } = {}): { brain: boolean; source: boolean } {
+export function routingFlagsFor(command: string, opts: { remote?: boolean } = {}): { brain: boolean; source: SourceFlag | false } {
const accepted = CLI_FLAG_REGISTRY[command];
if (accepted) {
const routed = CLI_ROUTING_FLAGS[command] ?? [];
- return { brain: !opts.remote && accepted.includes('--brain') && routed.includes('--brain'), source: accepted.includes('--source') && routed.includes('--source') };
+ const source = SOURCE_FLAGS.find(flag => accepted.includes(flag) && routed.includes(flag)) ?? false;
+ return { brain: !opts.remote && accepted.includes('--brain') && routed.includes('--brain'), source };
}
const op = opCommands.get(command);
if (!op) return { brain: false, source: false };
- return { brain: !opts.remote, source: !op.ownsSource && (!opts.remote || op.scopesSourceId) };
+ return { brain: !opts.remote, source: !op.ownsSource && (!opts.remote || op.scopesSourceId) ? '--source' : false };
}
const hasFlag = (head: readonly string[], flag: string) => head.some(a => a === flag || a.startsWith(`${flag}=`));
@@ -76,8 +80,11 @@ export function pinRouting(argv: readonly string[], routing: FixRouting | undefi
const head = end === -1 ? argv : argv.slice(0, end);
const add: string[] = [];
if (flags.brain && routing.brain && BRAIN_ID_RE.test(routing.brain) && !hasFlag(head, '--brain')) add.push('--brain', routing.brain);
- if (flags.source && routing.source && pinnableSource(routing.source) && !SOURCE_SELECTORS.some(f => hasFlag(head, f))) {
- add.push('--source', routing.source);
+ // Under `--source-id` a `--source` already present is that command's mode selector, not a source choice.
+ const selectors = flags.source === '--source-id' ? SOURCE_SELECTORS.filter(f => f !== '--source') : SOURCE_SELECTORS;
+ const pinnable = flags.source === '--source-id' ? SOURCE_ID_RE.test(routing.source ?? '') : pinnableSource(routing.source ?? '');
+ if (flags.source && routing.source && pinnable && !selectors.some(f => hasFlag(head, f))) {
+ add.push(flags.source, routing.source);
}
if (add.length === 0) return [...argv];
return end === -1 ? [...argv, ...add] : [...argv.slice(0, end), ...add, ...argv.slice(end)];
diff --git a/src/core/link-extraction-watermark.ts b/src/core/link-extraction-watermark.ts
index 9812766e98..85fff35c24 100644
--- a/src/core/link-extraction-watermark.ts
+++ b/src/core/link-extraction-watermark.ts
@@ -13,6 +13,18 @@
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
import { LINK_EXTRACTION_GENERATION_KEY } from './line-grammar.ts';
+/**
+ * #6803 (D5): every `LINK_EXTRACTOR_VERSION_TS` value carries its release note, written with the code and copied into
+ * the CHANGELOG at ship. A bump re-stales every page brain-wide, and a plain `gbrain extract --stale` drains a large
+ * brain only a few percent per 30-minute run, so the note names the re-extraction and the command that finishes it.
+ * Pinned by test/link-extractor-bump-notes.test.ts.
+ */
+export const EXTRACTOR_BUMP_NOTES: Readonly<Record<string, string>> = {
+ '2026-10-08T00:00:00Z': 'Link typing picks up the held-out-confirmed Q2 units (U1, U3, U4), so every page re-extracts its links once, brain-wide (zero model calls). ' +
+ 'Plain `gbrain extract --stale` drains it 30 minutes per run and resumes (the cron default); `gbrain extract --stale --catch-up` finishes it in one run on the brain host ' +
+ '(about 6 h at 290K pages and 10 ms RTT; each page commits alone, safe to interrupt). `gbrain extract --stale --dry-run --json` reports `actionable: 0` when done.',
+};
+
/** The later of two ISO-8601 instants, returned as written (a microsecond stamp keeps its precision). */
export function laterInstant(a: string, b: string | null | undefined): string {
if (!b) return a;
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index c223b1a701..e8a9aae5d4 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -103,6 +103,7 @@ export { parseInlineCitationTimelineEntries, type InlineCitationTimelineCandidat
// 2026-10-05T03: typed relation lines (core/line-grammar.ts) state their link's type; a per-edge verb that
// belongs to another link in the window no longer types this one; "joined [X] as <role>" reads as works_at.
// 2026-10-08: held-out-confirmed Q2 units U1, U3, U4 (core/link-typing-units.ts). Re-extract so pages pick these up.
+// A bump needs its entry in EXTRACTOR_BUMP_NOTES (link-extraction-watermark.ts), copied into the CHANGELOG at ship.
export const LINK_EXTRACTOR_VERSION_TS = '2026-10-08T00:00:00Z';
// ─── Entity references ──────────────────────────────────────────
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 17afb8b818..eb88e02358 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -171,13 +171,16 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
...(waitDrainMs !== undefined ? { waitDrainMs } : {}), ...(fetchTimeoutMs !== undefined ? { fetchTimeoutMs } : {}) }) };
}
if (operation === 'writer_extract_stale') {
- keys(params, ['source_id', 'dry_run']);
+ keys(params, ['source_id', 'dry_run', 'catch_up', 'source_mode']);
const writer = currentVerifiedLocalWriter();
if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Stale extraction requires a trusted CLI registration.');
const { managedPersistenceEnabled } = await import('./ownership.ts');
if (!await managedPersistenceEnabled(engine)) throw new OperationError('writer_coordinator_required', 'Owner-delegated stale extraction requires activated managed persistence.', WRITER_INSPECTION_HINT);
+ const sourceId = params.source_id === undefined ? undefined : source(params.source_id);
+ // #6803 (D2): the CLI validated --source before the hand-off; only the owner can see whether a source is named db.
+ if (params.source_mode === 'db') await (await import('../../commands/extract-stale-options.ts')).assertStaleSourceModeUnambiguous(engine, ['--stale', '--source', 'db', ...(sourceId ? ['--source-id', sourceId] : [])]);
return { ...await (await import('./links-maintenance.ts')).runManagedStaleExtraction(engine,
- { sourceId: params.source_id === undefined ? undefined : source(params.source_id), dryRun: params.dry_run === true }) };
+ { sourceId, dryRun: params.dry_run === true, catchUp: params.catch_up === true }) };
}
if (operation === 'writer_reindex_code') return (await import('./reindex-administration.ts')).runAuthenticatedCodeReindex(engine, params);
if (operation === 'writer_embed_facts') return (await import('./embed-facts-administration.ts')).runAuthenticatedFactEmbedding(engine, params, config);
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index b4c0a38045..261d95c13d 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -10,39 +10,52 @@ 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';
+import { STALE_TIME_BUDGET_MS, formatStaleCounts, staleExtractionCounts, type StaleExtractionCounts } from '../extraction-lag.ts';
export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number;
/** Pages skipped for a named reason (`page_body_segmented`: a segmented body over the 24 MiB single-string ceiling; it stays stale). */
skipped_reasons?: Record<string, number>;
/** The mention pass (absent when the caller ran links only, as sync does). */
- mentions?: MentionPassResult; mention_due?: number; mention_last_pass_at?: string | null; }
+ mentions?: MentionPassResult; mention_due?: number; mention_last_pass_at?: string | null;
+ /** #6803 (D3): the terminal counts (`gbrain extract --stale` only; sync's tail does not read them). */
+ counts?: StaleExtractionCounts; }
-/** `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner. */
-export async function runManagedStaleExtraction(engine: BrainEngine, opts: { sourceId?: string; dryRun?: boolean }): Promise<ManagedLinkExtraction> {
- if (!opts.dryRun) return extractManagedStaleLinks(engine, { sourceId: opts.sourceId });
+/**
+ * `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner: a plain run stops at the
+ * `STALE_TIME_BUDGET_MS` budget and the next resumes, `catchUp` runs until nothing is stale (#6803 D2).
+ */
+export async function runManagedStaleExtraction(engine: BrainEngine,
+ opts: { sourceId?: string; dryRun?: boolean; catchUp?: boolean; timeBudgetMs?: number; counts?: boolean }): Promise<ManagedLinkExtraction> {
+ const counts = async () => opts.counts === false ? {} : { counts: await staleExtractionCounts(engine, opts.sourceId) };
+ if (!opts.dryRun) {
+ const result = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, ...(opts.catchUp ? {} : { timeBudgetMs: opts.timeBudgetMs ?? STALE_TIME_BUDGET_MS }) });
+ return { ...result, ...await counts() };
+ }
const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: await effectiveLinkExtractorWatermark(engine) });
const m = await previewMentionPass(engine, opts.sourceId);
- return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining, mention_due: m.due, mention_last_pass_at: m.last_pass_at };
+ return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining, mention_due: m.due, mention_last_pass_at: m.last_pass_at, ...await counts() };
}
/** The `extract --stale` report for a managed brain, in the same text and JSON shapes as the unmanaged sweep. */
export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryRun: boolean, json: boolean): string {
+ const counts = result.counts;
if (json) {
- return JSON.stringify(dryRun ? { action: 'extract_stale_dry_run', stale_pages: result.remaining, mention_due_pages: result.mention_due ?? 0,
+ return JSON.stringify({ ...(dryRun ? { action: 'extract_stale_dry_run', stale_pages: result.remaining, mention_due_pages: result.mention_due ?? 0,
mention_last_pass_at: result.mention_last_pass_at ?? null } : {
action: 'extract_stale_done', links_created: result.created, links_removed: result.removed, timeline_created: result.timeline,
pages_processed: result.pages, stale_remaining: result.remaining + (result.mentions?.remaining ?? 0),
...(result.skipped ? { skipped_changed: result.skipped } : {}), ...(result.mentions ? mentionJsonFields(result.mentions) : {}),
- });
+ }), ...(counts ?? {}) });
}
+ const countsLine = counts ? `\n${formatStaleCounts(counts)}` : '';
if (dryRun) {
return `(dry run) ${result.remaining} page(s) need link/timeline extraction; ${result.mention_due ?? 0} page(s) need a mention pass ` +
- `(last pass: ${result.mention_last_pass_at ?? 'never'}). Run without --dry-run to extract.`;
+ `(last pass: ${result.mention_last_pass_at ?? 'never'}). Run without --dry-run to extract.${countsLine}`;
}
const mentionLine = result.mentions ? formatMentionSummary(result.mentions) : null;
return `Extract --stale: ${result.created} link(s) created, ${result.removed} removed, ${result.timeline} timeline entr(ies) from ${result.pages} page(s).` +
(result.skipped ? ` Skipped ${result.skipped} page(s) edited during extraction or with unresolved attendance; they stay stale.` : '') +
- (result.remaining ? ` ${result.remaining} page(s) remain stale.` : '') + (mentionLine ? `\n${mentionLine}` : '');
+ (result.remaining ? ` ${result.remaining} page(s) remain stale (raw total).` : '') + (mentionLine ? `\n${mentionLine}` : '') + countsLine;
}
/** #5984: pages a managed link extraction derives at once on Postgres. */
diff --git a/src/core/persistence/sync-tail.ts b/src/core/persistence/sync-tail.ts
index 1fcac0efe3..ae0ec75409 100644
--- a/src/core/persistence/sync-tail.ts
+++ b/src/core/persistence/sync-tail.ts
@@ -31,6 +31,8 @@ export interface SyncTailReport {
runs: number;
statistics: 'refreshed' | 'not_needed' | 'failed';
links?: ManagedLinkExtraction;
+ /** Pages this run imported that the tail's link extraction left underived (present when links ran); they stay stale. */
+ underived?: number;
notice?: Notice;
}
@@ -69,7 +71,7 @@ export async function runSyncTail(engine: BrainEngine, sourceId: string, opts: {
const underived = links ? Math.max(0, slugs.length - links.pages - links.skipped) : 0;
const truncated = underived > 0 && (Date.now() >= deadlineAt || links!.pages + links!.skipped >= SYNC_TAIL_MAX_PAGES);
const status: SyncTailReport['status'] = failure !== null ? 'failed' : !ran ? 'deferred' : truncated ? 'truncated' : statistics === 'failed' ? 'degraded' : 'done';
- return { status, runs: owed.length, statistics, ...(links ? { links } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, underived, failure }) }) };
+ return { status, runs: owed.length, statistics, ...(links ? { links, underived } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, underived, failure }) }) };
}
function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'], 'done'>, d: { statistics: SyncTailReport['statistics']; underived?: number; failure: string | null }): Notice {
diff --git a/test/e2e/extraction-nudge-6803-postgres.test.ts b/test/e2e/extraction-nudge-6803-postgres.test.ts
new file mode 100644
index 0000000000..8efac5ed52
--- /dev/null
+++ b/test/e2e/extraction-nudge-6803-postgres.test.ts
@@ -0,0 +1,4 @@
+/** #6803 part 6 on Postgres: the PGLite suite's DB-backed asserts (shared FILTER statement, refusals, JSON split). */
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../extraction-nudge-6803.test.ts'));
diff --git a/test/embed-facts-delegate.test.ts b/test/embed-facts-delegate.test.ts
index cbb916fd5d..4a07ed83e0 100644
--- a/test/embed-facts-delegate.test.ts
+++ b/test/embed-facts-delegate.test.ts
@@ -8,7 +8,9 @@ describe('owner-delegated CLI refusals name their own next step', () => {
test('every funnel call site carries a site-specific suggestion', () => {
expectFunnelSuggestions('src/commands/embed-facts-delegate.ts', 'invalid', 4);
expectFunnelSuggestions('src/core/embed-facts-options.ts', 'invalid', 6);
- expectFunnelSuggestions('src/commands/extract-stale-delegate.ts', 'invalid', 3);
+ // #6803 (D2): the --source refusal moved from the owner delegate to the validator both dispatch paths share.
+ expectFunnelSuggestions('src/commands/extract-stale-delegate.ts', 'invalid', 2);
+ expectFunnelSuggestions('src/commands/extract-stale-options.ts', 'invalid', 4);
expectFunnelSuggestions('src/commands/sync-persistence-delegate.ts', 'invalid', 3);
});
diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.ts
index 24da0a44b0..42e975ab2a 100644
--- a/test/extract-stale.test.ts
+++ b/test/extract-stale.test.ts
@@ -387,21 +387,11 @@ describe('gbrain extract --stale', () => {
});
test('--source fs is rejected (DB-source only)', async () => {
- const origErr = console.error;
- const origExit = process.exit;
- let exited = false; let msg = '';
- console.error = (m?: unknown) => { msg += String(m); };
- process.exit = ((_code?: number) => { exited = true; throw new Error('__exit__'); }) as unknown as typeof process.exit;
- try {
- await runExtract(engine, ['--stale', '--source', 'fs']);
- } catch (e) {
- if ((e as Error).message !== '__exit__') throw e;
- } finally {
- console.error = origErr;
- process.exit = origExit;
- }
- expect(exited).toBe(true);
- expect(msg).toContain('DB-source only');
+ // #6803 (D2): the refusal is a typed invalid_params (exit 2) instead of a bare process.exit(1).
+ let refusal: unknown;
+ try { await runExtract(engine, ['--stale', '--source', 'fs']); } catch (e) { refusal = e; }
+ expect((refusal as { code?: string }).code).toBe('invalid_params');
+ expect((refusal as Error).message).toContain('DB-source only');
});
// ─── #2576 bug 1: --stale must run the same resolver passes as
diff --git a/test/extraction-nudge-6803.test.ts b/test/extraction-nudge-6803.test.ts
new file mode 100644
index 0000000000..3dc7a54ca5
--- /dev/null
+++ b/test/extraction-nudge-6803.test.ts
@@ -0,0 +1,195 @@
+/**
+ * #6803 part 6: the extraction nudge matches doctor and names the command that finishes.
+ *
+ * Protects: doctor's links_extraction_lag and the end-of-sync nudge share one predicate (attendance-blocked pages
+ * excluded) and one threshold; the warn carries a default fix (plain \`gbrain extract --stale\`) plus both routes with an
+ * estimate, and a fix expected to outlast an agent tool call renders tell_user_to_run; extract's routing flag is
+ * --source-id, so rendered fixes never pin \`--source <id>\` (extract's fs|db mode selector); \`extract --stale --source <id>\`
+ * refuses with invalid_params instead of running brain-wide; \`--source db\` is ambiguous when a source is named db;
+ * \`extract --stale\` JSON splits actionable / attendance_blocked / mention_due; the per-source sync line counts only the
+ * sync's underived imports.
+ * Seams: none. PGLite always, Postgres when DATABASE_URL is set (test/e2e/extraction-nudge-6803-postgres.test.ts).
+ */
+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 type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { checkLinksExtractionLag } from '../src/commands/doctor.ts';
+import { maybeExtractionNudge } from '../src/commands/sync/report.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { printManagedSyncNotes } from '../src/commands/sync-diagnostics.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+import { cliRenderContext, renderAction, type Action } from '../src/core/agent-output.ts';
+import { pinRouting } from '../src/core/fix-routing.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+async function captured<T>(fn: () => Promise<T>): Promise<{ result?: T; error?: unknown; stdout: string; stderr: string }> {
+ const out: string[] = [], err: string[] = [];
+ const orig = { log: console.log, error: console.error, warn: console.warn, write: process.stdout.write.bind(process.stdout) };
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ console.warn = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ process.stdout.write = ((chunk: unknown) => { out.push(String(chunk)); return true; }) as typeof process.stdout.write;
+ try { return { result: await fn(), stdout: out.join('\n'), stderr: err.join('\n') }; }
+ catch (error) { return { error, stdout: out.join('\n'), stderr: err.join('\n') }; }
+ finally { console.log = orig.log; console.error = orig.error; console.warn = orig.warn; process.stdout.write = orig.write; }
+}
+
+const teambrain = { brain: 'teambrain', source: 'wiki' };
+const cli = (routing?: { brain?: string; source?: string }) => cliRenderContext({ routing });
+
+for (const backend of testBackends()) {
+ describe(`${backend}: #6803 extraction lag, nudge and extract --stale`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engine = pg.engine; close = pg.close;
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({}); await pglite.initSchema();
+ engine = pglite; close = () => pglite.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close(); }, 60_000);
+ beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
+ });
+
+ async function seed(n: number, opts: { prefix?: string; sourceId?: string; blocked?: boolean; fresh?: boolean } = {}): Promise<void> {
+ const prefix = opts.prefix ?? 'p', sourceId = opts.sourceId ?? 'default';
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at)
+ SELECT $1 || '/' || g, $2, 'concept', 'T' || g, '', '', '{}'::jsonb, $1 || 'h' || g, now() - interval '1 day', now() - interval '1 day'
+ FROM generate_series(1, $3::int) g`, [prefix, sourceId, n]);
+ if (opts.blocked) await engine.executeRaw(`UPDATE pages SET links_attendance_blocked_revision = knowledge_revision WHERE slug LIKE $1 || '/%'`, [prefix]);
+ if (opts.fresh) await engine.executeRaw(`UPDATE pages SET links_extracted_at = now() WHERE slug LIKE $1 || '/%'`, [prefix]);
+ }
+
+ test('an attendance-blocked majority: doctor ok and the sync nudge silent', async () => {
+ await seed(100, { prefix: 'm', blocked: true });
+ await seed(20, { prefix: 'p', fresh: true });
+ const check = await checkLinksExtractionLag(engine);
+ expect(check.status).toBe('ok');
+ expect((check.details as Record<string, unknown>).attendance_blocked).toBe(100);
+ const nudge = await captured(() => maybeExtractionNudge(engine));
+ expect(nudge.stderr).not.toContain('un-extracted edges');
+ });
+
+ test('a real backlog: doctor warns with the plain-route fix and both routes; the nudge prints the same count and both commands', async () => {
+ await seed(120);
+ const check = await checkLinksExtractionLag(engine);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain extract --stale');
+ expect(check.message).toContain('gbrain extract --stale --catch-up');
+ const fix = renderAction(check.fix as Action, cli({ brain: 'teambrain' }));
+ expect(fix.argv).toEqual(['gbrain', 'extract', '--stale', '--brain', 'teambrain']);
+ expect(fix.verify?.argv).toEqual(['gbrain', 'extract', '--stale', '--dry-run', '--json', '--brain', 'teambrain']);
+ expect(fix.next).toBe('run');
+ const routes = (check.details as { routes: Array<{ id: string; argv: string[]; label: string }> }).routes;
+ expect(routes.map(r => r.id)).toEqual(['plain', 'catch_up']);
+ expect(routes[1]!.argv).toContain('--catch-up');
+ expect(routes[1]!.label).toContain('estimate at 10 ms RTT; measure your pooler RTT');
+
+ const nudge = await captured(() => maybeExtractionNudge(engine, 'default'));
+ expect(nudge.stderr).toContain('120 page(s) have un-extracted edges');
+ expect(nudge.stderr).toContain('gbrain extract --stale --source-id default');
+ expect(nudge.stderr).toContain('gbrain extract --stale --catch-up --source-id default');
+ expect(nudge.stderr).toContain('each run resumes where the last stopped');
+ expect(nudge.stderr).not.toMatch(/--source default/);
+ });
+
+ test('an estimate over AGENT_TOOL_LIMIT_MS makes the fix the user\'s (tell_user_to_run); host_admin on a remote brain', async () => {
+ await seed(2_000);
+ const check = await checkLinksExtractionLag(engine);
+ expect(check.status).toBe('warn');
+ expect(renderAction(check.fix as Action, cli()).next).toBe('tell_user_to_run');
+ expect((check.fix as Action).actor).toBe('user');
+ expect((check.fix as Action).user_message).toContain('--catch-up');
+ const remote = await checkLinksExtractionLag(engine, { remote: true } as { sourceId?: string });
+ expect((remote.fix as Action).actor).toBe('host_admin');
+ });
+
+ test('a scoped fix and verify pin --source-id and the selected brain, never --source <id>', async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('wiki', 'wiki')");
+ await seed(30, { sourceId: 'wiki' });
+ const check = await checkLinksExtractionLag(engine, { sourceId: 'wiki' });
+ expect(check.status).toBe('warn');
+ const fix = renderAction(check.fix as Action, cli(teambrain));
+ expect(fix.argv).toEqual(['gbrain', 'extract', '--stale', '--source-id', 'wiki', '--brain', 'teambrain']);
+ expect(fix.verify?.argv).toEqual(['gbrain', 'extract', '--stale', '--dry-run', '--json', '--source-id', 'wiki', '--brain', 'teambrain']);
+ });
+
+ test('extract --stale --source <id> refuses with invalid_params naming --source-id instead of running brain-wide', async () => {
+ await seed(3);
+ const run = await captured(() => runExtract(engine, ['--stale', '--source', 'wiki', '--json']));
+ expect((run.error as { code?: string })?.code).toBe('invalid_params');
+ expect((run.error as { fix?: Action }).fix?.argv).toEqual(['gbrain', 'extract', '--stale', '--source-id', 'wiki', '--json']);
+ expect(Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE links_extracted_at IS NOT NULL'))[0]!.n)).toBe(0);
+ });
+
+ test('--source db is the read mode, and ambiguous once a source is named db', async () => {
+ await seed(3);
+ const plain = await captured(() => runExtract(engine, ['--stale', '--source', 'db', '--dry-run', '--json']));
+ expect(plain.error).toBeUndefined();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('db', 'db')");
+ const ambiguous = await captured(() => runExtract(engine, ['--stale', '--source', 'db', '--dry-run', '--json']));
+ expect((ambiguous.error as { code?: string })?.code).toBe('invalid_params');
+ expect((ambiguous.error as Error).message).toContain('ambiguous');
+ expect((ambiguous.error as { fix?: Action }).fix?.argv).toEqual(['gbrain', 'extract', '--stale', '--source-id', 'db', '--dry-run', '--json']);
+ });
+
+ test('extract --stale dry-run and completion JSON split actionable, attendance_blocked and mention_due', async () => {
+ await seed(4, { prefix: 'm', blocked: true });
+ await seed(3, { prefix: 'p' });
+ const dry = await captured(() => runExtract(engine, ['--stale', '--dry-run', '--json']));
+ const preview = JSON.parse(dry.stdout.trim().split('\n').filter(l => l.startsWith('{')).pop()!);
+ expect(preview).toMatchObject({ action: 'extract_stale_dry_run', actionable: 3, attendance_blocked: 4, complete: false });
+ expect('mention_due' in preview).toBe(true);
+ const done = await captured(() => runExtract(engine, ['--stale', '--json']));
+ const report = JSON.parse(done.stdout.trim().split('\n').filter(l => l.startsWith('{')).pop()!);
+ expect(report.action).toBe('extract_stale_done');
+ expect(report.actionable).toBe(0);
+ expect(typeof report.attendance_blocked).toBe('number');
+ expect('mention_due' in report && 'complete' in report).toBe(true);
+ });
+ });
+}
+
+describe('#6803 routing and reporting (engine-free)', () => {
+ test('extract routes --source-id: a brain-wide fix gets --source-id, a --source mode selector does not block it, --source is never pinned', () => {
+ expect(pinRouting(['gbrain', 'extract', '--stale'], teambrain)).toEqual(['gbrain', 'extract', '--stale', '--brain', 'teambrain', '--source-id', 'wiki']);
+ expect(pinRouting(['gbrain', 'extract', 'links', '--source', 'db'], teambrain)).toEqual(['gbrain', 'extract', 'links', '--source', 'db', '--brain', 'teambrain', '--source-id', 'wiki']);
+ expect(pinRouting(['gbrain', 'extract', '--stale', '--source-id', 'other'], teambrain)).toEqual(['gbrain', 'extract', '--stale', '--source-id', 'other', '--brain', 'teambrain']);
+ expect(pinRouting(['gbrain', 'sync', '--no-pull'], teambrain)).toEqual(['gbrain', 'sync', '--no-pull', '--brain', 'teambrain', '--source', 'wiki']);
+ });
+
+ test("the per-source sync line counts this sync's underived imports, not the source's whole stale backlog", () => {
+ const lines: string[] = [];
+ printManagedSyncNotes({ status: 'synced', links: { pages: 2, created: 1, removed: 0, timeline: 0, skipped: 0, remaining: 500 },
+ tail: { status: 'truncated', runs: 1, statistics: 'not_needed', underived: 3 } } as unknown as SyncResult, line => lines.push(line));
+ const line = lines.find(l => l.includes('Links:'))!;
+ expect(line).toContain('3 page(s) this sync imported still owe extraction');
+ expect(line).not.toContain('500');
+ });
+
+ test('real CLI: extract --stale --source <id> exits 2 invalid_params with the --source-id command, before any brain opens', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6803-extract-'));
+ try {
+ const run = await runCli(['extract', '--stale', '--source', 'wiki', '--json'], { home });
+ expect(run.exitCode, run.stderr).toBe(2);
+ const env = JSON.parse(run.stdout);
+ expect(env.code).toBe('invalid_params');
+ expect(env.fix.argv.slice(0, 5)).toEqual(['gbrain', 'extract', '--stale', '--source-id', 'wiki']);
+ const fs = await runCli(['extract', '--stale', '--source', 'fs', '--json'], { home });
+ expect(fs.exitCode, fs.stderr).toBe(2);
+ expect(JSON.parse(fs.stdout).code).toBe('invalid_params');
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 120_000);
+});
diff --git a/test/fix-routing.test.ts b/test/fix-routing.test.ts
index 9ad6313a20..9e05f5eb5e 100644
--- a/test/fix-routing.test.ts
+++ b/test/fix-routing.test.ts
@@ -58,11 +58,14 @@ describe('pinRouting', () => {
});
describe('routing table agrees with the command table and the generated registry', () => {
- test('every routes_source record pins --source and accepts it; nothing else does', () => {
+ test('every routes_source record pins its source flag and accepts it; nothing else does', () => {
const declared = CLI_COMMANDS.filter(r => r.routes_source).map(r => r.name).sort();
expect(declared.length).toBeGreaterThan(10);
- for (const name of declared) expect(CLI_FLAG_REGISTRY[name], `${name} accepts --source`).toContain('--source');
- expect(Object.keys(CLI_ROUTING_FLAGS).filter(k => CLI_ROUTING_FLAGS[k]!.includes('--source')).sort()).toEqual(declared);
+ // #6803 (D2): a record declares '--source-id' when its --source is a mode selector (extract: fs|db).
+ const flagOf = (name: string) => CLI_COMMANDS.find(r => r.name === name)!.routes_source === '--source-id' ? '--source-id' : '--source';
+ for (const name of declared) expect(CLI_FLAG_REGISTRY[name], `${name} accepts ${flagOf(name)}`).toContain(flagOf(name));
+ expect(Object.keys(CLI_ROUTING_FLAGS).filter(k => CLI_ROUTING_FLAGS[k]!.includes('--source') || CLI_ROUTING_FLAGS[k]!.includes('--source-id')).sort()).toEqual(declared);
+ for (const name of declared) expect(CLI_ROUTING_FLAGS[name], name).toContain(flagOf(name));
});
test('every engine-opening command pins --brain; pre-connect ones only when their code reads the brain option', () => {
diff --git a/test/link-extractor-bump-notes.test.ts b/test/link-extractor-bump-notes.test.ts
new file mode 100644
index 0000000000..24a604ee44
--- /dev/null
+++ b/test/link-extractor-bump-notes.test.ts
@@ -0,0 +1,17 @@
+/**
+ * #6803 (D5): a link-extractor watermark bump re-stales every page brain-wide. The pinned value below changes only
+ * together with an EXTRACTOR_BUMP_NOTES entry keyed by the new value (written with the code, copied into the CHANGELOG
+ * at ship) that names the brain-wide re-extraction and the command that finishes it.
+ */
+import { expect, test } from 'bun:test';
+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
+import * as watermark from '../src/core/link-extraction-watermark.ts';
+
+test('LINK_EXTRACTOR_VERSION_TS is pinned; a bump needs its EXTRACTOR_BUMP_NOTES entry naming the re-extraction and --catch-up', () => {
+ expect(LINK_EXTRACTOR_VERSION_TS).toBe('2026-10-08T00:00:00Z');
+ const notes = (watermark as { EXTRACTOR_BUMP_NOTES?: Record<string, string> }).EXTRACTOR_BUMP_NOTES;
+ const note = notes?.[LINK_EXTRACTOR_VERSION_TS];
+ expect(note).toBeDefined();
+ expect(note).toContain('brain-wide');
+ expect(note).toContain('gbrain extract --stale --catch-up');
+});