Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): --alert verdict (exit 17 act / 18 unknown) and foreign skills folder scoping (GBRA-224 W4)
garrytanc75500ed03ad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a196fa35b7..b6a984c124 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,16 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**Health alerts page only on what needs someone (GBRA-224 W4).**++A self-hoster running gbrain inside an agent harness got a weekly "score 30, 1 failing check, resolver_health: 60 issues" alert. The score counted the agent's own skills folder, graded against gbrain's conventions, the same as an outage, while the brain itself was healthy.++- `gbrain doctor --alert` runs only the page-class checks (database, writes, migrations, builds, sync and maintenance stalls, corrupt rows, schema exposure, the paid-loop breaker), fresh, under a 30 s budget, and exits 0 (`none`), 17 (`act`: `alert.items` carry each check's own fix) or 18 (`unknown`: a page-class check did not run fresh; `alert.consecutive_unknown` counts the runs in a row). Every doctor report carries `alert`; MCP `run_doctor` with `only` naming page-class checks runs them on the serve, redacted.+- A skills folder found by walking up from the current directory that gbrain did not install no longer lowers the score: resolver_health and skill_currency report "not a gbrain skills folder (<path>)". `--skills-dir`, `GBRAIN_SKILLS_DIR` and `OPENCLAW_WORKSPACE` still grade it.+- `health_score`, `brain_checks_score`, `category_scores` and `status` are unchanged for every existing check set.+## [0.60.475.0] - 2026-10-27**A repository's own commit checks now apply to commits gbrain makes.**diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex bbd623b297..4892e439cf 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -41,6 +41,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eveSize ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. #6453: with no PGLite lock, an HTTP registration gets a credential-free 3 s GET of `/health` (`probeHttpRegistration`): gbrain `ok` → `wired_running` + `mcp_access: 'unverified'`; refused loopback `http:` → `http_serve_missing` + fix; else `http_serve_unreachable`/`http_serve_unhealthy`, no fix. `redactRegistrationUrl` strips userinfo, query and fragment from every printed URL (`test/harness-wiring-redaction-6453.test.ts`). `agent_contract` reads the whole size-bounded log (`readAgentContractEvents(Infinity)`, 7-day window) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.+- `src/commands/doctor/alert.ts` — GBRA-224 W4 `DoctorReport.alert`: `computeAlert(checks, { ran, render })` (called by `computeDoctorReport` after fixes render) grades only `PAGE_CHECK_LEVELS` (`src/core/doctor-categories.ts`): `act` items keep the check's rendered `fix` plus a stable `code` and `docs`; `unknown` items (budget, bound, errored, last_known, not_run) name the check, `budget_ms` and a measuring `fix`; act over unknown over none. `ran` (`alertRanChecks`: none without an ok `connection`, else the page checks whose entry runs at the tier) makes a page check the run executed but did not emit "did not apply"; without it a missing page check is unknown. A non-CLI render omits messages and redacts. `alertRunArgs` turns `--alert` into `--only <page class> --budget-ms 30000 --scope=brain` unless `--tier`/`--only`/`--budget-ms` is given; `recordAlertStreak` keeps the per-brain consecutive-unknown count in `doctor-alert-state.json` (atomic, read-only home tolerated); exit 0/17/18 via `alertExitCode`. Tests: `test/doctor-alert-w4.test.ts`, `test/doctor-alert-cli-w4.test.ts`.- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 126 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. The run is one `withGitListingCache` scope (`src/core/git-visible-files.ts`), so entries that list the same source checkout (frontmatter scan, fence census, slug collisions) share one `git ls-files` per listing and one "not a git repository" verdict per directory (`ls-files`, `discoverGitRoot`, the census HEAD probe; any repository-changing `sync-git.ts` command or `invalidateGitListingCache()` drops the scope's memo: `test/git-listing-memo.serial.test.ts`). Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` — a live serve owner warns with the exclusive two-step fix, a `pglite_busy` reason `legacy_owner_unverified` fails with details.reason and the refusal's ask_user preview fix, anything else is classified for `db-repair` — and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). A pre-gate entry declares the names it only emits with a connected engine in `engineChecks` (#6303), so `onlyNeedsEngine` connects for `--only` of them; `test/doctor-only-engine-checks.test.ts` is the drift guard. To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run, cursor in config `doctor.timeline_history.scan:<sources>` so runs finish a pass (a clean pass stays `ok` until a newer row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, non-round-trippable rows informational, repair `gbrain repair timeline`; segmented pages counted apart (`segmented_*`), no repair advice), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). It drops every walked path sync would refuse (`unsyncableReason(prefix + relPath)`: metafiles such as root `AGENTS.md`/`CLAUDE.md`, pruned dirs, malformed names) before probing, so a same-slug page on `default` is not reported for a file sync never imports (#6681). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. `graph_coverage` and `orphan_ratio` count the entity types the active schema pack declares (#4772, `src/core/schema-pack/entity-types.ts`, resolved per source: brain-wide for `graph_coverage`, the asked source for `orphan_ratio --source`); a pack that does not load makes `graph_coverage` a warn naming the pack (never the old hardcoded list) and `orphan_ratio` answers with an "entity count unknown" caveat instead of a vacuous ok. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.diff --git a/docs/architecture/key-files/skills.md b/docs/architecture/key-files/skills.mdindex 7d41635e5c..dcb59c2ea1 100644--- a/docs/architecture/key-files/skills.md+++ b/docs/architecture/key-files/skills.md@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/skill-frontmatter.ts` — shared content-based SKILL.md frontmatter parser. Array fields (`writes_to`, `tools`, `triggers`) use `js-yaml` with the failsafe schema, accepting block lists and single-line or wrapped flow sequences while preserving the tolerant legacy regex fallback for partially malformed YAML; CRLF is normalized before fence parsing. Recognizes the `brain_first: 'exempt'` declarative opt-out and surfaces near-miss declarations (`brain-first`, `BrainFirst`, quoted values, unknown values) as a typed `brain_first_typo` field so doctor can emit a paste-ready hint rather than fail silently. Single canonical form: snake_case `brain_first: exempt`, lowercase, unquoted.-- `src/core/skill-manifest.ts` — parser for `skill-manifest.json` records. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting.+- `src/core/skill-manifest.ts` — parser for `skill-manifest.json` records. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting. `isGbrainManagedSkillsDir(dir)` (W4) is the one marker for "gbrain installed this skills folder": `skills.lock.json`, a valid on-disk `manifest.json`, or the `SKILLPACK_MANAGED_BEGIN` block in a resolver file there or at the workspace root; doctor's resolver_health and skill_currency report a walk-up folder without it as info (`test/skill-manifest-managed-dir.test.ts`).- `src/core/skill-trigger-index.ts` — Shared loader that unions per-skill SKILL.md frontmatter `triggers:` with curated RESOLVER.md / AGENTS.md rows from `skillsDir` AND the parent dir (preserves the OpenClaw workspace-root layout). UNION semantics: explicit RESOLVER.md rows ADD to frontmatter triggers (don't replace). Dedup keyed on `(skillPath, trigger.trim().toLowerCase())`. Three consumers fold through this primitive — `checkResolvable`, `runRoutingEvalCli`, `mounts-cache.composeResolvers` — so fixing frontmatter reaches all of them. Exports `loadSkillTriggerIndex(skillsDir): SkillTriggerEntry[]`, `entriesToResolverContent(entries): string` (synthesizes a markdown-table resolver string for `runRoutingEval`'s string-content API), `findPrimaryResolverPath(skillsDir): string | null`, the `FRONTMATTER_SECTION` constant, and `_resetWarnedSkillsForTests`. Skip rules: non-directory entries (a symlink dirent is followed via `statSync` — `readdirSync` dirents report the link's OWN type without following, so skill dirs symlinked in from a shared store, e.g. `~/.agents/skills/<name>`, still load), `_*`/`.*` prefixes, `conventions/`+`migrations/` subdirs, skills with no `SKILL.md` (deprecated `install/` graceful-skipped), no `triggers:` array, or malformed YAML (warn-once + skip). Reuses `parseSkillFrontmatter` from `src/core/skill-frontmatter.ts`, including block and wrapped flow-sequence arrays. Pinned by `test/skill-trigger-index.test.ts` (18 hermetic cases). CI gate `bun run check:resolver` (= `bun src/cli.ts check-resolvable --strict --skills-dir skills/`) wired into `bun run verify`.diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex 8c38f2ec88..1fc4150cae 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -74,6 +74,11 @@ those (`maintenance_lock_busy`) and the holder runs them.# wrapper below (gbrain-run), never a bare `gbrain` or `bun run src/cli.ts`.0 6 * * 1 gbrain-run doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain-run embed --stale+# Health alert — hourly. Page on the alert verdict, never on health_score:+# exit 0 none, 17 act (alert.items carry each fix), 18 unknown (a page-class+# check did not run fresh); page on 18 only from the second run in a row.+17 * * * * gbrain-run doctor --alert --json > /tmp/gbrain-alert.json 2>> /tmp/gbrain-alert.err; rc=$?; case $rc in 0) ;; 17) your-notify "gbrain needs action" ;; 18) [ "$(jq -r '.alert.consecutive_unknown // 0' /tmp/gbrain-alert.json)" -ge 2 ] && your-notify "gbrain health unknown twice in a row" ;; *) your-notify "gbrain doctor --alert failed (exit $rc)" ;; esac+# Autopilot health gate — daily at 7 AM. The exit code is the signal:# 0 fresh (or nothing installed), 1 needs attention (stale heartbeat,# never ran, paused, or brain-wide maintenance stalled: no completed pass@@ -475,8 +480,8 @@ echo "Dream cycle starting at $(date)"# Phase 2: Shipped maintenance cycle (lint, backlinks, extract, sync, embed, synthesize)gbrain dream-# Phase 3: Surface anything the cycle flagged-gbrain doctor --json | jq '.checks[] | select(.status=="warn")'+# Phase 3: Surface anything that needs someone (exit 17 act, 18 unknown)+gbrain doctor --alert --json | jq '.alert'echo "Dream cycle complete at $(date)"```diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 6eafb98264..c5f7170825 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1111,6 +1111,28 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu|---|---|---|---|---|---|---|| Commit or stash canonical skill edits before optimization. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### doctor_alert_act++<a id="doctor_alert_act"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `gbrain doctor --alert` found a page-class check that needs someone now (database unreachable, writes failing or stalled, migrations pending or wedged, more than one build running, sync or maintenance stalled, corrupt rows, a public schema exposed, or a tripped paid-loop breaker). | Only page-class checks page; skill, advisory and coaching checks never do, so health_score warnings alone exit 0. Each item in --json alert.items keeps that check's own fix, consent, actor and verify. | Read alert.items in the --json document and follow each fix.next; page the operator for items whose fix needs them. Run: gbrain doctor --alert --json | agent | `gbrain doctor --json` | 17 | no |++More: [docs/guides/troubleshooting.md#doctor-alert-act](../../docs/guides/troubleshooting.md#doctor-alert-act)++### doctor_alert_unknown++<a id="doctor_alert_unknown"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| `gbrain doctor --alert` found nothing to act on, but at least one page-class check did not run fresh in this run, so the brain's health is unknown, not clear. | A check that timed out, errored, was reported from its last known result or was skipped by the tier proves nothing; reading it as healthy would hide an outage. alert.consecutive_unknown counts the alert runs in a row that ended unknown, and agent crons page on the second. | Run each alert.unknown item fix (it measures that check alone); if a check keeps running out of time, raise --budget-ms or run gbrain doctor --alert --tier standard --json. Run: gbrain doctor --alert --budget-ms 0 --json | agent | `repeat the read that failed` | 18 | yes |++Reasons: `budget`, `bound`, `errored`, `last_known`, `not_run`.++More: [docs/guides/troubleshooting.md#doctor-alert-unknown](../../docs/guides/troubleshooting.md#doctor-alert-unknown)+### doctor_tier_unavailable<a id="doctor_tier_unavailable"></a>diff --git a/docs/guides/exit-codes.md b/docs/guides/exit-codes.mdindex 5d92702396..e072fcf7d6 100644--- a/docs/guides/exit-codes.md+++ b/docs/guides/exit-codes.md@@ -19,6 +19,8 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it || 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) || 14 | `bootstrap_cleanup_pending`: `gbrain bootstrap harness` (or `--status`) wired and verified the harness, but earlier shared-skills enrollments or carried token ids are not cleaned up yet | the harness result with `status: "cleanup_pending"`, a per-id `cleanup` list and `fix` | follow `fix.next`: `run` re-runs the same command; `tell_user_to_run` relays the owner's revoke or restore step, then re-run ([cleanup pending](bootstrap.md#cleanup-pending)) |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now (database, writes, migrations, builds, sync or maintenance stalls, corrupt rows, schema exposure, paid-loop breaker) | the doctor report; `alert.level: "act"`, `alert.items` with each check's `fix` | follow each item's `fix.next` ([doctor alert](troubleshooting.md#doctor-alert-act)) |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but at least one page-class check did not run fresh (budget, error, last known result, tier) | the doctor report; `alert.level: "unknown"`, `alert.unknown` naming each check, its budget and a `fix`, and `alert.consecutive_unknown` | run each `fix`; an agent cron pages only from the second unknown run in a row ([doctor alert](troubleshooting.md#doctor-alert-unknown)) || 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) || 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry || 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) |diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 37aac2e35a..da121d1904 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -12,6 +12,9 @@| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| `gbrain doctor --alert` exits 17 (`doctor_alert_act`, `alert.level: act`) | follow each `alert.items[].fix` in the `--json` document; it is that check's own fix, with its consent and actor ([doctor alert](#doctor-alert-act)) | the item's `fix.actor` | the item's `fix.consent` | `gbrain doctor --alert --json` exits 0 |+| `gbrain doctor --alert` exits 18 (`doctor_alert_unknown`, `alert.level: unknown`), or an agent cron pages "health unknown twice in a row" | run each `alert.unknown[].fix` (it measures that check alone); a check that keeps running out of time needs `--budget-ms` raised or `gbrain doctor --alert --tier standard --json` ([doctor alert](#doctor-alert-unknown)) | agent | none | `gbrain doctor --alert --json` exits 0 and `alert.consecutive_unknown` is 0 |+| Doctor's score drops (resolver_health fails, skill_currency warns "new built-in skill(s) available") only when run from an agent's own workspace | nothing to fix: since the W4 scoping both report `not a gbrain skills folder (<path>)` for a skills folder gbrain did not install; to grade it on purpose pass `--skills-dir <path>` ([doctor alert](#doctor-alert)) | agent | none | `gbrain doctor --only resolver_health --json` || A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |@@ -713,6 +716,68 @@ the phase, its blocker key and back-off, or the last failed job.3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`after a pass completes with the phase passing.+## Doctor alert++<a id="doctor-alert"></a>++**What should an agent cron page on?** `gbrain doctor --alert`, never+`health_score`. The score is 100 − 20 per failing check − 5 per warning check+over every check, so an advisory skill-routing warning costs as much as an+outage, and a healthy brain can read 30. `--alert` runs only the page-class+checks, fresh, under a 30 s budget (`--budget-ms` overrides it; `--tier+standard` grades a full run instead), and prints one verdict in+`alert.level`:++| Exit | `alert.level` | Meaning |+|---|---|---|+| 0 | `none` | every page-class check ran fresh and none needs anyone |+| 17 | `act` | a page-class check needs someone now; `alert.items` carry its fix |+| 18 | `unknown` | nothing to act on, but a page-class check did not run fresh; `alert.consecutive_unknown` counts the runs in a row |++`act` wins over `unknown`; both lists are always kept. Page on 17, and on 18+from the second run in a row. Exit 1 means doctor itself failed. The counter+lives per brain in `doctor-alert-state.json` under the gbrain home; a+read-only home still gets a verdict (`consecutive_unknown: null` when the+state can be neither read nor written). Remote reports (`run_doctor`) omit+check messages and name a host-admin step instead of local commands.++The page class (`PAGE_CHECK_LEVELS` in `src/core/doctor-categories.ts`); every+other check, skill checks included, never pages:++| Condition | Check | Pages on |+|---|---|---|+| database unreachable | `connection` | fail |+| migrations pending or wedged | `schema_version`, `minions_migration` | warn |+| tables the applied migrations created hold user data and are missing | `schema_missing_tables` | fail |+| writes failing | `persistence_terminal_failures` | warn |+| writes wedged | `persistence_write_stall` | warn |+| more than one gbrain build running | `runtime_build_skew` | fail |+| managed sync stopped or not moving past its window | `managed_sync_blocked`, `managed_sync_not_moving` | fail |+| brain-wide maintenance stalled a week | `global_maintenance_stalled` | fail |+| double-encoded JSONB rows | `jsonb_integrity` | warn |+| public schema readable with the anon key | `rls` | fail |+| a tripped paid-loop breaker | `dream_paid_loop` | warn |++<a id="doctor-alert-act"></a>++**Exit 17 (`act`).** Each item has `check`, a stable `code`, `status`, the+check's `message`, `docs` and the check's own rendered `fix` (`next`,+`command` or MCP call, `consent`, `actor`, `verify`). Follow `fix.next` as+everywhere else: run it, ask the user first, or tell the user or brain host to+run it. Then re-run `gbrain doctor --alert --json`.++<a id="doctor-alert-unknown"></a>++**Exit 18 (`unknown`).** Each item names the `check`, the `reason` it is not+fresh (`budget`, `bound`, `errored`, `last_known`, `not_run`), the+`budget_ms` it ran under and a `fix` that measures it alone. `not_run` on+every database check means the database checks did not run: read the+`connection` check (a live `gbrain serve` holding a PGLite brain is the+common case: run the alert where the serve's brain is reachable, or stop the+serve first). A check that keeps hitting its budget on a large brain needs a+larger `--budget-ms` in the cron line. A thin client refuses `--alert`+(`doctor_tier_unavailable`): schedule it on the brain host.+## Content-drift sweep**Doctor reports `content_drift_sweep` as a warning, or an embed run printsdiff --git a/docs/mcp/HERMES.md b/docs/mcp/HERMES.mdindex 635deea025..6164068183 100644--- a/docs/mcp/HERMES.md+++ b/docs/mcp/HERMES.md@@ -106,11 +106,27 @@ Hermes cron is fully non-interactive, which makes it a natural scheduler forbrain maintenance:```bash-hermes cron create --name gbrain-sync '0 */4 * * *' 'Run gbrain sync and report anything unusual'+hermes cron create --name gbrain-sync '0 */4 * * *' 'Run gbrain sync; report only a non-zero exit, with its error code and fix'hermes cron tick # run due jobs once and exit — deterministic testinghermes cron list```+For health, page on `gbrain doctor --alert`, never on `health_score` or a+summary of the full doctor report. The score counts advisory warnings (skill+routing, coaching) the same as an outage; the alert verdict pages only on the+page class ([doctor --alert](../guides/troubleshooting.md#doctor-alert)):++```bash+hermes cron create --name gbrain-alert '17 * * * *' 'Run `gbrain doctor --alert --json 2>>~/.gbrain/alert-stderr.log` and read its exit code. 0: say nothing. 17: report each alert.items entry with its fix. 18: report only when alert.consecutive_unknown is 2 or more, with each alert.unknown fix. Any other exit: report the exit code and the last lines of ~/.gbrain/alert-stderr.log. Never report health_score.'+```++The same rule as a plain crontab line (through the+[wrapper](../guides/cron-schedule.md#calling-gbrain-unattended)):++```bash+17 * * * * gbrain-run doctor --alert --json > /tmp/gbrain-alert.json 2>> /tmp/gbrain-alert.err; rc=$?; case $rc in 0) ;; 17) your-notify "gbrain needs action: $(jq -c '[.alert.items[].check]' /tmp/gbrain-alert.json)" ;; 18) [ "$(jq -r '.alert.consecutive_unknown // 0' /tmp/gbrain-alert.json)" -ge 2 ] && your-notify "gbrain health unknown twice in a row" ;; *) your-notify "gbrain doctor --alert failed (exit $rc), see /tmp/gbrain-alert.err" ;; esac+```+See [docs/guides/cron-schedule.md](../guides/cron-schedule.md) for the fullbrain maintenance protocol (sync, embed, dream cycle).diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 2fd96466b5..bd4dc5bc97 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -1013,6 +1013,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |diff --git a/llms-full.txt b/llms-full.txtindex 8bb509c82f..47696f13a1 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4526,6 +4526,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |@@ -7899,6 +7901,11 @@ those (`maintenance_lock_busy`) and the holder runs them.# wrapper below (gbrain-run), never a bare `gbrain` or `bun run src/cli.ts`.0 6 * * 1 gbrain-run doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain-run embed --stale+# Health alert — hourly. Page on the alert verdict, never on health_score:+# exit 0 none, 17 act (alert.items carry each fix), 18 unknown (a page-class+# check did not run fresh); page on 18 only from the second run in a row.+17 * * * * gbrain-run doctor --alert --json > /tmp/gbrain-alert.json 2>> /tmp/gbrain-alert.err; rc=$?; case $rc in 0) ;; 17) your-notify "gbrain needs action" ;; 18) [ "$(jq -r '.alert.consecutive_unknown // 0' /tmp/gbrain-alert.json)" -ge 2 ] && your-notify "gbrain health unknown twice in a row" ;; *) your-notify "gbrain doctor --alert failed (exit $rc)" ;; esac+# Autopilot health gate — daily at 7 AM. The exit code is the signal:# 0 fresh (or nothing installed), 1 needs attention (stale heartbeat,# never ran, paused, or brain-wide maintenance stalled: no completed pass@@ -8300,8 +8307,8 @@ echo "Dream cycle starting at $(date)"# Phase 2: Shipped maintenance cycle (lint, backlinks, extract, sync, embed, synthesize)gbrain dream-# Phase 3: Surface anything the cycle flagged-gbrain doctor --json | jq '.checks[] | select(.status=="warn")'+# Phase 3: Surface anything that needs someone (exit 17 act, 18 unknown)+gbrain doctor --alert --json | jq '.alert'echo "Dream cycle complete at $(date)"```@@ -10221,6 +10228,9 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| Symptom | Next step | Who acts | Consent | Verify ||---|---|---|---|---|+| `gbrain doctor --alert` exits 17 (`doctor_alert_act`, `alert.level: act`) | follow each `alert.items[].fix` in the `--json` document; it is that check's own fix, with its consent and actor ([doctor alert](#doctor-alert-act)) | the item's `fix.actor` | the item's `fix.consent` | `gbrain doctor --alert --json` exits 0 |+| `gbrain doctor --alert` exits 18 (`doctor_alert_unknown`, `alert.level: unknown`), or an agent cron pages "health unknown twice in a row" | run each `alert.unknown[].fix` (it measures that check alone); a check that keeps running out of time needs `--budget-ms` raised or `gbrain doctor --alert --tier standard --json` ([doctor alert](#doctor-alert-unknown)) | agent | none | `gbrain doctor --alert --json` exits 0 and `alert.consecutive_unknown` is 0 |+| Doctor's score drops (resolver_health fails, skill_currency warns "new built-in skill(s) available") only when run from an agent's own workspace | nothing to fix: since the W4 scoping both report `not a gbrain skills folder (<path>)` for a skills folder gbrain did not install; to grade it on purpose pass `--skills-dir <path>` ([doctor alert](#doctor-alert)) | agent | none | `gbrain doctor --only resolver_health --json` || A withdrawal committed but a large page's file still shows the withdrawn row; writer status lists its mirror parked with [`segmented_mirror_writer_gate`](write-refusals.md#segmented_mirror_writer_gate), or an effect retrying with [`recovery_version_unsupported`](write-refusals.md#recovery_version_unsupported) (or `effect_unavailable` on v0.60.290.0) holds every write on the worktree | `gbrain upgrade` on the hosts the refusal or a doctor `segmented_storage` warning names (for `recovery_version_unsupported`, the owner host; doctor's information case, this host's own superseded pre-upgrade writes, does not hold the mirror), then restart their serve, sync and worker processes. A gated mirror resumes by itself once the older writes are 7 days old; never delete a recovery record or its staging file | brain host | none | `gbrain sources writer status --source <source> --json` shows no parked or retrying mirror || The dream cycle's purge phase fails every night with `managed_purge_failed` (`42P01`, relation `query_cache` does not exist), or doctor `schema_missing_tables` warns | upgrade (#6911: the purge skips a missing rebuildable cache), then preview recreating it: `gbrain repair missing-tables` ([missing tables](repair.md#missing-tables)); apply the printed `--apply --expect <hash>` command. Pages parked by the earlier failures: `gbrain pages purge-deleted --retry-parked --dry-run`, then without `--dry-run` | agent, after the user agrees | `destructive` (the parked-page retry purges them) | `gbrain doctor --only schema_missing_tables --json` reports ok || A managed source's autopilot freshness `sync` jobs each land about one page, or `sources status` says `parked` while a sync job runs | upgrade (#6706: sync jobs drain to their deadline and count as the source's live drain), then restart `gbrain jobs work` / the supervisor so the worker loads the handler; a job result with `incomplete: true` names its follow-up (`continuation_job_id`) or the next step in `next` | agent | none | `gbrain sync status --source <id> --json` shows `live_job_id` or a cursor at `done`; `gbrain jobs get <id> --json` shows `outcome` |@@ -10922,6 +10932,68 @@ the phase, its blocker key and back-off, or the last failed job.3. Confirm with `gbrain doctor --only global_maintenance_stalled`: it is `ok`after a pass completes with the phase passing.+## Doctor alert++<a id="doctor-alert"></a>++**What should an agent cron page on?** `gbrain doctor --alert`, never+`health_score`. The score is 100 − 20 per failing check − 5 per warning check+over every check, so an advisory skill-routing warning costs as much as an+outage, and a healthy brain can read 30. `--alert` runs only the page-class+checks, fresh, under a 30 s budget (`--budget-ms` overrides it; `--tier+standard` grades a full run instead), and prints one verdict in+`alert.level`:++| Exit | `alert.level` | Meaning |+|---|---|---|+| 0 | `none` | every page-class check ran fresh and none needs anyone |+| 17 | `act` | a page-class check needs someone now; `alert.items` carry its fix |+| 18 | `unknown` | nothing to act on, but a page-class check did not run fresh; `alert.consecutive_unknown` counts the runs in a row |++`act` wins over `unknown`; both lists are always kept. Page on 17, and on 18+from the second run in a row. Exit 1 means doctor itself failed. The counter+lives per brain in `doctor-alert-state.json` under the gbrain home; a+read-only home still gets a verdict (`consecutive_unknown: null` when the+state can be neither read nor written). Remote reports (`run_doctor`) omit+check messages and name a host-admin step instead of local commands.++The page class (`PAGE_CHECK_LEVELS` in `src/core/doctor-categories.ts`); every+other check, skill checks included, never pages:++| Condition | Check | Pages on |+|---|---|---|+| database unreachable | `connection` | fail |+| migrations pending or wedged | `schema_version`, `minions_migration` | warn |+| tables the applied migrations created hold user data and are missing | `schema_missing_tables` | fail |+| writes failing | `persistence_terminal_failures` | warn |+| writes wedged | `persistence_write_stall` | warn |+| more than one gbrain build running | `runtime_build_skew` | fail |+| managed sync stopped or not moving past its window | `managed_sync_blocked`, `managed_sync_not_moving` | fail |+| brain-wide maintenance stalled a week | `global_maintenance_stalled` | fail |+| double-encoded JSONB rows | `jsonb_integrity` | warn |+| public schema readable with the anon key | `rls` | fail |+| a tripped paid-loop breaker | `dream_paid_loop` | warn |++<a id="doctor-alert-act"></a>++**Exit 17 (`act`).** Each item has `check`, a stable `code`, `status`, the+check's `message`, `docs` and the check's own rendered `fix` (`next`,+`command` or MCP call, `consent`, `actor`, `verify`). Follow `fix.next` as+everywhere else: run it, ask the user first, or tell the user or brain host to+run it. Then re-run `gbrain doctor --alert --json`.++<a id="doctor-alert-unknown"></a>++**Exit 18 (`unknown`).** Each item names the `check`, the `reason` it is not+fresh (`budget`, `bound`, `errored`, `last_known`, `not_run`), the+`budget_ms` it ran under and a `fix` that measures it alone. `not_run` on+every database check means the database checks did not run: read the+`connection` check (a live `gbrain serve` holding a PGLite brain is the+common case: run the alert where the serve's brain is reachable, or stop the+serve first). A check that keeps hitting its budget on a large brain needs a+larger `--budget-ms` in the cron line. A thin client refuses `--alert`+(`doctor_tier_unavailable`): schedule it on the brain host.+## Content-drift sweep**Doctor reports `content_drift_sweep` as a warning, or an embed run prints@@ -11124,6 +11196,8 @@ the exit code first, then reads the JSON document (`--json`) for the details:| 12 | `no_results`: `gbrain recall` (an entity, text, `--grep`, `--question` or `--query` lookup) or `gbrain entity` matched nothing. Opt-in: only with `GBRAIN_FAIL_ON_EMPTY=1`; otherwise a miss exits 0 | recall's list output: `status: "no_results"`; entity: `found: false` | treat it as a miss, not a failure; a script that filters stdout can branch on it || 13 | `pending_verify`: `gbrain bootstrap harness --token` wired a PGLite brain while no serve answered; nothing failed, nothing verified yet | the harness result with `status: "pending_verify"` and `fix` | tell the user to start `gbrain serve --http`, then run `fix.command` with the same token; `bootstrap harness --status` stays partial until it passes ([pending verify](bootstrap.md#pending-verify)) || 14 | `bootstrap_cleanup_pending`: `gbrain bootstrap harness` (or `--status`) wired and verified the harness, but earlier shared-skills enrollments or carried token ids are not cleaned up yet | the harness result with `status: "cleanup_pending"`, a per-id `cleanup` list and `fix` | follow `fix.next`: `run` re-runs the same command; `tell_user_to_run` relays the owner's revoke or restore step, then re-run ([cleanup pending](bootstrap.md#cleanup-pending)) |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now (database, writes, migrations, builds, sync or maintenance stalls, corrupt rows, schema exposure, paid-loop breaker) | the doctor report; `alert.level: "act"`, `alert.items` with each check's `fix` | follow each item's `fix.next` ([doctor alert](troubleshooting.md#doctor-alert-act)) |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but at least one page-class check did not run fresh (budget, error, last known result, tier) | the doctor report; `alert.level: "unknown"`, `alert.unknown` naming each check, its budget and a `fix`, and `alert.consecutive_unknown` | run each `fix`; an agent cron pages only from the second unknown run in a row ([doctor alert](troubleshooting.md#doctor-alert-unknown)) || 69 | `gbrain serve` exited on its own after its persistence consumer reported `restart_required` for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS` (`serve_unhealthy_exit`; opt-in) | `[gbrain serve] error code=serve_unhealthy_exit` line on stderr | nothing: the supervisor (the installed service restarts on failure) starts a fresh serve; if it repeats, follow [the unhealthy exit](../ENGINES.md#serve-unhealthy-exit) || 75 | another runner holds the migration lock, or an engine graduation owns the brain (`graduation_in_progress`) | error envelope | wait for the other runner, then retry || 124 | the command's own deadline elapsed | error envelope | inspect what is still running (the message names the status command) |diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex 98b8739441..876691d33c 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -1015,6 +1015,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.mdindex 1f7bc04bf3..8da5db6bc6 100644--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md@@ -476,9 +476,9 @@ your operational heartbeat.### On every heartbeat (hourly or per-session)-Run `gbrain doctor --json` and check for degradation. Report any failing checks-to the user. Key signals: connection health, schema version, RLS status, embedding-staleness.+Run `gbrain doctor --alert --json`. Exit 0: report nothing. Exit 17: report each+`alert.items` entry with its fix. Exit 18: report only when+`alert.consecutive_unknown` is 2 or more. Never alert on `health_score`.### Weekly maintenancediff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex 98b8739441..876691d33c 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -1015,6 +1015,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex 98b8739441..876691d33c 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -1015,6 +1015,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.mdindex 1f7bc04bf3..8da5db6bc6 100644--- a/plugin/skills/maintain/SKILL.md+++ b/plugin/skills/maintain/SKILL.md@@ -476,9 +476,9 @@ your operational heartbeat.### On every heartbeat (hourly or per-session)-Run `gbrain doctor --json` and check for degradation. Report any failing checks-to the user. Key signals: connection health, schema version, RLS status, embedding-staleness.+Run `gbrain doctor --alert --json`. Exit 0: report nothing. Exit 17: report each+`alert.items` entry with its fix. Exit 18: report only when+`alert.consecutive_unknown` is 2 or more. Never alert on `health_score`.### Weekly maintenancediff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bfa01bceb3..248d416789 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,7 +5,7 @@# Columns: path max_lines policy notesrc/cli/main.ts 2956 ratchet +1 #7619: the --flag=value gate call after the handler-free help printers, covering the hand-parsed search subcommands and the exact-token validation-exempt paths (logic, findUnknownFlag included, in cli/flag-equals.ts); +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 measured)src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)-src/commands/doctor.ts 700 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks)+src/commands/doctor.ts 706 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts); +8 #7276: DoctorReport.unknown_count field and the unknown category/count lines of the text headline (scoring logic in doctor/budget.ts scoredChecks); +6 GBRA-224 W4: DoctorReport.alert field, the alert computation call and the --alert branch of runDoctor (logic in doctor/alert.ts)src/commands/embed.ts 2306 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +2 agent operator wave D2: --json failure envelope via writeCliErrorsrc/commands/extract-conversation-facts.ts 1949 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left; +1 GBRA-159: facts from a private page are private (tightenToPage per page; helper in core/facts/visibility.ts); +3 #7438: ExtractConversationFactsResult.facts_skipped_purged (interface field) and one notePurgedSkips call (the count and log live in core/facts/conversation-publication.ts); grown v0.46.x per-provider gateway-unavailable copy; re-summed at the Wave B PR 4 merge with v0.60.452.0 (1949 measured)src/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug list@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: linksrc/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)-src/core/behavior-change-notice.ts 1518 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row+src/core/behavior-change-notice.ts 1520 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this row; +2 GBRA-224 W4 doctor_foreign_skills_folder rowdiff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex 98b8739441..876691d33c 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -1015,6 +1015,8 @@ that work in this conversation.| 12 | `no_results`: a recall or entity lookup matched nothing (only with `GBRAIN_FAIL_ON_EMPTY=1`) | treat it as a miss, not a failure || 13 | `pending_verify`: a harness wired, verification waits for the serve | start the serve, then run `fix.command` || 14 | `bootstrap_cleanup_pending`: a harness is wired; old shared-skills enrollments or token ids still await cleanup | follow `fix.next` (re-run, or relay the owner's revoke step), then re-run |+| 17 | `doctor_alert_act`: `gbrain doctor --alert` found a page-class check that needs someone now | follow each `alert.items[].fix` in the `--json` document |+| 18 | `doctor_alert_unknown`: `gbrain doctor --alert` found nothing to act on, but a page-class check did not run fresh | run each `alert.unknown[].fix`; page only when `alert.consecutive_unknown` is 2 or more || 75 | another runner holds the migration lock | wait, then retry || 124 | the command's deadline elapsed | inspect what is still running || 130 | interrupted | ask the user whether to re-run |diff --git a/skills/maintain/SKILL.md b/skills/maintain/SKILL.mdindex 31effe2cc7..cffb9596e5 100644--- a/skills/maintain/SKILL.md+++ b/skills/maintain/SKILL.md@@ -475,9 +475,9 @@ your operational heartbeat.### On every heartbeat (hourly or per-session)-Run `gbrain doctor --json` and check for degradation. Report any failing checks-to the user. Key signals: connection health, schema version, RLS status, embedding-staleness.+Run `gbrain doctor --alert --json`. Exit 0: report nothing. Exit 17: report each+`alert.items` entry with its fix. Exit 18: report only when+`alert.consecutive_unknown` is 2 or more. Never alert on `health_score`.### Weekly maintenancediff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex d6f73e4d80..7ff277370e 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -44,7 +44,7 @@"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e","context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",- "conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235",+ "conventions/agent-operator-protocol.md": "d90e71155ce33e80a1269aca4ba53776aa1c5b887a0e545ac1fb247511175ebc","conventions/brain-first.md": "e0e4d7c4b760213325dffd286baf934720816a0b6aac5338538a0463e8fe77d2","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",@@ -94,7 +94,7 @@"idea-lineage/SKILL.md": "8cb36179dbf94abc17065613b8e773b1bb2b22670742aa77347b91ac885a05c5","idea-lineage/routing-eval.jsonl": "ee2e00704b9accb7dd58bb8f126a3bc04a2c40be499180fa505dbf6d5061cd41","ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",- "maintain/SKILL.md": "fd08497f175ede76befe530a6a56adeed39ac37f9ea0ee19f2b9757488e36731",+ "maintain/SKILL.md": "412749303c3b1ce208049f0ab6cf4609d7a57c9b0bbf5464ab34ff8215f01855","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4","mcp-access/SKILL.md": "1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96","measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.tsindex 0e794b1eef..716818e4ce 100644--- a/src/cli/commands/doctor.ts+++ b/src/cli/commands/doctor.ts@@ -13,8 +13,10 @@ import {import type { BrainEngine } from '../../core/engine.ts';import type { CliDispatchContext } from '../command-table.ts';-export async function run(args: string[], ctx: CliDispatchContext): Promise<void> {+export async function run(argv: string[], ctx: CliDispatchContext): Promise<void> {const { connectEngine, dbMarkerBrainId } = ctx;+ // W4: --alert runs the page class alone (the alert tier) under its own budget unless --tier / --only / --budget-ms say otherwise.+ const args = argv.includes('--alert') ? (await import('../../commands/doctor/alert.ts')).alertRunArgs(argv) : argv;// Multi-topology v1: thin-client doctor. When `~/.gbrain/config.json`// has remote_mcp set, every DB-bound check is irrelevant. Route to the// outbound-HTTP probe set in `src/core/doctor-remote.ts` and return@@ -27,7 +29,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<voidconst tier = args.find((a, i) => args[i - 1] === '--tier') ?? args.find((a) => a.startsWith('--tier='))?.slice('--tier='.length);if (tier !== undefined || (only && only.size > 0 && [...only].every((n) => doctorCheckNames().has(n)))) {const { runScopedRemoteDoctor } = await import('../../core/doctor-remote-tier.ts');- await runScopedRemoteDoctor(cfgForDoctor!, { tier, only, json: args.includes('--json'), label: args.filter((a) => a !== '--json').join(' ') });+ await runScopedRemoteDoctor(cfgForDoctor!, { tier, only, json: args.includes('--json'), label: args.filter((a) => a !== '--json').join(' '), alert: argv.includes('--alert') });return;}const { runRemoteDoctor } = await import('../../core/doctor-remote.ts');diff --git a/src/cli/help/doctor.ts b/src/cli/help/doctor.tsindex a28fec78ff..0a88623b82 100644--- a/src/cli/help/doctor.ts+++ b/src/cli/help/doctor.ts@@ -7,6 +7,7 @@ export const help: CliHelpSpec = {'gbrain doctor [--fast] [--json] [--fix [--dry-run]] [--scope=brain] [--source <id>] [--no-migrate] [--locks]','gbrain doctor --tier ops|quick|standard|deep [--budget-ms <n>] [--json]','gbrain doctor --only <check>[,<check>…] [--tier ops] [--json]',+ 'gbrain doctor --alert [--tier <t>] [--budget-ms <n>] [--json]','gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]','gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]',' [--max-jobs <n>] [--no-embed] [--dry-run] [--resume [<plan_hash>]] [--json]',@@ -14,6 +15,7 @@ export const help: CliHelpSpec = {flags: [{ name: '--json', type: 'boolean', desc: 'Print one JSON document (checks, score, findings) on stdout.' },{ 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: '--alert', type: 'boolean', desc: 'What an agent cron pages on: runs only the page-class checks (database, writes, migrations, builds, sync and maintenance stalls, corrupt rows, schema exposure, paid-loop breaker), fresh, under a 30 s budget, and exits 0 (alert none), 17 (act: alert.items carry each fix) or 18 (unknown: a page-class check did not run fresh; alert.consecutive_unknown counts the runs in a row). Read-only. With --tier, grades that tier\'s full run instead.' },{ name: '--fast', type: 'boolean', desc: 'Skip database checks; filesystem and config checks only.' },{ name: '--tier', type: 'enum', values: ['ops', 'quick', '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). quick: the health gate for agents on large brains: the ops sections plus schema version, sync failures, queue health and partial embeddings under a 10 s deadline; every other check is reported from its last known result with its age, checks with none from the last 24 h are named as unknown, and a background doctor-refresh job is queued to measure them. standard (default): ops first, then the rest; a brain-wide run records each finished check as its last known result. 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; 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.' },diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 55607d634e..8eb765d22c 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -141,6 +141,7 @@ export { doctorRunSummary, type DoctorRunSummary } from './doctor/budget.ts';import { runDoctorRegistry, parseOnlyChecks, doctorRefreshRegistry } from './doctor/registry.ts';import { finalizeCheckFixes, fixLine, unknownScoreCategories, type CheckAgentFields } from './doctor/check-fix.ts';import { throttleDoctorHeartbeat } from './doctor/heartbeat.ts';+import { alertRanChecks, computeAlert, printAlertReport, type DoctorAlert } from './doctor/alert.ts';import type { RenderContext } from '../core/agent-output.ts';export interface Check extends CheckAgentFields {name: string;@@ -232,6 +233,8 @@ export interface DoctorReport {* the ranking. Additive + optional; schema_version stays at 2.*/top_issues?: RankedIssue[];+ /** W4: what an agent cron pages on (none / act / unknown, ./doctor/alert.ts); additive, the scores are unchanged. */+ alert?: DoctorAlert;/*** db-availability loop — which engine this report was measured against and* where its URL came from. Additive + optional (schema_version stays 2);@@ -280,7 +283,7 @@ function _penaltyScore(checks: Check[]): number {*/export function computeDoctorReport(checks: Check[],- extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; render?: RenderContext; run?: DoctorRunSummary },+ extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; render?: RenderContext; run?: DoctorRunSummary; alertRan?: ReadonlySet<string> },): DoctorReport {const tagged = finalizeCheckFixes(checks, extras?.render).map((c) =>c.category ? c : { ...c, category: categorizeCheck(c.name) },@@ -312,6 +315,7 @@ export function computeDoctorReport(},checks: tagged,top_issues: rankIssues(tagged),+ alert: computeAlert(tagged, { ran: extras?.alertRan, render: extras?.render }),...(extras?.engine ? { engine: extras.engine } : {}),...(extras?.db_url_source !== undefined ? { db_url_source: extras.db_url_source } : {}),...(capped_by.length ? { capped_by } : {}),@@ -528,7 +532,9 @@ export async function runDoctor(if (args.includes('--probe') && !(await (await import('./doctor/probe-consent.ts')).authorizeProviderProbe(engine, args, jsonOutput))) return;const checks = await buildChecks(engine, args, dbSource, connectError, deadline, { lastKnown: 'cli' });const run = doctorRunSummary(args, deadline);- const hasFail = outputResults(checks, jsonOutput, { engine: engine?.kind, db_url_source: dbSource ?? null, run });+ const extras = { engine: engine?.kind, db_url_source: dbSource ?? null, run, alertRan: alertRanChecks(checks, parseDoctorTier(args)) };+ if (args.includes('--alert')) return setCliExitVerdict(printAlertReport(computeDoctorReport(checks, extras), jsonOutput));+ const hasFail = outputResults(checks, jsonOutput, extras);// Features teaser (non-JSON, non-failing only; never under the ops deadline)if (!jsonOutput && !hasFail && engine && run?.tier !== 'ops') {@@ -560,7 +566,7 @@ export function doctorProgressOptions(jsonOutput: boolean) {function outputResults(checks: Check[],json: boolean,- extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; run?: DoctorRunSummary },+ extras?: Parameters<typeof computeDoctorReport>[1],): boolean {// v0.41.19.0 — render goes through computeDoctorReport so the human// output, JSON output, and remote MCP envelope all share one shape.diff --git a/src/commands/doctor/alert.ts b/src/commands/doctor/alert.tsnew file mode 100644index 0000000000..fd2cbf0120--- /dev/null+++ b/src/commands/doctor/alert.ts@@ -0,0 +1,244 @@+/**+ * W4: the doctor's alert verdict (`DoctorReport.alert`), what an agent cron+ * pages on instead of `health_score`.+ *+ * Only the page class pages (PAGE_CHECK_LEVELS in src/core/doctor-categories.ts):+ * - act: a page-class check reported its paging status; each item keeps the+ * check's own rendered fix (argv or MCP call, consent, actor, verify).+ * - unknown: a page-class check did not run fresh in this run (over its+ * budget, stopped at a bound, errored, served from its last known result,+ * skipped by the tier, or the database checks did not run). Each item names+ * the check, the budget it ran under and the command that measures it.+ * - none: every page-class check ran fresh and none pages.+ * act dominates unknown, which dominates none; both item lists are kept.+ *+ * gbrain doctor --alert runs the page class alone (the alert tier: every+ * page-class entry, fresh, under ALERT_BUDGET_MS_DEFAULT), so a healthy brain+ * reaches none on every run. It keeps a consecutive-unknown counter per brain+ * on the file plane (doctor-alert-state.json under GBRAIN_HOME) so a cron can+ * page on the second unknown in a row. A remote report omits check messages+ * (they can carry local paths) and gives a host-admin step where no MCP fix exists.+ */+import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { atomicWriteFileSync } from '../../core/atomic-write.ts';+import { cliRenderContext, redactForTransport, renderAction, type RenderContext, type RenderedAction } from '../../core/agent-output.ts';+import { gbrainPath, loadConfig } from '../../core/config.ts';+import { PAGE_CHECK_LEVELS, PAGE_CHECK_NAMES } from '../../core/doctor-categories.ts';+import { DOCTOR_ALERT_ACT_EXIT_CODE, DOCTOR_ALERT_UNKNOWN_EXIT_CODE } from '../../core/exit-codes.ts';+import type { Check, DoctorReport } from '../doctor.ts';+import { fixLine } from './check-fix.ts';+import { writeJsonDocument } from '../../core/cli-force-exit.ts';+import { entryRunsAt } from './budget.ts';+import { agentFix, type FixUnavailableReason } from './check-fix.ts';+import type { DoctorTier } from './context.ts';+import { DOCTOR_CHECK_REGISTRY } from './registry.ts';++export type AlertLevel = 'none' | 'act' | 'unknown';+export type AlertUnknownReason = 'budget' | 'bound' | 'errored' | 'last_known' | 'not_run';++export interface AlertActItem {+ /** Stable: the check's own details.code when it has one, else the check name. */+ code: string;+ check: string;+ status: 'warn' | 'fail';+ /** The check's message; omitted on a remote report (it can name local paths). */+ message?: string;+ docs: string;+ fix?: RenderedAction;+ fix_unavailable_reason?: FixUnavailableReason;+}++export interface AlertUnknownItem {+ code: 'doctor_alert_unknown';+ check: string;+ reason: AlertUnknownReason;+ /** The budget the check ran under, when a budget stopped it. */+ budget_ms: number | null;+ message: string;+ /** Measures this check fresh (with a larger budget when a budget stopped it). */+ fix: RenderedAction;+ /** Set by doctor --alert: how many alert runs in a row (this one included) ended unknown. */+ consecutive_unknown_runs?: number;+}++export interface DoctorAlert {+ level: AlertLevel;+ items: AlertActItem[];+ unknown: AlertUnknownItem[];+ /** Set by doctor --alert: alert runs in a row ending unknown (0 after a none or act run); null when the state file can be neither read nor written. */+ consecutive_unknown?: number | null;+ docs: string;+}++/** The alert tier's default end-to-end budget (connect included); --budget-ms overrides it. */+export const ALERT_BUDGET_MS_DEFAULT = 30_000;+export const ALERT_DOCS = 'docs/guides/troubleshooting.md#doctor-alert';+const STATE_FILE = 'doctor-alert-state.json';++/** The arguments --alert runs with: the page class alone (unless --tier / --only is given) under the alert budget, skill checks skipped. */+export function alertRunArgs(args: readonly string[]): string[] {+ const has = (flag: string) => args.some((a) => a === flag || a.startsWith(`${flag}=`));+ const out = [...args];+ if (!has('--tier') && !has('--only')) out.push('--only', [...PAGE_CHECK_NAMES].join(','));+ if (!has('--budget-ms')) out.push('--budget-ms', String(ALERT_BUDGET_MS_DEFAULT));+ if (!args.includes('--scope=brain')) out.push('--scope=brain');+ return out;+}++/**+ * The page-class checks this run executed: none when the database checks did not run (no connection check that is+ * ok), else every page-class check whose entry runs at tier. A page-class check missing from such a run did not apply.+ */+export function alertRanChecks(checks: readonly Pick<Check, 'name' | 'status'>[], tier: DoctorTier): Set<string> {+ if (!checks.some((c) => c.name === 'connection' && c.status === 'ok')) return new Set();+ return new Set([...PAGE_CHECK_NAMES].filter((name) => DOCTOR_CHECK_REGISTRY.some((e) => e.emits.includes(name) && entryRunsAt(e.tier, tier))));+}++function unknownReason(c: Check): AlertUnknownReason | null {+ if (c.details?.last_known !== undefined) return 'last_known';+ if (c.details?.health === 'unknown') return c.details.reason === 'budget' ? 'budget' : c.details.reason === 'bound' ? 'bound' : 'errored';+ if (c.fix_unavailable_reason === 'check_errored') return 'errored';+ if (c.readiness_state === 'unknown' && c.status !== 'fail') return 'not_run';+ return null;+}++function pages(c: Check): boolean {+ return c.status === 'fail' || (c.status === 'warn' && PAGE_CHECK_LEVELS.get(c.name) === 'warn');+}++function isRendered(fix: Check['fix']): fix is RenderedAction {+ return !!fix && typeof (fix as RenderedAction).next === 'string';+}++const UNKNOWN_WHY: Record<AlertUnknownReason, string> = {+ budget: 'did not finish within its budget',+ bound: 'stopped at one of its own bounds before reading everything',+ errored: 'could not be checked',+ last_known: 'was reported from its last known result, not measured in this run',+ not_run: 'did not run (the database checks did not run, or this tier or report skips it)',+};++/**+ * The alert verdict of a finalized check list (computeDoctorReport calls it after rendering fixes). ran: the+ * page-class checks this run executed, so one it did not emit did not apply; without it a missing page-class check+ * is unknown (a focused or remote report that never runs it).+ */+export function computeAlert(checks: readonly Check[], opts: { ran?: ReadonlySet<string>; render?: RenderContext } = {}): DoctorAlert {+ const render = opts.render ?? cliRenderContext();+ const remote = render.transport !== 'cli';+ const items: AlertActItem[] = [];+ const unknown: AlertUnknownItem[] = [];+ for (const name of PAGE_CHECK_NAMES) {+ const found = checks.filter((c) => c.name === name);+ if (found.length === 0) {+ if (!opts.ran?.has(name)) unknown.push(unknownItem(name, 'not_run', null, render));+ continue;+ }+ const paging = found.find((c) => unknownReason(c) === null && pages(c));+ const stale = found.find((c) => unknownReason(c) !== null);+ if (paging) items.push(actItem(paging, remote, render));+ else if (stale) unknown.push(unknownItem(name, unknownReason(stale)!, stale, render));+ }+ const level: AlertLevel = items.length ? 'act' : unknown.length ? 'unknown' : 'none';+ const alert: DoctorAlert = { level, items, unknown, docs: ALERT_DOCS };+ return remote ? redactForTransport(alert, 'http') : alert;+}++function actItem(c: Check, remote: boolean, render: RenderContext): AlertActItem {+ const code = typeof c.details?.code === 'string' ? c.details.code : c.name;+ const docs = typeof c.details?.docs === 'string' ? c.details.docs : `${ALERT_DOCS}-act`;+ const fix = isRendered(c.fix) ? c.fix : remote+ ? renderAction({ argv: ['gbrain', 'doctor', '--only', c.name, '--json'], consent: [], actor: 'host_admin', requires_exclusive: false, docs,+ why: `Run on the brain host: the local report says what ${c.name} found and how to fix it.` }, render)+ : undefined;+ return {+ code, check: c.name, status: c.status as 'warn' | 'fail',+ ...(remote ? {} : { message: c.message }),+ docs,+ ...(fix ? { fix } : { fix_unavailable_reason: c.fix_unavailable_reason ?? 'unstructured' }),+ };+}++function unknownItem(name: string, reason: AlertUnknownReason, c: Check | null, render: RenderContext): AlertUnknownItem {+ const budgetMs = typeof c?.details?.budget_ms === 'number' ? c.details.budget_ms : null;+ const fix = reason === 'budget' && isRendered(c?.fix) ? c!.fix as RenderedAction+ : renderAction(agentFix(['gbrain', 'doctor', '--only', name, '--budget-ms', '0', '--json'],+ 'Measures only this check now, with no overall budget; read-only.', name, { docs: ALERT_DOCS }), render);+ const budget = budgetMs !== null ? ` (budget ${budgetMs} ms)` : '';+ const step = fix.command ?? (fix.mcp ? `the ${fix.mcp.tool} tool` : 'the fix');+ return {+ code: 'doctor_alert_unknown', check: name, reason, budget_ms: budgetMs,+ message: `${name} ${UNKNOWN_WHY[reason]}${budget}, so its health is unknown, not clear. Measure it with ${step}, `+ + 'run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).',+ fix,+ };+}++/** The brain this home's alert state is kept for: a hash of its database URL or path, never the value itself. */+function brainKey(): string {+ let id = 'default';+ try {+ const cfg = loadConfig();+ id = cfg?.database_url ?? cfg?.database_path ?? 'default';+ } catch { /* unreadable config: one shared key */ }+ return createHash('sha256').update(id).digest('hex').slice(0, 16);+}++/**+ * doctor --alert: count this run into the brain's consecutive-unknown streak (reset by a none or act run), stamp the+ * count on the alert and its unknown items, and persist it atomically. A home that cannot be written (read-only)+ * still gets this run's count from what it read; null only when it could neither read nor write the state.+ */+export function recordAlertStreak(alert: DoctorAlert, now = new Date()): DoctorAlert {+ const path = gbrainPath(STATE_FILE);+ type BrainState = { consecutive_unknown: number; last_level: AlertLevel; updated_at: string };+ let brains: Record<string, BrainState> = {};+ let readable = true;+ try {+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));+ if (parsed && typeof parsed.brains === 'object' && parsed.brains) brains = parsed.brains;+ } catch (err) {+ readable = (err as NodeJS.ErrnoException)?.code === 'ENOENT';+ }+ const key = brainKey();+ const prev = Number(brains[key]?.consecutive_unknown ?? 0);+ const count = alert.level === 'unknown' ? (Number.isSafeInteger(prev) && prev > 0 ? prev : 0) + 1 : 0;+ brains[key] = { consecutive_unknown: count, last_level: alert.level, updated_at: now.toISOString() };+ let written = true;+ try {+ atomicWriteFileSync(path, JSON.stringify({ schema_version: 1, brains }, null, 2) + '\n', { mode: 0o600 });+ } catch {+ written = false;+ }+ if (!readable && !written) return { ...alert, consecutive_unknown: null };+ return {+ ...alert,+ consecutive_unknown: count,+ unknown: alert.unknown.map((u) => ({ ...u, consecutive_unknown_runs: count, message: `${u.message} Unknown for ${count} consecutive alert run(s).` })),+ };+}++/** The exit status of a doctor --alert run: 0 none, 17 act, 18 unknown. */+export function alertExitCode(level: AlertLevel): number {+ return level === 'act' ? DOCTOR_ALERT_ACT_EXIT_CODE : level === 'unknown' ? DOCTOR_ALERT_UNKNOWN_EXIT_CODE : 0;+}++/** `gbrain doctor --alert`: print the verdict (with this brain's consecutive-unknown count) and return the exit code. */+export function printAlertReport(report: DoctorReport, json: boolean): number {+ const alert = recordAlertStreak(report.alert!);+ if (json) {+ void writeJsonDocument(JSON.stringify({ ...report, alert }));+ return alertExitCode(alert.level);+ }+ const streak = alert.level === 'unknown' && alert.consecutive_unknown ? ` (${alert.consecutive_unknown} consecutive unknown run(s))` : '';+ console.log(`Alert: ${alert.level}${streak}`);+ for (const item of alert.items) {+ console.log(` [ACT] ${item.check}: ${item.message ?? item.code}`);+ const fix = fixLine(item.fix);+ if (fix) console.log(` Fix: ${fix}`);+ }+ for (const item of alert.unknown) console.log(` [UNKNOWN] ${item.check}: ${item.message}`);+ console.log(`Health score: ${report.health_score}/100 (context only; page on the alert level).`);+ return alertExitCode(alert.level);+}diff --git a/src/commands/doctor/checks/skill-group.ts b/src/commands/doctor/checks/skill-group.tsindex fa002dea84..d3da2b8152 100644--- a/src/commands/doctor/checks/skill-group.ts+++ b/src/commands/doctor/checks/skill-group.ts@@ -20,12 +20,26 @@ import { checkVolunteerChannels } from './core-health.ts';import { buildRetrievalReflexCheck, buildMemoryVerbsCheck } from './verbs-reflex.ts';import type { Check } from '../../doctor.ts';import type { DoctorContext, DoctorEntry } from '../context.ts';-import { checkError } from '../check-fix.ts';+import { checkError, infoCheck } from '../check-fix.ts';+import { isGbrainManagedSkillsDir } from '../../../core/skill-manifest.ts';++/**+ * W4: a skills folder found only by walking up from the cwd that gbrain did not install (an agent's own skills, no+ * gbrain manifest or skillpack block) is not graded against gbrain's conventions: resolver_health and skill_currency+ * report it as info. --skills-dir, $GBRAIN_SKILLS_DIR and $OPENCLAW_WORKSPACE still grade whatever they name.+ */+function foreignSkillsCheck(ctx: DoctorContext, name: string): Check | null {+ const { dir, source } = ctx.skillsDirResolution;+ if (!dir || (source !== 'cwd_walk_up' && source !== 'cwd_skills') || isGbrainManagedSkillsDir(dir)) return null;+ return infoCheck(name, `not a gbrain skills folder (${dir}); pass --skills-dir to grade it`, 'not_applicable');+}async function runResolverHealth(ctx: DoctorContext): Promise<Check[]> {const { skillsDirResolution: detected, doFix, dryRun, jsonOutput, scope } = ctx;const skillsDir = detected.dir;const checks: Check[] = [];+ const foreign = scope === 'all' ? foreignSkillsCheck(ctx, 'resolver_health') : null;+ if (foreign) return [foreign];if (scope === 'all' && skillsDir) {@@ -166,7 +180,7 @@ async function runSkillConformance(ctx: DoctorContext): Promise<Check[]> {// `requires:`. Currency is filesystem-only; preconditions need the engine// and skip cleanly without one.if (scope === 'all' && skillsDir) {- checks.push(skillCurrencyCheck(skillsDir));+ checks.push(foreignSkillsCheck(ctx, 'skill_currency') ?? skillCurrencyCheck(skillsDir));checks.push(await skillPreconditionsCheck(skillsDir, engine));}return checks;diff --git a/src/commands/doctor/remote-tier.ts b/src/commands/doctor/remote-tier.tsindex eb89056809..add11a55fe 100644--- a/src/commands/doctor/remote-tier.ts+++ b/src/commands/doctor/remote-tier.ts@@ -12,6 +12,9 @@ import { invalidParam } from '../../core/ops/op-fix.ts';import { computeDoctorReport, doctorReportRemote, buildChecks, type DoctorReport } from '../doctor.ts';import { doctorCheckNames, opsCheckNames } from './registry.ts';import { startDoctorDeadline } from './budget.ts';+import { ALERT_BUDGET_MS_DEFAULT, alertRanChecks } from './alert.ts';+import { PAGE_CHECK_NAMES } from '../../core/doctor-categories.ts';+import { redactForTransport } from '../../core/agent-output.ts';export async function runRemoteDoctorTier(ctx: OperationContext, p: Record<string, unknown>): Promise<DoctorReport> {if (p.tier !== undefined && p.tier !== 'ops') {@@ -34,6 +37,15 @@ export async function runRemoteDoctorTier(ctx: OperationContext, p: Record<strinconst checks = await buildChecks(ctx.engine, args, undefined, undefined, deadline, { sourceIds, remote: ctx.remote !== false });return computeDoctorReport(checks, { engine: ctx.engine.kind, render, run: { tier: 'ops', startedAt: deadline.startedAt, budgetMs: deadline.budgetMs } });}+ // W4: `only` naming page-class checks runs them on the serving host (the alert tier), so a harness whose serve holds+ // the brain gets a fresh alert verdict over MCP; check text is redacted like every remote report.+ if (only && only.every((n) => PAGE_CHECK_NAMES.has(n))) {+ const args = ['--json', '--only', only.join(','), '--budget-ms', String(ALERT_BUDGET_MS_DEFAULT), '--scope=brain'];+ const deadline = startDoctorDeadline(args);+ const raw = await buildChecks(ctx.engine, args, undefined, undefined, deadline, { sourceIds, remote: ctx.remote !== false });+ const checks = transport === 'cli' ? raw : redactForTransport(raw, 'http');+ return computeDoctorReport(checks, { engine: ctx.engine.kind, render, alertRan: alertRanChecks(checks, 'standard') });+ }const report = await doctorReportRemote(ctx.engine, { sourceIds, remote: ctx.remote, render });const kept = report.checks.filter((c) => only!.includes(c.name));return computeDoctorReport(kept, { engine: report.engine, render });diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 59b8c1aa07..9203860271 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1319,6 +1319,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7705 (strict door planned state). `since` is stamped at the merge slot.{ since: '0.60.471.0', id: 'door_planned_state', text: 'On a source with `canonical: git`, a page write now commits exactly the bytes it published, or nothing. A file edited on disk while the write was publishing refuses `git_target_changed`: nothing is committed, the edit stays on disk and the source\'s writes pause until `gbrain repair stuck-recovery` resolves it (before, Git committed the edit while the database recorded the write\'s content). A staged change of the page\'s file refuses `git_index_conflict`, with the index untouched; commit or unstage it, then retry (before, the write replaced the staged change in the index). When the index still holds the version from before an earlier gbrain commit whose index update failed, the next write restores it and says so with a `git_index_restored` notice.' },// #7679 / #7685 orphaned worktree refresh. `since` is stamped at the merge slot.+ // GBRA-224 W4 (doctor alert). `since` is stamped at the merge slot.+ { since: '0.60.475.0', id: 'doctor_foreign_skills_folder', text: '`gbrain doctor` no longer grades a skills folder it found by walking up from the current directory unless gbrain installed it (a skills.lock.json, a valid manifest.json or the skillpack block in its resolver file): resolver_health and skill_currency report "not a gbrain skills folder (<path>)" as info, so an agent\'s own skills folder no longer lowers health_score or fails doctor. Pass --skills-dir (or set GBRAIN_SKILLS_DIR / OPENCLAW_WORKSPACE) to grade it as before. Agent crons should page on the new `gbrain doctor --alert` (exit 17 act, 18 unknown), not on health_score.' },{ since: '0.60.472.0', id: 'refresh_orphan_7679', text: 'A managed `gbrain sources refresh` whose process died (for example a container replaced mid-refresh) no longer wedges the checkout: the next plain `gbrain sources refresh` on the owner host finishes the orphaned refresh through the `--resume` path before its own refresh and reports it as `recovered`, and the owner completes an orphaned `syncing` refresh once every member has synced to its target. A refresh whose holder is still running, or is recorded on another host, is never taken over. `gbrain sources writer status` and `gbrain sync status` now name the holder and its `liveness` (`live`, `orphaned`, `unknown`) with a fix naming `--resume`. With `--json`, a refusal that carries a structured fix (`refresh_in_progress`, `refresh_diverged`, a git read failure) now prints `fix` as an object (argv, actor, next) instead of a string; the prose stays in `suggestion`, so read that when a script needs text. A plain refresh of a checkout whose interrupted refresh needs a reset decision now refuses `refresh_recovery_required` (it refused `refresh_in_progress`).' },];diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 736d3ab293..dea52c53a8 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -50,7 +50,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--after', '--aggressive', '--alert', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--cursor', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--run', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -76,14 +76,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--batch-check', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--literal-pathspecs', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--after', '--alert', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--alert', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],@@ -131,7 +131,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--body', '--brain', '--break-lock', '--cached', '--check', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--alert', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--body', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--type', '--unindexed', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 71ffac93f4..9e93d157b0 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -501,3 +501,27 @@ export function categorizeCheck(name: string): CheckCategory {* categorization and the per-check categorization aligned.*/export const SKILL_CHECK_GROUP_NAMES: ReadonlySet<string> = SKILL_CHECK_NAMES;++/**+ * W4: the page class of `DoctorReport.alert`. Each name is an existing check that, at the status given or worse,+ * means the brain needs someone now; every other check (skill checks included) never pages. `warn`: a warning+ * pages too; `fail`: only a failure pages (that check's warning is an early or advisory state). Drift-guarded in+ * test/doctor-categories.test.ts against the emitted check names.+ */+export const PAGE_CHECK_LEVELS: ReadonlyMap<string, 'warn' | 'fail'> = new Map([+ ['connection', 'fail'],+ ['schema_version', 'warn'],+ ['schema_missing_tables', 'fail'],+ ['minions_migration', 'warn'],+ ['persistence_terminal_failures', 'warn'],+ ['persistence_write_stall', 'warn'],+ ['runtime_build_skew', 'fail'],+ ['managed_sync_blocked', 'fail'],+ ['managed_sync_not_moving', 'fail'],+ ['global_maintenance_stalled', 'fail'],+ ['jsonb_integrity', 'warn'],+ ['rls', 'fail'],+ ['dream_paid_loop', 'warn'],+]);++export const PAGE_CHECK_NAMES: ReadonlySet<string> = new Set(PAGE_CHECK_LEVELS.keys());diff --git a/src/core/doctor-remote-tier.ts b/src/core/doctor-remote-tier.tsindex ad398f6124..d722f83a1a 100644--- a/src/core/doctor-remote-tier.ts+++ b/src/core/doctor-remote-tier.ts@@ -54,7 +54,7 @@ export function bandChecks(bands: BandsResult, only: ReadonlySet<string> | null)}/** `tier` / `only` as parsed by the doctor dispatch (src/cli/commands/doctor.ts); `label` names the request in the handoff. */-export async function runScopedRemoteDoctor(config: GBrainConfig, req: { tier?: string; only: ReadonlySet<string> | null; json: boolean; label: string }): Promise<void> {+export async function runScopedRemoteDoctor(config: GBrainConfig, req: { tier?: string; only: ReadonlySet<string> | null; json: boolean; label: string; alert?: boolean }): Promise<void> {const { tier, only, json } = req;const handoff = (why: string) => {const out = renderCliError(opError('doctor_tier_unavailable', `The remote brain cannot answer gbrain doctor ${req.label} for this client: ${why}`,@@ -71,6 +71,7 @@ export async function runScopedRemoteDoctor(config: GBrainConfig, req: { tier?:if (runDoctor && needs.every((p) => runDoctor.params.includes(p))) {try {const report = unpackToolResult<{ status: string; checks: unknown[] }>(await callRemoteTool(config, 'run_doctor', { ...(tier ? { tier } : {}), ...(only ? { only: [...only] } : {}) }));+ if (req.alert) return printAlert(report, json);return print(report, json);} catch (e) {if (!(e instanceof RemoteMcpError && isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason))) throw e;@@ -88,6 +89,24 @@ export async function runScopedRemoteDoctor(config: GBrainConfig, req: { tier?:: 'the serve predates the doctor ops tier (run_doctor lists no tier or only parameter and get_brain_health is not served).');}+/**+ * W4 `gbrain doctor --alert` on a thin client: the serve ran the page-class checks (run_doctor `only`); exit by its+ * alert verdict with this client's consecutive-unknown count. A serve older than the alert reports none: unknown.+ */+async function printAlert(report: Record<string, unknown>, json: boolean): Promise<void> {+ const { recordAlertStreak, alertExitCode, ALERT_DOCS } = await import('../commands/doctor/alert.ts');+ const served = report.alert as import('../commands/doctor/alert.ts').DoctorAlert | undefined;+ const alert = recordAlertStreak(served ?? { level: 'unknown', items: [], unknown: [], docs: ALERT_DOCS });+ if (!served) process.stderr.write('[gbrain doctor] the remote serve predates doctor --alert, so the verdict is unknown; upgrade and restart it.\n');+ if (json) void writeJsonDocument(JSON.stringify({ ...report, alert }));+ else {+ console.log(`Alert (remote): ${alert.level}`);+ for (const item of alert.items) console.log(` [ACT] ${item.check}: ${item.fix?.command ?? item.fix?.user_message ?? item.code}`);+ for (const item of alert.unknown) console.log(` [UNKNOWN] ${item.check}: ${item.message}`);+ }+ setCliExitVerdict(alertExitCode(alert.level));+}+function print(report: { status: string; checks: unknown[] } & Record<string, unknown>, json: boolean): void {if (json) void writeJsonDocument(JSON.stringify(report));else {diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex c4d30ed271..58bb8430d4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -248,6 +248,8 @@ export const CODES = {verify: { argv: ['gbrain', 'doctor', '--only', 'managed_sync_not_moving', '--json'] } } },dream_breaker_tripped: { class: 'unavailable', summary: "A dream synthesize or patterns submission died (or, for patterns, was cancelled at its timeout after paid work) the breaker limit of times within 24 hours, so it was not submitted again.", why: "A run that keeps dying keeps paying; the breaker stops resubmitting until the cause is fixed and the key is reset. Patterns count per source (`dream:patterns:source:<id>`) whatever reflections each run read, and a completed run resets that count.", docs: 'docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions', fix: { argv: ['gbrain', 'doctor', '--only', 'dream_paid_loop', '--json'], consent: [], actor: 'agent', why: 'Shows the tripped dream keys with their counts and reset commands, read-only.', requires_exclusive: false } },dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },+ doctor_alert_act: { class: 'host_only', retryable: false, exit: 17, summary: "`gbrain doctor --alert` found a page-class check that needs someone now (database unreachable, writes failing or stalled, migrations pending or wedged, more than one build running, sync or maintenance stalled, corrupt rows, a public schema exposed, or a tripped paid-loop breaker).", why: "Only page-class checks page; skill, advisory and coaching checks never do, so health_score warnings alone exit 0. Each item in --json alert.items keeps that check's own fix, consent, actor and verify.", docs: 'docs/guides/troubleshooting.md#doctor-alert-act', suggestion: 'Read alert.items in the --json document and follow each fix.next; page the operator for items whose fix needs them.', fix: { argv: ['gbrain', 'doctor', '--alert', '--json'], consent: [], actor: 'agent', why: 'Read-only: the alert verdict with each item and its fix.', requires_exclusive: false } },+ doctor_alert_unknown: { class: 'retryable', exit: 18, reasons: ['budget', 'bound', 'errored', 'last_known', 'not_run'], summary: "`gbrain doctor --alert` found nothing to act on, but at least one page-class check did not run fresh in this run, so the brain's health is unknown, not clear.", why: "A check that timed out, errored, was reported from its last known result or was skipped by the tier proves nothing; reading it as healthy would hide an outage. alert.consecutive_unknown counts the alert runs in a row that ended unknown, and agent crons page on the second.", docs: 'docs/guides/troubleshooting.md#doctor-alert-unknown', suggestion: 'Run each alert.unknown item fix (it measures that check alone); if a check keeps running out of time, raise --budget-ms or run gbrain doctor --alert --tier standard --json.', fix: { argv: ['gbrain', 'doctor', '--alert', '--budget-ms', '0', '--json'], consent: [], actor: 'agent', why: 'Read-only: the alert verdict with no overall budget, so every page-class check can finish.', requires_exclusive: false } },doctor_tier_unavailable: { class: 'host_only', actor: 'host_admin', summary: "The remote serve cannot answer this doctor tier or check for this client, so the thin client ran nothing.", why: "A serve older than the doctor ops tier does not advertise run_doctor's tier and only parameters or get_brain_health, and a token without admin scope cannot call run_doctor; the thin client never falls back to the full report.", docs: 'docs/guides/troubleshooting.md#doctor-ops-tier', fix: { argv: ['gbrain', 'doctor', '--tier', 'ops', '--json'], consent: [], actor: 'host_admin', why: 'The ops report, run on the brain host (or after upgrading and restarting its serve).', requires_exclusive: false } },effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },embed_backfill_stalled: { class: 'unavailable', actor: 'agent',diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.tsindex 0d113dab1a..122e142ffb 100644--- a/src/core/exit-codes.ts+++ b/src/core/exit-codes.ts@@ -8,6 +8,7 @@* 11 resumable budget stop · 13 harness wired, verification pending ·* 12 no results (a lookup matched nothing; opt-in, GBRAIN_FAIL_ON_EMPTY=1) ·* 14 harness wired, shared-skills/token cleanup pending ·+ * 17 doctor --alert: act · 18 doctor --alert: unknown ·* 69 serve exited unhealthy · 75 migration* lock held · 124 timeout · 130 interrupted. `test/exit-codes.test.ts` enumerates every literal* exit 3 in src/ so a new one cannot reuse it.@@ -75,6 +76,19 @@ export const HARNESS_PENDING_VERIFY_EXIT_CODE = 13;*/export const HARNESS_CLEANUP_PENDING_EXIT_CODE = 14;+/**+ * W4 `gbrain doctor --alert` (`doctor_alert_act`): a page-class check needs someone now; `--json` `alert.items`+ * carries each check's fix. 0 is `alert.level: none`; 1 stays "doctor itself failed".+ */+export const DOCTOR_ALERT_ACT_EXIT_CODE = 17;++/**+ * W4 `gbrain doctor --alert` (`doctor_alert_unknown`): no page-class check needs action, but at least one did not run+ * fresh (budget, error, last known result, tier). `alert.consecutive_unknown` counts the runs in a row; agent crons+ * page on the second.+ */+export const DOCTOR_ALERT_UNKNOWN_EXIT_CODE = 18;+/*** #6543: `gbrain serve` exited on its own because its persistence consumer* reported `restart_required` continuously for `GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS`diff --git a/src/core/skill-manifest.ts b/src/core/skill-manifest.tsindex ff06485988..0aa5c7c560 100644--- a/src/core/skill-manifest.ts+++ b/src/core/skill-manifest.ts@@ -26,8 +26,13 @@*/import { existsSync, readFileSync, readdirSync, statSync } from 'fs';-import { join } from 'path';+import { dirname, join } from 'path';import { atomicWriteFileSync } from './atomic-write.ts';+import { findAllResolverFiles } from './resolver-filenames.ts';+import { SKILLS_MANIFEST_FILENAME } from './skills-integrity.ts';++/** First line of the block `gbrain skillpack install` writes into a workspace's resolver file. */+export const SKILLPACK_MANAGED_BEGIN = '<!-- gbrain:skillpack:begin -->';export interface ManifestEntry {name: string;@@ -146,6 +151,24 @@ export function loadOrDeriveManifest(skillsDir: string): ManifestLoadResult {return { skills: deriveManifest(skillsDir), derived: true };}+/**+ * Whether gbrain installed or ships this skills folder, read from files only+ * gbrain writes: its tamper manifest (`skills.lock.json`), a valid+ * `manifest.json` on disk (a derived one does not count), or the skillpack+ * managed block in a resolver file (RESOLVER.md / AGENTS.md here or at the+ * workspace root). A generic RESOLVER.md alone is not a gbrain marker. Doctor+ * grades an auto-detected skills folder against gbrain's conventions only when+ * this holds; an agent's own skills folder found by walking up from the cwd is+ * not gbrain's to grade.+ */+export function isGbrainManagedSkillsDir(dir: string): boolean {+ if (existsSync(join(dir, SKILLS_MANIFEST_FILENAME))) return true;+ if (existsSync(join(dir, 'manifest.json')) && !loadOrDeriveManifest(dir).derived) return true;+ return [...findAllResolverFiles(dir), ...findAllResolverFiles(dirname(dir))].some((file) => {+ try { return readFileSync(file, 'utf-8').includes(SKILLPACK_MANAGED_BEGIN); } catch { return false; }+ });+}+/*** #4831: register exactly the given just-scaffolded skills in an existing,* valid `skillsDir/manifest.json`. Appends `{name, path}` for each slug notdiff --git a/src/core/skillpack/installer.ts b/src/core/skillpack/installer.tsindex 7affe3637f..560f9e660f 100644--- a/src/core/skillpack/installer.ts+++ b/src/core/skillpack/installer.ts@@ -40,6 +40,7 @@ import {type BundleManifest,} from './bundle.ts';import { findResolverFile } from '../resolver-filenames.ts';+import { SKILLPACK_MANAGED_BEGIN } from '../skill-manifest.ts';// ---------------------------------------------------------------------------// Types@@ -258,7 +259,7 @@ function releaseLock(workspace: string): void {// Managed block (AGENTS.md / RESOLVER.md)// ----------------------------------------------------------------------------const MANAGED_BEGIN = '<!-- gbrain:skillpack:begin -->';+const MANAGED_BEGIN = SKILLPACK_MANAGED_BEGIN;const MANAGED_END = '<!-- gbrain:skillpack:end -->';// Receipt comment embedded inside the fence on every write. Lets thediff --git a/test/doctor-alert-cli-w4.test.ts b/test/doctor-alert-cli-w4.test.tsnew file mode 100644index 0000000000..9ede97ed4b--- /dev/null+++ b/test/doctor-alert-cli-w4.test.ts@@ -0,0 +1,148 @@+/**+ * W4 end to end through the real CLI, on a repo-less brain (gbrain init --pglite --no-embedding, no git repo) and a+ * repo brain (a git source added):+ * - the reported alert: doctor run from a directory holding an agent's own skills folder+ * (skills/<category>/<name>/SKILL.md, no RESOLVER.md, nothing gbrain installed) used to fail resolver_health and+ * warn skill_currency (score 75, unhealthy, brain category 100). Now both report "not a gbrain skills folder";+ * --skills-dir still grades it, and a gbrain-managed folder found the same way is still graded;+ * - doctor --alert: exit 0 / 17 / 18, --json alert.level, the consecutive-unknown counter and its reset, a home whose+ * state file cannot be read or written, the human output, and convergence on a larger synthetic brain.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { makeDoctorHome, runGbrain, type DoctorHome } from './helpers/doctor-json-golden.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const homes: DoctorHome[] = [];+afterAll(() => { for (const h of homes) h.cleanup(); });++async function brain(kind: 'repo-less' | 'repo'): Promise<DoctorHome> {+ const h = makeDoctorHome(`w4-${kind}`);+ homes.push(h);+ const init = await runGbrain(h, ['init', '--pglite', '--no-embedding']);+ if (init.exitCode !== 0) throw new Error(`init failed: ${init.stderr}`);+ if (kind === 'repo') {+ const repo = join(h.home, 'notes');+ mkdirSync(repo);+ writeFileSync(join(repo, 'example.md'), '---\ntitle: Example\n---\nHello world\n');+ const git = (args: string[]) => Bun.spawnSync(['git', '-c', '[email protected]', '-c', 'user.name=fixture', ...args], { cwd: repo });+ git(['init', '-q']); git(['add', '.']); git(['commit', '-qm', 'init']);+ const add = await runGbrain(h, ['sources', 'add', 'notes', '--path', repo]);+ if (add.exitCode !== 0) throw new Error(`sources add failed: ${add.stderr}`);+ }+ return h;+}++/** An agent's own skills folder in the doctor's cwd: category folders, no resolver file, nothing gbrain wrote. */+function agentSkills(h: DoctorHome): string {+ const dir = join(h.work, 'skills');+ for (const [cat, name] of [['research', 'web-digest'], ['devops', 'deploy-notes']]) {+ mkdirSync(join(dir, cat, name), { recursive: true });+ writeFileSync(join(dir, cat, name, 'SKILL.md'), `---\nname: ${name}\ndescription: An example agent skill.\n---\n# ${name}\n`);+ }+ return dir;+}++const check = (report: any, name: string) => report.checks.find((c: any) => c.name === name);++async function corruptJsonb(h: DoctorHome, fix = false): Promise<void> {+ const cfg = JSON.parse(readFileSync(join(h.home, '.gbrain', 'config.json'), 'utf-8'));+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: cfg.database_path });+ try {+ await engine.executeRaw(fix+ ? `DELETE FROM ingest_log WHERE source_ref = 'w4-alert-fixture'`+ : `INSERT INTO ingest_log (source_type, source_ref, pages_updated) VALUES ('fixture', 'w4-alert-fixture', to_jsonb('["notes/alpha-example"]'::text))`);+ } finally {+ await engine.disconnect();+ }+}++for (const kind of ['repo-less', 'repo'] as const) {+ describe(`${kind} brain`, () => {+ test('an agent skills folder found by walking up from the cwd is not graded against gbrain conventions', async () => {+ const h = await brain(kind);+ const dir = agentSkills(h);+ const run = await runGbrain(h, ['doctor', '--json']);+ const report = run.json as any;+ for (const name of ['resolver_health', 'skill_currency']) {+ expect(check(report, name)).toMatchObject({ status: 'ok', severity: 'info', message: `not a gbrain skills folder (${dir}); pass --skills-dir to grade it` });+ }+ expect(report.checks.filter((c: any) => c.category === 'skill' && c.status !== 'ok').map((c: any) => c.name)).toEqual([]);+ expect(report.category_scores.skill).toBe(100);+ expect(report.alert.level).toBe('none');++ const graded = (await runGbrain(h, ['doctor', '--json', '--skills-dir', dir])).json as any;+ expect(check(graded, 'resolver_health').status).toBe('fail');+ expect(check(graded, 'skill_currency').status).toBe('warn');+ expect(graded.health_score).toBeLessThan(report.health_score);+ expect(graded.alert.level).toBe('none');++ writeFileSync(join(dir, 'RESOLVER.md'), '# RESOLVER\n\n<!-- gbrain:skillpack:begin -->\n<!-- gbrain:skillpack:end -->\n');+ const managed = (await runGbrain(h, ['doctor', '--json'])).json as any;+ expect(check(managed, 'resolver_health').severity).toBeUndefined();+ expect(check(managed, 'resolver_health').message).not.toContain('not a gbrain skills folder');+ }, 180_000);++ test('doctor --alert: none (exit 0), act (exit 17), unknown (exit 18) with a consecutive counter that resets', async () => {+ const h = await brain(kind);+ agentSkills(h);+ const healthy = await runGbrain(h, ['doctor', '--alert', '--json']);+ expect(healthy.exitCode).toBe(0);+ expect((healthy.json as any).alert).toMatchObject({ level: 'none', items: [], unknown: [], consecutive_unknown: 0 });++ const first = await runGbrain(h, ['doctor', '--alert', '--json', '--budget-ms', '1']);+ expect(first.exitCode).toBe(18);+ expect((first.json as any).alert.level).toBe('unknown');+ expect((first.json as any).alert.consecutive_unknown).toBe(1);+ const second = await runGbrain(h, ['doctor', '--alert', '--json', '--budget-ms', '1']);+ expect(second.exitCode).toBe(18);+ const alert2 = (second.json as any).alert;+ expect(alert2.consecutive_unknown).toBe(2);+ expect(alert2.unknown[0].consecutive_unknown_runs).toBe(2);+ expect(alert2.unknown[0].message).toContain('Unknown for 2 consecutive alert run(s).');++ await corruptJsonb(h);+ const act = await runGbrain(h, ['doctor', '--alert', '--json']);+ expect(act.exitCode).toBe(17);+ const actAlert = (act.json as any).alert;+ expect(actAlert.level).toBe('act');+ expect(actAlert.consecutive_unknown).toBe(0);+ expect(actAlert.items.map((i: any) => i.check)).toEqual(['jsonb_integrity']);+ const human = await runGbrain(h, ['doctor', '--alert']);+ expect(human.exitCode).toBe(17);+ expect(human.stdout).toContain('Alert: act');+ expect(human.stdout).toContain('[ACT] jsonb_integrity');++ await corruptJsonb(h, true);+ const back = await runGbrain(h, ['doctor', '--alert', '--json']);+ expect(back.exitCode).toBe(0);+ expect((back.json as any).alert.level).toBe('none');+ }, 240_000);+ });+}++describe('doctor --alert state and scale', () => {+ test('a state file that cannot be read or written still reports and exits by level', async () => {+ const h = await brain('repo-less');+ mkdirSync(join(h.home, '.gbrain', 'doctor-alert-state.json'));+ const run = await runGbrain(h, ['doctor', '--alert', '--json', '--budget-ms', '1']);+ expect(run.exitCode).toBe(18);+ expect((run.json as any).alert.consecutive_unknown).toBeNull();+ }, 120_000);++ test('repeated alert runs on a larger synthetic repo-less brain converge to none', async () => {+ const h = await brain('repo-less');+ const dir = join(h.home, 'pages');+ mkdirSync(dir);+ for (let i = 0; i < 300; i++) writeFileSync(join(dir, `note-${i}.md`), `---\ntitle: Note ${i}\n---\nExample note ${i} about acme-example.\n`);+ const imported = await runGbrain(h, ['import', dir, '--no-embed', '--json'], {}, 300_000);+ expect(imported.exitCode).toBe(0);+ for (let i = 0; i < 2; i++) {+ const run = await runGbrain(h, ['doctor', '--alert', '--json']);+ expect((run.json as any).alert.unknown).toEqual([]);+ expect(run.exitCode).toBe(0);+ }+ }, 400_000);+});diff --git a/test/doctor-alert-w4.test.ts b/test/doctor-alert-w4.test.tsnew file mode 100644index 0000000000..3f5d1d28d1--- /dev/null+++ b/test/doctor-alert-w4.test.ts@@ -0,0 +1,229 @@+/**+ * W4: DoctorReport.alert (src/commands/doctor/alert.ts) — what an agent cron pages on.+ *+ * Synthetic check lists pin the verdict rules per page-class check (act / unknown / none, act over unknown, a+ * warnings-only report staying none, remote redaction); real in-memory PGLite pins the alert tier end to end+ * (healthy repo-less brain: none; a double-encoded JSONB row: act); the golden fixtures pin health_score,+ * brain_checks_score, category_scores and status as unchanged by the alert.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { readdirSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { computeDoctorReport, buildChecks, type Check } from '../src/commands/doctor.ts';+import { alertRanChecks, alertRunArgs, computeAlert } from '../src/commands/doctor/alert.ts';+import { budgetUnknownCheck } from '../src/commands/doctor/budget.ts';+import { PAGE_CHECK_LEVELS, PAGE_CHECK_NAMES } from '../src/core/doctor-categories.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runRemoteDoctorTier } from '../src/commands/doctor/remote-tier.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';++const ok = (name: string): Check => ({ name, status: 'ok', message: `${name} ok` });+const healthy = (): Check[] => [...PAGE_CHECK_NAMES].map(ok);+const ALL = new Set(PAGE_CHECK_NAMES);++describe('alert verdict per page-class check', () => {+ test('every page-class check ok, run fresh: none', () => {+ const alert = computeDoctorReport(healthy(), { alertRan: ALL }).alert!;+ expect(alert.level).toBe('none');+ expect(alert.items).toEqual([]);+ expect(alert.unknown).toEqual([]);+ });++ for (const [name, level] of PAGE_CHECK_LEVELS) {+ test(`${name} fail pages (act) with its own fix`, () => {+ const fix = { argv: ['gbrain', 'doctor', '--only', name, '--json'], consent: [], actor: 'agent' as const, why: 'example', requires_exclusive: false };+ const checks = healthy().map((c) => c.name === name ? { ...c, status: 'fail' as const, message: `${name} broke`, fix } : c);+ const alert = computeDoctorReport(checks, { alertRan: ALL }).alert!;+ expect(alert.level).toBe('act');+ expect(alert.items.map((i) => i.check)).toEqual([name]);+ expect(alert.items[0]!.code).toBe(name);+ expect(alert.items[0]!.message).toBe(`${name} broke`);+ expect(alert.items[0]!.fix?.argv).toEqual(fix.argv);+ expect(alert.items[0]!.fix?.next).toBe('run');+ expect(alert.items[0]!.fix?.verify?.argv ?? null).toBeNull();+ expect(alert.items[0]!.docs).toContain('doctor-alert');+ });+ test(`${name} warn ${level === 'warn' ? 'pages' : 'does not page'}`, () => {+ const checks = healthy().map((c) => c.name === name ? { ...c, status: 'warn' as const, message: 'warned' } : c);+ expect(computeDoctorReport(checks, { alertRan: ALL }).alert!.level).toBe(level === 'warn' ? 'act' : 'none');+ });+ }++ test('a stable details.code is the item code, and details.docs its docs', () => {+ const checks = healthy().map((c) => c.name === 'global_maintenance_stalled'+ ? { ...c, status: 'fail' as const, details: { code: 'global_maintenance_stalled', docs: 'docs/guides/troubleshooting.md#global-maintenance-stalled' } } : c);+ const item = computeDoctorReport(checks, { alertRan: ALL }).alert!.items[0]!;+ expect(item.code).toBe('global_maintenance_stalled');+ expect(item.docs).toBe('docs/guides/troubleshooting.md#global-maintenance-stalled');+ });++ test('warnings-only report outside the page class stays none, whatever health_score says', () => {+ const noise: Check[] = [+ { name: 'resolver_health', status: 'fail', message: '60 issue(s): 1 error(s), 59 warning(s)' },+ ...['skill_currency', 'embed_staleness', 'backup_coverage', 'orphan_ratio', 'fence_integrity', 'derived_visibility', 'embedding_provider', 'sync_freshness', 'stale_locks', 'integrity']+ .map((name): Check => ({ name, status: 'warn', message: 'advisory' })),+ ];+ const report = computeDoctorReport([...healthy(), ...noise], { alertRan: ALL });+ expect(report.health_score).toBe(30);+ expect(report.status).toBe('unhealthy');+ expect(report.alert!.level).toBe('none');+ });++ test('a timed-out page-class check makes the verdict unknown, naming its budget and the rerun', () => {+ const timedOut = budgetUnknownCheck('jsonb_integrity', 30_000, 30_000, 'overall');+ const checks = healthy().map((c) => c.name === 'jsonb_integrity' ? timedOut : c);+ const alert = computeDoctorReport(checks, { alertRan: ALL }).alert!;+ expect(alert.level).toBe('unknown');+ expect(alert.items).toEqual([]);+ expect(alert.unknown).toHaveLength(1);+ const u = alert.unknown[0]!;+ expect(u).toMatchObject({ code: 'doctor_alert_unknown', check: 'jsonb_integrity', reason: 'budget', budget_ms: 30_000 });+ expect(u.fix.argv).toEqual((timedOut.fix as { argv: string[] }).argv);+ expect(u.fix.argv?.slice(0, 5)).toEqual(['gbrain', 'doctor', '--only', 'jsonb_integrity', '--budget-ms']);+ expect(u.message).toContain('--budget-ms');+ expect(u.message).toContain('--tier standard');+ });++ test('a page-class check reported from its last known result, errored, or not run is unknown', () => {+ const checks = healthy().map((c) =>+ c.name === 'schema_version' ? { ...c, details: { last_known: { age_ms: 1000 } } }+ : c.name === 'rls' ? { ...c, status: 'warn' as const, fix_unavailable_reason: 'check_errored' as const }+ : c);+ const withoutRuntime = checks.filter((c) => c.name !== 'runtime_build_skew');+ const alert = computeDoctorReport(withoutRuntime, { alertRan: new Set([...ALL].filter((n) => n !== 'runtime_build_skew')) }).alert!;+ expect(alert.level).toBe('unknown');+ expect(Object.fromEntries(alert.unknown.map((u) => [u.check, u.reason]))).toEqual({ schema_version: 'last_known', rls: 'errored', runtime_build_skew: 'not_run' });+ });++ test('a page-class check this run executed but did not emit did not apply', () => {+ const checks = healthy().filter((c) => c.name !== 'dream_paid_loop');+ expect(computeDoctorReport(checks, { alertRan: ALL }).alert!.level).toBe('none');+ expect(computeDoctorReport(checks).alert!.unknown.map((u) => u.check)).toEqual(['dream_paid_loop']);+ });++ test('act beats unknown, and both item lists are kept', () => {+ const checks = healthy().map((c) => c.name === 'connection' ? { ...c, status: 'fail' as const, message: 'refused' }+ : c.name === 'jsonb_integrity' ? budgetUnknownCheck('jsonb_integrity', 5, 5) : c);+ const alert = computeDoctorReport(checks, { alertRan: ALL }).alert!;+ expect(alert.level).toBe('act');+ expect(alert.items.map((i) => i.check)).toEqual(['connection']);+ expect(alert.unknown.map((u) => u.check)).toEqual(['jsonb_integrity']);+ });++ test('a connection that did not open is unknown for every database check', () => {+ const conn: Check = { name: 'connection', status: 'warn', readiness_state: 'unknown', message: 'held by a live serve. The database checks did not run.' };+ const alert = computeDoctorReport([conn], { alertRan: alertRanChecks([conn], 'standard') }).alert!;+ expect(alert.level).toBe('unknown');+ expect(alert.unknown.map((u) => u.check).sort()).toEqual([...PAGE_CHECK_NAMES].sort());+ });++ test('the ops and quick tiers leave the page checks they skip unknown', () => {+ const ran = alertRanChecks([ok('connection')], 'ops');+ expect(ran.has('persistence_terminal_failures')).toBe(true);+ expect(ran.has('jsonb_integrity')).toBe(false);+ expect(alertRanChecks([ok('connection')], 'standard')).toEqual(ALL);+ });+});++describe('remote alert items', () => {+ test('omit check messages and local paths; a CLI-only fix becomes a host-admin step', () => {+ const render = { transport: 'http' as const, isCallable: () => false, preapproved: () => false };+ const checks = healthy().map((c) => c.name === 'persistence_write_stall'+ ? { ...c, status: 'warn' as const, message: 'Request r1 on source source-a, root /home/alice-example/brain/notes, is stuck',+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'source-a', '--json'], consent: [], actor: 'agent' as const, why: 'read-only', requires_exclusive: false } }+ : c.name === 'rls' ? { ...c, status: 'fail' as const, message: 'exposed at /var/lib/example/brain' } : c);+ const alert = computeDoctorReport(checks, { alertRan: ALL, render }).alert!;+ expect(alert.level).toBe('act');+ const text = JSON.stringify(alert);+ expect(text).not.toContain('/home/alice-example');+ expect(text).not.toContain('/var/lib/example');+ for (const item of alert.items) {+ expect(item.message).toBeUndefined();+ expect(item.fix?.actor).toBe('host_admin');+ expect(item.fix?.next).toBe('tell_user_to_run');+ }+ });++ test('the focused remote report (no ran set) is unknown for the page checks it never runs', () => {+ const render = { transport: 'http' as const, isCallable: () => false, preapproved: () => false };+ const alert = computeAlert([ok('connection'), ok('schema_version')], { render });+ expect(alert.level).toBe('unknown');+ expect(alert.unknown.every((u) => u.fix.actor === 'host_admin')).toBe(true);+ });+});++describe('alert run arguments', () => {+ test('--alert runs the page class alone under its budget; --tier, --only and --budget-ms win', () => {+ const args = alertRunArgs(['--alert', '--json']);+ expect(args).toContain('--scope=brain');+ expect(args[args.indexOf('--only') + 1]!.split(',').sort()).toEqual([...PAGE_CHECK_NAMES].sort());+ expect(args[args.indexOf('--budget-ms') + 1]).toBe('30000');+ expect(alertRunArgs(['--alert', '--tier', 'standard'])).not.toContain('--only');+ expect(alertRunArgs(['--alert', '--budget-ms', '0']).filter((a) => a === '--budget-ms')).toHaveLength(1);+ });+});++describe('health_score, brain_checks_score, category_scores and status are unchanged by the alert (decision 4)', () => {+ const dir = join(import.meta.dir, 'fixtures', 'goldens', 'doctor');+ for (const file of readdirSync(dir).filter((f) => f.endsWith('.json'))) {+ const golden = JSON.parse(readFileSync(join(dir, file), 'utf-8')).golden;+ const reports = [golden?.report, ...Object.values(golden ?? {}).map((v: any) => v?.report)].filter((r: any) => r && Array.isArray(r.checks) && typeof r.health_score === 'number');+ if (!reports.length) continue;+ test(file, () => {+ for (const stored of reports as any[]) {+ const again = computeDoctorReport(stored.checks.map(({ category: _c, ...c }: any) => c));+ expect({ health_score: again.health_score, brain_checks_score: again.brain_checks_score, category_scores: again.category_scores, status: again.status })+ .toEqual({ health_score: stored.health_score, brain_checks_score: stored.brain_checks_score, category_scores: stored.category_scores, status: stored.status });+ }+ });+ }+});++describe('alert tier on a real repo-less PGLite brain', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('notes/alpha-example', { title: 'Alpha Example', type: 'concept' as const, compiled_truth: 'A note.\n' });+ });+ afterAll(async () => { await engine.disconnect(); });++ const run = async () => {+ const args = alertRunArgs(['--alert', '--json']);+ const checks = await buildChecks(engine, args);+ return computeDoctorReport(checks, { alertRan: alertRanChecks(checks, 'standard') });+ };++ test('healthy brain: every page-class check runs fresh and the verdict is none, on repeated runs', async () => {+ for (let i = 0; i < 3; i++) {+ const report = await run();+ expect(report.checks.map((c) => c.name).sort()).toEqual([...PAGE_CHECK_NAMES].sort());+ expect(report.alert!.unknown).toEqual([]);+ expect(report.alert!.level).toBe('none');+ }+ }, 60_000);++ test('MCP run_doctor with only = the page class runs them on the serve: a fresh, redacted verdict (remote=true)', async () => {+ const ctx = { engine, remote: true, transport: 'http', sourceId: 'default', config: {} as never,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const report = await runRemoteDoctorTier(ctx, { only: [...PAGE_CHECK_NAMES] });+ expect(report.checks.map((c) => c.name).sort()).toEqual([...PAGE_CHECK_NAMES].sort());+ expect(report.alert!.level).toBe('none');+ const partial = await runRemoteDoctorTier(ctx, { only: ['schema_version', 'brain_score'] });+ expect(partial.alert!.level).toBe('unknown');+ expect(partial.alert!.unknown.every((u) => u.fix.actor === 'host_admin')).toBe(true);+ }, 60_000);++ test('a double-encoded JSONB row (data integrity) pages with the repair command', async () => {+ await engine.executeRaw(`UPDATE pages SET frontmatter = to_jsonb(frontmatter::text) WHERE slug = 'notes/alpha-example'`);+ try {+ const report = await run();+ expect(report.alert!.level).toBe('act');+ expect(report.alert!.items.map((i) => i.check)).toEqual(['jsonb_integrity']);+ expect(report.alert!.items[0]!.message).toContain('gbrain repair-jsonb');+ } finally {+ await engine.executeRaw(`UPDATE pages SET frontmatter = (frontmatter #>> '{}')::jsonb WHERE slug = 'notes/alpha-example'`);+ }+ }, 60_000);+});diff --git a/test/doctor-categories.test.ts b/test/doctor-categories.test.tsindex d84d7d895b..5591262565 100644--- a/test/doctor-categories.test.ts+++ b/test/doctor-categories.test.ts@@ -21,9 +21,12 @@ import {SKILL_CHECK_NAMES,OPS_CHECK_NAMES,META_CHECK_NAMES,+ PAGE_CHECK_LEVELS,+ PAGE_CHECK_NAMES,categorizeCheck,_resetUnknownCheckWarningsForTest,} from '../src/core/doctor-categories.ts';+import { doctorCheckNames } from '../src/commands/doctor/registry.ts';const ONBOARD_CHECKS_TS_PATH = join(import.meta.dir, '..', 'src', 'core', 'onboard', 'checks.ts');@@ -190,3 +193,16 @@ describe('categorizeCheck', () => {}});});++describe('W4 page class drift guard', () => {+ test('every page-class name is an emitted doctor check and a registry check name', () => {+ const discovered = enumerateCheckNames();+ const registry = doctorCheckNames();+ expect([...PAGE_CHECK_NAMES].filter((n) => !discovered.has(n) || !registry.has(n))).toEqual([]);+ expect(PAGE_CHECK_NAMES.size).toBe(PAGE_CHECK_LEVELS.size);+ });++ test('no skill-category check pages', () => {+ expect([...PAGE_CHECK_NAMES].filter((n) => SKILL_CHECK_NAMES.has(n))).toEqual([]);+ });+});diff --git a/test/exit-codes.test.ts b/test/exit-codes.test.tsindex 6f1577f4c2..466e9d68dd 100644--- a/test/exit-codes.test.ts+++ b/test/exit-codes.test.ts@@ -38,6 +38,8 @@ describe('exit code table', () => {expect(exitCodes.NO_RESULTS_EXIT_CODE).toBe(12);expect(exitCodes.HARNESS_PENDING_VERIFY_EXIT_CODE).toBe(13);expect(exitCodes.HARNESS_CLEANUP_PENDING_EXIT_CODE).toBe(14);+ expect(exitCodes.DOCTOR_ALERT_ACT_EXIT_CODE).toBe(17);+ expect(exitCodes.DOCTOR_ALERT_UNKNOWN_EXIT_CODE).toBe(18);expect(exitCodes.SERVE_UNHEALTHY_EXIT_CODE).toBe(69);expect(exitCodes.MIGRATIONS_RUNNING_EXIT_CODE).toBe(75);expect(exitCodes.TIMEOUT_EXIT_CODE).toBe(124);@@ -56,6 +58,8 @@ describe('exit code table', () => {expect(exitCodeForCode('write_pending')).toBe(10);expect(exitCodeForCode('pending_verify')).toBe(13);expect(exitCodeForCode('bootstrap_cleanup_pending')).toBe(14);+ expect(exitCodeForCode('doctor_alert_act')).toBe(17);+ expect(exitCodeForCode('doctor_alert_unknown')).toBe(18);expect(exitCodeForCode('serve_unhealthy_exit')).toBe(69);expect(exitCodeForCode('timeout')).toBe(124);expect(exitCodeForCode('interrupted')).toBe(130);diff --git a/test/fixtures/goldens/doctor/content-pglite-json.json b/test/fixtures/goldens/doctor/content-pglite-json.jsonindex a91ded81fa..215d627250 100644--- a/test/fixtures/goldens/doctor/content-pglite-json.json+++ b/test/fixtures/goldens/doctor/content-pglite-json.json@@ -8,6 +8,12 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 60,"budget_ms": "<volatile>","capped_by": [diff --git a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json b/test/fixtures/goldens/doctor/hot-checks-pglite-json.jsonindex 38296aff3e..2ec0b9a31f 100644--- a/test/fixtures/goldens/doctor/hot-checks-pglite-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-pglite-json.json@@ -9,6 +9,12 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 45,"budget_ms": "<volatile>","capped_by": [@@ -4755,6 +4761,12 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 45,"budget_ms": "<volatile>","capped_by": [diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex f0d4b32c6b..7d1218c05d 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -9,6 +9,12 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 45,"budget_ms": "<volatile>","capped_by": [@@ -4756,6 +4762,12 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 45,"budget_ms": "<volatile>","capped_by": [diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex bfd69e8f61..3301bcff6d 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -8,6 +8,12 @@],"exit_code": 0,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 90,"budget_ms": "<volatile>","category_scores": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.jsonindex 4d1ca44ac2..c6c117f681 100644--- a/test/fixtures/goldens/doctor/json-pglite-fast.json+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json@@ -9,6 +9,469 @@],"exit_code": 0,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "unknown",+ "unknown": [+ {+ "budget_ms": "<volatile>",+ "check": "connection",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "connection",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only connection --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "connection",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "connection did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only connection --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "schema_version",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_version --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_version did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_version --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "schema_missing_tables",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_missing_tables did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_terminal_failures",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_terminal_failures did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_write_stall",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_write_stall did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "runtime_build_skew",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "runtime_build_skew did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_blocked",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_blocked did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_not_moving",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_not_moving did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "global_maintenance_stalled",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "global_maintenance_stalled did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "jsonb_integrity",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "jsonb_integrity did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "rls",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only rls --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "rls did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only rls --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "dream_paid_loop",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "dream_paid_loop did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ }+ ]+ },"brain_checks_score": 100,"budget_ms": "<volatile>","category_scores": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 51067b4375..b014942d29 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -8,6 +8,12 @@],"exit_code": 0,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 100,"budget_ms": "<volatile>","capped_by": [diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex ee81dbafcf..74ed4a27ce 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -8,6 +8,12 @@],"exit_code": 0,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "none",+ "unknown": []+ },"brain_checks_score": 100,"budget_ms": "<volatile>","capped_by": [diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.jsonindex 070b59a802..4c2084575b 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json@@ -9,6 +9,507 @@],"exit_code": 0,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [],+ "level": "unknown",+ "unknown": [+ {+ "budget_ms": "<volatile>",+ "check": "connection",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "connection",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only connection --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "connection",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "connection did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only connection --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "schema_version",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_version --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_version did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_version --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "schema_missing_tables",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_missing_tables did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "minions_migration",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "minions_migration",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only minions_migration --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "minions_migration",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "minions_migration did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only minions_migration --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_terminal_failures",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_terminal_failures did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_write_stall",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_write_stall did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "runtime_build_skew",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "runtime_build_skew did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_blocked",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_blocked did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_not_moving",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_not_moving did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "global_maintenance_stalled",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "global_maintenance_stalled did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "jsonb_integrity",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "jsonb_integrity did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "rls",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only rls --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "rls did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only rls --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "dream_paid_loop",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "dream_paid_loop did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ }+ ]+ },"brain_checks_score": 100,"budget_ms": "<volatile>","category_scores": {diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.jsonindex e116f0916e..858d7dcfcc 100644--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json@@ -8,6 +8,503 @@],"exit_code": 1,"report": {+ "alert": {+ "docs": "docs/guides/troubleshooting.md#doctor-alert",+ "items": [+ {+ "check": "connection",+ "code": "connection",+ "docs": "docs/guides/troubleshooting.md#doctor-alert-act",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "db-repair",+ "--brain",+ "host"+ ],+ "command": "gbrain db-repair --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/ENGINES.md#engine-detection-and-access-repair",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "connection",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Connection refused: nothing accepted the connection at the configured host and port. Check that the database server is running and that the URL names the right host and port. `gbrain db-repair` diagnoses the database URL and access without changing anything (it prints the --yes command for a safe fix)."+ },+ "message": "Cannot connect to database: connect ECONNREFUSED <REDACTED:ipv4>:1. Fix: Check the database URL; `gbrain engine status --probe` names where it comes from (environment variable or the config file under GBRAIN_HOME) (database URL from database_url in <home>/.gbrain/config.json)",+ "status": "fail"+ }+ ],+ "level": "act",+ "unknown": [+ {+ "budget_ms": "<volatile>",+ "check": "schema_version",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_version --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_version",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_version did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_version --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "schema_missing_tables",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "schema_missing_tables",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "schema_missing_tables did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only schema_missing_tables --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "minions_migration",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "minions_migration",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only minions_migration --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "minions_migration",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "minions_migration did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only minions_migration --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_terminal_failures",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_terminal_failures",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_terminal_failures did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_terminal_failures --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "persistence_write_stall",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "persistence_write_stall",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "persistence_write_stall did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only persistence_write_stall --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "runtime_build_skew",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "runtime_build_skew",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "runtime_build_skew did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only runtime_build_skew --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_blocked",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_blocked",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_blocked did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_blocked --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "managed_sync_not_moving",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "managed_sync_not_moving",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "managed_sync_not_moving did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only managed_sync_not_moving --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "global_maintenance_stalled",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "global_maintenance_stalled",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "global_maintenance_stalled did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only global_maintenance_stalled --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "jsonb_integrity",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "jsonb_integrity",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "jsonb_integrity did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only jsonb_integrity --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "rls",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only rls --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "rls",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "rls did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only rls --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ },+ {+ "budget_ms": "<volatile>",+ "check": "dream_paid_loop",+ "code": "doctor_alert_unknown",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--budget-ms",+ "0",+ "--json",+ "--brain",+ "host"+ ],+ "command": "gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host",+ "consent": [],+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/troubleshooting.md#doctor-alert",+ "next": "run",+ "requires_exclusive": false,+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "dream_paid_loop",+ "--json",+ "--brain",+ "host"+ ]+ },+ "why": "Measures only this check now, with no overall budget; read-only."+ },+ "message": "dream_paid_loop did not run (the database checks did not run, or this tier or report skips it), so its health is unknown, not clear. Measure it with gbrain doctor --only dream_paid_loop --budget-ms 0 --json --brain host, run the full tier (gbrain doctor --alert --tier standard --json) or raise the alert budget (--budget-ms).",+ "reason": "not_run"+ }+ ]+ },"brain_checks_score": 100,"budget_ms": "<volatile>","category_scores": {diff --git a/test/skill-manifest-managed-dir.test.ts b/test/skill-manifest-managed-dir.test.tsnew file mode 100644index 0000000000..ae479cc3c0--- /dev/null+++ b/test/skill-manifest-managed-dir.test.ts@@ -0,0 +1,51 @@+/**+ * W4: isGbrainManagedSkillsDir — the marker doctor uses to grade an auto-detected skills folder (and GBRA-225's+ * skill_health check reuses). Only files gbrain writes count; a generic RESOLVER.md does not.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { isGbrainManagedSkillsDir } from '../src/core/skill-manifest.ts';++const roots: string[] = [];+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });++function workspace(): { root: string; skills: string } {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-managed-skills-'));+ roots.push(root);+ const skills = join(root, 'skills');+ mkdirSync(join(skills, 'research', 'web-digest'), { recursive: true });+ writeFileSync(join(skills, 'research', 'web-digest', 'SKILL.md'), '---\nname: web-digest\n---\n# web-digest\n');+ return { root, skills };+}++describe('isGbrainManagedSkillsDir', () => {+ test('an agent skills folder with no gbrain file is not managed, even with its own RESOLVER.md or AGENTS.md', () => {+ const { root, skills } = workspace();+ expect(isGbrainManagedSkillsDir(skills)).toBe(false);+ writeFileSync(join(skills, 'RESOLVER.md'), '# RESOLVER\n\n| Trigger | Skill |\n|---|---|\n');+ writeFileSync(join(root, 'AGENTS.md'), '# Agent\n');+ expect(isGbrainManagedSkillsDir(skills)).toBe(false);+ });++ test('a malformed manifest.json is not a marker (the loader derives one)', () => {+ const { skills } = workspace();+ writeFileSync(join(skills, 'manifest.json'), '{"skills": {"not": "an array"}}');+ expect(isGbrainManagedSkillsDir(skills)).toBe(false);+ });++ test('skills.lock.json, a valid manifest.json, or the skillpack managed block marks it managed', () => {+ const lock = workspace();+ writeFileSync(join(lock.skills, 'skills.lock.json'), '{}');+ expect(isGbrainManagedSkillsDir(lock.skills)).toBe(true);++ const manifest = workspace();+ writeFileSync(join(manifest.skills, 'manifest.json'), JSON.stringify({ skills: [{ name: 'web-digest', path: 'research/web-digest/SKILL.md' }] }));+ expect(isGbrainManagedSkillsDir(manifest.skills)).toBe(true);++ const block = workspace();+ writeFileSync(join(block.root, 'AGENTS.md'), '# Agent\n\n<!-- gbrain:skillpack:begin -->\n<!-- gbrain:skillpack:end -->\n');+ expect(isGbrainManagedSkillsDir(block.skills)).toBe(true);+ });+});