Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): checks carry fix (Action) or fix_unavailable_reason; gbrain doctor --only (E1)
garrytanf5d6fb8c133c
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bcb69c4cd9..0c2c75266d 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,7 +5,7 @@# Columns: path max_lines policy notesrc/cli.ts 3211 ratchet +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 formatResultsrc/commands/autopilot.ts 1639 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)-src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts+src/commands/doctor.ts 662 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2217 ratchet 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)src/commands/extract-conversation-facts.ts 2182 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)src/commands/extract.ts 2528 ratchet 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)diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.tsindex a10542383d..60b636df7d 100644--- a/src/cli/commands/doctor.ts+++ b/src/cli/commands/doctor.ts@@ -3,7 +3,7 @@* handleCliOnly before the connectEngine() terminator. Moved verbatim from* src/cli.ts (refactor wave 1, W4 cli); the record lives in src/cli/command-table.ts.*/-import { finishCliTeardown } from '../../core/cli-force-exit.ts';+import { finishCliTeardown, setCliExitVerdict } from '../../core/cli-force-exit.ts';import { getDbUrlSource, isThinClient, loadConfig } from '../../core/config.ts';import {classifyPgAccessError as classifyDbAccessError,@@ -45,6 +45,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void// Doctor runs filesystem checks first (no DB needed), then DB checks.// --fast skips DB checks entirely.const { runDoctor } = await import('../../commands/doctor.ts');+ if (await runDoctorOnly(args, connectEngine, runDoctor)) return;if (args.includes('--fast')) {// Pass the DB URL source so doctor can tell "no config at all" from// "user chose --fast while config is present".@@ -89,3 +90,49 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void}}}++/**+ * `gbrain doctor --only <check>[,…] [--json]` — the default `fix.verify`:+ * read-only, observational startup (probeOnly: no migrations or maintenance),+ * engine-free when every requested check is a filesystem check. Unknown names+ * exit 2 with the valid list. Returns false when `--only` is absent.+ */+async function runDoctorOnly(+ args: string[],+ connectEngine: CliDispatchContext['connectEngine'],+ runDoctor: typeof import('../../commands/doctor.ts').runDoctor,+): Promise<boolean> {+ const { parseOnlyChecks, doctorCheckNames, onlyNeedsEngine } = await import('../../commands/doctor/registry.ts');+ const only = parseOnlyChecks(args);+ if (!only) return false;+ const known = doctorCheckNames();+ const unknown = [...only].filter((n) => !known.has(n));+ if (only.size === 0 || unknown.length > 0) {+ const { opError } = await import('../../core/ops/contract.ts');+ const { renderCliError } = await import('../../core/agent-output.ts');+ const { suggestNearest } = await import('../../core/levenshtein.ts');+ const nearest = unknown[0] ? suggestNearest(unknown[0], [...known]) : null;+ const err = opError('invalid_params', `Unknown doctor check: ${unknown.join(', ') || '(none given)'}`,+ `${nearest ? `Did you mean "${nearest}"? ` : ''}Valid names: ${[...known].sort().join(', ')}.`,+ { fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'The full report lists every check name this brain emits.' } });+ const out = renderCliError(err, { json: args.includes('--json'), command: 'doctor', tty: !!process.stderr.isTTY });+ if (out.stdout) process.stdout.write(out.stdout);+ if (out.stderr) process.stderr.write(out.stderr);+ setCliExitVerdict(out.exitCode);+ return true;+ }+ if (!onlyNeedsEngine(only)) {+ await runDoctor(null, args, getDbUrlSource());+ return true;+ }+ let eng: BrainEngine | null = null;+ try {+ eng = await connectEngine({ probeOnly: true });+ await runDoctor(eng, args);+ } catch (e) {+ await runDoctor(null, args, getDbUrlSource(), e);+ } finally {+ if (eng) await finishCliTeardown({ engine: eng });+ }+ return true;+}diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 7072343caa..ebfa4b034c 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -137,8 +137,10 @@ export {buildRetrievalReflexCheck,} from './doctor/checks/verbs-reflex.ts';import type { DoctorContext } from './doctor/context.ts';-import { runDoctorRegistry } from './doctor/registry.ts';-export interface Check {+import { runDoctorRegistry, parseOnlyChecks } from './doctor/registry.ts';+import { finalizeCheckFixes, fixLine, type CheckAgentFields } from './doctor/check-fix.ts';+import type { RenderContext } from '../core/agent-output.ts';+export interface Check extends CheckAgentFields {name: string;status: 'ok' | 'warn' | 'fail';message: string;@@ -231,6 +233,8 @@ export interface DoctorReport {*/engine?: 'postgres' | 'pglite';db_url_source?: DbUrlSource | null;+ /** E2: capabilities off by choice that bound what this brain can do (e.g. `embeddings_disabled`). Additive. */+ capped_by?: string[];}function _penaltyScore(checks: Check[]): number {@@ -258,11 +262,12 @@ function _penaltyScore(checks: Check[]): number {*/export function computeDoctorReport(checks: Check[],- extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null },+ extras?: { engine?: 'postgres' | 'pglite'; db_url_source?: DbUrlSource | null; render?: RenderContext },): DoctorReport {- const tagged = checks.map((c) =>+ const tagged = finalizeCheckFixes(checks, extras?.render).map((c) =>c.category ? c : { ...c, category: categorizeCheck(c.name) },);+ const capped_by = tagged.some((c) => c.name === 'embeddings' && c.readiness_state === 'disabled_by_choice') ? ['embeddings_disabled'] : [];const hasFail = tagged.some((c) => c.status === 'fail');const hasWarn = tagged.some((c) => c.status === 'warn');@@ -289,6 +294,7 @@ export function computeDoctorReport(top_issues: rankIssues(tagged),...(extras?.engine ? { engine: extras.engine } : {}),...(extras?.db_url_source !== undefined ? { db_url_source: extras.db_url_source } : {}),+ ...(capped_by.length ? { capped_by } : {}),};}@@ -445,6 +451,7 @@ export async function buildChecks(autoFixReport: null,schemaVersion: 0,connectionFailed: false,+ only: parseOnlyChecks(args),};return runDoctorRegistry(ctx);@@ -546,7 +553,7 @@ function outputResults(for (const issue of shown) {const icon = issue.status === 'fail' ? 'FAIL' : 'WARN';const dn = issue.downstream_of ? ` (likely downstream of ${issue.downstream_of})` : '';- console.log(` [${icon}] ${issue.name}${dn} → ${issue.fix}`);+ console.log(` [${icon}] ${issue.name}${dn} → ${fixLine(issue.action) ?? issue.fix}`);}if (topIssues.length > shown.length) {console.log(` +${topIssues.length - shown.length} more — see full list below`);@@ -555,8 +562,10 @@ function outputResults(}for (const c of report.checks) {- const icon = c.status === 'ok' ? 'OK' : c.status === 'warn' ? 'WARN' : 'FAIL';+ const icon = c.status === 'ok' ? (c.severity === 'info' ? 'INFO' : 'OK') : c.status === 'warn' ? 'WARN' : 'FAIL';console.log(` [${icon}] ${c.name}: ${c.message}`);+ const fix = c.status === 'ok' ? null : fixLine(c.fix);+ if (fix) console.log(` Fix: ${fix}`);if (c.issues) {for (const issue of c.issues) {console.log(` → ${issue.type.toUpperCase()}: ${issue.skill}`);diff --git a/src/commands/doctor/check-fix.ts b/src/commands/doctor/check-fix.tsnew file mode 100644index 0000000000..9bc3d0eaed--- /dev/null+++ b/src/commands/doctor/check-fix.ts@@ -0,0 +1,120 @@+/**+ * Doctor checks speak the agent operator contract (agent-first operator wave,+ * Lane E1/E2): every non-ok check carries a `fix` (Action) or a+ * `fix_unavailable_reason`, the generic "Could not check X" sites go through+ * `checkError()`, and a capability that is off by choice or not applicable is+ * reported `ok` + `severity: 'info'` + `readiness_state` with the enable+ * command as `fix` (information, never coaching).+ *+ * Stored checks carry `Action`; `finalizeCheckFixes` renders them for the+ * report's transport (CLI `gbrain doctor --json`, MCP `run_doctor`).+ */+import { cliRenderContext, renderAction, type Action, type RenderContext, type RenderedAction } from '../../core/agent-output.ts';+import type { ReadinessEntry, ReadinessState } from '../../core/readiness.ts';+import { classifyPgAccessError } from '../../core/pg-access-classify.ts';+import type { Check } from '../doctor.ts';++/**+ * Why a non-ok check has no runnable `fix`:+ * - `check_errored`: the probe itself failed, so there is nothing to repair yet (message carries the error).+ * - `operator_judgement`: the finding needs a human decision about the data; the message explains it.+ * - `no_safe_automatic_fix`: a fix exists only as a manual, case-by-case repair.+ * - `unstructured`: legacy check whose guidance is still prose in `message` (shrinking; see check-fix tests).+ */+export type FixUnavailableReason = 'check_errored' | 'operator_judgement' | 'no_safe_automatic_fix' | 'unstructured';++/** Agent-contract fields every doctor Check may carry (additive; schema_version stays 2). */+export interface CheckAgentFields {+ /** Stored as an Action; rendered (RenderedAction: `next`, `command`, absolute `docs`) in reports. */+ fix?: Action | RenderedAction;+ fix_unavailable_reason?: FixUnavailableReason;+ /** `info`: status stays `ok`; the capability is off by choice or not applicable (readiness_state says which). */+ severity?: 'info';+ readiness_state?: ReadinessState;+}++interface CheckLike extends CheckAgentFields {+ name: string;+ status: 'ok' | 'warn' | 'fail';+ message: string;+ details?: Record<string, unknown>;+}++/** The read-only verification every doctor fix points at. */+export function doctorVerify(check: string): { argv: string[] } {+ return { argv: ['gbrain', 'doctor', '--only', check, '--json'] };+}++/** A gbrain command the agent may run with no consent (read-only or a reversible local repair). */+export function agentFix(argv: string[], why: string, verifyCheck: string, extra: Partial<Action> = {}): Action {+ return { argv, consent: [], actor: 'agent', why, verify: doctorVerify(verifyCheck), requires_exclusive: false, ...extra };+}++/**+ * Information, not a problem: status `ok`, `severity: 'info'`. Use for a+ * capability that is `disabled_by_choice` or `not_applicable` (keyless brain,+ * empty brain, no serve running). `fix` is the enable command, if any.+ */+export function infoCheck(name: string, message: string, state: ReadinessState, fix?: Action, details?: Record<string, unknown>): Check {+ return {+ name, status: 'ok' as const, message, severity: 'info' as const, readiness_state: state,+ ...(fix ? { fix } : {}), ...(details ? { details } : {}),+ };+}++/** A readiness entry rendered as a doctor info check (keeps its why and enable fix). */+export function readinessInfoCheck(name: string, entry: ReadinessEntry, message?: string): Check {+ return infoCheck(name, message ?? entry.why, entry.state, entry.fix);+}++/**+ * The one shape for "this check could not run": `warn`, the original+ * `Could not <what>: <error>` message, and either a DB-access fix (when the+ * error classifies as a database access problem) or+ * `fix_unavailable_reason: 'check_errored'`.+ */+export function checkError(name: string, what: string, err?: unknown, opts: { status?: 'warn' | 'fail'; details?: Record<string, unknown> } = {}): Check {+ const msg = err === undefined ? '' : err instanceof Error ? err.message : String(err);+ const message = msg ? `Could not ${what}: ${msg}` : `Could not ${what}`;+ let fix: Action | undefined;+ if (err !== undefined) {+ try {+ const d = classifyPgAccessError(err);+ if (d.reason !== 'unknown') {+ fix = agentFix(['gbrain', 'db-repair'], `The database refused the check (${d.reason}). \`gbrain db-repair\` diagnoses it without changing anything.`, name,+ { docs: 'docs/ENGINES.md#engine-detection-and-access-repair' });+ }+ } catch { /* classification is best-effort */ }+ }+ return {+ name, status: opts.status ?? 'warn', message,+ ...(fix ? { fix } : { fix_unavailable_reason: 'check_errored' as const }),+ ...(opts.details ? { details: opts.details } : {}),+ };+}++function isRendered(fix: Action | RenderedAction): fix is RenderedAction {+ return typeof (fix as RenderedAction).next === 'string';+}++/**+ * Report-time pass: render every stored `fix` for the caller's transport and+ * mark any non-ok check that still has neither a fix nor a reason as+ * `unstructured` (its message is the guidance).+ */+export function finalizeCheckFixes<T extends CheckLike>(checks: readonly T[], render: RenderContext = cliRenderContext()): T[] {+ return checks.map((c) => {+ if (c.fix) return isRendered(c.fix) ? c : { ...c, fix: renderAction(c.fix, render) };+ if (c.status === 'ok' || c.fix_unavailable_reason) return c;+ return { ...c, fix_unavailable_reason: 'unstructured' as const };+ });+}++/** One-line human rendering of a check's fix (`Fix: <command>` / tool call), or null. */+export function fixLine(fix: CheckAgentFields['fix']): string | null {+ if (!fix) return null;+ const r = isRendered(fix) ? fix : renderAction(fix, cliRenderContext());+ const step = r.command ?? (r.mcp ? `${r.mcp.tool} ${JSON.stringify(r.mcp.arguments)}` : null);+ if (!step) return r.user_message ? `Ask the user: ${r.user_message}` : null;+ return r.next === 'run' ? step : `${step} (${r.next.replace(/_/g, ' ')})`;+}diff --git a/src/commands/doctor/context.ts b/src/commands/doctor/context.tsindex 1aa4b1ece3..9786fa83fc 100644--- a/src/commands/doctor/context.ts+++ b/src/commands/doctor/context.ts@@ -47,6 +47,8 @@ export interface DoctorContext {schemaVersion: number;/** Written by the connection entry when `getStats` fails; the next entry stops the run. */connectionFailed: boolean;+ /** `--only <check>[,…]`: run only the entries that emit these checks (plus the connection lane). */+ only?: ReadonlySet<string> | null;}/**diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex a09e7f6a8d..c0e85db21b 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -89,6 +89,7 @@ import { unlinkedFactsEntry } from './checks/unlinked-facts.ts';import { plannerStatsEntry } from './checks/planner-stats.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';import type { Check } from '../doctor.ts';+import { infoCheck } from './check-fix.ts';export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [resolverHealthEntry,@@ -152,17 +153,60 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [searchModeEntry,];+const CONNECTION_LANE: ReadonlySet<DoctorEntry> = new Set([offlineConnectionEntry, dbChecksGateEntry, connectionEntry, connectionGateEntry]);++/** Every check name the registry can emit (the `--only` vocabulary). */+export function doctorCheckNames(): Set<string> {+ return new Set(DOCTOR_CHECK_REGISTRY.flatMap((e) => e.emits));+}++/** `--only a,b` / `--only=a,b` (repeatable) → the requested check names, or null when absent. */+export function parseOnlyChecks(args: readonly string[]): Set<string> | null {+ const raw: string[] = [];+ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--only' && i + 1 < args.length) raw.push(args[++i]);+ else if (args[i].startsWith('--only=')) raw.push(args[i].slice('--only='.length));+ }+ if (raw.length === 0) return null;+ return new Set(raw.flatMap((r) => r.split(',')).map((n) => n.trim()).filter(Boolean));+}++/** True when any requested check is a DB check (ordered after the DB-checks early stop). */+export function onlyNeedsEngine(only: ReadonlySet<string>): boolean {+ const gate = DOCTOR_CHECK_REGISTRY.indexOf(dbChecksGateEntry);+ return DOCTOR_CHECK_REGISTRY.some((e, i) => i > gate && e.emits.some((n) => only.has(n)));+}++function selected(entry: DoctorEntry, only: ReadonlySet<string> | null | undefined): boolean {+ return !only || CONNECTION_LANE.has(entry) || entry.emits.some((n) => only.has(n));+}++/** `--only`: keep the requested checks; a requested check that produced nothing says why. */+function onlyResult(checks: Check[], only: ReadonlySet<string>, stopped: boolean): Check[] {+ const missing = [...only].filter((n) => !checks.some((c) => c.name === n));+ const kept = checks.filter((c) => only.has(c.name) || (stopped && missing.length > 0 && c.name === 'connection'));+ for (const name of missing) {+ kept.push(stopped+ ? { name, status: 'warn', message: 'Not run: the database checks stopped early (see the connection check).', fix_unavailable_reason: 'check_errored' }+ : infoCheck(name, 'No finding: this check does not apply to this brain right now.', 'not_applicable'));+ }+ return kept;+}+/*** Run the registry in order. A STOP_DOCTOR result ends the run with the checks* gathered so far; a completed run finishes the DB-checks progress phase.+ * Under `--only`, entries that emit none of the requested checks are skipped+ * (the connection lane always runs so its early stops still hold).*/export async function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];for (const entry of DOCTOR_CHECK_REGISTRY) {+ if (!selected(entry, ctx.only)) continue;const result = await entry.run(ctx);- if (result === STOP_DOCTOR) return checks;+ if (result === STOP_DOCTOR) return ctx.only ? onlyResult(checks, ctx.only, true) : checks;checks.push(...result);}ctx.progress.finish();- return checks;+ return ctx.only ? onlyResult(checks, ctx.only, false) : checks;}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex d39b92219b..e7ed749792 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],'loops': ['--all', '--as-of', '--brain', '--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', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--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', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],@@ -122,7 +122,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],diff --git a/src/core/doctor-cause-rank.ts b/src/core/doctor-cause-rank.tsindex 647c6ba8b9..9f7918d50e 100644--- a/src/core/doctor-cause-rank.ts+++ b/src/core/doctor-cause-rank.ts@@ -28,6 +28,7 @@ import {OPS_CHECK_NAMES,META_CHECK_NAMES,} from './doctor-categories.ts';+import type { RenderedAction } from './agent-output.ts';/** Minimal structural shape of a doctor Check that ranking needs. */export interface RankableCheck {@@ -35,6 +36,8 @@ export interface RankableCheck {status: 'ok' | 'warn' | 'fail';message: string;details?: Record<string, unknown>;+ /** Agent contract v1: the check's rendered fix, when it has one. */+ fix?: unknown;}export interface RankedIssue {@@ -53,6 +56,12 @@ export interface RankedIssue {downstream_of?: string;/** One-line fix. Prefers `details.fix_hint`; falls back to the check message. */fix: string;+ /**+ * Agent contract v1: the check's structured fix (RenderedAction: `next`,+ * `command`/`argv`, `consent`, `verify`). Additive sibling of the legacy+ * `fix` string, which keeps its type.+ */+ action?: RenderedAction;}/**@@ -94,6 +103,10 @@ const DOWNSTREAM_EDGES: Readonly<Record<string, string>> = {supervisor: 'worker_oom_loop',};+function isRenderedAction(v: unknown): v is RenderedAction {+ return !!v && typeof v === 'object' && typeof (v as RenderedAction).next === 'string';+}+function tierOf(name: string): 'root' | 'symptom' {return ROOT_CAUSE_CHECKS.has(name) ? 'root' : 'symptom';}@@ -118,6 +131,7 @@ export function rankIssues(checks: RankableCheck[]): RankedIssue[] {tier: tierOf(c.name),...(downstream_of ? { downstream_of } : {}),fix,+ ...(isRenderedAction(c.fix) ? { action: c.fix } : {}),};});diff --git a/test/helpers/doctor-registry-ast.ts b/test/helpers/doctor-registry-ast.tsindex f59ac858a9..16d99032f9 100644--- a/test/helpers/doctor-registry-ast.ts+++ b/test/helpers/doctor-registry-ast.ts@@ -207,6 +207,8 @@ class Extractor {lastAdded: string | null = null;private seenNames = new Set<string>();private active = new Set<string>();+ /** Call-site string arguments bound to the walked function's parameters (name-forwarding helpers such as `checkError(name, …)`). */+ private paramBindings = new Map<string, string>();add(name: string) {this.lastAdded = name;@@ -222,6 +224,8 @@ class Extractor {if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) return e.text;if (ts.isTemplateExpression(e)) return templateText(e);if (ts.isIdentifier(e)) {+ const bound = this.paramBindings.get(e.text);+ if (bound !== undefined && isParameterOfEnclosingFunction(e)) return bound;const decl = findDeclaration(e);if (decl?.initializer) return this.nameValue(decl.initializer, file);}@@ -276,7 +280,7 @@ class Extractor {return;}const fn = resolveCallee(file, e.expression);- if (fn) this.fromFunction(fn);+ if (fn) this.fromFunction(fn, e.arguments, file);else this.unresolved.push(`${relative(REPO_ROOT, file)}: unresolved call ${e.expression.getText()}`);return;}@@ -303,10 +307,18 @@ class Extractor {}/** Every check a function can emit: Check-shaped literals + Check-returning callees, in source order. */- fromFunction(fn: FnRef) {+ fromFunction(fn: FnRef, args: readonly ts.Expression[] = [], argFile = fn.file) {const key = `${fn.file}#${fn.name}`;if (this.active.has(key)) return;this.active.add(key);+ const saved = this.paramBindings;+ const bindings = new Map<string, string>();+ fn.node.parameters.forEach((p, i) => {+ if (!ts.isIdentifier(p.name) || !args[i]) return;+ const v = this.nameValue(args[i], argFile);+ if (v !== null && !v.startsWith('${')) bindings.set(p.name.text, v);+ });+ this.paramBindings = bindings;const visit = (node: ts.Node) => {if (ts.isObjectLiteralExpression(node)) {const n = this.checkObjectName(node, fn.file);@@ -316,16 +328,25 @@ class Extractor {for (const id of waveCheckIds(node, fn.file)) this.add(id);} else {const callee = resolveCallee(fn.file, node.expression);- if (callee && returnsCheck(callee.node)) this.fromFunction(callee);+ if (callee && returnsCheck(callee.node)) this.fromFunction(callee, node.arguments, fn.file);}}ts.forEachChild(node, visit);};if (fn.node.body) visit(fn.node.body);+ this.paramBindings = saved;this.active.delete(key);}}+/** True when `id` names a parameter of the function it appears in (and no closer local shadows it). */+function isParameterOfEnclosingFunction(id: ts.Identifier): boolean {+ if (findDeclaration(id)) return false;+ let n: ts.Node | undefined = id.parent;+ while (n && !ts.isFunctionLike(n)) n = n.parent;+ return !!n && (n as ts.SignatureDeclaration).parameters.some((p) => ts.isIdentifier(p.name) && p.name.text === id.text);+}+function returnsCheck(fn: FnNode): boolean {return !!fn.type && /\bCheck\b|CheckResult\b/.test(fn.type.getText());}