Skip to content

doctor

doctor

mzt doctor — environment health check.

Inspired by flutter doctor. Checks Python version, Marianne version, conductor status, instrument availability, and safety configuration. Reports issues with clear status indicators and actionable suggestions.

This command is designed to work WITHOUT a running conductor — it's the first thing a new user runs after installation.

Classes

Functions:

doctor

doctor(json=Option(False, '--json', help='Output results as JSON'), clean=Option(False, '--clean', help='Delete storage-hygiene findings (dead nested state tree, stale one-off backups) after explicit confirmation (#352).'), live=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.'))

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.

Source code in src/marianne/cli/commands/doctor.py
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
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()