Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): timeline --source db writes through the coordinator and exits non-zero on refusals (#5904)
garrytan81da669fe92a
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 12ddc9c92d..36b8ee9598 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -32,6 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).- `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); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. 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, and every other file looked deleted and was skipped in silence; 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 directory-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. 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: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). `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.serial.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.+- `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 per page in a page-locked, revision-bound `withCoordinatedWrite` transaction: retract rows the current text no longer produces, then insert the canonical tuples with no stored row (`unrecordedCanonicalTimeline`); unmanaged brains batch raw inserts. A refused write prints `refused: <code>; nothing written; existing timeline rows are untouched`, the summary counts written versus refused 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`.- 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`.- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 50b9f037e7..2525f1e0b0 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -59,6 +59,7 @@ of making a duplicate.| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). || <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. || <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |+| <a id="extract-timeline-refused"></a>timeline extract refused | the printed code, usually `writer_coordinator_required` | `gbrain extract timeline --source db` (or a timeline-only `gbrain extract timeline` on a managed brain) could not write a page's timeline rows. It prints `refused: <code>; nothing written; existing timeline rows are untouched` per page, a summary of written versus refused, and exits 1. The rows import already stored for each page stay as they were. | `gbrain extract --stale` (add `--source-id <id>` when you scoped the run) publishes links and missing timeline rows on the managed path. If it refuses too, follow the row for the printed code. || unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. || <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. || <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 7a8df14bb3..9c0c4437c7 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1637 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2190 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stalesrc/commands/extract-conversation-facts.ts 2182 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch)-src/commands/extract.ts 2623 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference)+src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.tssrc/core/ai/gateway.ts 4391 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge)diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsnew file mode 100644index 0000000000..54b29938f9--- /dev/null+++ b/src/commands/extract-timeline-db.ts@@ -0,0 +1,195 @@+/**+ * `gbrain extract timeline --source db` (#5904 probe, E28).+ *+ * `timeline_entries` is a guarded table: on a managed brain (every fresh+ * `gbrain init` brain is one) a raw batch insert is refused by+ * `managed_writer_guard`. Managed brains therefore publish each page's+ * timeline through the coordinator: under the page lock, bound to the+ * revision that was read, the rows an earlier version produced and the+ * current text no longer does are retracted and the timeline tuples the+ * canonical body projects with no stored row are inserted. Unmanaged brains+ * keep the batched raw insert.+ *+ * A refused write is reported as what it is: nothing was written and the+ * timeline rows import already stored are untouched. Refusals are counted+ * apart from written rows and make the command exit non-zero.+ */+import type { BrainEngine, TimelineBatchInput } from '../core/engine.ts';+import type { Page, PageType } from '../core/types.ts';+import { parseTimelineEntries, deriveTimelineAnchor } from '../core/link-extraction.ts';+import { retractRemovedTimelineEntries } from '../core/timeline-extract.ts';+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';+import { withCoordinatedWrite } from '../core/persistence/context.ts';+import { unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';+import { createProgress } from '../core/progress.ts';+import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';+import { filterRefsSince } from './extract.ts';++const BATCH_SIZE = 100;+export const TIMELINE_REFUSAL_DOCS = 'docs/guides/write-refusals.md#extract-timeline-refused';++export interface TimelineDbResult {+ created: number;+ pages: number;+ /** Pages (managed) or rows (unmanaged batches) whose write was refused. */+ refused: number;+ /** Managed pages edited during the run; they keep their stored rows and are picked up by the next run. */+ skipped: number;+ refusal_codes: string[];+}++export interface TimelineDbOptions {+ dryRun: boolean;+ jsonMode: boolean;+ quiet?: boolean;+ typeFilter?: PageType;+ since?: string;+ sourceIdFilter?: string;+ inferDates?: boolean;+ /** Restrict the walk to these slugs (requires sourceIdFilter). */+ slugs?: readonly string[];+}++/** The refusal reason: the guard's `code: message` prefix, else the error's own code. */+export function refusalCode(error: unknown): string {+ const message = error instanceof Error ? error.message : String(error);+ const prefixed = /^([a-z][a-z0-9_]+):/.exec(message);+ if (prefixed) return prefixed[1];+ const code = (error as { code?: unknown })?.code;+ return typeof code === 'string' && /^[a-z][a-z0-9_]+$/.test(code) ? code : 'storage_error';+}++function reportRefusal(opts: TimelineDbOptions, code: string, where: string, message: string): void {+ if (opts.jsonMode) {+ process.stderr.write(JSON.stringify({ event: 'timeline_refused', code, where, error: message }) + '\n');+ } else {+ console.error(` refused: ${code}; nothing written; existing timeline rows are untouched (${where})`);+ }+}++function anchorFor(page: Page, slug: string) {+ return deriveTimelineAnchor({ slug, title: page.title, effectiveDate: page.effective_date, effectiveDateSource: page.effective_date_source });+}++async function walkRefs(engine: BrainEngine, opts: TimelineDbOptions) {+ const all = opts.sourceIdFilter+ ? (await engine.listAllPageRefs()).filter(r => r.source_id === opts.sourceIdFilter)+ : await engine.listAllPageRefs();+ const wanted = opts.slugs ? new Set(opts.slugs) : null;+ return filterRefsSince(wanted ? all.filter(r => wanted.has(r.slug)) : all, opts.since);+}++/**+ * Walk the selected pages from the database and add their timeline rows.+ * Managed brains publish per page through the coordinator; unmanaged brains+ * batch raw inserts (`ON CONFLICT DO NOTHING`).+ */+export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDbOptions): Promise<TimelineDbResult> {+ const refs = await walkRefs(engine, opts);+ const result: TimelineDbResult = { created: 0, pages: 0, refused: 0, skipped: 0, refusal_codes: [] };+ const codes = new Set<string>();+ const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));+ progress.start('extract.timeline_db', refs.length);+ const managed = !opts.dryRun && await managedPersistenceEnabled(engine);+ const dryRunSeen = opts.dryRun ? new Set<string>() : null;+ const batch: TimelineBatchInput[] = [];++ async function flush() {+ if (batch.length === 0) return;+ const snapshot = batch.slice();+ batch.length = 0;+ try {+ result.created += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_db' });+ } catch (e) {+ const code = refusalCode(e);+ codes.add(code);+ result.refused += snapshot.length;+ reportRefusal(opts, code, `batch of ${snapshot.length} rows`, e instanceof Error ? e.message : String(e));+ }+ }++ for (const { slug, source_id } of refs) {+ if (managed) {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: source_id });+ if (!snapshot || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) continue;+ try {+ const added = await engine.transaction(tx => withCoordinatedWrite(tx, [source_id], async () => {+ await tx.lockPageKeys([{ sourceId: source_id, slug }]);+ const current = await tx.readPageSnapshot(slug, { sourceId: source_id });+ if (current?.revision !== snapshot.revision) return null;+ const fullContent = current.page.compiled_truth + '\n' + current.page.timeline;+ await retractRemovedTimelineEntries(tx, slug, source_id, fullContent);+ let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(tx, current.page.id, current.page, slug);+ if (entries.length === 0 && opts.inferDates && parseTimelineEntries(fullContent).length === 0) {+ const anchor = anchorFor(current.page, slug);+ if (anchor) entries = [anchor];+ }+ if (entries.length === 0) return 0;+ return tx.addTimelineEntriesBatch(entries.map(entry => ({ slug, date: entry.date, source: entry.source,+ summary: entry.summary, detail: entry.detail || '', source_id })), { auditSite: 'extract.timeline_db' });+ }));+ if (added === null) result.skipped++;+ else { result.created += added; result.pages++; }+ } catch (e) {+ const code = refusalCode(e);+ codes.add(code);+ result.refused++;+ reportRefusal(opts, code, `${source_id}:${slug}`, e instanceof Error ? e.message : String(e));+ }+ progress.tick(1);+ continue;+ }++ const page = await engine.getPage(slug, { sourceId: source_id });+ if (!page) continue;+ if (opts.typeFilter && page.type !== opts.typeFilter) continue;+ const fullContent = page.compiled_truth + '\n' + page.timeline;+ if (!opts.dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);+ let entries = parseTimelineEntries(fullContent);+ // --infer-dates: pages with no in-body timeline line but a trustworthy+ // content date (frontmatter / filename) get one anchor entry at that date.+ if (entries.length === 0 && opts.inferDates) {+ const anchor = anchorFor(page, slug);+ if (anchor) entries = [anchor];+ }+ for (const entry of entries) {+ if (dryRunSeen) {+ const key = `${source_id}::${slug}::${entry.date}::${entry.summary}`;+ if (dryRunSeen.has(key)) continue;+ dryRunSeen.add(key);+ if (opts.jsonMode) {+ process.stdout.write(JSON.stringify({+ action: 'add_timeline', slug, source_id, date: entry.date,+ summary: entry.summary, ...(entry.detail ? { detail: entry.detail } : {}),+ }) + '\n');+ } else if (!opts.quiet) {+ console.log(` ${slug}: ${entry.date} — ${entry.summary}`);+ }+ result.created++;+ } else {+ batch.push({ slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id });+ if (batch.length >= BATCH_SIZE) await flush();+ }+ }+ result.pages++;+ progress.tick(1);+ }+ await flush();+ progress.finish();+ result.refusal_codes = [...codes];++ if (!opts.jsonMode && !opts.quiet) {+ const label = opts.dryRun ? '(dry run) would create' : 'created';+ console.log(`Timeline: ${label} ${result.created} entries from ${result.pages} pages (db source)` ++ (result.skipped ? `; ${result.skipped} page(s) changed during the run were left for the next run` : ''));+ }+ if (result.refused > 0) {+ const unit = managed ? 'page(s)' : 'row(s)';+ console.error(+ `[extract timeline] refused: ${result.refusal_codes.join(', ')}; ${result.refused} ${unit} not written, ${result.created} written. ` ++ `Existing timeline rows are untouched (import already stored the rows of each page it wrote). ` ++ `Recovery: gbrain extract --stale${opts.sourceIdFilter ? ` --source-id ${opts.sourceIdFilter}` : ''}. Docs: ${TIMELINE_REFUSAL_DOCS}`,+ );+ }+ return result;+}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 5eddb80514..febabbdda9 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -247,6 +247,8 @@ interface ExtractResult {skipped_missing_target?: number;skipped_attendance_incomplete?: number;skipped_cross_source?: number;+ /** #5904: timeline writes the writer refused (DB path); the command exits non-zero. */+ timeline_refused?: number;}// --- Shared walker ---@@ -745,6 +747,12 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Prconst r = await extractManagedStaleLinks(engine, { sourceId: opts.sourceId, slugs: opts.slugs, signal: opts.signal, maxPages: opts.slugs?.length });progress.finish(); return { links_created: r.created, timeline_entries_created: r.timeline, pages_processed: r.pages };}+ // #5904: a timeline-only pass on a managed brain publishes each page's canonical timeline through the coordinator.+ if (!dryRun && opts.mode === 'timeline' && opts.slugs?.length !== 0 && await managedPersistenceEnabled(engine)) {+ const { extractTimelineFromDB } = await import('./extract-timeline-db.ts');+ const r = await extractTimelineFromDB(engine, { dryRun, jsonMode, quiet: quiet || jsonMode, sourceIdFilter: opts.sourceId, slugs: opts.slugs });+ return { links_created: 0, timeline_entries_created: r.created, pages_processed: r.pages, ...(r.refused ? { timeline_refused: r.refused } : {}) };+ }// Incremental path: if specific slugs provided, only extract from those files.// This is the cycle path — sync tells us what changed, we only re-extract those.@@ -1214,9 +1222,8 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?if (r.skippedAttendanceIncomplete) result.skipped_attendance_incomplete = r.skippedAttendanceIncomplete;}if (subcommand === 'timeline' || subcommand === 'all') {- const r = await extractTimelineFromDB(engine, dryRun, jsonMode, typeFilter, since, { sourceIdFilter, inferDates });- result.timeline_entries_created = r.created;- result.pages_processed = Math.max(result.pages_processed, r.pages);+ const r = await (await import('./extract-timeline-db.ts')).extractTimelineFromDB(engine, { dryRun, jsonMode, typeFilter, since, sourceIdFilter, inferDates });+ Object.assign(result, { timeline_entries_created: r.created, pages_processed: Math.max(result.pages_processed, r.pages) }, r.refused ? { timeline_refused: r.refused } : {});}}} else {@@ -1238,6 +1245,7 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?workers,});}+ if (result.timeline_refused) setCliExitVerdict(1);} catch (e) {console.error(e instanceof Error ? e.message : String(e));process.exit(1);@@ -1751,7 +1759,7 @@ export async function extractTimelineForSlugs(* rows (updated_at > since); an unparseable `since` is rejected upstream in* runExtract, so the pass-through here is belt-and-braces only.*/-function filterRefsSince<T extends { updated_at: Date }>(+export function filterRefsSince<T extends { updated_at: Date }>(refs: T[],since: string | undefined,): T[] {@@ -1980,109 +1988,6 @@ async function extractLinksFromDB(return { created, pages: processed, unresolved, skippedMissingTarget, skippedCrossSource, skippedAttendanceIncomplete };}-async function extractTimelineFromDB(- engine: BrainEngine,- dryRun: boolean,- jsonMode: boolean,- typeFilter: PageType | undefined,- since: string | undefined,- opts?: { sourceIdFilter?: string; inferDates?: boolean },-): Promise<{ created: number; pages: number }> {- // v0.32.8: listAllPageRefs enumerates (slug, source_id) pairs so we can- // thread sourceId to getPage and addTimelineEntriesBatch. Pre-fix used- // getAllSlugs() which collapsed same-slug-different-source pages.- //- // v0.37.7.0 #1204: when sourceIdFilter is set, scope the walk to one- // source so federated brain users can extract per-source.- const sourceIdFilter = opts?.sourceIdFilter;- const inferDates = opts?.inferDates ?? false;- const allRefs = sourceIdFilter- ? (await engine.listAllPageRefs()).filter(r => r.source_id === sourceIdFilter)- : await engine.listAllPageRefs();- // #4304: --since prunes at the ref level — no getPage round-trip for- // pages outside the window.- const walkRefs = filterRefsSince(allRefs, since);- let processed = 0, created = 0;-- const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));- progress.start('extract.timeline_db', walkRefs.length);-- // Dedup in dry-run only — DB enforces uniqueness via ON CONFLICT in batch writes.- const dryRunSeen = dryRun ? new Set<string>() : null;-- const batch: TimelineBatchInput[] = [];- async function flush() {- if (batch.length === 0) return;- const snapshot = batch.slice();- batch.length = 0;- try {- created += await engine.addTimelineEntriesBatch(snapshot, { auditSite: 'extract.timeline_db' });- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- if (jsonMode) {- process.stderr.write(JSON.stringify({ event: 'batch_error', size: snapshot.length, error: msg }) + '\n');- } else {- console.error(` batch error (${snapshot.length} timeline rows lost): ${msg}`);- }- }- }-- for (const { slug, source_id } of walkRefs) {- const page = await engine.getPage(slug, { sourceId: source_id });- if (!page) continue;- if (typeFilter && page.type !== typeFilter) continue;-- const fullContent = page.compiled_truth + '\n' + page.timeline;- if (!dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);- let entries = parseTimelineEntries(fullContent);- // --infer-dates: pages with no in-body timeline line but a trustworthy- // content date (frontmatter / filename) get one anchor entry at that date.- // Applied ONLY on the zero-entry path so it never shadows a real timeline.- if (entries.length === 0 && inferDates) {- const anchor = deriveTimelineAnchor({- slug,- title: page.title,- effectiveDate: page.effective_date,- effectiveDateSource: page.effective_date_source,- });- if (anchor) entries = [anchor];- }-- for (const entry of entries) {- if (dryRunSeen) {- const key = `${source_id}::${slug}::${entry.date}::${entry.summary}`;- if (dryRunSeen.has(key)) continue;- dryRunSeen.add(key);- if (jsonMode) {- process.stdout.write(JSON.stringify({- action: 'add_timeline', slug, source_id, date: entry.date,- summary: entry.summary, ...(entry.detail ? { detail: entry.detail } : {}),- }) + '\n');- } else {- console.log(` ${slug}: ${entry.date} — ${entry.summary}`);- }- created++;- } else {- // v0.32.8 F4: thread source_id so the JOIN matches the right page- // when two sources share the same slug. #3957: thread the parsed- // source label too — see extractStaleFromDB's twin.- batch.push({ slug, date: entry.date, source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id });- if (batch.length >= BATCH_SIZE) await flush();- }- }- processed++;- progress.tick(1);- }- await flush();- progress.finish();-- if (!jsonMode) {- const label = dryRun ? '(dry run) would create' : 'created';- console.log(`Timeline: ${label} ${created} entries from ${processed} pages (db source)`);- }- return { created, pages: processed };-}-/*** v0.42.7 (#1696) — `gbrain extract --stale`: incremental link + timeline* extraction over pages whose `links_extracted_at` watermark is stale (NULL,diff --git a/src/core/minions/handlers/extract.ts b/src/core/minions/handlers/extract.tsindex 3756ce281a..310a0b4111 100644--- a/src/core/minions/handlers/extract.ts+++ b/src/core/minions/handlers/extract.ts@@ -55,6 +55,9 @@ export function makeExtractHandler(engine: BrainEngine): MinionHandler {// drops every row on a non-'default' brain (silent "created 0"), and the// full-walk watermark stamp targets the wrong source.const sourceId = typeof job.data.sourceId === 'string' ? job.data.sourceId : undefined;- return await runExtractCore(engine, { mode, dir, dryRun: !!job.data.dryRun, sourceId });+ const result = await runExtractCore(engine, { mode, dir, dryRun: !!job.data.dryRun, sourceId });+ // #5904: refused timeline writes fail the job instead of completing over rows that were never written.+ if (result.timeline_refused) throw new Error(`extract: ${result.timeline_refused} timeline write(s) refused; nothing written for them. Run gbrain extract --stale.`);+ return result;};}diff --git a/test/e2e/extract-timeline-db-postgres.test.ts b/test/e2e/extract-timeline-db-postgres.test.tsnew file mode 100644index 0000000000..6b3b1e7c49--- /dev/null+++ b/test/e2e/extract-timeline-db-postgres.test.ts@@ -0,0 +1,12 @@+/**+ * Postgres arm of the #5904 probe (E28): `extract timeline --source db` on a+ * managed Postgres brain writes through the coordinator; a refusal exits non-zero.+ */+import { describe, test } from 'bun:test';+import { managedTimelineDbRefusalExitsNonZero, managedTimelineDbWritesThroughCoordinator } from '../helpers/extract-timeline-db-scenarios.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres managed extract timeline --source db', () => {+ test('writes the missing rows through the coordinator', () => managedTimelineDbWritesThroughCoordinator(url), 180_000);+ test('a refused write says nothing was written and exits non-zero', () => managedTimelineDbRefusalExitsNonZero(url), 180_000);+});diff --git a/test/extract-timeline-db-managed.test.ts b/test/extract-timeline-db-managed.test.tsnew file mode 100644index 0000000000..8214da16a4--- /dev/null+++ b/test/extract-timeline-db-managed.test.ts@@ -0,0 +1,9 @@+/**+ * #5904 probe (E28): `extract timeline --source db` on a managed PGLite brain.+ * Postgres arm: test/e2e/extract-timeline-db-postgres.test.ts.+ */+import { test } from 'bun:test';+import { managedTimelineDbRefusalExitsNonZero, managedTimelineDbWritesThroughCoordinator } from './helpers/extract-timeline-db-scenarios.ts';++test('managed extract timeline --source db writes the missing rows through the coordinator', () => managedTimelineDbWritesThroughCoordinator(), 120_000);+test('a refused timeline write says nothing was written and exits non-zero', () => managedTimelineDbRefusalExitsNonZero(), 120_000);diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 886cd4c090..544a6fb3d9 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -580,6 +580,7 @@"extractStaleFromDB","extractTimelineForSlugs","extractTimelineFromContent",+ "filterRefsSince","logBatchRetry","reconcileSourceLinks","resolveBasenameMatchesFromSlugs",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 9bbcf5a744..dc302dc075 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -78,7 +78,7 @@"findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>","findDuplicatePage?: ((sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>) | undefined","findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",- "findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; }>>",+ "findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>","findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>","getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>","getAllConfig: () => Promise<Record<string, string>>",@@ -981,7 +981,7 @@"findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>","findDuplicatePage: (sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>","findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",- "findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; }>>",+ "findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>","findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>","getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>","getAllConfig: () => Promise<Record<string, string>>",@@ -3045,7 +3045,7 @@"findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>","findDuplicatePage?: ((sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>) | undefined","findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",- "findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; }>>",+ "findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>","findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>","getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>","getAllConfig: () => Promise<Record<string, string>>",@@ -4007,6 +4007,13 @@"(content: string, slug: string) => ExtractedTimelineEntry[]"]},+ {+ "kind": "function",+ "name": "filterRefsSince",+ "signature": [+ "<T extends { updated_at: Date; }>(refs: T[], since: string | undefined) => T[]"+ ]+ },{"kind": "function","name": "logBatchRetry",@@ -5623,7 +5630,7 @@"findCandidateDuplicates: (source_id: string, entitySlug: string, factText: string, opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; }) => Promise<FactRow[]>","findDuplicatePage: (sourceId: string, opts: { hash: string; frontmatterId?: string | null; excludeSlug?: string; }) => Promise<{ slug: string; id: number; } | null>","findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",- "findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; }>>",+ "findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>","findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>","getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>","getAllConfig: () => Promise<Record<string, string>>",diff --git a/test/fresh-init-db-extract.serial.test.ts b/test/fresh-init-db-extract.serial.test.tsnew file mode 100644index 0000000000..e1dca0b971--- /dev/null+++ b/test/fresh-init-db-extract.serial.test.ts@@ -0,0 +1,103 @@+/**+ * Real CLI against a fresh `gbrain init --pglite` brain (a managed brain):+ * - #5877: the command doctor's `orphan_ratio` hint prints runs and exits 0+ * (the bare `--by-mention` hint exited 2 on the default fs source).+ * - #5904 probe (E28, GBRA-40): `extract timeline --source db` no longer+ * reports "rows lost" and exits 0 over refused writes; it writes through+ * the coordinator and leaves the rows import stored untouched.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runDoctor, type DoctorReport } from '../src/commands/doctor.ts';+import { setCliOptions } from '../src/core/cli-options.ts';++const REPO = join(import.meta.dir, '..');+let home: string;++function cli(args: string[], input?: string) {+ const r = spawnSync('bun', ['run', join(REPO, 'src/cli.ts'), ...args], {+ cwd: home,+ input,+ encoding: 'utf8',+ timeout: 180_000,+ env: {+ ...process.env, GBRAIN_HOME: home, HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_SKILL_NAG: '1',+ } as NodeJS.ProcessEnv,+ });+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };+}++/** The fix command doctor prints for a high orphan ratio, from a seeded in-memory brain. */+async function doctorHintCommand(): Promise<string> {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });+ for (let i = 0; i < 100; i++) {+ await engine.putPage(`people/person-${i}`, { type: 'person', title: `Person ${i}`, compiled_truth: 'b', timeline: '', frontmatter: {} });+ }+ const out: string[] = [];+ const log = console.log;+ const err = console.error;+ const exit = process.exit;+ console.log = (msg?: unknown) => { out.push(String(msg)); };+ console.error = () => {};+ (process as { exit: unknown }).exit = (() => { throw new Error('__exit'); }) as unknown as typeof process.exit;+ try {+ await runDoctor(engine, ['--json']);+ } catch (e) {+ if (!(e instanceof Error && e.message === '__exit')) throw e;+ } finally {+ console.log = log; console.error = err; (process as { exit: unknown }).exit = exit;+ await engine.disconnect();+ }+ for (let i = out.length - 1; i >= 0; i--) {+ try {+ const report = JSON.parse(out[i]!) as DoctorReport;+ const check = report.checks?.find(c => c.name === 'orphan_ratio');+ const match = check?.message.match(/Run: (gbrain extract links[^(]*?)\s{2,}/);+ if (match) return match[1]!.trim();+ } catch { /* not the report */ }+ }+ throw new Error('orphan_ratio hint not found');+}++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-fresh-db-extract-'));+ const init = cli(['init', '--pglite', '--no-embedding', '--non-interactive']);+ if (init.status !== 0) throw new Error(`init failed: ${init.stderr}`);+ const put = cli(['put', 'people/alice-example'],+ '---\ntitle: Alice Example\ntype: person\n---\nAlice works at Acme.\n\n## Timeline\n\n- **2024-01-05** | Joined Acme as CTO\n- **2024-03-01** | Shipped v2\n');+ if (put.status !== 0) throw new Error(`put failed: ${put.stderr}`);+}, 240_000);++afterAll(() => { rmSync(home, { recursive: true, force: true }); });++describe('fresh gbrain init brain', () => {+ test('#5877: the printed orphan_ratio fix command runs and exits 0', async () => {+ const command = await doctorHintCommand();+ expect(command).toBe('gbrain extract links --by-mention --source db');+ const r = cli(command.split(' ').slice(1));+ expect(r.stderr).not.toContain('requires --source db');+ expect(r.status).toBe(0);+ }, 240_000);++ test('#5904: extract timeline --source db is honest and keeps the rows import stored', () => {+ const before = cli(['timeline', 'people/alice-example']);+ expect(before.stdout).toContain('Joined Acme as CTO');+ expect(before.stdout).toContain('Shipped v2');+ const r = cli(['extract', 'timeline', '--source', 'db']);+ expect(r.stderr).not.toContain('rows lost');+ expect(r.stderr).not.toContain('refused');+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('Timeline: created 0 entries from 1 pages (db source)');+ const after = cli(['timeline', 'people/alice-example']);+ expect(after.stdout).toContain('Joined Acme as CTO');+ expect(after.stdout).toContain('Shipped v2');+ }, 240_000);+});diff --git a/test/helpers/extract-timeline-db-scenarios.ts b/test/helpers/extract-timeline-db-scenarios.tsnew file mode 100644index 0000000000..1b4f8736f3--- /dev/null+++ b/test/helpers/extract-timeline-db-scenarios.ts@@ -0,0 +1,106 @@+/**+ * #5904 probe (E28): `gbrain extract timeline --source db` on a managed brain+ * writes through the coordinator, and a refused write is reported honestly+ * with a non-zero exit. Shared by the PGLite test and the Postgres E2E.+ */+import { expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';+import { runExtract } from '../../src/commands/extract.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';+import { managedBrain } from './managed-brain.ts';++const put = (ctx: OperationContext, slug: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',+ params: { slug, request_id: randomUUID(), content: `---\ntype: person\ntitle: ${slug}\n---\n\n${body}\n` } });++const rows = (engine: BrainEngine, slug: string) => engine.executeRaw<{ date: string; summary: string }>(+ `SELECT t.date::text AS date, t.summary FROM timeline_entries t JOIN pages p ON p.id = t.page_id+ WHERE p.slug = $1 ORDER BY t.date`, [slug]);++/** A page published before timeline projection: its stored rows are gone, its body still has the bullets. */+async function dropStoredTimeline(engine: BrainEngine, slug: string) {+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw('DELETE FROM timeline_entries WHERE page_id = (SELECT id FROM pages WHERE slug = $1)', [slug])));+}++async function runCaptured(engine: BrainEngine, args: string[]) {+ const out: string[] = [];+ const err: string[] = [];+ const log = console.log;+ const error = console.error;+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };+ _resetCliExitVerdictForTests();+ try {+ await runExtract(engine, args);+ } finally {+ console.log = log;+ console.error = error;+ }+ const exitCode = currentExitCode();+ _resetCliExitVerdictForTests();+ return { stdout: out.join('\n'), stderr: err.join('\n'), exitCode };+}++const ALICE = 'people/alice-example';+const BOB = 'people/bob-example';+const BODY = 'A person.\n\n## Timeline\n\n- **2026-01-02** | test — Met Acme\n- **2026-02-03** | test — Joined Acme';++export async function managedTimelineDbWritesThroughCoordinator(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('auto_link', 'false');+ await put(ctx, ALICE, BODY);+ await disposePersistenceConsumer(engine);+ await dropStoredTimeline(engine, ALICE);+ expect(await rows(engine, ALICE)).toEqual([]);++ const run = await runCaptured(engine, ['timeline', '--source', 'db']);+ expect(run.stderr).not.toContain('refused');+ expect(run.stderr).not.toContain('rows lost');+ expect(run.exitCode).toBe(0);+ expect(await rows(engine, ALICE)).toEqual([+ { date: '2026-01-02', summary: 'Met Acme' },+ { date: '2026-02-03', summary: 'Joined Acme' },+ ]);+ expect(run.stdout).toContain('Timeline: created 2 entries from 1 pages (db source)');++ const again = await runCaptured(engine, ['timeline', '--source', 'db']);+ expect(again.exitCode).toBe(0);+ expect(again.stdout).toContain('Timeline: created 0 entries from 1 pages (db source)');+ expect(await rows(engine, ALICE)).toHaveLength(2);+ }, { databaseUrl });+}++export async function managedTimelineDbRefusalExitsNonZero(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await engine.setConfig('auto_link', 'false');+ await put(ctx, BOB, BODY);+ await put(ctx, ALICE, BODY);+ await disposePersistenceConsumer(engine);+ await dropStoredTimeline(engine, ALICE);+ const bobBefore = await rows(engine, BOB);+ expect(bobBefore).toHaveLength(2);++ await engine.executeRaw(`CREATE OR REPLACE FUNCTION test_refuse_timeline() RETURNS trigger LANGUAGE plpgsql AS $$+ BEGIN RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: refused by test'; END $$`);+ await engine.executeRaw('CREATE TRIGGER test_refuse_timeline BEFORE INSERT ON timeline_entries FOR EACH ROW EXECUTE FUNCTION test_refuse_timeline()');+ try {+ const run = await runCaptured(engine, ['timeline', '--source', 'db']);+ expect(run.exitCode).toBe(1);+ expect(run.stderr).toContain('refused: writer_coordinator_required; nothing written; existing timeline rows are untouched');+ expect(run.stderr).not.toContain('rows lost');+ expect(run.stderr).toContain('1 page(s) not written, 0 written');+ expect(run.stderr).toContain('gbrain extract --stale');+ expect(run.stderr).toContain('docs/guides/write-refusals.md#extract-timeline-refused');+ expect(await rows(engine, BOB)).toEqual(bobBefore);+ expect(await rows(engine, ALICE)).toEqual([]);+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS test_refuse_timeline ON timeline_entries');+ await engine.executeRaw('DROP FUNCTION IF EXISTS test_refuse_timeline()');+ }+ }, { databaseUrl });+}