Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(repair): explicit_only repair kinds, enforced at execution (ENG-O1)
garrytan4d72ac799cf2
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 49f13ab076..9598536295 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -30,6 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.- `src/core/errors.ts` — `StructuredAgentError` + `buildError` + `serializeError`. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches the `CycleReport.PhaseResult.error` shape.+- `src/core/error-catalogue.ts` — fix wave 5 refusal catalogue (DX-O2): `ERROR_CATALOGUE` maps each refusal name to its stable wire code and its `docs/guides/repair.md` or `write-refusals.md` anchor; `catalogueError` builds the `OperationError` (hint as `suggestion`, anchor as `docs`), `catalogueStructuredError` the `StructuredError` envelope (`hint`, `docs_url`). `test/error-catalogue.test.ts` resolves every anchor against the guides' headings and `<a id>` tags.- `src/core/eval-capture-scrub.ts` — zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 623ee6cf90..4195089a98 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -3,7 +3,7 @@[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. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `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. 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`.+- `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. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `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`; stubs in `stale-atoms.ts` and `extractor-facts.ts` that refuse with `unavailable` until their fix wave 5 lanes land) 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. Tests: `test/repair-explicit-only.test.ts`. 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`.- `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()`.diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex 9e274b3918..a2b83b7b93 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -20,6 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.+- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).diff --git a/llms-full.txt b/llms-full.txtindex 5529f172c4..9738742f77 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9067,6 +9067,46 @@ covers the whole retry budget each grant authorizes. A resumed run replays thegrant it already made instead of granting another cycle. A signature-mismatchedvector is never reconciled; it is re-embedded.+## Wave 5 refusal codes++Each heading below is the `docs` anchor a refusal carries. The full recovery+steps land with the fix that raises each code.++### Explicit-only repair kinds++`stale-atoms` and `extractor-facts` run only when named:+`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply --expect <hash>`+applies exactly the previewed set. `gbrain repair --all`, the remediation plan+and `gbrain doctor --remediate --include-repairs` list them with their preview+command (`explicit_kind_required`) and never run them. A build without the+kind refuses with `unavailable`.++### Preview changed++`preview_changed`: the hash passed with `--expect` names no saved preview, or a+preview older than 7 days. Nothing was applied. Re-run the printed preview+command and apply with the new hash.++### Legacy job authority++`permission_denied` for a job row with SQL NULL submission authority left by an+upgrade across v0.50.++### Legacy jobs active++`legacy_jobs_active`: a legacy-job preview found active jobs. Stop producers+and workers and cancel the listed jobs first.++### Legacy job selection invalid++`legacy_job_selection_invalid`: `--select` named an unknown key or value. The+message lists the valid ones.++### Projection owner resident++`projection_owner_resident`: a projection drain was refused because a resident+owner holds the PGLite datastore.+## Related- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery command@@ -9142,6 +9182,8 @@ of making a duplicate.| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. || <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). || unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |+| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A slug containing `:` cannot be written through to a file on Windows. | Write it on a non-Windows host, or choose a slug without `:`. |+| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). | Check which key is in effect and replace it. |### Other error codesdiff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.tsindex a18c160691..2366c6ecec 100644--- a/src/commands/doctor/remediate.ts+++ b/src/commands/doctor/remediate.ts@@ -11,10 +11,14 @@* cap is cumulative across the original run and every `--resume`; the cap,* consent and step manifest live in the local remediation checkpoint.*+ * Explicit-only repair kinds are never steps: the plan lists each with its+ * read-only preview command (`explicit_kind_required`).+ ** After a run, every wave check is classified (cleared, pending,- * consent_required, operator_required, unsupported). Exit status: 0 when no- * automatically repairable finding remains and no step failed, even if- * operator-required or unsupported findings remain (they are listed); 1+ * consent_required, operator_required, explicit_kind_required, unsupported).+ * Exit status: 0 when no automatically repairable finding remains and no step+ * failed, even if operator-required, explicit-kind or unsupported findings+ * remain (they are listed); 1* otherwise and on budget exhaustion; 2 when the target is unreachable and* there is no repair step to run, or a resume is refused.*/@@ -22,6 +26,7 @@ import type { BrainEngine } from '../../core/engine.ts';import { setCliExitVerdict } from '../../core/cli-force-exit.ts';import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';import type { RepairPlanStep } from '../../core/remediation/repairs.ts';+import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]@@ -117,6 +122,7 @@ interface RemediationPlanShape {est_total_usd_cost: number;blocked: Array<{ check: string; reason: string }>;repair_steps?: RepairPlanStep[];+ explicit_repairs?: ExplicitRepairNotice[];}/**@@ -152,6 +158,10 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScolines.push(` apply: ${step.command}`);}}+ if (plan.explicit_repairs?.length) {+ lines.push('\nExplicit-only repairs (never run by --remediate or gbrain repair --all; preview each by name on this host):');+ for (const notice of plan.explicit_repairs) lines.push(` ${notice.kind}: ${notice.preview_command}`);+ }if (plan.plan.length > 0 || repairs.length > 0) {lines.push(`\nApply everything${repairs.length ? ' after the user agrees' : ''}: ${combinedRemediateCommand(plan, targetScore)}`);if (repairs.length) lines.push('Ask the user before applying any repair step.');@@ -163,7 +173,7 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetScoreturn lines;}-export type FindingClass = 'cleared' | 'pending' | 'consent_required' | 'operator_required' | 'unsupported';+export type FindingClass = 'cleared' | 'pending' | 'consent_required' | 'operator_required' | 'explicit_kind_required' | 'unsupported';export interface RemediationFinding {check_id: string;@@ -197,6 +207,10 @@ export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[]// A repairable finding the repair can only report blocked needs the operator first.const blocked = now.check.details?.operator_instruction;if (typeof blocked === 'string') { findings.push({ ...base, class: 'operator_required', instruction: blocked, ...(kind ? { repair_kind: kind } : {}) }); continue; }+ if (kind && repairSpec(kind).explicit_only) {+ findings.push({ ...base, class: 'explicit_kind_required', repair_kind: kind, command: repairPreviewCommand(kind) });+ continue;+ }const skipped = result.repairs_skipped?.find(step => step.kind === kind);findings.push({ ...base, class: skipped ? 'consent_required' : 'pending', ...(kind ? { repair_kind: kind } : {}),...(skipped ? { command: skipped.command } : kind ? { command: `gbrain repair ${kind} --apply` } : {}) });diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsindex 917c4cbadb..6b27ca1224 100644--- a/src/commands/doctor/upgrade-banner.ts+++ b/src/commands/doctor/upgrade-banner.ts@@ -5,10 +5,13 @@* selected brain, the count per finding, the read-only preview command and* the instruction to ask the user before applying anything. It never prints* an applying command (`--yes`, `--apply`): applying is the user's decision.- * A clean brain prints nothing.+ * A finding cleared by an explicit-only repair kind names that kind's own+ * read-only preview (`explicit_kind_required`), because the remediation plan+ * never runs it. A clean brain prints nothing.*/import type { BrainEngine } from '../../core/engine.ts';-import { runWaveChecks } from './wave-checks.ts';+import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';+import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */@@ -28,15 +31,21 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>*/export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote];+/** One banner line for a non-ok wave finding. */+export function bannerFindingLine({ spec, check, state }: WaveFinding): string {+ if (state === 'unknown') return `[AGENT] ${spec.id}: could not be checked (health unknown)`;+ const kind = waveRepairKind(spec);+ const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind)}`+ : spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';+ return `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`;+}+export async function postUpgradeRecoveryBanner(engine: BrainEngine, brainLabel: string): Promise<string[]> {const findings = (await runWaveChecks(engine)).filter(f => f.state !== 'ok');const notes = (await Promise.all(POST_UPGRADE_NOTES.map(note => note(engine).catch(() => null)))).filter((n): n is string => !!n);if (!findings.length && !notes.length) return [];const lines = ['', `[AGENT] Relay this to your operator: brain ${brainLabel} has residual state to review after the upgrade.`];- for (const { spec, check, state } of findings) {- const how = spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';- lines.push(state === 'unknown' ? `[AGENT] ${spec.id}: could not be checked (health unknown)` : `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`);- }+ for (const finding of findings) lines.push(bannerFindingLine(finding));for (const note of notes) lines.push(`[AGENT] ${note}`);lines.push('[AGENT] Preview (read-only): gbrain doctor --remediation-plan');lines.push('[AGENT] Ask the user before applying any repair; the plan prints the exact commands. Recipe: docs/guides/repair.md#recover-after-upgrading-to-this-release');diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 18f8aafa36..7c774f0cd8 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -6,12 +6,15 @@* coordinated page write (or, for `safe-chunks`, a projection-only rebuild* that takes no admission), resumes after an interruption, and stops before* crossing 90% of a cumulative journal cap. Thin clients refuse (cli.ts).+ * Explicit-only kinds run only when named; `--all` and the no-kind preview+ * list them with their preview command instead, and only they accept+ * `--expect <hash>` and `--include-ambiguous` (their preview-bound apply).*/import type { BrainEngine } from '../core/engine.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { OperationError } from '../core/ops/contract.ts';-import { REPAIR_KINDS, resolveRepairScope, runRepair, type RepairKind, type RepairResult } from '../core/repair/core.ts';-import { REPAIR_REGISTRY, repairMaySpend, repairRunner, repairSpec } from '../core/repair/registry.ts';+import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';function wrap(text: string, indent: number, width = 80): string {const lines: string[] = [];@@ -24,34 +27,43 @@ function wrap(text: string, indent: number, width = 80): string {return lines.join(`\n${' '.repeat(indent)}`);}+const explicitKinds = EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind).join(', ');+export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]gbrain repair --all [--apply] [--source <id>] [--json]+ gbrain repair <explicit-only kind> [--include-ambiguous] [--apply --expect <preview-hash>] [--source <id>] [--json]Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.Kinds:-${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(spec.summary, 15)}`).join('\n')}+${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(`${spec.explicit_only+ ? `[explicit-only; preview: ${repairPreviewCommand(spec.kind)}] ` : ''}${spec.summary}`, 15)}`).join('\n')}Options:--apply Write the repair (no prompt). Without it, only preview.--source <id> Limit to one source (default: every active source).--limit <n> Repair at most n items; rerun the same command to continue.--no-embed safe-chunks, contextual-mode: no provider call; embed later with gbrain embed --stale.- --all Run every kind in order (${REPAIR_KINDS.join(', ')}).+ --all Run every kind in order (${AUTO_REPAIR_REGISTRY.map(spec => spec.kind).join(', ')}).+ Explicit-only kinds (${explicitKinds}) never run here; name each one.+ --expect <hash>+ Explicit-only kinds: apply exactly the set the preview printed under this hash.+ --include-ambiguous+ Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).--json Machine-readable output with a stable shape.Any other option is refused. There is no --max-usd here: to cap paid embeddingwork, run the repairs through gbrain doctor --remediate --yes --include-repairs --max-usd <n>.With no kind, previews every kind. Run it on the brain host.`;-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed']);-const VALUE_FLAGS = new Set(['--source', '--limit']);+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous']);+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect']);-interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; source?: string; limit?: string }+interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; source?: string; limit?: string; expect?: string }/** Strict parse: every flag is known, value flags carry a value, at most one kind. */export function parseRepairArgs(args: string[]): RepairArgs {- const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false };+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false };const positional: string[] = [];for (let i = 0; i < args.length; i++) {const token = args[i]!;@@ -69,6 +81,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {if (flag === '--apply') parsed.apply = true;else if (flag === '--all') parsed.all = true;else if (flag === '--json') parsed.json = true;+ else if (flag === '--include-ambiguous') parsed.includeAmbiguous = true;else parsed.noEmbed = true;continue;}@@ -76,11 +89,17 @@ export function parseRepairArgs(args: string[]): RepairArgs {const value = equal >= 0 ? token.slice(equal + 1) : args[++i];if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);if (flag === '--source') parsed.source = value;+ else if (flag === '--expect') parsed.expect = value;else parsed.limit = value;}if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,`Kinds: ${REPAIR_KINDS.join(', ')}.`);parsed.kind = positional[0];+ const bound = parsed.expect !== undefined ? '--expect' : parsed.includeAmbiguous ? '--include-ambiguous' : undefined;+ if (bound && !EXPLICIT_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {+ throw new OperationError('invalid_params', `${bound} applies only to an explicit-only kind named on the command line (${explicitKinds}).`,+ `Preview one by name: ${repairPreviewCommand(EXPLICIT_REPAIR_REGISTRY[0]!.kind)}`);+ }return parsed;}@@ -101,7 +120,7 @@ function human(result: RepairResult): string {export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }- const { kind, apply, all, json, noEmbed, source, limit: limitText } = parseRepairArgs(args);+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, limit: limitText } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw new OperationError('invalid_params', '--limit must be a positive integer.');if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {@@ -109,23 +128,26 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro}if (kind && all) throw new OperationError('invalid_params', 'Pass either a kind or --all, not both.');if (!kind && apply && !all) throw new OperationError('invalid_params', 'Name a kind or pass --all with --apply.');- const kinds: RepairKind[] = kind ? [kind as RepairKind] : [...REPAIR_KINDS];+ const kinds: RepairKind[] = kind ? [kind as RepairKind] : AUTO_REPAIR_REGISTRY.map(spec => spec.kind);+ const explicitKindsNotRun = kind ? [] : explicitRepairNotices({ source });const scope = await resolveRepairScope(engine, source);const runner = await repairRunner(engine, { apply, noEmbed });const results: Array<RepairResult & { paid: boolean }> = [];for (const k of kinds) {- const result = await runner.run(k, scope, { limit, sourceFlag: source });+ const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous });results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });if (result.stopped) break;}const paidKinds = results.filter(r => r.paid).map(r => r.kind);if (json) {- console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds }, null, 2));+ console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds,+ ...(explicitKindsNotRun.length ? { explicit_kinds: explicitKindsNotRun } : {}) }, null, 2));} else {console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}`);for (const result of results) console.log(human(result));if (!apply && paidKinds.length) console.log(`Kinds that may queue paid embeddings: ${paidKinds.join(', ')} (pass --no-embed to skip; `+ 'page-write kinds are re-embedded by their publication either way; cap spend with gbrain doctor --remediate --yes --include-repairs --max-usd <n>).');+ if (explicitKindsNotRun.length) console.log(`Explicit-only kinds (not run without their name; preview each): ${explicitKindsNotRun.map(n => n.preview_command).join('; ')}`);}if (results.some(r => r.stopped)) setCliExitVerdict(1);}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex e23f26d2ea..bf2878ab6d 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -96,7 +96,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],- 'repair': ['--all', '--apply', '--brain', '--help', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],+ 'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],diff --git a/src/core/remediation/plan.ts b/src/core/remediation/plan.tsindex c957d04029..ed638cbd41 100644--- a/src/core/remediation/plan.ts+++ b/src/core/remediation/plan.ts@@ -12,6 +12,7 @@ import {import { loadRecommendationContext } from './context.ts';import type { RemediationPlan, RemediationPlanOpts } from './types.ts';import { planRepairSteps } from './repairs.ts';+import { explicitRepairNotices } from '../repair/registry.ts';/*** Synthetic check list for classification. computeRecommendations operates@@ -74,6 +75,6 @@ export async function computeRemediationPlan(est_total_seconds: estTotalSeconds,est_total_usd_cost: Number(estTotalUsd.toFixed(2)),blocked,- ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }) } : {}),+ ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }), explicit_repairs: explicitRepairNotices() } : {}),};}diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.tsindex d6eb8fcf55..ca1e274bce 100644--- a/src/core/remediation/repairs.ts+++ b/src/core/remediation/repairs.ts@@ -8,12 +8,14 @@* repair step always runs to completion. A paid step (one that may queue* embeddings) is not started when its estimate exceeds the remaining budget;* free steps still run. Repairs run in-process on the brain host through the- * same runner `gbrain repair` uses, never as Minion jobs.+ * same runner `gbrain repair` uses, never as Minion jobs. Explicit-only kinds+ * are never planned or run here: the plan lists them with their preview+ * command, and `runRepairSteps` refuses a supplied step that names one.*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { resolveRepairScope, type RepairKind } from '../repair/core.ts';-import { REPAIR_REGISTRY, repairApplyCommand, repairMaySpend, repairRunner } from '../repair/registry.ts';+import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMaySpend, repairRunner, repairSpec } from '../repair/registry.ts';export interface RepairPlanStep {step: number;@@ -46,12 +48,12 @@ export interface RepairStepResult {message?: string;}-/** Brain-wide preview of every registered kind; kinds with nothing pending are omitted. */+/** Brain-wide preview of every kind `--all` runs; kinds with nothing pending are omitted. */export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanStep[]> {const scope = await resolveRepairScope(engine);const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });const steps: RepairPlanStep[] = [];- for (const spec of REPAIR_REGISTRY) {+ for (const spec of AUTO_REPAIR_REGISTRY) {if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;const preview = await runner.run(spec.kind, scope);// contextual-mode stamps only sealed pages; pages the safe-chunks step re-seals become eligible during the run.@@ -70,7 +72,8 @@ export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boo* Apply repair steps in order. `remainingUsd()` is the budget still available* (undefined = no cap); a paid step whose estimate exceeds it (or cannot be* estimated under a cap) is refused before it starts and the run continues- * with the next step. Only a trusted local caller may run repairs.+ * with the next step. Only a trusted local caller may run repairs, and a step+ * naming an explicit-only kind refuses the whole run before any step starts.*/export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[], opts: {remote: boolean; noEmbed?: boolean; remainingUsd: () => number | undefined;@@ -84,6 +87,8 @@ export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[}): Promise<RepairStepResult[]> {if (opts.remote !== false) throw new OperationError('permission_denied', 'Repair steps are PROTECTED: only a trusted local caller on the brain host can run them.','On the brain host, run: gbrain doctor --remediation-plan');+ const explicit = steps.find(step => repairSpec(step.kind)?.explicit_only);+ if (explicit) throw explicitKindRequired(explicit.kind);const { BudgetExhausted } = await import('../budget/budget-tracker.ts');const scope = await resolveRepairScope(engine);const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed });diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.tsindex b6f986c1ab..3d591bece4 100644--- a/src/core/remediation/types.ts+++ b/src/core/remediation/types.ts@@ -10,6 +10,7 @@import type { RemediationStep } from '../remediation-step.ts';import type { RepairPlanStep, RepairStepResult } from './repairs.ts';+import type { ExplicitRepairNotice } from '../repair/registry.ts';/*** Options for computeRemediationPlan. All fields are optional with@@ -51,6 +52,8 @@ export interface RemediationPlan {blocked: Array<{ check: string; reason: string }>;/** Present when `repairs` was requested: PROTECTED steps that need `--include-repairs`. */repair_steps?: RepairPlanStep[];+ /** Present with `repair_steps`: explicit-only kinds, never planned as steps; preview each by name. */+ explicit_repairs?: ExplicitRepairNotice[];}/**diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 1e58c385a1..f3a59bb01e 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects'] as const;+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'stale-atoms', 'extractor-facts'] as const;export type RepairKind = typeof REPAIR_KINDS[number];export interface RepairScope { brain_id: string; source_ids: string[] }@@ -41,8 +41,13 @@ export interface RepairPlan {items: RepairItem[];/** Counts of rows the kind keeps and reports instead of repairing. */residuals: Record<string, number>;+ /** Preview-bound kinds: the `previewHash` an apply must pass back with `--expect`. */+ preview_hash?: string;}+/** What the run was asked to do; preview-bound (explicit-only) kinds read `expect` and `includeAmbiguous`. */+export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean }+export interface RepairHandler {kind: RepairKind;/** `projection`: items rebuild derived rows only and take no journal admission. Default `coordinated`. */@@ -50,7 +55,7 @@ export interface RepairHandler {/** False for kinds whose items are bookkeeping rows, not pages: no embedding cost. */embeds?: boolean;/** Pending items after `after`, in cursor order. */- plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null): Promise<RepairPlan>;+ plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts?: RepairPlanOptions): Promise<RepairPlan>;/*** Apply one item; `false` when it no longer needs repair. `embed` is false* under --no-embed. `runId` identifies this repair run and survives a resume.@@ -159,11 +164,19 @@ function writerHeld(error: unknown): error is OperationError {return error instanceof OperationError && ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code);}+/**+ * `explicit`: the operator named this kind on the command line. An+ * explicit-only kind (registry `explicit_only`) refuses without it, so no+ * `--all` loop or supplied remediation step can run one.+ */export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,- opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[] }): Promise<RepairResult> {+ opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];+ explicit?: boolean; expect?: string; includeAmbiguous?: boolean }): Promise<RepairResult> {+ const { repairSpec, explicitKindRequired } = await import('./registry.ts');+ if (repairSpec(handler.kind)?.explicit_only && opts.explicit !== true) throw explicitKindRequired(handler.kind);if (opts.apply) await initializeLocalPersistence(ctx);const { cursor: resumed, runId: storedRunId } = await readCursor(ctx.engine, handler.kind, scope);- const plan = await handler.plan(ctx.engine, scope, resumed);+ const plan = await handler.plan(ctx.engine, scope, resumed, { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous });const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;const counters = await capacity(ctx);const admits = (handler.publication ?? 'coordinated') === 'coordinated' ? pending.length : 0;@@ -174,7 +187,8 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sembedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel) },capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),resumed_from: resumed, applied: 0, skipped: 0, complete: false,- apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')} --apply`,+ apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`+ + `${opts.includeAmbiguous ? ' --include-ambiguous' : ''} --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}`,};if (!opts.apply) {result.complete = pending.length === plan.items.length;diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.tsnew file mode 100644index 0000000000..148468b78f--- /dev/null+++ b/src/core/repair/extractor-facts.ts@@ -0,0 +1,19 @@+/**+ * `gbrain repair extractor-facts` (#5731): registry stub from the fix wave 5 shared+ * commit. The kind is explicit-only (never run by `--all` or a remediation+ * step) and preview-bound through `persistence/preview-approval.ts`. Until its+ * lane replaces this handler, every preview and apply refuses.+ */+import { catalogueError } from '../error-catalogue.ts';+import type { RepairHandler } from './core.ts';++function notBuilt(): never {+ throw catalogueError('repair_kind_unavailable', 'gbrain repair extractor-facts is not implemented in this build.',+ 'Upgrade on the brain host, then preview again: gbrain upgrade && gbrain repair extractor-facts');+}++export const extractorFactsRepair: RepairHandler = {+ kind: 'extractor-facts',+ plan: async () => notBuilt(),+ apply: async () => notBuilt(),+};diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.tsindex f4b3b32e18..6e899c8313 100644--- a/src/core/repair/registry.ts+++ b/src/core/repair/registry.ts@@ -11,6 +11,12 @@* page write whose embedding effect the persistence consumer runs (outside* this process, not affected by `--no-embed`); `inline` kinds embed in this* process unless `--no-embed` is given.+ *+ * `explicit_only` kinds run only when the operator names them+ * (`gbrain repair <kind>`): `--all`, the remediation plan and run, and the+ * post-upgrade banner list them with their preview command+ * (`explicit_kind_required`) but never run them, and `runRepair` refuses one+ * that was not named, so a supplied remediation step cannot run it either.*/import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';@@ -25,6 +31,10 @@ import { requestIndexesRepair } from './request-indexes.ts';import { connectorFencesRepair } from './connector-fences.ts';import { orphanBindingsRepair } from './orphan-bindings.ts';import { embeddingEffectsRepair } from './embedding-effects.ts';+import { staleAtomsRepair } from './stale-atoms.ts';+import { extractorFactsRepair } from './extractor-facts.ts';+import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';+import type { OperationError } from '../ops/contract.ts';export interface RepairKindSpec {kind: RepairKind;@@ -35,6 +45,8 @@ export interface RepairKindSpec {embeds: 'effect' | 'inline' | 'none';/** Doctor check ids whose findings this kind clears. */checks: string[];+ /** Runs only when named on the command line; never from `--all`, the remediation plan or a supplied step. */+ explicit_only?: true;}const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {@@ -83,6 +95,14 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {+ 'Each effect is reconciled (current vectors pass the effect verifier), superseded (page deleted, or a newer revision owns its own effect), '+ 'retry_queued for its owner (paid; a consumed retry allowance gets one new bounded cycle per explicit run) or blocked with the reason. Never drops an obligation.',},+ 'stale-atoms': {+ handler: staleAtomsRepair, embeds: 'none', checks: [], explicit_only: true,+ summary: 'Retire managed atoms whose source page changed or was deleted (#5770). Not implemented in this build.',+ },+ 'extractor-facts': {+ handler: extractorFactsRepair, embeds: 'none', checks: [], explicit_only: true,+ summary: 'Restore extractor facts expired by the pre-fix re-extraction (#5731). Not implemented in this build.',+ },};export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));@@ -92,10 +112,35 @@ export function repairMaySpend(spec: RepairKindSpec, noEmbed?: boolean): booleanreturn spec.embeds === 'effect' || (spec.embeds === 'inline' && !noEmbed);}+/** The kinds `--all`, the remediation plan and `gbrain repair` with no kind run, in dependency order. */+export const AUTO_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => !spec.explicit_only);++/** The explicit-only kinds, listed by those surfaces with their preview command but never run by them. */+export const EXPLICIT_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => spec.explicit_only);+export function repairSpec(kind: RepairKind): RepairKindSpec {return REPAIR_REGISTRY.find(spec => spec.kind === kind)!;}+/** `gbrain repair <kind> [--source <id>]`, the read-only preview of one kind. */+export function repairPreviewCommand(kind: RepairKind, opts: { source?: string } = {}): string {+ return `gbrain repair ${kind}${opts.source ? ` --source ${opts.source}` : ''}`;+}++/** How `--all`, the remediation plan and the banner report an explicit-only kind instead of running it. */+export interface ExplicitRepairNotice { kind: RepairKind; code: 'explicit_kind_required'; preview_command: string; docs: string }++export function explicitRepairNotices(opts: { source?: string } = {}): ExplicitRepairNotice[] {+ return EXPLICIT_REPAIR_REGISTRY.map(spec => ({ kind: spec.kind, code: 'explicit_kind_required' as const,+ preview_command: repairPreviewCommand(spec.kind, opts), docs: ERROR_CATALOGUE.explicit_kind_required.docs }));+}++/** `explicit_kind_required`: an explicit-only kind reached a runner without being named. */+export function explicitKindRequired(kind: RepairKind): OperationError {+ return catalogueError('explicit_kind_required', `gbrain repair ${kind} is explicit-only and runs only when named, never from --all or a remediation step.`,+ `Preview it on the brain host: ${repairPreviewCommand(kind)}`);+}+/** The registered kind that clears a doctor check's findings, if any. */export function repairForCheck(checkId: string): RepairKindSpec | undefined {return REPAIR_REGISTRY.find(spec => spec.checks.includes(checkId));@@ -118,11 +163,13 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;const logger = opts.logger ?? { info: console.error, warn: console.error, error: console.error };return {embeddingModel,- async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string } = {}): Promise<RepairResult> {+ /** `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 } = {}): Promise<RepairResult> {const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } 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'] : [] });+ embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],+ explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous });},};}diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.tsnew file mode 100644index 0000000000..431b26cf4a--- /dev/null+++ b/src/core/repair/stale-atoms.ts@@ -0,0 +1,19 @@+/**+ * `gbrain repair stale-atoms` (#5770): registry stub from the fix wave 5 shared+ * commit. The kind is explicit-only (never run by `--all` or a remediation+ * step) and preview-bound through `persistence/preview-approval.ts`. Until its+ * lane replaces this handler, every preview and apply refuses.+ */+import { catalogueError } from '../error-catalogue.ts';+import type { RepairHandler } from './core.ts';++function notBuilt(): never {+ throw catalogueError('repair_kind_unavailable', 'gbrain repair stale-atoms is not implemented in this build.',+ 'Upgrade on the brain host, then preview again: gbrain upgrade && gbrain repair stale-atoms');+}++export const staleAtomsRepair: RepairHandler = {+ kind: 'stale-atoms',+ plan: async () => notBuilt(),+ apply: async () => notBuilt(),+};diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.tsindex 2d92e0ede3..49c98ed9be 100644--- a/test/fix-wave-3-integration.test.ts+++ b/test/fix-wave-3-integration.test.ts@@ -40,7 +40,7 @@ import { localHostId, registerLocalWriter, withVerifiedLocalRegistration } fromimport { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';import { resolveRepairScope } from '../src/core/repair/core.ts';-import { REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';import { planRepairSteps } from '../src/core/remediation/repairs.ts';import { runWaveChecks, remoteWaveHandoff, WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';import { writerVersionCheck } from '../src/commands/doctor/checks/writer-version.ts';@@ -430,7 +430,7 @@ test('check 9: every registered repair kind reaches the remediation plan with itawait disposePersistenceConsumer(engine);await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL,chunker_version=1,text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug='people/second-example'", [f.id]);await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);- const kinds = REPAIR_REGISTRY.map(spec => spec.kind);+ const kinds = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));expect(planned['contextual-mode']).toMatchObject({ paid: false, embeds: 'inline', command: 'gbrain repair contextual-mode --no-embed --apply' });diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.tsindex 696948d0f0..95fcf80f30 100644--- a/test/fix-wave-4-integration.test.ts+++ b/test/fix-wave-4-integration.test.ts@@ -49,7 +49,7 @@ import { readAllSourceHolds } from '../src/core/connectors/item-holds-store.ts';import { retryHeld } from '../src/commands/sources-retry-held.ts';import { planRepairSteps } from '../src/core/remediation/repairs.ts';import { runRemediate } from '../src/commands/doctor/remediate.ts';-import { REPAIR_REGISTRY } from '../src/core/repair/registry.ts';+import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';import { capture } from './helpers/wave-scenarios.ts';import { createConnectorFixture, contact, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';import { addThread, fakeGmail, gmailFetch } from './helpers/connector-holds-fixture.ts';@@ -207,7 +207,7 @@ test('X6: deactivate refuses while a connector item is held (classic mode cannottest('X11: the remediation run reaches every new repair kind, runs the free ones under --max-usd 0 and clears their doctor findings', async () => withEnv(env, async () => {for (const engine of engines) {- expect(REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints',+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints','request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);// Pending work for Lane A (a dropped index) and Lane D (an orphan binding of a removed source).await engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_run_open');diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.tsnew file mode 100644index 0000000000..0b52300deb--- /dev/null+++ b/test/repair-explicit-only.test.ts@@ -0,0 +1,159 @@+/**+ * Explicit-only repair kinds (fix wave 5, ENG-O1(a) / DX-O4 / ENG-O13):+ * `stale-atoms` and `extractor-facts` are registered with `explicit_only`.+ * They run only when named; `gbrain repair --all`, the no-kind preview, the+ * remediation plan and the post-upgrade banner list them with their preview+ * command instead, and the runner refuses one that reaches it unnamed, so a+ * supplied remediation step cannot run it.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';+import { resolveRepairScope, runRepair, type RepairKind } from '../src/core/repair/core.ts';+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, repairRunner, repairSpec } from '../src/core/repair/registry.ts';+import { staleAtomsRepair } from '../src/core/repair/stale-atoms.ts';+import { planRepairSteps, runRepairSteps, type RepairPlanStep } from '../src/core/remediation/repairs.ts';+import { computeRemediationPlan } from '../src/core/remediation/index.ts';+import { classifyWaveFindings, renderRemediationPlanLines } from '../src/commands/doctor/remediate.ts';+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';+import type { WaveCheckSpec, WaveFinding } from '../src/commands/doctor/wave-checks.ts';+import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { withEnv } from './helpers/with-env.ts';++const EXPLICIT: RepairKind[] = ['stale-atoms', 'extractor-facts'];+let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++async function refusal(run: () => Promise<unknown>): Promise<OperationError> {+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++async function captured(args: string[]): Promise<string> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, args)); } finally { console.log = original; }+ return lines.join('\n');+}++/** A wave check whose findings an explicit-only kind clears (the lanes add the real check ids). */+function withExplicitCheck<T>(run: (spec: WaveCheckSpec) => T): T {+ const checks = repairSpec('stale-atoms').checks;+ checks.push('fixture_stale_atoms');+ const spec: WaveCheckSpec = { id: 'fixture_stale_atoms', resolution: 'repair', registration: 'wave', impact: 'fixture', count: d => Number(d.count ?? 0),+ run: async () => ({ name: 'fixture_stale_atoms', status: 'warn', message: 'stale atoms' }) };+ try { return run(spec); } finally { checks.pop(); }+}++describe('registry', () => {+ test('stale-atoms and extractor-facts are registered explicit-only and excluded from the --all set', () => {+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(EXPLICIT);+ for (const kind of EXPLICIT) expect(REPAIR_REGISTRY.map(spec => spec.kind)).toContain(kind);+ expect(AUTO_REPAIR_REGISTRY.some(spec => spec.explicit_only)).toBe(false);+ expect(AUTO_REPAIR_REGISTRY.length + EXPLICIT_REPAIR_REGISTRY.length).toBe(REPAIR_REGISTRY.length);+ });+});++describe('execution-time enforcement', () => {+ test('runRepair refuses an explicit-only handler that was not named, then reaches the stub refusal when named', async () => {+ const scope = await resolveRepairScope(engine);+ const ctx = { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: true, remote: false } as unknown as OperationContext;+ const unnamed = await refusal(() => runRepair(ctx, staleAtomsRepair, scope, { apply: false }));+ expect(unnamed.toJSON()).toMatchObject({ error: 'explicit_kind_required', suggestion: 'Preview it on the brain host: gbrain repair stale-atoms',+ docs: 'docs/guides/repair.md#explicit-only-repair-kinds' });+ const named = await refusal(() => runRepair(ctx, staleAtomsRepair, scope, { apply: false, explicit: true }));+ expect(named.toJSON()).toMatchObject({ error: 'unavailable', message: 'gbrain repair stale-atoms is not implemented in this build.' });+ });++ test('the shared runner refuses an unnamed explicit-only kind', async () => {+ const runner = await repairRunner(engine, { apply: true, logger: { info() {}, warn() {}, error() {} } });+ const scope = await resolveRepairScope(engine);+ expect((await refusal(() => runner.run('extractor-facts', scope))).code).toBe('explicit_kind_required');+ });++ test('a supplied remediation step naming an explicit-only kind refuses the whole run before any step starts', async () => {+ const step = (kind: RepairPlanStep['kind'], n: number): RepairPlanStep => ({ step: n, id: `repair:${kind}`, kind, affected: 1, command: `gbrain repair ${kind} --apply`,+ requires_user_agreement: true, protected: true, paid: false, embeds: 'none', est_usd_cost: 0, lifetime_ids: 0, checks: [], rationale: 'supplied' });+ const started: string[] = [];+ for (const kind of EXPLICIT) {+ const error = await refusal(() => withEnv({ GBRAIN_HOME: home }, () => runRepairSteps(engine, [step('connector-checkpoints', 1), step(kind, 2)],+ { remote: false, remainingUsd: () => undefined, onStep: s => { started.push(s.kind); } })));+ expect(error.code).toBe('explicit_kind_required');+ expect(error.message).toContain(kind);+ }+ expect(started).toEqual([]);+ });+});++describe('surfaces that list instead of run', () => {+ test('gbrain repair --all and the no-kind preview never run explicit kinds and list their preview commands', async () => {+ for (const args of [['--all', '--json'], ['--json']]) {+ const out = JSON.parse(await captured(args)) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string }> };+ expect(out.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));+ expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,+ docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));+ }+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair stale-atoms; gbrain repair extractor-facts');+ });++ test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {+ _resetCliExitVerdictForTests();+ const out = JSON.parse(await captured(['--all', '--apply', '--json'])) as { results: Array<{ kind: string; stopped?: unknown }> };+ expect(out.results.some(r => EXPLICIT.includes(r.kind as RepairKind))).toBe(false);+ expect(out.results.every(r => !r.stopped)).toBe(true);+ expect(currentExitCode()).toBe(0);+ });++ test('naming an explicit kind runs it (here: the stub refusal) instead of explicit_kind_required', async () => {+ const error = await refusal(() => withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['extractor-facts'])));+ expect(error.code).toBe('unavailable');+ expect(error.suggestion).toContain('gbrain repair extractor-facts');+ });++ test('help marks explicit kinds with their preview and keeps them out of the --all list; --expect is accepted only for them', () => {+ expect(REPAIR_HELP).toContain('[explicit-only; preview: gbrain repair stale-atoms]');+ const allLine = REPAIR_HELP.split('\n').find(line => line.trimStart().startsWith('--all'))!;+ for (const kind of EXPLICIT) expect(allLine).not.toContain(kind);+ expect(parseRepairArgs(['stale-atoms', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'stale-atoms', apply: true, expect: 'abc' });+ expect(parseRepairArgs(['extractor-facts', '--include-ambiguous'])).toMatchObject({ includeAmbiguous: true });+ for (const args of [['timeline', '--expect', 'abc'], ['--all', '--expect', 'abc'], ['visibility', '--include-ambiguous']]) {+ expect(() => parseRepairArgs(args)).toThrow(/applies only to an explicit-only kind/);+ }+ });++ test('the remediation plan never plans explicit kinds and lists each with its preview command', async () => {+ expect((await planRepairSteps(engine)).some(step => EXPLICIT.includes(step.kind))).toBe(false);+ const plan = await withEnv({ GBRAIN_HOME: home }, () => computeRemediationPlan(engine, { repairs: {} }));+ expect(plan.repair_steps!.some(step => EXPLICIT.includes(step.kind))).toBe(false);+ expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(EXPLICIT.map(kind => [kind, 'explicit_kind_required', `gbrain repair ${kind}`]));+ const text = renderRemediationPlanLines(plan, 90).join('\n');+ expect(text).toContain('Explicit-only repairs');+ expect(text).toContain(' stale-atoms: gbrain repair stale-atoms');+ expect(text).not.toContain('gbrain repair stale-atoms --apply');+ });++ test('the banner and the remediation classification report explicit_kind_required with the preview, never an apply', () => withExplicitCheck(spec => {+ const finding: WaveFinding = { spec, check: { name: spec.id, status: 'warn', message: 'stale atoms', details: { count: 3 } }, state: 'finding' };+ const line = bannerFindingLine(finding);+ expect(line).toBe('[AGENT] fixture_stale_atoms: 3 (explicit_kind_required; preview with: gbrain repair stale-atoms)');+ expect(line).not.toContain('--apply');+ expect(classifyWaveFindings([finding], [finding], {})).toEqual([{ check_id: spec.id, message: 'stale atoms', class: 'explicit_kind_required',+ repair_kind: 'stale-atoms', command: 'gbrain repair stale-atoms' }]);+ }));+});diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.tsindex 8f5e22be0c..96039e3504 100644--- a/test/repair-flags.test.ts+++ b/test/repair-flags.test.ts@@ -12,6 +12,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { OperationError } from '../src/core/ops/contract.ts';import { REPAIR_KINDS } from '../src/core/repair/core.ts';import { REPAIR_HELP, runRepairCommand } from '../src/commands/repair.ts';+import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';import { withEnv } from './helpers/with-env.ts';let engine: PGLiteEngine;@@ -76,7 +77,7 @@ describe('gbrain repair flags', () => {const out = await captured(['--all', '--json']);const parsed = JSON.parse(out) as { mode: string; results: Array<{ kind: string; cost: Record<string, unknown>; paid: boolean }>; paid_kinds: string[] };expect(parsed.mode).toBe('dry_run');- expect(parsed.results.map(r => r.kind)).toEqual([...REPAIR_KINDS]);+ expect(parsed.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));for (const result of parsed.results) {expect(result.cost).toHaveProperty('lifetime_ids');expect(result.cost).toHaveProperty('embedding_usd');