Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract): managed timeline extract publishes a maintenance request per changed page (#5904, E10/E24)
garrytan97504fc43d0a
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.mdindex 36b8ee9598..b3d7c0310c 100644--- a/docs/architecture/key-files/commands-3.md+++ b/docs/architecture/key-files/commands-3.md@@ -32,7 +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`.+- `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`.- 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/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex 54b29938f9..1584d71c0a 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -3,12 +3,14 @@** `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.+ * `managed_writer_guard`. Managed brains therefore publish each page that+ * needs a change as one database-only maintenance request+ * (`managed_maintenance_timeline_extract`, owner-checked by+ * `maintenancePreflight`): 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. A page with nothing to change+ * admits no request. 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@@ -19,13 +21,20 @@ 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 { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';+import { authorizeWrite } from '../core/persistence/authority.ts';+import { getWriteRequest } from '../core/persistence/journal.ts';+import { isTerminal, type WriteRequest } from '../core/persistence/model.ts';+import { digest } from '../core/persistence/digest.ts';+import type { PreparedMutation } from '../core/persistence/coordinator.ts';+import { OperationError } from '../core/ops/contract.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_EXTRACT_INTENT = 'managed_maintenance_timeline_extract';export const TIMELINE_REFUSAL_DOCS = 'docs/guides/write-refusals.md#extract-timeline-refused';export interface TimelineDbResult {@@ -35,6 +44,8 @@ export interface TimelineDbResult {refused: number;/** Managed pages edited during the run; they keep their stored rows and are picked up by the next run. */skipped: number;+ /** Managed pages whose request was accepted but has not committed yet; rerunning resumes the same request. */+ pending: number;refusal_codes: string[];}@@ -50,13 +61,17 @@ export interface TimelineDbOptions {slugs?: readonly string[];}-/** The refusal reason: the guard's `code: message` prefix, else the error's own code. */+/**+ * The refusal reason: the error's own code, unless it is the coordinator's+ * generic `storage_error`, whose message carries the database refusal+ * (`writer_coordinator_required: ...`) that names the real reason.+ */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';+ const own = typeof code === 'string' && /^[a-z][a-z0-9_]+$/.test(code) ? code : null;+ if (own && own !== 'storage_error') return own;+ return /(?:^|[\s(])([a-z][a-z0-9]*_[a-z0-9_]+):/.exec(message)?.[1] ?? own ?? 'storage_error';}function reportRefusal(opts: TimelineDbOptions, code: string, where: string, message: string): void {@@ -86,7 +101,12 @@ async function walkRefs(engine: BrainEngine, opts: TimelineDbOptions) {*/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 result: TimelineDbResult = { created: 0, pages: 0, refused: 0, skipped: 0, pending: 0, refusal_codes: [] };+ const authorities = new Map<string, Promise<MaintenanceAuthority>>();+ const authorityFor = (sourceId: string) => {+ if (!authorities.has(sourceId)) authorities.set(sourceId, maintenancePreflight(engine, sourceId).then(a => a!));+ return authorities.get(sourceId)!;+ };const codes = new Set<string>();const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));progress.start('extract.timeline_db', refs.length);@@ -110,26 +130,11 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDfor (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++; }+ const outcome = await publishPageTimeline(engine, await authorityFor(source_id), slug, source_id, opts);+ if (outcome === 'skipped') result.skipped++;+ else if (outcome === 'pending') result.pending++;+ else if (outcome !== null) { result.created += outcome; result.pages++; }} catch (e) {const code = refusalCode(e);codes.add(code);@@ -181,7 +186,8 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDif (!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` : ''));+ (result.skipped ? `; ${result.skipped} page(s) changed during the run were left for the next run` : '') ++ (result.pending ? `; ${result.pending} page(s) accepted but still pending (writer busy); rerun the same command to confirm` : ''));}if (result.refused > 0) {const unit = managed ? 'page(s)' : 'row(s)';@@ -193,3 +199,70 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD}return result;}++/** The timeline change one page needs: removed rows to retract and canonical tuples (or an inferred anchor) to insert. */+async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean) {+ const fullContent = page.compiled_truth + '\n' + page.timeline;+ const removed = await retractRemovedTimelineEntries(engine, slug, sourceId, fullContent, { dryRun: true });+ let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id, page, slug);+ if (entries.length === 0 && inferDates && parseTimelineEntries(fullContent).length === 0) {+ const anchor = anchorFor(page, slug);+ const [stored] = anchor ? await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL', [page.id]) : [{ n: 1 }];+ if (anchor && !stored?.n) entries = [anchor];+ }+ return { fullContent, removed: removed.length, entries };+}++/** Under the coordinator's page lock: retract removed rows, insert the planned tuples. */+async function writePageTimeline(tx: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean): Promise<number> {+ const plan = await plannedTimeline(tx, page, slug, sourceId, inferDates);+ if (plan.removed) await retractRemovedTimelineEntries(tx, slug, sourceId, plan.fullContent);+ if (!plan.entries.length) return 0;+ return tx.addTimelineEntriesBatch(plan.entries.map(entry => ({ slug, date: entry.date, source: entry.source,+ summary: entry.summary, detail: entry.detail || '', source_id: sourceId })), { auditSite: 'extract.timeline_db' });+}++/**+ * One page on a managed brain: null when the page is missing or filtered out,+ * 0 when nothing changes (no request admitted), else the rows the committed+ * request added. The request id is bound to the page revision, so a rerun+ * replays an accepted request instead of admitting a second one.+ */+async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAuthority, slug: string, sourceId: string,+ opts: TimelineDbOptions): Promise<number | null | 'skipped' | 'pending'> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) return null;+ const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true);+ if (!plan.removed && !plan.entries.length) return 0;+ for (let attempt = 0; ; attempt++) {+ const h = digest(['extract-timeline-db-v1', sourceId, slug, snapshot.revision, attempt]);+ const requestId = `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;+ try {+ const receipt = await submitDatabaseMaintenanceIntent(engine, authority, slug,+ { kind: TIMELINE_EXTRACT_INTENT, expected_revision: snapshot.revision, infer_dates: opts.inferDates === true }, requestId);+ return Number(receipt.added ?? 0);+ } catch (error) {+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return 'skipped';+ if (error instanceof OperationError && error.code === 'write_pending') return 'pending';+ throw error;+ }+ }+}++/** Preparer for `managed_maintenance_timeline_extract`: a database-only publication on the page key. */+export async function prepareTimelineExtract(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw new OperationError('page_identity_changed', 'The page was deleted or replaced before its timeline was extracted.');+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);+ const inferDates = (row.intent as { infer_dates?: unknown } | null)?.infer_dates === true;+ return { observedRevision: snapshot.revision, noop: true,+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },+ apply: async tx => {+ const current = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });+ if (!current) throw new OperationError('page_identity_changed', 'The page disappeared before its timeline was extracted.');+ return { status: 'completed', added: await writePageTimeline(tx, current.page, row.slug, row.source_id, inferDates) };+ } };+}diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex febabbdda9..d5c1a55cb5 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -247,7 +247,7 @@ 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. */+ /** #5904: timeline writes the writer refused or left pending (DB path); the command exits non-zero. */timeline_refused?: number;}@@ -751,7 +751,7 @@ export async function runExtractCore(engine: BrainEngine, opts: ExtractOpts): Prif (!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 } : {}) };+ return { links_created: 0, timeline_entries_created: r.created, pages_processed: r.pages, ...(r.refused + r.pending ? { timeline_refused: r.refused + r.pending } : {}) };}// Incremental path: if specific slugs provided, only extract from those files.@@ -1223,7 +1223,7 @@ export async function runExtract(engine: BrainEngine, args: string[], authority?}if (subcommand === 'timeline' || subcommand === 'all') {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 } : {});+ Object.assign(result, { timeline_entries_created: r.created, pages_processed: Math.max(result.pages_processed, r.pages) }, r.refused + r.pending ? { timeline_refused: r.refused + r.pending } : {});}}} else {diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 2947d62d08..329ab26235 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -283,6 +283,7 @@ export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: nuexport async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);+ if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);if (row.intent?.kind === 'managed_maintenance_page') {const prepared = await preparePageMutation(engine, row.intent.expected_revision === null? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);diff --git a/test/helpers/extract-timeline-db-scenarios.ts b/test/helpers/extract-timeline-db-scenarios.tsindex ca5098d410..bdb523eac9 100644--- a/test/helpers/extract-timeline-db-scenarios.ts+++ b/test/helpers/extract-timeline-db-scenarios.ts@@ -93,7 +93,8 @@ export async function managedTimelineDbRefusalExitsNonZero(databaseUrl?: string)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');+ // The coordinator reports a database refusal inside its publication as storage_error.+ expect(run.stderr).toContain('refused: storage_error; 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');diff --git a/test/helpers/managed-connector-job-contract.ts b/test/helpers/managed-connector-job-contract.tsindex d52e6193ec..7a2b5affbc 100644--- a/test/helpers/managed-connector-job-contract.ts+++ b/test/helpers/managed-connector-job-contract.ts@@ -96,7 +96,6 @@ export const EXPECTED_FAILURES: Partial<Record<ContractCase, { issue: string; siatom_drain_opted_in: { issue: '#5856', signature: /extract-atoms-drain ended dead after 3 attempt\(s\): Atom maintenance requires the configured canonical owner/ },atom_dispatch: { issue: '#5856', signature: /auto-drain submitted extract-atoms-drain for the connector source with connector atoms off/, engines: ['postgres'] },synthesize_publish_busy_writer: { issue: '#5854', signature: /The write is accepted and is still pending/ },- extract_timeline_db: { issue: '#5904', signature: /guard refusals: timeline_entries=/ },};/**