Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

doctor, sync status: #6803 lane C docs, behavior rows, weights and doctor-scale bench

garrytan6dc56eddf745
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 0b984c4067..158f5c1b5b 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -29,5 +29,5 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/keyword-plan.ts` — `keyword_plan` (#6495, OPS, wave check with operator resolution; the keyword-side twin of `vector_plan` in commands-2.md). Postgres only: reads the commonest lexeme the planner knows for `content_chunks.search_vector` (`pg_stats.most_common_elems` with its frequency), EXPLAINs (no ANALYZE) the strict page-count statement for it (`buildKeywordCountStatement`, the builder the engine uses) and times the engine's own bounded `countKeywordPages(term, { timeoutMs: 2000 })`; warns `canary_timed_out` when that count hits its bound and `canary_slow` when it takes more than half of `search.keyword_statement_timeout_ms`, naming the knob with its range (1000-60000), the fail-open to the vector arm (`keyword_arm_failed`), that a longer bound buys time and not a cheaper statement, that one canary term is not workload coverage, and that a timed-out count is never "no matches". Skipped on PGLite, below 10,000 chunks (`pg_class.reltuples`) and without planner statistics (it names `ANALYZE content_chunks`); a failing probe reports unknown health. `engineKeywordPlanProbe(engine)` is the database side; `keywordPlanCheck(engine, probe?)` takes a fake for tests. Tested in `test/doctor-keyword-plan-6495.test.ts` (fake probe for every outcome; with DATABASE_URL the real probe on a seeded brain and a lock-forced timeout).
- `src/commands/doctor/checks/image-embedding-coverage.ts` — `image_embedding_coverage` (#6529, brain category, after `image_assets`). Counts live image pages (`page_kind = 'image'`), those with no `embedding_image` chunk, those with a NULL `source_path`, and the `managed_image_sync_unsupported` holds per source, and reads `isMultimodalEnabled()`. Ok when the brain has no image pages, when every image page has an image vector and a `source_path` and nothing is held, or when multimodal embedding is off (the counts are then informational: image search is not expected to work). On a multimodal install it warns with the counts (text coverage counts those pages as embedded while image search does not see them) and names `gbrain embed --stale --images` and `gbrain sync --no-pull --source <id>` for the holds. Read-only; no paid call. Test: `test/doctor-image-embedding-coverage.test.ts`.
- `src/commands/doctor/checks/provider-consent.ts` — `provider_consent` (OPS, engine-free filesystem lane right after `embedding_key_source`; not in `doctorReportRemote`): the provider-use decision `gbrain setup` recorded for this install (`localSetupRecords` in `src/core/setup/local-receipts.ts`). A decline (any live receipt; opt-outs win) is `ok` + info `disabled_by_choice`, "skipped by consent", naming the provider key variables present (names only) and carrying `providerConsentFix`: `gbrain setup <harness> --providers` (+ `--name`/`--scope project`), actor `user`, consent `paid`+`egress`, so `next: tell_user_to_run`. Accepted is plain `ok`; no receipt is info `not_applicable`. The same fix rides `embedding_provider`'s `--probe` skip (`checks/embedding-health.ts`), and `probe-consent.ts` authorizes nothing when a decline is recorded. Reads files only; sends nothing. Pinned by `test/doctor-provider-consent.serial.test.ts` (request counter: zero outbound under a decline, controls prove discovery and the probe are seen otherwise).
-- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those, reads through `deadlineEngine` (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`.
+- `src/commands/doctor/budget.ts` + `checks/ops-sections.ts` + `checks/orphan-estimate.ts` — doctor tiers and budgets (#6696 B1). `parseDoctorTier` (`--tier ops|standard|deep`, a bad value is `invalid_params`), `parseBudgetMs` (`--budget-ms`, default 4000 under ops, none otherwise) and `startDoctorDeadline` build the `DoctorDeadline` the CLI starts before connecting. `runDoctorRegistry` runs the entries tagged `tier: 'ops'` (persistence capacity, terminal failures, managed sync movement, persistence compaction, serve build drift, schema-pack consistency, embedding state) right after the connection lane; under `--tier ops` it runs only those (each `executeRaw` gets the absolute `deadlineAt`, so `SET LOCAL statement_timeout` is the time left after the pool wait: `postgres-engine/bounded-statement.ts`), reports an entry marked `opsPglite: 'not_applicable'` as an `ok` info row on PGLite, and stays complete. Every other tier bounds each entry by `doctor.entry_budget_ms` (default 15000). An entry past its budget, an unknown reported after the overall deadline, or a connect the deadline ended becomes `budgetUnknownCheck` (warn, `details.health: 'unknown'`, `reason: 'budget'`, `exact: false`, a rerun-alone fix), never a clear result; every check carries `elapsed_ms`, and the report adds `tier`/`complete`/`unknown_sections`/`elapsed_ms`/`budget_ms` only when `--tier` or `--budget-ms` was given (`doctorRunSummary`). `doctorHealth(ctx)` memoizes `getHealth` for one run. `orphan_ratio` estimates from a `TABLESAMPLE SYSTEM` sample above `doctor.orphan_ratio.full_scan_max_pages` (default 50000) unless `--tier deep`. Capacity (`persistence_capacity`, PR A's forecast) and compaction freshness (`persistence_compaction`) run as ops entries in `checks/ops-sections.ts`. #6803 (Part 5): on every tier each entry runs inside its own `StatementDeadline` (`src/core/statement-deadline.ts`: an AsyncLocalStorage scope plus `deadlineBoundEngine`, one stable Proxy per real engine that refuses any engine call past the deadline, carries the deadline to the server on Postgres `executeRaw`, and marks the scope expired on a cancel even when the check catches it; `engineCacheKey` maps the wrapper to the real engine for engine-keyed caches; PGLite gets only the pre-statement refusal). The budget-config read is one bounded statement (2 s, default kept). `CHEAP_INCIDENT_CHECKS` (by check name: persistence capacity, managed sync movement, `text_projection_readiness`, `partial_embedding`, `links_extraction_lag`, now its own entry) run right after the ops sections, before any full scan. `scanDeadline` clips the frontmatter walk and the fence census to the entry deadline less 250 ms, so they report partial results. `--only` with an explicit `--budget-ms` gives the selected entries the whole overall budget; `budgetUnknownCheck` names the limiting budget (`details.limit`: `entry` or `overall`) and fixes with `--only <check> --budget-ms N` (N ten times that budget; actor agent while N fits `AGENT_TOOL_LIMIT_MS` less 10 s, else actor user). `--budget-ms 0` is no overall budget. `default-budget.ts`: a plain non-interactive CLI `doctor --json` (stderr not a TTY; no `--budget-ms`, `--tier`, `--fix`, `--remediate` or `--remediation-plan`) caps its check run at `doctor.default_budget_ms` (file plane, default 90000, 0 off), started by `startDeferredDeadline` when the registry starts (connect and migrations are outside it), with one stderr line; the report then carries the tier fields. `capacity-memo.ts` `doctorCapacityForecast`: one forecast per run (shared by `persistence_capacity` and `persistence_request_growth`) read under the run's overall deadline and dropped from the memo on a deadline failure, which makes the waiting check unknown instead of a counter-only verdict. `persistence_session_timeouts` reads `SHOW statement_timeout` outside the entry deadline. Tests: `test/doctor-tier-6696.test.ts`, `test/doctor-day-zero.test.ts` (`--tier ops`), `test/e2e/doctor-ops-tier-postgres.test.ts`, `test/doctor-entry-deadline-6803.test.ts` (plus `test/e2e/doctor-entry-deadline-postgres.test.ts`, in the PgBouncer matrix), `test/doctor-default-budget-6803.test.ts`; bench `scripts/bench/doctor-scale.ts`.
- `src/commands/doctor/brain-health-bands.ts` + `remote-tier.ts` + `ops-snapshot.ts`, `src/core/doctor-remote-tier.ts`, `src/core/persistence/capacity-view.ts` — the ops tier for agents and remote clients (#6696 B2). `readCapacityView` (for `/admin/api/ops`) reads the counter rows, `capacityDiagnostics`, the light `readCapacityForecast` (null when unreadable: days unknown) and `readLastCompaction`; the bands read `cachedCapacitySnapshot`; `capacityVerify()` is the verify of every capacity fix (`gbrain doctor --only persistence_capacity --json` plus MCP `get_brain_health`). `readBrainHealthBands` backs the read-scope `get_brain_health` op: capacity band and days band, write failures and active blockers as count bands for the caller's readable sources, no slugs or exact counters, cached 60 s per engine and scope. `runRemoteDoctorTier` backs `run_doctor`'s `tier: "ops"` / `only` (admin). `runScopedRemoteDoctor` is the thin client's `gbrain doctor --tier ops` / `--only <registry check>`: it reads `tools/list` and uses `run_doctor` with the parameters, else the bands (`BAND_CHECKS`), else refuses `doctor_tier_unavailable`; it never runs the full remote report in their place. `cachedOpsSnapshot` serves `/admin/api/ops` from one ops run a minute. Tests: `test/doctor-ops-remote-6696.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.md
index 165e095a15..c379f605cd 100644
--- a/docs/architecture/key-files/core-persistence-capacity.md
+++ b/docs/architecture/key-files/core-persistence-capacity.md
@@ -6,7 +6,7 @@ Cumulative write caps (permanent request ids, receipt bytes) and the paths that
- `src/core/persistence/receipt-true-up.ts` — `trueUpRequests(engine, ids)`: after the settling transaction commits, in its own short transaction, locks the brain and principal counters in key order, then a compare-and-set on each request row (still `terminal_reservation` as read, no queued or running effect, same effect bytes) shrinks it to `retainedReceiptBytes` and releases the difference. Idempotent; never touches `updated_at`. Called from the effect runner (`effects.ts`, every claimed request), `embedding-settlement.ts`, `embedding-noop-settle.ts` (the `embed --stale` bulk settle), `effect-retry.ts` (reconciled) and `backup/snapshot.ts` (restore). `test/persistence-true-up-sites.test.ts` fails on an effect state-change site that is not wired. `sweepCompactedReservations` is the bounded one-shot pass over receipts compacted with their full reservation (cursor `persistence.true_up.compacted_through`, `done` at the end).
- `src/core/persistence/admission-origin.ts` — `withAdmissionOrigin('interactive' | 'background')` (an outer background scope wins), `resolveAdmissionOrigin` (unset reads background, never derived from `ctx.remote`), `persistence.capacity.background_pause_pct` (default 80) and `backgroundPaused`, the `write_capacity_backpressure` refusal background producers get past the line.
- `src/core/persistence/capacity-forecast.ts` — `readCapacityForecast`: per principal, one statement walks `persistence_requests_principal` newest first until `created_at` leaves the 7-day window and buckets by day; gross and net (compacted) receipt rates, `days_to_exhaustion`, `basis` (`:legacy_under_reserved` while receipts admitted before the intent-sized reservation remain), `recommended_limit`. `light` skips the reclaim read and table size. Thresholds `persistence.capacity.warn_days` (30) and `fail_days` (7).
-- `src/core/persistence/capacity-snapshot.ts` — `cachedCapacitySnapshot`: one light forecast per engine per 60 s, shared by every caller; `capacityNotices` builds `write_capacity_low` (kind `info`, muteable; hourly per process per scope on write and sync receipts, `scopes` limits a remote caller to the brain and its own principal) and `write_capacity_backpressure` (once per pause start). Read by `mcp/dispatch.ts`, `cli/main.ts`, `commands/sync/{run,operator}.ts`, `cycle.ts` and the admin `/metrics` gauges in `serve-http-metrics.ts`.
+- `src/core/persistence/capacity-snapshot.ts` — `cachedCapacitySnapshot`: one light forecast per engine per 60 s, shared by every caller; `capacityNotices` builds `write_capacity_low` (kind `info`, muteable; hourly per process per scope on write and sync receipts, `scopes` limits a remote caller to the brain and its own principal) and `write_capacity_backpressure` (once per pause start). Read by `mcp/dispatch.ts`, `cli/main.ts`, `commands/sync/{run,operator}.ts`, `cycle.ts` and the admin `/metrics` gauges in `serve-http-metrics.ts`. #6803: the cache keys on the real engine (`engineCacheKey`), the shared fetch is bounded at `CAPACITY_FETCH_BOUND_MS` (10 s) and a timed-out fetch is never cached; `capacitySnapshotWithin` (sync status, write and sync receipts: `CAPACITY_READ_WAIT_MS`, 1.5 s) returns `unknown` for that call alone, and `capacityNotices` on an unknown snapshot returns no notice and leaves throttle and pause state as it was. Test: `test/capacity-bounded-read-6803.test.ts`.
- `src/core/persistence/compaction-pass.ts` — `runCompactionPass`, the consumer's idle and volume maintenance: `compactWriteReceiptsDetailed`, one sweep step, and the `persistence.maintenance.last_compaction` record (`at`, `host_id`, `compacted`, `freed_bytes`, `skipped_by_reason`). `journal.ts` `compactReceipt` compacts one receipt in its own transaction (counters first, `lock_timeout` 2 s, `statement_timeout` 15 s) and skips open managed-sync runs (`OPEN_SYNC_CURSOR_EXCLUSION`) and the newest sync receipt per worktree (`newestSyncReceipt`).
- `src/core/repair/receipt-compaction.ts` — `gbrain repair receipt-compaction`: explicit-only, preview-bound, destructive consent, `publication: 'projection'`; `--older-than` (the `pages purge-deleted` grammar) floored at the configured retention unless `--force`, committed only unless `--include-failures`; the approved set binds an absolute cutoff and the newest sequence. Test: `test/repair-receipt-compaction.test.ts`.
- `src/core/persistence/refusal-breaker.ts` — `assertRefusalBreakerClosed`: `submitMaintenance` refuses before admission after `persistence.maintenance.refusal_breaker_threshold` (3; 0 off) same-code terminal refusals in 24 h for the same request `digest` (source, slug, intent with its revision and planner); `listSuppressedWrites` feeds doctor `maintenance_write_drift`. The ghost case (`canonical_file_missing`, tagged by `page-prepare.ts`, kept in `error_detail.origin`, returned by `liveFileDrift`) refuses before admission in `prepared-maintenance.ts`. Test: `test/maintenance-ghost-breaker-6696.test.ts`.
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 582f19201b..e18044235a 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -37,7 +37,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks with `identity: 'reservation'` (#5914: it publishes nothing, so a recreated directory whose reservation names the worktree and whose stamp carries the same token releases; a token mismatch refuses), then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.
- `src/core/persistence/sync-page-fault.ts` — #6340: a page that moved under a managed catch-up holds the page, not the run. `headCommittedBytes` returns the working-tree bytes of a path when their blob id equals `HEAD:<path>` (sha1 or sha256 by HEAD's id length), so `freezeEntry` imports bytes committed past the pinned target as HEAD has them (the later pin..HEAD diff re-imports them as a no-op; idea and first test from PR #6323, which this supersedes) and `prepareManagedSyncMutation`'s `newerWorkingTree` screen never sees them. `pageChangeProof` is #6194's revision-linked proof usable at freeze time; `pageChangedHold` builds the `concurrent_write` hold for a database page that was edited, deleted or re-bound after enumeration (with the competing request when proven, else `page_revision` + `expected_revision`), `worktreeDirtyHold` the new `worktree_dirty` hold (pinned `blob_oid`, `working_hash`) for uncommitted bytes that match neither the pin nor the page, `pinnedWorktreeConflict` recognizes that receipt and `pageMovedSinceAdmission` a `revision_conflict` receipt whose page really moved (a run-level conflict with the page where it was still blocks). In `sync-run.ts`: `freezeEntry` resolves the three freeze-time throws (`page_identity_changed`, `revision_conflict`, the renamed-source conflict) into holds when holds are on (a page that still holds exactly what the import carries is re-bound to its new revision and passed by the waiver screen; `sync.holds=fail` and company-brain cursors keep the refusals), `holdFailedFenceRequest` converts the two receipts (imports and deletes) through `receiptPageFaultHold`, re-freezes an entry once under a fresh request when its file changed between admission and publication (`fileChangedAfterAdmission`, the `raw_file_changed` receipt: committed bytes then import as HEAD has them, a second change under the re-frozen request is held `worktree_dirty`; `holdUnderGate` takes `refrozen` in place of `hold` and records the conversion as `refrozen`), `convertBlockedCursor` converts a cursor an older release left blocked (re-freezing a dirty file that is committed now), `originFaultHold` holds an entry whose recorded origin no longer identifies the enumerated page (`assertSyncPageOrigin` at freeze), every page-fault hold marks the cursor `overtaken` (#5522: another cursor may have checkpointed this target), and the `--retry-failed` start tries that conversion before rediscovering, so the frozen manifest survives. `writeGitHold` counts `meta.attempts` per re-hold with the same code; `HOLD_ATTEMPTS_NEEDS_HUMAN` (3) turns a page hold into `needs_human`. The run's catch skips the failure ledger for `isRetryableConnError` / statement timeouts. Tests: `test/managed-sync-page-fault-holds.test.ts` (freeze-time DB edit → hold, same content → re-bind, dirty → `worktree_dirty` → commit → import, committed past pin → HEAD bytes, old blocked cursor → in-place conversion with attempts, connection death → no ledger row, same run on relaunch, one extra pass), the updated expectations in `test/persistence-managed-sync.test.ts` and `test/managed-sync-concurrent-write-hold.test.ts`.
-- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).
+- `src/core/persistence/sync-fault-class.ts` + `sync-status.ts` + `src/commands/sync/operator.ts` — #6340: the operator contract. `SYNC_FAULT_TABLE` / `classifySyncFault` turn a code (plus a receipt `detail`, a hold's `attempts`, an error message) into `{ class: page | connection | systemic, safe_actions, needs_human, human_reason }`; `docs/guides/sync-unblock-runbook.md` renders the table between `sync-fault-table` markers and `test/sync-runbook-table.test.ts` pins the two. `readSyncStatus` joins the cursor header (index/total, pinned target, last advance, rate; #6518: the newest cursor recorded under the source's *current* incarnation, the only one a current sync can select), `committed_last_10m` (committed managed page requests of the source), every hold (with `gitHoldFix`) and the last ledger failure (never the read view's `sync_incomplete`) into `SyncStatus` with one `next` action (a human's fix with `user_message`, else `gbrain sync unblock --apply`, else the resume command, `--retry-failed` when a ledger row exists). When no current-incarnation cursor or failure exists but an unfinished cursor stands under an older incarnation, the status is `cursor: null` with `last_error.code: cursor_incarnation_retired` (table row: systemic, `repair`, no human) and `next` is the `gbrain repair managed-sync-orphans --source <id>` preview, never a sync that selects nothing. #6712 PR 2 (L5): `state`/`reason` (`SYNC_STATUS_REASONS`), the bounded `oldest_blocker` (the drain's head probe) and `recovery` probes; `readSyncStatus(…, { detail })` skips the terminal summary, blocker list and cursor join when false (the plain CLI), each with a `<field>_read` `not_read` sibling; `syncStatusHeadline` is the text headline. `unblockSync(engine, sourceId, { apply, noRepair?, noLlm?, maxLlmUsd?, registry? })` schedules a re-screen (`requestGitHoldRetry`) for a `worktree_dirty` hold whose file is committed at HEAD now and for a `preparation_stalled` hold; for a repair-class hold whose code `CONTENT_REPAIR_HOLD_KINDS` maps to a content-repair lane kind (#6377; `invalid_fence` → `fences`) it runs that kind on exactly those paths through `runContentLane` as one bounded apply (`UNBLOCK_REPAIR_BUDGET_MS` = 120 s, the `fences.repair` caps, `noLlm` for the free tiers), re-reads the holds, and reports each path as `applied[].action: 'repair'` with `repair: { kind, outcome: repaired | held | needs_human | skipped, reason?, tier?, llm_usd?, receipt? (the write's location-only detail), next }` (a path the kind kept out of its plan takes the reason the kind recorded on the hold); repaired paths join the re-screen. It refuses `still_dirty`, `concurrent_write`, exhausted holds, repair-class holds no lane kind clears yet (or all of them under `noRepair`), and holds whose stored repair state says a person decides (`contentHoldDisposition`: a manual or paid fence state, a recommended merge; these are listed, never retried) by name with their fix; previews without `--apply` (repair holds listed as `skipped` / `preview`); and is idempotent. `holdVerdict` makes `readSyncStatus` report such a hold `needs_human` with the paragraph (the fault table's when it names the lane's codes, else a sentence naming the state), and `next` says when unblock would write hash-bound repairs with a receipt per file. The CLI subcommands `gbrain sync status --source <id> [--json]` and `gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]` (routed in `sync/run.ts` like `sync trigger`; `cli.ts` skips the sync watchdog and the serve delegations for them; #6803: `syncOperatorVerb` is the one classifier both use, so `gbrain sync --status` is the same status read with a stderr hint, and `--preview` and `--check`, which no sync path reads, refuse `invalid_params` with a `--dry-run` fix; test `test/sync-status-flag-6803.test.ts`) print the envelope with `next` (and each repair outcome's `next`) rendered through `renderAction`, plus a receipt line per repaired file; `--json` writes the envelope through `writeJsonDocument`, so under the D2 guard it is the one stdout document. Tests: `test/sync-status-unblock.test.ts`, `test/cli-json-guard.test.ts`. #6402: `cancelled` (a knock-on window cancel) is a `page` / `retry` row, not needs_human, so `sync status` hands the loop the same retry sync's own `Next:` prints (`sync-cancelled-knock-on.test.ts`).
- `src/core/persistence/sync-drain.ts` (#6340 additions) — `isConnectionDrop` (a retryable connection error that is not #6329's `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` settle discard; `retry-matcher.ts` now matches `ECONNABORTED`, `ETIMEDOUT` and `EPIPE` beside `ECONNRESET`); `runDrain` reconnects (`DrainInput.reconnect`, `engine.reconnect` from `drainManagedSync`) and retries a dropped pass on `CONNECTION_RETRY_MS` (5/15/45 s), resets the count on every committed page, and after `CONNECTION_STRIKES` drops with no commit between them ends `blocked` / `connection_lost` with `drain.connection { drops, last_error }` (URLs stripped) and the resume command as a loopable `next` (`sync_drain_connection_lost` in the catalogue, `connection_lost` in the registry). `drainManagedSync` takes exactly one extra pass (`drain.extra_pass { from, to }`, counts merged by `mergeExtraPass`) when HEAD moved past the pinned target during a `synced` run, so a live checkout ends at HEAD without looping. Tests: `test/sync-drain-connection.test.ts`. In-pass governor: `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted with `DrainPassAbandoned` (the pass's `assertActive` / `stampDrainStep` boundaries throw it, so it admits and writes nothing more; `stampDrainStep` does not throw the caller's own cancel, which still banks admitted work) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_progress` / `owner_missing` (#6712 PR 2 retired `no_admission`); a live preparation is left to its own budget and ceiling. The pass returns at the checkpoint commit (`managed_sync.finish` counts as a commit); its tail runs after the lease is released (`sync-tail.ts`). `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts` reports a delegated stop as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-drain-finish-tail.test.ts`, `test/sync-waivers-chunk.test.ts`.
- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). W4.4: when `git rev-parse` fails for a directory that holds a `.git` entry (damaged HEAD, dubious ownership, timeout, Git missing), `detectManifestScope` refuses `writer_manifest_unsafe` with a `git -C <dir> status` fix instead of falling back to `tree` (which read ignored files); only a directory that `git-checkout.ts` `classifyGitCheckout` reads as `not_git` (no `.git` entry at or above it, no `GIT_DIR`) keeps `tree` scope. Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). #6510: `trackedBytes` checks for symlinks with `lstat` on every directory component between the canonical root and the leaf, then the leaf, on every read (no cache across files: a parent swapped to a symlink after the first file would otherwise let a later leaf read outside the root), reading through the Git spelling; the former `realpath(path) === path` proxy refused a checkout whose volume spells a name differently (APFS NFC/NFD, case-insensitive volumes) with no symlink anywhere. Tests: `test/persistence-manifest-git-scope.test.ts`, `test/worktree-manifest-unicode.test.ts` (synthetic realpath-spelling spy on Linux, parent-swap, case-spelling where the tmpdir is case-insensitive), `test/hardened-git-filters.test.ts`.
- `src/core/git-checkout.ts` — #6210 (fix wave 12): `classifyGitCheckout(dir, env = process.env): 'git' | 'not_git' | 'unknown'` decides from the filesystem alone whether a directory is inside a Git checkout: `not_git` only when the directory exists and no `.git` entry (directory or gitdir file) is at or above it and `GIT_DIR` is unset; `unknown` for a missing directory or any lookup error other than absence. Git's own exit 128 is locale-dependent and also means a damaged HEAD, a bad gitdir or dubious ownership, so callers that soften "not a checkout" use this instead. `isDurabilityHardenedAsync` (`brain-repo-durability.ts`) returns false only for `not_git` or an absent hook; every other failure (a git probe run with `LC_ALL=C` failing, a timeout, an unreadable hook) rejects `git_unavailable`, and `runPersistenceEffects` (`persistence/effects.ts`) settles each cached per-root probe to `{durable}|{error}` and records the error on every coalesced effect, so the effects stay queued (and park after repeated failures) instead of completing as `durability_not_enabled`. Tests: `test/git-checkout.test.ts`, `test/persistence-git-durability-probe-6210.slow.test.ts` (Postgres via `test/e2e/persistence-git-durability-probe-6210-postgres.test.ts`; fix wave 16 split it out of the 5530 coalescing file, whose fixture both share through `test/helpers/git-coalescing-fixture.ts`).
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index e52dec1db3..e10d6ff38c 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -251,7 +251,7 @@ A running sync is not one of these: `gbrain repair fences` now runs during a cat
<a id="write-capacity"></a>**Managed writes refused with `queue_capacity`, or doctor warns `persistence_capacity`?** A per-principal or per-brain write-journal limit (`persistence.limits.*`) is full (`queue_capacity`), or doctor sees lifetime request IDs or receipt bytes at 80% or more (`persistence_capacity`). For the cumulative limits (lifetime request IDs and receipt bytes), the warning and the refusal print a `gbrain config set persistence.limits.<limit> <value>` sized for about one more year; run it on the brain host, then retry with the same request ID. For outstanding-request or queued-byte limits, let outstanding writes finish and check `gbrain sources writer status`. Receipt compaction age is `persistence.receipt_retention_days` (default 30). Limits and defaults: [bounded admission and retention](concurrent-writes.md#bounded-admission-and-retention).
-<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction freshness (`persistence_compaction`, see [receipt compaction](repair.md#receipt-compaction)), a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, bounds every other check by `doctor.entry_budget_ms` (default 15000), and estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).
+<a id="doctor-ops-tier"></a>**`gbrain doctor` is slow on a large brain, or you need to see what is wrong in seconds?** Run `gbrain doctor --tier ops --json`. It runs only the operator sections (write capacity, unresolved write failures, a managed sync cursor that stopped moving, receipt compaction freshness (`persistence_compaction`, see [receipt compaction](repair.md#receipt-compaction)), a serve running an older build, schema-pack consistency, embedding state) under a 4000 ms deadline; `--budget-ms <n>` changes it. A section the deadline cut off is reported as unknown (`details.health: "unknown"`, `reason: "budget"`, `exact: false`), never as clear, and the report says `complete: false` with the section in `unknown_sections`; rerun it alone with `gbrain doctor --only <name> --json`. On PGLite, sections that need a Postgres serve (managed sync, terminal-failure receipts, schema packs) read `not_applicable` and the report stays complete. The default doctor runs the same sections first, then the cheap incident checks (`links_extraction_lag`, `partial_embedding`, content sanity), and bounds every other check by `doctor.entry_budget_ms` (default 15000): a check's database statements stop at its budget, and the frontmatter and fence scans report what they read by then. A non-interactive `gbrain doctor --json` (stderr not a terminal, no `--budget-ms`, `--tier`, `--fix` or remediation flag) caps its check run at `doctor.default_budget_ms` (file plane, default 90000; connect and migrations are not counted) and prints one stderr line saying so; `--budget-ms 0` turns that off for one run and `gbrain config set doctor.default_budget_ms 0` for good. A check past its budget names the budget (`details.limit`: `entry` or `overall`) and prints `gbrain doctor --only <check> --budget-ms N --json`, which gives that check the whole N (above about 110000 ms it is the user's to run in a terminal). PGLite cannot stop a statement already running, so a check there can finish late. It also estimates `orphan_ratio` from a sample above `doctor.orphan_ratio.full_scan_max_pages` pages (default 50000); `--tier deep` scans fully. From a thin client, `gbrain doctor --tier ops` (or `--only persistence_capacity`) asks the serve: an admin token gets the ops report, a read token gets the `get_brain_health` bands (capacity and write failures as bands, no raw counts), and a serve that predates the ops tier refuses `doctor_tier_unavailable`: run `gbrain doctor --tier ops --json` on the brain host or upgrade and restart its serve. Agents without a shell call MCP `get_brain_health` (read scope) or `run_doctor` with `tier: "ops"` (admin).
<a id="dream-paid-loop"></a>**Dream keeps skipping one transcript, or doctor warns `dream_paid_loop`?** A dream key died `dream.breaker.max_dead_submissions` times (default 3) in 24 hours and is refused so it stops billing you. Fix the cause, then `gbrain dream reset-key --list` and `gbrain dream reset-key '<key>'`. See [the paid-loop breaker](../operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions).
diff --git a/scripts/bench/doctor-scale.ts b/scripts/bench/doctor-scale.ts
new file mode 100644
index 0000000000..459de705e1
--- /dev/null
+++ b/scripts/bench/doctor-scale.ts
@@ -0,0 +1,150 @@
+#!/usr/bin/env bun
+/**
+ * #6803 C7: doctor at scale, with a pass criterion. A bench, not a test (not in CI).
+ *
+ * bun scripts/bench/doctor-scale.ts --url <postgres-url> [--admin-url <url>] [--pages 10000] [--receipts 0] [--load 0] [--out receipt.json]
+ * bun scripts/bench/doctor-scale.ts --engine pglite [--pages 10000] [--out receipt.json]
+ *
+ * Postgres: --url is what the CLI connects to (point it at a transaction-mode PgBouncer with
+ * ?prepare=false to measure the pooled path); --admin-url (default --url) creates a scratch database
+ * `gbrain_bench_doctor_<n>›, reached through --url's host with the same credentials, and drops it
+ * afterwards. PGLite: a scratch data dir.
+ *
+ * Fixture (an unmanaged brain built with initSchema): --pages note pages (about 2 KB each, one source),
+ * --receipts committed managed write receipts (the capacity forecast reads them), and --load concurrent
+ * whole-table scans running through the whole measurement (the resident/autopilot pressure the 90 s
+ * default must survive). No chunks, embeddings, links or facts.
+ *
+ * Measured through the real CLI, non-interactive (stderr is a pipe), so plain `doctor --json› runs under
+ * the doctor.default_budget_ms default: wall time and the report's complete/unknown_sections, plus
+ * `doctor --tier ops --json› and `sync status --json›.
+ *
+ * Pass: every cheap incident check (CHEAP_INCIDENT_CHECKS in src/commands/doctor/registry.ts) the run
+ * emits reports a health other than unknown, and the plain run returns within the 90 s default plus
+ * 20 s for process start and connect. Exit 0 on pass, 1 on fail. Prints the receipt and one Markdown row.
+ */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import postgres from '#postgres';
+import { CHEAP_INCIDENT_CHECKS } from '../../src/commands/doctor/registry.ts';
+import { DEFAULT_BUDGET_MS } from '../../src/commands/doctor/default-budget.ts';
+import { PROVIDER_ENV_KEYS } from '../../test/helpers/provider-env.ts';
+
+const REPO = resolve(import.meta.dir, '..', '..');
+const argv = process.argv.slice(2);
+const flag = (name: string, fallback?: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : fallback; };
+const engineKind = flag('--engine', 'postgres') as 'postgres' | 'pglite';
+const pages = Number(flag('--pages', '10000'));
+const receipts = Number(flag('--receipts', '0'));
+const load = Number(flag('--load', '0'));
+const out = flag('--out');
+const url = flag('--url');
+const adminUrl = flag('--admin-url', url);
+if (engineKind === 'postgres' && !url) { console.error('--url <postgres-url> is required with --engine postgres'); process.exit(2); }
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-bench-doctor-'));
+const cleanups: Array<() => Promise<void>> = [async () => rmSync(home, { recursive: true, force: true })];
+
+async function cli(args: string[], timeoutMs = 300_000): Promise<{ ms: number; exit: number; stdout: string; stderr: string }> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;
+ for (const k of [...PROVIDER_ENV_KEYS, 'DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[k];
+ Object.assign(env, { HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1', NO_COLOR: '1' });
+ const started = performance.now();
+ const proc = Bun.spawn(['bun', '--no-env-file', join(REPO, 'src/cli.ts'), ...args], { cwd: home, env, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
+ const killer = setTimeout(() => proc.kill('SIGKILL'), timeoutMs);
+ const [stdout, stderr, exit] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ clearTimeout(killer);
+ return { ms: Math.round(performance.now() - started), exit, stdout, stderr };
+}
+
+async function fixtureUrl(): Promise<string> {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ if (engineKind === 'pglite') {
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite'), embedding_disabled: true }));
+ return '';
+ }
+ const name = `gbrain_bench_doctor_${Date.now()}`;
+ const admin = postgres(adminUrl!, { max: 1, prepare: false });
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ cleanups.push(async () => { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); await admin.end(); });
+ const target = new URL(url!);
+ target.pathname = `/${name}`;
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: target.toString(), embedding_disabled: true }));
+ return target.toString();
+}
+
+async function seed(brainUrl: string): Promise<void> {
+ const { createEngine } = await import('../../src/core/engine-factory.ts');
+ const engine = await createEngine({ engine: engineKind });
+ await engine.connect(engineKind === 'pglite' ? { database_path: join(home, '.gbrain', 'brain.pglite') } : { database_url: brainUrl, poolSize: 2 });
+ try {
+ await engine.initSchema();
+ for (let from = 1; from <= pages; from += 10_000) {
+ const to = Math.min(pages, from + 9_999);
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)
+ SELECT 'notes/acme-example-' || g, 'default', 'note', 'Note ' || g, repeat('Bench body text for doctor scale. ', 60), '{}', md5('bench-' || g), now(), now()
+ FROM generate_series($1::int, $2::int) AS g`, [from, to]);
+ }
+ if (receipts > 0) {
+ const { requestFixture } = await import('../../test/helpers/persistence-request-fixture.ts');
+ const fixture = await requestFixture(engine);
+ for (let i = 0; i < receipts; i++) await fixture.publish(await fixture.admit(`bench-${i}`) as never);
+ }
+ await engine.executeRaw('ANALYZE');
+ } finally {
+ await engine.disconnect();
+ }
+}
+
+function startLoad(brainUrl: string): () => Promise<void> {
+ if (load <= 0 || engineKind === 'pglite') return async () => undefined;
+ const sql = postgres(brainUrl, { max: load, prepare: false });
+ let running = true;
+ const loops = Array.from({ length: load }, async () => {
+ while (running) await sql`SELECT count(*), sum(length(compiled_truth)) FROM pages`.catch(() => undefined);
+ });
+ return async () => { running = false; await Promise.all(loops); await sql.end(); };
+}
+
+interface Row { check: string; status: string; health: string; elapsed_ms: number | null }
+
+async function main(): Promise<number> {
+ const brainUrl = await fixtureUrl();
+ await seed(brainUrl);
+ const stopLoad = startLoad(brainUrl);
+ let plain, ops, status;
+ try {
+ plain = await cli(['doctor', '--json']);
+ ops = await cli(['doctor', '--tier', 'ops', '--json']);
+ status = await cli(['sync', 'status', '--source', 'default', '--json']);
+ } finally {
+ await stopLoad();
+ }
+ const report = JSON.parse(plain.stdout) as { complete?: boolean; unknown_sections?: string[]; budget_ms?: number; checks: Array<{ name: string; status: string; elapsed_ms?: number; details?: { health?: string } }> };
+ const opsReport = JSON.parse(ops.stdout) as { complete?: boolean; unknown_sections?: string[] };
+ const cheap: Row[] = report.checks.filter(c => CHEAP_INCIDENT_CHECKS.has(c.name))
+ .map(c => ({ check: c.name, status: c.status, health: c.details?.health ?? 'known', elapsed_ms: c.elapsed_ms ?? null }));
+ const unknownCheap = cheap.filter(r => r.health === 'unknown').map(r => r.check);
+ const withinBudget = plain.ms <= DEFAULT_BUDGET_MS + 20_000;
+ const pass = unknownCheap.length === 0 && withinBudget;
+ const receipt = {
+ engine: engineKind, pooled: /prepare=false/.test(url ?? ''), pages, receipts, load,
+ doctor: { wall_ms: plain.ms, exit: plain.exit, budget_ms: report.budget_ms ?? null, complete: report.complete ?? null, unknown_sections: report.unknown_sections ?? [] },
+ doctor_ops: { wall_ms: ops.ms, complete: opsReport.complete ?? null, unknown_sections: opsReport.unknown_sections ?? [] },
+ sync_status: { wall_ms: status.ms, exit: status.exit },
+ cheap_incident_checks: cheap, pass, fail_reasons: [...(withinBudget ? [] : [`doctor took ${plain.ms} ms`]), ...unknownCheap.map(c => `${c} unknown`)],
+ };
+ if (out) writeFileSync(out, JSON.stringify(receipt, null, 2));
+ console.log(JSON.stringify(receipt, null, 2));
+ console.log('\n| engine | pages | receipts | load | doctor wall | complete | unknown | ops wall | ops complete | sync status | cheap checks | pass |');
+ console.log('|---|---|---|---|---|---|---|---|---|---|---|---|');
+ console.log(`| ${engineKind}${receipt.pooled ? ' (pgbouncer)' : ''} | ${pages} | ${receipts} | ${load} | ${(plain.ms / 1000).toFixed(1)} s | ${receipt.doctor.complete} | ${receipt.doctor.unknown_sections.length} | `
+ + `${(ops.ms / 1000).toFixed(1)} s | ${receipt.doctor_ops.complete} | ${(status.ms / 1000).toFixed(1)} s | ${cheap.map(r => `${r.check}=${r.health === 'unknown' ? 'unknown' : r.status}`).join(', ')} | ${pass ? 'PASS' : 'FAIL'} |`);
+ return pass ? 0 : 1;
+}
+
+let code = 1;
+try { code = await main(); } catch (error) { console.error(error); } finally { for (const c of cleanups.reverse()) await c().catch(() => undefined); }
+process.exit(code);
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index e3c0797811..cf2a0577c3 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -68,3 +68,4 @@ test/e2e/oauth-client-registered-via-postgres.test.ts
test/e2e/oauth-owner-consent-source-postgres.test.ts
test/e2e/entity-names-parity-postgres.test.ts
test/e2e/segment-gc-parity.test.ts
+test/e2e/doctor-entry-deadline-postgres.test.ts
diff --git a/scripts/e2e-weights.json b/scripts/e2e-weights.json
index 557e6df7ad..c95e506b42 100644
--- a/scripts/e2e-weights.json
+++ b/scripts/e2e-weights.json
@@ -101,6 +101,7 @@
"test/e2e/derived-page-visibility.test.ts": 5780,
"test/e2e/derived-visibility-repair.test.ts": 9940,
"test/e2e/doctor-connectors-pglite.test.ts": 2150,
+ "test/e2e/doctor-entry-deadline-postgres.test.ts": 32000,
"test/e2e/doctor-hot-checks-golden.test.ts": 23850,
"test/e2e/doctor-json-golden.test.ts": 8760,
"test/e2e/doctor-ops-tier-postgres.test.ts": 2009.9999999999998,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 55d73ee069..5c29bede15 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -84,6 +84,7 @@
"e2e:test/e2e/derived-page-visibility.test.ts": 1836,
"e2e:test/e2e/derived-visibility-repair.test.ts": 5196,
"e2e:test/e2e/doctor-connectors-pglite.test.ts": 1756,
+ "e2e:test/e2e/doctor-entry-deadline-postgres.test.ts": 32000,
"e2e:test/e2e/doctor-json-golden.test.ts": 8538,
"e2e:test/e2e/doctor-progress.test.ts": 9112,
"e2e:test/e2e/doctor-revision-backfill-postgres.test.ts": 4619,
@@ -1114,6 +1115,7 @@
"unit:test/canonical-projection-history.test.ts": 4904,
"unit:test/canonical-writer-inventory.test.ts": 623,
"unit:test/capability.test.ts": 131,
+ "unit:test/capacity-bounded-read-6803.test.ts": 1500,
"unit:test/capture-build-content.test.ts": 320,
"unit:test/capture-dedup.test.ts": 10034,
"unit:test/capture-explicit-type.test.ts": 163,
@@ -1529,11 +1531,13 @@
"unit:test/doctor-cycle-phase-scope.test.ts": 471,
"unit:test/doctor-day-zero.test.ts": 7174,
"unit:test/doctor-decide-health.test.ts": 2312,
+ "unit:test/doctor-default-budget-6803.test.ts": 9000,
"unit:test/doctor-drift-advice.test.ts": 471,
"unit:test/doctor-effective-date-health.test.ts": 5194,
"unit:test/doctor-embedding-backlog.test.ts": 363,
"unit:test/doctor-embedding-env-override.test.ts": 5291,
"unit:test/doctor-embedding-width.test.ts": 2189,
+ "unit:test/doctor-entry-deadline-6803.test.ts": 16000,
"unit:test/doctor-extract-atoms-backlog.test.ts": 4689,
"unit:test/doctor-extract-health.test.ts": 1730,
"unit:test/doctor-fast-supervisor.test.ts": 928,
@@ -3409,6 +3413,7 @@
"unit:test/sync-repo-source-routing.test.ts": 2056,
"unit:test/sync-slug-root-mode-4342.test.ts": 3844,
"unit:test/sync-sole-non-default-routing.test.ts": 3257,
+ "unit:test/sync-status-flag-6803.test.ts": 35000,
"unit:test/sync-strategy.test.ts": 171,
"unit:test/sync-timeout-cli-dispatch.test.ts": 1607,
"unit:test/sync-timeout.test.ts": 154,
diff --git a/src/cli/help/doctor.ts b/src/cli/help/doctor.ts
index e89a625d8e..2473f20247 100644
--- a/src/cli/help/doctor.ts
+++ b/src/cli/help/doctor.ts
@@ -16,7 +16,7 @@ export const help: CliHelpSpec = {
{ name: '--only', type: 'string', desc: 'Read-only: run just the named checks (comma-separated or repeated; no migrations). The usual fix.verify. An unknown name exits 2 with the valid list.' },
{ name: '--fast', type: 'boolean', desc: 'Skip database checks; filesystem and config checks only.' },
{ name: '--tier', type: 'enum', values: ['ops', 'standard', 'deep'], desc: 'ops: only the operational sections (capacity, write failures, embedding state, sync movement, compaction, serve build, schema pack) under a 4 s deadline, observational (no migrations). standard (default): ops first, then the rest. deep: adds full scans (orphan_ratio on brains over 50,000 pages).' },
- { name: '--budget-ms', type: 'number', desc: 'Absolute end-to-end deadline in ms, counted from before the connect (default 4000 with --tier ops; none otherwise). Checks past it report health unknown (reason budget); the report says complete: false.' },
+ { name: '--budget-ms', type: 'number', desc: 'Absolute end-to-end deadline in ms, counted from before the connect (default 4000 with --tier ops; 0: none). A plain non-interactive --json run caps its check run at doctor.default_budget_ms (file plane, default 90000, 0 off) instead. With --only, the named checks get the whole budget. Checks past it report health unknown (reason budget, which budget in details.limit); the report says complete: false.' },
{ name: '--fix', type: 'boolean', desc: 'Apply the local fixes doctor knows (skill files, stale locks); pair with --dry-run to preview.' },
{ name: '--dry-run', type: 'boolean', desc: 'Preview --fix or --remediate without changing anything.' },
{ name: '--scope', type: 'enum', values: ['all', 'brain'], desc: 'Pass --scope=brain to skip the skill-file check group (default all).' },
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d66ca9f462..4c1d72bf9c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -722,6 +722,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// W2 belief ledger page-at-time. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.267.0', text: 'A page rename (a sync that sees a file move, a frontmatter slug repair, a held-file or import move) now saves the page as it stood before the move as a version, as an edit does, so `get_versions` and `gbrain history` list one more snapshot per rename. The move advances the page\'s revision, and until now no version held the body from before it.' },
{ since: '0.60.267.0', text: '`purge_fact` now saves each page it rewrites as a version before dropping the purged fence row, and its version redaction then removes the claim from that version as from every other, so `get_versions` and `gbrain history` list one more snapshot per page a fact purge rewrites. The snapshot holds the page as it stood before the purge, without the purged claim.' },
+ // #6803 lane C (bounded status and doctor reads). `since` is a placeholder equal to the branch VERSION until the merge-slot stamp.
+ { since: '0.60.267.0', text: '`gbrain sync --status` now prints the `gbrain sync status` envelope (with a one-line hint) instead of running a full sync of the source, which nothing used to stop because no sync path read the flag. `gbrain sync --preview` and `--check`, which sync never read either, now refuse with `invalid_params` and a `--dry-run` fix; `--dry-run` is unchanged.' },
+ { since: '0.60.267.0', text: 'A plain non-interactive CLI `gbrain doctor --json` (stderr not a terminal, no `--budget-ms`, `--tier`, `--fix` or remediation flag) now caps its check run at `doctor.default_budget_ms` (90000 ms; file plane; connect and migrations are not counted) and prints one stderr line saying so; checks past it report health unknown, and the JSON gains `tier`, `complete`, `unknown_sections`, `elapsed_ms` and `budget_ms`. `--budget-ms 0` turns it off for one run and `gbrain config set doctor.default_budget_ms 0` for good. `gbrain config set` now accepts `doctor.entry_budget_ms` and `doctor.orphan_ratio.full_scan_max_pages`.' },
+ { since: '0.60.267.0', text: 'Doctor entries now stop their database statements at their own budget on every tier (Postgres cancels the statement; PGLite refuses the next one), so a slow check no longer keeps a backend running after the report. The cheap incident checks (`links_extraction_lag`, now its own entry, `partial_embedding` and content sanity) run right after the ops sections, the frontmatter and fence scans report partial results at the deadline, `--only <check> --budget-ms N` gives that check the whole N, and a check past its budget names which budget (`details.limit`) and prints that rerun.' },
+ { since: '0.60.267.0', text: '`gbrain sync status` and write and sync receipts wait at most 1.5 s for the shared capacity snapshot and read capacity as unknown for that call when it is late, without clearing or re-announcing a background pause; a snapshot fetch that timed out is no longer cached for a minute. Doctor now computes the capacity forecast once per run instead of twice.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */