Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): apply waits for each publication with the CLI write wait (#6185)

garrytan9a957ae87612
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index c9b6b593c1..aba379ff65 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -3,9 +3,9 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (an applying runner resolves the CLI write wait once, before any kind runs, and puts it on the ctx as `writeWaitMs`, so every publication waits like other CLI writes and a malformed `GBRAIN_WRITE_WAIT_MS` refuses before a checkpoint; a preview never reads it); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
-- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
+- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, replays a still-pending request with the ctx's CLI write wait, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).
- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.
- `src/core/repair/failed-writes.ts` — `gbrain repair failed-writes` (#5983), explicit-only and preview-bound: candidates are failed, uncompacted `persistence_requests` refused by the managed writer guard (`writer_coordinator_required`, or `storage_error` "Publication failed (P0001)"). Caller writes (`put_page` without an internal `kind`, `add_timeline_entry`, `remember`) are classified `replay` / `already_written` / `duplicate` / `superseded` / `unpinned_target` by later requests on the same page and by a committed replay request id; owner-produced writes are `producer_owned` residuals with the producer command. The approved set records each target page's revision. Apply resumes an admitted replay attempt, otherwise reclassifies and rechecks the revision, re-runs `authorizeStoredRequest` on the failed row, and resubmits the retained intent on the original trust lane (`laneContext`: remote, take holders, delegated prefixes) through `submitPageMutation` / `submitRememberMutation`, with `put_page` bound to the previewed revision and `remember` pinned to its resolved subject, under a request id derived from the failed request id and attempt (`repair-failed-writes-5983.test.ts`).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 8136d0fe4f..2091a45491 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -832,6 +832,12 @@ crash replays the same write instead of making a second one. If the run stops
with "still pending publication" or "the canonical writer ... is held", check
`gbrain sources writer status <source>`, then rerun the printed apply command.
+Every applying kind waits for each publication with the CLI write wait: `--wait <seconds>`, then
+`GBRAIN_WRITE_WAIT_MS`, then `persistence.write_wait_ms`, else 30 seconds. That includes the doctor
+remediation run and the replay of a restore a previous `extractor-facts` apply left pending. A malformed
+`GBRAIN_WRITE_WAIT_MS` refuses the apply with `invalid_write_wait` before anything is written; a preview
+never reads it.
+
## Capacity stop
`timeline` and `visibility` write through the managed write journal, which has
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 449dee9b44..2f41a3bc43 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -257,6 +257,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.97.0', text: 'Google Calendar sync writes only events between `historyDays` back and 60 days ahead; `gbrain sync --full` removes pages for in-window events the calendar no longer lists (more than 200 is refused and reported partial).' },
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
+ { since: '0.0.0-wave11', text: '`gbrain repair <kind> --apply` and `gbrain doctor --remediate` now wait for each publication with the CLI write wait (`--wait`, `GBRAIN_WRITE_WAIT_MS`, `persistence.write_wait_ms`, else 30 s) instead of 5 s, so one run repairs a slow source; `--wait 0` stops at the first pending write and the rerun resumes.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.ts
index d7e7b1532f..0a14fa8235 100644
--- a/src/core/repair/extractor-facts.ts
+++ b/src/core/repair/extractor-facts.ts
@@ -320,7 +320,7 @@ export const extractorFactsRepair: RepairHandler = {
async apply(ctx, entry): Promise<RepairItemOutcome> {
const { page, hash, last } = entry as PageItem;
const result = await managedPersistenceEnabled(ctx.engine)
- ? await restoreManaged(ctx.engine, ctx.config, page, hash)
+ ? await restoreManaged(ctx.engine, ctx.config, page, hash, ctx.writeWaitMs)
: await maintenanceTransaction(ctx.engine, async tx => {
await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
return restorePageFacts(tx, page, false);
@@ -334,7 +334,8 @@ export const extractorFactsRepair: RepairHandler = {
interface RestoreResult { restored: number[]; changed: number[] }
-async function restoreManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: ExtractorFactsPage, hash: string): Promise<RestoreResult> {
+async function restoreManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: ExtractorFactsPage, hash: string,
+ writeWaitMs: number | undefined): Promise<RestoreResult> {
const unchanged: RestoreResult = { restored: [], changed: page.facts.map(f => f.id) };
const authority = (await maintenancePreflight(engine, page.source_id))!;
for (let attempt = 0; ; attempt++) {
@@ -345,7 +346,8 @@ async function restoreManaged(engine: BrainEngine, config: Parameters<typeof wai
let receipt: Record<string, unknown>;
if (prior) {
await authorizeStoredRequest(engine, prior);
- receipt = writeResponse(await waitForWrite(engine, prior, config));
+ // #6185: a pending restore replayed by a resumed apply waits like the apply's own writes.
+ receipt = writeResponse(await waitForWrite(engine, prior, config, writeWaitMs));
} else {
const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
if (!snapshot || snapshot.page.id !== page.page_id) return unchanged;
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index b026a20b0c..1d533e4dca 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -21,6 +21,7 @@
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
import { loadConfig } from '../config.ts';
+import { currentCliWriteWait } from '../persistence/write-wait.ts';
import { REPAIR_KINDS, runRepair, type RepairHandler, type RepairKind, type RepairResult, type RepairScope } from './core.ts';
import { timelineRepair } from './timeline.ts';
import { visibilityRepair } from './visibility.ts';
@@ -236,6 +237,10 @@ export function repairApplyCommand(kind: RepairKind, opts: { source?: string; no
* so a kind previews and applies identically from either entry point.
*/
export async function repairRunner(engine: BrainEngine, opts: { apply: boolean; noEmbed?: boolean; logger?: OperationContext['logger'] }) {
+ // #6185: an apply waits for each publication like every other CLI write (`--wait`, GBRAIN_WRITE_WAIT_MS,
+ // persistence.write_wait_ms, else 30 s). Resolved before any kind runs, so a malformed value refuses before
+ // a checkpoint is written; a preview never publishes and never reads it.
+ const writeWaitMs = opts.apply ? currentCliWriteWait().waitMs : undefined;
const config = loadConfig() ?? { engine: engine.kind };
let embeddingModel: string | undefined;
try { embeddingModel = config.embedding_disabled ? undefined : (await import('../ai/gateway.ts')).getEmbeddingModel(); } catch { embeddingModel = undefined; }
@@ -244,7 +249,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
embeddingModel,
/** `explicit`: the operator named `kind`; required for explicit-only kinds. */
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[] } = {}): Promise<RepairResult> {
- const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } as OperationContext;
+ const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
const spec = repairSpec(kind);
return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag,
embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],
diff --git a/test/repair-command.test.ts b/test/repair-command.test.ts
index bf7331d608..11c2fb8623 100644
--- a/test/repair-command.test.ts
+++ b/test/repair-command.test.ts
@@ -24,6 +24,10 @@ import { withEnv } from './helpers/with-env.ts';
import { testBackends } from './helpers/test-backends.ts';
import { runCli } from './helpers/cli-spawn.ts';
import { MinionQueue } from '../src/core/minions/queue.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { getCliOptions, setCliOptions } from '../src/core/cli-options.ts';
+import { repairRunner } from '../src/core/repair/registry.ts';
+import { planRepairSteps, runRepairSteps } from '../src/core/remediation/repairs.ts';
const backends = testBackends();
@@ -216,6 +220,77 @@ describe('gbrain repair timeline', () => {
}, 120_000);
});
+/** Every publication stalls at the consumer for `ms` before it commits (#6185). */
+async function withSlowPublications<T>(ms: number, run: () => Promise<T>): Promise<T> {
+ installFaultHook(async point => { if (point === 'consumer:prepared') await new Promise(resolve => setTimeout(resolve, ms)); });
+ try { return await run(); } finally { installFaultHook(undefined); }
+}
+
+async function withWriteWait<T>(writeWaitMs: number | undefined, run: () => Promise<T>): Promise<T> {
+ const previous = getCliOptions();
+ setCliOptions({ ...previous, writeWaitMs });
+ try { return await run(); } finally { setCliOptions(previous); }
+}
+
+describe('#6185: repair --apply waits with the CLI write wait', () => {
+ test('a publication slower than the 5 s agent wait commits within the CLI default, and one run repairs every page', async () => {
+ await brain(async (engine, [source]) => {
+ for (const slug of ['notes/a', 'notes/b']) await pageWithHistory(engine, source, slug);
+ const scope = await resolveRepairScope(engine);
+ const runner = await repairRunner(engine, { apply: true, noEmbed: true, logger: { info() {}, warn() {}, error() {} } });
+ const applied = await withSlowPublications(5_500, () => runner.run('timeline', scope));
+ expect(applied.stopped).toBeUndefined();
+ expect(applied).toMatchObject({ applied: 2, complete: true });
+ expect(await markedPages(engine, source)).toEqual(['notes/a', 'notes/b']);
+ });
+ }, 120_000);
+
+ test('--wait 0 still stops at the pending write with the resume message, and the rerun finishes', async () => {
+ await brain(async (engine, [source]) => {
+ await pageWithHistory(engine, source, 'notes/a');
+ const scope = await resolveRepairScope(engine);
+ const quiet = { info() {}, warn() {}, error() {} };
+ const stopped = await withWriteWait(0, async () => withSlowPublications(1_000,
+ async () => (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope)));
+ expect(stopped.applied).toBe(0);
+ expect(stopped.stopped).toEqual({ reason: 'write_pending', message: `The repair of ${source}:notes/a was accepted and is still pending publication. `
+ + 'Rerun `gbrain repair timeline --apply` to resume; the same request is replayed.' });
+ const resumed = await (await repairRunner(engine, { apply: true, noEmbed: true, logger: quiet })).run('timeline', scope);
+ expect(resumed).toMatchObject({ complete: true });
+ expect(await markedPages(engine, source)).toEqual(['notes/a']);
+ });
+ }, 120_000);
+
+ test('the doctor remediation run uses the same wait: under --wait 0 a slow publication reports stopped', async () => {
+ await brain(async (engine, [source]) => {
+ await pageWithHistory(engine, source, 'notes/a');
+ const steps = (await planRepairSteps(engine, { noEmbed: true, kinds: ['timeline'] }));
+ expect(steps.map(step => step.kind)).toEqual(['timeline']);
+ const [result] = await withWriteWait(0, () => withSlowPublications(1_000,
+ () => runRepairSteps(engine, steps, { remote: false, noEmbed: true, remainingUsd: () => undefined })));
+ expect(result).toMatchObject({ kind: 'timeline', status: 'stopped', applied: 0 });
+ expect(result.message).toContain('still pending publication');
+ });
+ }, 120_000);
+
+ test('a malformed GBRAIN_WRITE_WAIT_MS refuses the apply before any checkpoint; the preview still runs', async () => {
+ await brain(async (engine, [source]) => {
+ await pageWithHistory(engine, source, 'notes/a');
+ await withEnv({ GBRAIN_WRITE_WAIT_MS: 'soon' }, async () => {
+ await expect(repairRunner(engine, { apply: true, noEmbed: true })).rejects.toMatchObject({ code: 'invalid_write_wait' });
+ await expect(runRepairCommand(engine, ['timeline', '--apply'])).rejects.toMatchObject({ code: 'invalid_write_wait' });
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair'")).toEqual([]);
+ expect(await markedPages(engine, source)).toEqual([]);
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { out.push(args.join(' ')); };
+ try { await runRepairCommand(engine, ['timeline', '--json']); } finally { console.log = log; }
+ expect(JSON.parse(out[0]).results[0]).toMatchObject({ mode: 'dry_run', affected: 1 });
+ });
+ });
+ }, 120_000);
+});
+
describe('timeline_history doctor check', () => {
test('exact counts on a seeded brain, a lower bound when the scan is capped, and ok after the repair', async () => {
await brain(async (engine, [source]) => {
diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.ts
index 658f76ef7e..7cc3201847 100644
--- a/test/repair-extractor-facts.test.ts
+++ b/test/repair-extractor-facts.test.ts
@@ -37,6 +37,8 @@ import { compactWriteReceipts } from '../src/core/persistence/journal.ts';
import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
@@ -305,6 +307,32 @@ for (const backend of testBackends()) {
} });
}, 120_000);
+ test('#6185: a resumed apply replays a still-pending restore with the CLI write wait, not the 5 s agent wait', async () => {
+ const seeded: Record<string, number[]> = {};
+ await managedBrain(async ({ engine, ctx }) => {
+ await prefixExpire(engine, ctx, 'conversations/slow');
+ const hash = hashOf(await repair(engine, null, []));
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ installFaultHook(async point => { if (point === 'consumer:prepared') await gate; });
+ try {
+ const restoreWait = __setMaintenanceWriteWaitForTests(0);
+ let first: RepairJson;
+ try { first = await repair(engine, null, ['--apply', '--expect', hash]); } finally { restoreWait(); }
+ expect((first.results[0] as { stopped?: { reason: string } }).stopped?.reason).toBe('write_pending');
+ expect(await activeIds(engine, seeded.slow)).toEqual([]);
+ // The publication is still held when the rerun starts and commits 5.5 s into its replay wait.
+ setTimeout(release, 5_500);
+ const resumed = await repair(engine, null, ['--apply', '--expect', hash]);
+ expect((resumed.results[0] as { stopped?: unknown }).stopped).toBeUndefined();
+ expect(resumed.results[0]).toMatchObject({ applied: 1, outcomes: { restored: 1 } });
+ expect(await activeIds(engine, seeded.slow)).toEqual(seeded.slow);
+ } finally { release(); installFaultHook(undefined); }
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ seeded.slow = await conversation(engine, 'conversations/slow', ['Alice sends the deck'], root);
+ } });
+ }, 120_000);
+
test('the preview warns, naming the host, when a consumer older than this release published after the cutoff', async () => {
await managedBrain(async ({ engine, ctx }) => {
const request = await prefixExpire(engine, ctx, 'conversations/mixed');