def doctor(
json: bool = typer.Option(False, "--json", help="Output results as JSON"),
clean: bool = typer.Option(
False,
"--clean",
help="Delete storage-hygiene findings (dead nested state tree, "
"stale one-off backups) after explicit confirmation (#352).",
),
live: bool = typer.Option(
False,
"--live",
help="Also run one real prompt through every ready agent instrument "
"(and one schema-mode prompt where the profile declares "
"json_schema_flag), the same check as `mzt instruments check --live`. "
"Proves each profile against its installed CLI; spends model calls.",
),
) -> None:
"""Check Marianne environment health.
Validates Python version, Marianne installation, conductor status,
available instruments, safety configuration, and storage hygiene.
Use this after installation to verify everything is set up correctly.
"""
out = default_console
# Collect all check results
checks: list[dict[str, Any]] = []
warnings: list[str] = []
errors: list[str] = []
# --- Python version ---
py_version = platform.python_version()
py_ok = sys.version_info >= (3, 11)
checks.append({
"name": "Python",
"status": "ok" if py_ok else "error",
"detail": py_version,
"hint": "Python 3.11+ required" if not py_ok else None,
})
if not py_ok:
errors.append("Python 3.11+ required")
# --- Marianne version ---
checks.append({
"name": "Marianne",
"status": "ok",
"detail": f"v{__version__}",
"hint": None,
})
# --- Conductor status ---
conductor_status, conductor_pid = _check_conductor_status()
conductor_ok = conductor_status == "running"
detail = f"running (pid {conductor_pid})" if conductor_ok else "not running"
checks.append({
"name": "Conductor",
"status": "ok" if conductor_ok else "warning",
"detail": detail,
"hint": "Start with: mzt start" if not conductor_ok else None,
})
if not conductor_ok:
warnings.append("Conductor not running")
# --- Last hot-reload (GH #450) ---
# A profile that failed to load on reload keeps its PREVIOUS entry live,
# so `doctor` reading the files on disk would call it ready while the
# conductor runs older bytes. Ask the conductor what it actually kept.
last_reload = _last_conductor_reload() if conductor_ok else None
reload_findings: list[str] = []
if last_reload:
for failed in last_reload.get("failed_profiles") or []:
retained = failed.get("retained") or ""
keep = f" (previous entry '{retained}' retained)" if retained else ""
reload_findings.append(
f"Reload declined {failed.get('path')}: {failed.get('reason_code')}{keep}"
)
if last_reload.get("schema_stale"):
reload_findings.append(
"Conductor predates a profile's schema: restart at a job-free "
"boundary to load the file as written"
)
checks.append({
"name": "Conductor schema",
"status": "warning",
"detail": "older than a profile on disk",
"hint": "Restart when no jobs run: mzt stop && mzt start",
})
warnings.extend(reload_findings)
# --- Instruments ---
all_profiles = _get_all_profiles()
active_rate_limits = (
_active_rate_limited_instruments() if conductor_ok else {}
)
instrument_results: list[dict[str, Any]] = []
ready_count = 0
for profile in all_profiles.values():
# One probe for every command that answers "can this run here"
# (GH #447). Its four states have one definition in availability.py.
probe = probe_profile(profile)
is_rate_limited = profile.name in active_rate_limits
limit_seconds = active_rate_limits.get(profile.name)
execution_status, execution_note = _profile_execution_state(profile)
execution_ready = execution_status != "unsupported"
if probe.state == "ready":
status = "warning" if is_rate_limited or not execution_ready else "ok"
detail_str = probe.binary_path or profile.display_name
if profile.kind == "http" and profile.http and profile.http.base_url:
detail_str += f" ({profile.http.base_url})"
if not execution_ready:
detail_str += (
f" — {execution_status}"
f"{(': ' + execution_note) if execution_note else ''}"
)
warnings.append(f"Instrument {profile.name} is {execution_status}")
if is_rate_limited:
detail_str += f" — rate-limited {_format_seconds(limit_seconds)}"
warnings.append(f"Instrument {profile.name} is rate-limited")
if not is_rate_limited and execution_ready and not profile.raw_prompt:
# A raw shell profile (`cli`) always "runs"; it is not an agent
# and must not make a fresh install read as ready.
ready_count += 1
elif probe.state == "unchecked":
# A remote endpoint is never probed; say so instead of "ok".
status = "unchecked"
detail_str = f"{profile.display_name} — {probe.reason}"
elif probe.state == "unreachable":
status = "optional"
detail_str = f"not answering ({probe.reason})"
else:
status = "optional"
detail_str = f"not found ({probe.reason})"
instrument_results.append({
"name": profile.name,
"display_name": profile.display_name,
"kind": profile.kind,
"status": status,
"probe": probe.state,
"detail": detail_str,
"execution_status": execution_status,
"execution_status_detail": execution_note,
"execution_ready": execution_ready,
"rate_limited": is_rate_limited,
"rate_limit_seconds_remaining": limit_seconds,
})
if live:
from marianne.cli.commands.instruments import live_failure, live_probe
live_ready = 0
for row in instrument_results:
if row["probe"] != "ready" or not row["execution_ready"]:
continue
profile = all_profiles[row["name"]]
if profile.raw_prompt:
continue
report = live_probe(profile, timeout=150.0)
row["live"] = report
if report["ok"]:
live_ready += 1
continue
row["status"] = "warning"
mode, reason = live_failure(report) or ("plain", "unknown")
row["detail"] = f"{row['detail']} — live {mode} probe failed: {reason}"
warnings.append(f"Instrument {profile.name} failed its live {mode} probe ({reason})")
if ready_count and live_ready == 0:
errors.append(
"No instrument passed its live probe: every ready instrument failed "
"a real prompt. Run `mzt instruments check <name> --live` for detail."
)
# "Marianne is ready" means a score can run: at least one agent instrument
# is runnable now. Zero runnable instruments is an error, not a warning —
# `doctor` used to say "ready" on a fresh install with none (GH #447).
if ready_count == 0:
errors.append(
"No runnable instrument: nothing on PATH and no local server serving "
"its model. Install one agent CLI (e.g. claude-code, codex-cli, "
"opencode) or pull the local model `mzt instruments check ollama` names."
)
# --- Safety checks ---
safety_warnings: list[str] = []
# Check for cost limits configuration
# The default CostLimitConfig has enabled=False
safety_warnings.append("No cost limits configured. Recommend: cost_limits.max_cost_per_job")
# GH #335: an explicit `inherit_env` opt-out without an allowlist hands the
# instrument the conductor's whole environment, every credential included.
# Name each ready one together with how many credential-shaped variables
# are set right now, so the exposure is visible where the operator looks.
exposed = _credential_exposure(all_profiles, instrument_results)
if exposed:
names = ", ".join(sorted(exposed))
count = len(_credential_env_names())
safety_warnings.append(
f"{len(exposed)} ready CLI instrument(s) inherit the full environment "
f"({count} credential-shaped variable(s) set): {names}. Declare "
"cli.command.required_env or remove inherit_env to pass only what it needs (GH #335)."
)
# GH #335 migration: a user profile that never declared an env policy
# used to inherit the shell's credentials and now gets none. Name it
# before a sheet fails on authentication.
for name, executable, present in _silently_filtered(all_profiles, instrument_results):
safety_warnings.append(
f"{name} runs `{executable}` with no cli.command.required_env, so the "
f"{', '.join(present)} set in this environment no longer reach it "
"(filtered by default since GH #335). Declare required_env with the "
"variables it authenticates by, or required_env: [] if it reads its own store."
)
# --- Storage hygiene (#352) ---
storage_findings = _scan_storage_findings()
cleaned_paths: list[str] = []
if clean and storage_findings:
total = sum(f["size_bytes"] for f in storage_findings)
out.print()
out.print("[bold]Storage cleanup candidates:[/bold]")
for f in storage_findings:
out.print(
f" - {f['path']} ({_human_size(f['size_bytes'])}) — {f['detail']}"
)
if typer.confirm(
f"Delete the above ({_human_size(total)} total)?", default=False
):
cleaned_paths = _clean_storage_findings(storage_findings)
out.print(f"[green]Removed {len(cleaned_paths)} item(s).[/green]")
storage_findings = _scan_storage_findings()
else:
out.print("Aborted — nothing deleted.")
# --- Instrument hygiene (GH #443) ---
unreferenced_profiles = _scan_unreferenced_user_profiles()
shadowing_copies = _scan_shadowing_copies()
# --- Provider checks (GH #499): REA's own doctor for each REA pool entry ---
provider_checks = _rea_provider_checks(_rea_pool_entries())
# --- Musician hooks (GH #536) ---
musician_hooks = _musician_hook_report(
_claude_user_settings_path(), disabled=_claude_code_hooks_disabled(),
)
# --- JSON output ---
if json:
result: dict[str, Any] = {
"python_version": py_version,
"marianne_version": __version__,
"conductor": {
"status": conductor_status,
"pid": conductor_pid,
"last_reload": last_reload,
},
"instruments": instrument_results,
"safety_warnings": safety_warnings,
"storage_findings": storage_findings,
"unreferenced_profiles": unreferenced_profiles,
"shadowing_copies": shadowing_copies,
"provider_checks": provider_checks,
"musician_hooks": musician_hooks,
"cleaned_paths": cleaned_paths,
"warnings_count": len(warnings) + len(safety_warnings)
+ len(storage_findings) + len(unreferenced_profiles) + len(shadowing_copies)
+ sum(1 for row in provider_checks if row["status"] != "ok")
+ (1 if musician_hooks["status"] != "ok" else 0),
"errors_count": len(errors),
}
out.print_json(json_mod.dumps(result))
return
# --- Rich output ---
out.print()
out.print("[bold]Marianne Doctor[/bold]")
out.print()
# Core checks
for check in checks:
icon = _status_icon(check["status"])
line = f" {icon} {check['name']:<24} {check['detail']}"
out.print(line)
if check.get("hint"):
out.print(f" [dim]{check['hint']}[/dim]")
# Instruments section
out.print()
out.print(" [bold]Instruments:[/bold]")
for inst in instrument_results:
icon = _status_icon(inst["status"])
out.print(f" {icon} {inst['name']:<24} {inst['detail']}")
# Safety section
if safety_warnings:
out.print()
out.print(" [bold]Safety:[/bold]")
for warn in safety_warnings:
out.print(f" [yellow]![/yellow] {warn}")
warnings.append(warn)
# Last hot-reload section (GH #450)
if reload_findings:
out.print()
out.print(" [bold]Config reload:[/bold]")
for finding in reload_findings:
out.print(f" [yellow]![/yellow] {finding}")
# Storage hygiene section (#352)
if storage_findings:
out.print()
out.print(" [bold]Storage:[/bold]")
for f in storage_findings:
out.print(
f" [yellow]![/yellow] {f['path']} "
f"({_human_size(f['size_bytes'])}) — {f['detail']}"
)
warnings.append(f"storage: {f['path']}")
out.print(" [dim]Reclaim with: mzt doctor --clean[/dim]")
# Instrument hygiene section (GH #443): reported, never auto-deleted.
if unreferenced_profiles:
out.print()
out.print(
f" [bold]Instrument hygiene:[/bold] {len(unreferenced_profiles)} "
f"profile(s) no submitted score names"
)
for f in unreferenced_profiles:
out.print(f" [yellow]![/yellow] {f['name']:<24} {f['path']}")
warnings.append(f"unreferenced profile: {f['name']}")
out.print(
" [dim]A seat is an alias over an existing profile (GH #443). "
"Archive these files, or submit the score that needs them.[/dim]"
)
# Whole copies of a builtin (GH #543): key names only, never values.
if shadowing_copies:
out.print()
# One heading for the section: the unreferenced list above may have
# printed it already.
heading = " " if unreferenced_profiles else " [bold]Instrument hygiene:[/bold] "
out.print(
f"{heading}{len(shadowing_copies)} profile(s) replace a builtin whole"
)
for f in shadowing_copies:
out.print(f" [yellow]![/yellow] {f['name']:<24} {f['path']}")
for label, keys in (
("top-level", f["missing_top_level"]),
("cli", f["missing_cli"]),
("cli.interactive", f["missing_cli_interactive"]),
):
if keys:
out.print(f" lacks {label}: {', '.join(keys)}")
warnings.append(f"profile replaces builtin: {f['name']}")
out.print(
" [dim]Fix: put `extends: <name>` in the file and keep only the "
"keys that differ from the builtin.[/dim]"
)
# Provider checks (GH #499): REA speaks for its own toolchain.
if provider_checks:
out.print()
out.print(" [bold]Providers:[/bold]")
for row in provider_checks:
icon = _status_icon("ok" if row["status"] == "ok" else "warning")
out.print(f" {icon} rea ({row['entry']}){'':<10} {row['detail']}")
for c in row.get("checks", []):
if c.get("ok") is False:
out.print(f" [dim]{c.get('name')}: {c.get('detail')}[/dim]")
if row["status"] != "ok":
warnings.append(f"provider rea ({row['entry']}): {row['detail']}")
out.print(
" [dim]REA's doctor is read-only; it never installs. Fix a provider gap "
"with REA's own setup (`npx rea-agents setup`), then rerun.[/dim]"
)
# Musician hooks (GH #536)
if musician_hooks["hooks"]:
out.print()
out.print(" [bold]Musician hooks:[/bold]")
icon = _status_icon(musician_hooks["status"])
out.print(f" {icon} {musician_hooks['detail']}")
for hook in musician_hooks["hooks"]:
out.print(
f" [dim]{hook['event']}: {hook['command']} ({hook['effect']})[/dim]"
)
if musician_hooks["status"] != "ok":
warnings.append(f"musician hooks: {musician_hooks['detail']}")
out.print(
" [dim]A hook detects a musician with MARIANNE_SHEET "
"(see docs/instrument-guide.md).[/dim]"
)
# Summary
out.print()
total_warnings = len(warnings)
total_errors = len(errors)
if total_errors > 0:
out.print(
f"[red]{total_errors} error(s), {total_warnings} warning(s). "
f"Marianne is not ready.[/red]"
)
elif total_warnings > 0:
out.print(
f"[yellow]{total_warnings} warning(s).[/yellow] Marianne is ready "
f"({ready_count} runnable instrument(s))."
)
else:
out.print(
f"[green]No issues found. Marianne is ready "
f"({ready_count} runnable instrument(s)).[/green]"
)
out.print()