Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(cli): split doctor_cmd into a package (#723)
Raghav Chamadiya2c04d113cdad
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/__init__.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/__init__.pynew file mode 100644index 000000000..3aa06a0af--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/__init__.py@@ -0,0 +1,49 @@+"""``repowise doctor`` command package.++Split out of a single ~1k-line module into cohesive parts:++* :mod:`._types` — the ``DoctorCheck`` NamedTuple + tiny formatting helpers+* :mod:`.advisories` — advisory-only signals (CLAUDE.md stamp, CLI version)+* :mod:`.repo_checks` — the per-repo check battery + ``--repair``+* :mod:`.workspace_checks` — workspace-level validation + MCP detection+* :mod:`.command` — the Click command + single/workspace orchestration++This package re-exports the public command plus the leading-underscore names+that the test-suite imports from ``repowise.cli.commands.doctor_cmd``, so the+import surface is unchanged. ``console``/``err_console`` are re-exported too+because some tests monkeypatch them at the package level.+"""++from __future__ import annotations++from repowise.cli.helpers import console, err_console++from . import advisories, command, repo_checks, workspace_checks+from ._types import DoctorCheck, _check+from .advisories import (+ _advise_claude_md_stamp,+ _claude_md_stamp_status,+ _print_cli_version_status,+)+from .command import doctor_command+from .repo_checks import _decision_vector_ids, _distill_checks+from .workspace_checks import _check_mcp_registered, _run_workspace_checks++__all__ = [+ "DoctorCheck",+ "_advise_claude_md_stamp",+ "_check",+ "_check_mcp_registered",+ "_claude_md_stamp_status",+ "_decision_vector_ids",+ "_distill_checks",+ "_print_cli_version_status",+ "_run_workspace_checks",+ "advisories",+ "command",+ "console",+ "doctor_command",+ "err_console",+ "repo_checks",+ "workspace_checks",+]diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_types.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_types.pynew file mode 100644index 000000000..3dec67f87--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_types.py@@ -0,0 +1,19 @@+"""Shared value types and tiny formatting helpers for ``repowise doctor``."""++from __future__ import annotations++from typing import NamedTuple+++class DoctorCheck(NamedTuple):+ name: str+ ok: bool+ detail: str = ""+++def _check(name: str, ok: bool, detail: str = "") -> DoctorCheck:+ return DoctorCheck(name, ok, detail)+++def _status_markup(ok: bool) -> str:+ return "[green]OK[/green]" if ok else "[red]FAIL[/red]"diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/advisories.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/advisories.pynew file mode 100644index 000000000..32e1452af--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/advisories.py@@ -0,0 +1,110 @@+"""Advisory-only doctor signals (never flip the pass/fail outcome)."""++from __future__ import annotations++from rich.table import Table++from repowise.cli.helpers import console+++def _claude_md_stamp_status(repo_path, state: dict) -> tuple[bool, str] | None:+ """Compare the managed CLAUDE.md "Last indexed" commit to state.json.++ Returns ``(ok, detail)`` or ``None`` to skip the check (no CLAUDE.md, no+ stamp, or no synced commit yet). After any index/update the stamp and+ ``state.json``'s ``last_sync_commit`` should agree; a mismatch means+ editor-file regeneration stopped (e.g. the workspace-update refresh bug or+ ``editor_files.claude_md`` disabled), so the injected "Last indexed" line is+ stale and trains agents to distrust the index. Compared against the synced+ commit, not live HEAD, so being a few commits behind HEAD is not flagged.+ """+ import re++ claude_md = repo_path / ".claude" / "CLAUDE.md"+ try:+ text = claude_md.read_text(encoding="utf-8")+ except OSError:+ return None+ m = re.search(r"Last indexed:.*?\(commit\s+([0-9a-fA-F]{7,})\)", text)+ if not m:+ # No stamp, or a too-short/abbreviated sha we can't compare safely.+ return None+ stamp = m.group(1).lower()+ synced = ((state or {}).get("last_sync_commit") or "").lower()+ if not synced:+ return None+ if synced.startswith(stamp) or stamp.startswith(synced):+ return (True, f"in sync at {stamp}")+ return (+ False,+ f"stamp {stamp} != index {synced[:8]} — run `repowise update` "+ "or `repowise claude-md` to refresh",+ )+++def _advise_claude_md_stamp(repo_path, state: dict) -> None:+ """Print an advisory line when the CLAUDE.md stamp lags the index.++ Advisory only (never flips the doctor's pass/fail): a stamp can briefly lag+ when a commit lands mid-update, which self-heals on the next sync. Skipped+ entirely when ``editor_files.claude_md`` is disabled, since there is nothing+ to refresh and the advice would be un-actionable.+ """+ from repowise.cli.editor_integrations.claude import _claude_md_enabled++ if not _claude_md_enabled(repo_path):+ return+ status = _claude_md_stamp_status(repo_path, state)+ if status is None:+ return+ ok, detail = status+ if not ok:+ console.print(f"[yellow]CLAUDE.md stamp drift:[/yellow] {detail}")+++def _print_cli_version_status() -> None:+ """Print a best-effort CLI update-check line.++ Advisory only: an outdated CLI is informational, not a broken repo, so this+ never affects doctor's pass/fail outcome and never fails on network errors.+ Runs once per invocation (the CLI version is global, not per-repo).+ """+ try:+ from repowise.cli.update_check import get_cli_update_check++ check = get_cli_update_check()+ except Exception:+ return # never let the update check break doctor++ # Show the full running command and resolved path verbatim — they can+ # differ (e.g. a stale shim on PATH vs the venv that launched this process),+ # and surfacing that mismatch is the point of this row.+ path_detail = check.resolved_executable or "not on PATH"+ running = check.running_executable or "?"++ if check.latest_version is None:+ status = "[green]OK[/green]"+ detail = (+ f"current {check.current_version}, could not check latest version, "+ f"path {path_detail}, running {running}"+ )+ elif check.update_available:+ status = "[yellow]WARN[/yellow]"+ detail = (+ f"current {check.current_version}, latest {check.latest_version}, "+ f"path {path_detail}, running {running}"+ )+ else:+ status = "[green]OK[/green]"+ detail = f"current {check.current_version} (latest), path {path_detail}, running {running}"++ table = Table(show_header=False, box=None, pad_edge=False)+ table.add_column(style="cyan")+ table.add_column()+ table.add_column()+ table.add_row("CLI version", status, detail)+ console.print(table)++ if check.update_available:+ console.print(f" [yellow]Update available:[/yellow] {check.suggested_command}")+ console.print(" [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]")diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.pynew file mode 100644index 000000000..b2634a145--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py@@ -0,0 +1,156 @@+"""The ``repowise doctor`` Click command entrypoint."""++from __future__ import annotations++import json++import click++from repowise.cli.helpers import (+ console,+ err_console,+ resolve_command_target,+ silence_logs_for_machine_output,+)++from ._types import DoctorCheck+from .advisories import _print_cli_version_status+from .repo_checks import _run_repo_checks+from .workspace_checks import _run_workspace_checks++[email protected]("doctor")[email protected]("path", required=False, default=None)[email protected]("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")+ "--workspace",+ "-w",+ is_flag=True,+ default=False,+ help="Force workspace mode (run checks against every repo in the workspace).",+)+ "--no-workspace",+ is_flag=True,+ default=False,+ help="Force single-repo mode even when invoked from a workspace.",+)+ "--format",+ "fmt",+ default="table",+ type=click.Choice(["table", "json"]),+ help="Output format. json is read-only (incompatible with --repair) and exits "+ "1 when any check fails.",+)+def doctor_command(+ path: str | None,+ repair: bool,+ workspace: bool,+ no_workspace: bool,+ fmt: str,+) -> None:+ """Run health checks on the wiki setup.++ Auto-detects workspace mode when invoked from a workspace root. In+ workspace mode, runs the full check battery against each indexed repo+ and prints a per-repo table plus a workspace-level summary.+ """+ if fmt != "table" and repair:+ raise click.UsageError(+ "--repair is not supported with --format json (json mode is read-only)."+ )++ if fmt != "table":+ silence_logs_for_machine_output()++ status = err_console if fmt != "table" else console++ target = resolve_command_target(+ path=path,+ workspace_flag=workspace,+ no_workspace_flag=no_workspace,+ )+ target.notice(status, command="doctor")++ if fmt == "table":+ # Advisory CLI update check, printed once above the repo check table(s).+ _print_cli_version_status()++ if not target.is_workspace:+ assert target.repo_path is not None+ all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)+ if fmt != "table":+ payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}+ click.echo(json.dumps(payload, indent=2))+ if not all_ok:+ raise SystemExit(1)+ return++ # Workspace mode — iterate over every entry, run workspace-level+ # validation, and report a summary table at the end so the user knows+ # which repos need attention.+ assert target.ws_root is not None and target.ws_config is not None+ ws_root = target.ws_root+ ws_config = target.ws_config++ ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair, fmt=fmt)++ overall_ok = True+ not_indexed: list[str] = []+ all_checks: list[DoctorCheck] = []+ for entry in ws_config.repos:+ abs_path = (ws_root / entry.path).resolve()+ if not abs_path.is_dir():+ continue+ if not (abs_path / ".repowise").is_dir():+ not_indexed.append(entry.alias)+ continue+ if fmt == "table":+ console.print()+ console.print(+ f"[bold]── {entry.alias}[/bold] "+ f"[dim]({entry.path})[/dim]"+ + (+ " [bold cyan](primary)[/bold cyan]"+ if entry.alias == ws_config.default_repo+ else ""+ )+ )+ ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)+ overall_ok = overall_ok and ok+ all_checks.extend(DoctorCheck(f"{entry.alias}: {c.name}", c.ok, c.detail) for c in checks)++ if fmt != "table":+ all_ok = overall_ok and not ws_issues and not not_indexed+ payload = {+ "ok": all_ok,+ "checks": [c._asdict() for c in all_checks],+ "workspace": {+ "checked": True,+ "issues": list(ws_issues),+ "not_indexed": not_indexed,+ },+ }+ click.echo(json.dumps(payload, indent=2))+ if not all_ok:+ raise SystemExit(1)+ return++ console.print()+ if not_indexed:+ console.print(f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}")+ console.print(" Run [bold]repowise update --workspace[/bold] to index them.")+ if ws_issues and not repair:+ console.print(+ f"[yellow]{len(ws_issues)} workspace-level issue(s); "+ f"rerun with [bold]--repair[/bold] to attempt fixes.[/yellow]"+ )++ workspace_clean = not ws_issues and overall_ok and not not_indexed+ if workspace_clean:+ console.print("[bold green]Workspace healthy.[/bold green]")+ elif overall_ok and not ws_issues:+ console.print("[bold yellow]All indexed repos healthy; some repos unindexed.[/bold yellow]")+ else:+ console.print("[bold yellow]Some checks failed across the workspace.[/bold yellow]")diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pysimilarity index 61%rename from packages/cli/src/repowise/cli/commands/doctor_cmd.pyrename to packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex ec50b62a5..fc211ad31 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -1,94 +1,22 @@-"""``repowise doctor`` — health check for the wiki setup."""+"""Per-repo doctor checks: store consistency, drift, distill, and repair."""from __future__ import annotationsimport contextlib-import jsonfrom pathlib import Path as _DoctorPath-from typing import NamedTuple-import clickfrom rich.table import Tablefrom repowise.cli.helpers import (console,- err_console,get_db_url_for_repo,get_repowise_dir,load_state,- resolve_command_target,run_async,- silence_logs_for_machine_output,)--class DoctorCheck(NamedTuple):- name: str- ok: bool- detail: str = ""---def _check(name: str, ok: bool, detail: str = "") -> DoctorCheck:- return DoctorCheck(name, ok, detail)---def _status_markup(ok: bool) -> str:- return "[green]OK[/green]" if ok else "[red]FAIL[/red]"---def _claude_md_stamp_status(repo_path, state: dict) -> tuple[bool, str] | None:- """Compare the managed CLAUDE.md "Last indexed" commit to state.json.-- Returns ``(ok, detail)`` or ``None`` to skip the check (no CLAUDE.md, no- stamp, or no synced commit yet). After any index/update the stamp and- ``state.json``'s ``last_sync_commit`` should agree; a mismatch means- editor-file regeneration stopped (e.g. the workspace-update refresh bug or- ``editor_files.claude_md`` disabled), so the injected "Last indexed" line is- stale and trains agents to distrust the index. Compared against the synced- commit, not live HEAD, so being a few commits behind HEAD is not flagged.- """- import re-- claude_md = repo_path / ".claude" / "CLAUDE.md"- try:- text = claude_md.read_text(encoding="utf-8")- except OSError:- return None- m = re.search(r"Last indexed:.*?\(commit\s+([0-9a-fA-F]{7,})\)", text)- if not m:- # No stamp, or a too-short/abbreviated sha we can't compare safely.- return None- stamp = m.group(1).lower()- synced = ((state or {}).get("last_sync_commit") or "").lower()- if not synced:- return None- if synced.startswith(stamp) or stamp.startswith(synced):- return (True, f"in sync at {stamp}")- return (- False,- f"stamp {stamp} != index {synced[:8]} — run `repowise update` "- "or `repowise claude-md` to refresh",- )---def _advise_claude_md_stamp(repo_path, state: dict) -> None:- """Print an advisory line when the CLAUDE.md stamp lags the index.-- Advisory only (never flips the doctor's pass/fail): a stamp can briefly lag- when a commit lands mid-update, which self-heals on the next sync. Skipped- entirely when ``editor_files.claude_md`` is disabled, since there is nothing- to refresh and the advice would be un-actionable.- """- from repowise.cli.editor_integrations.claude import _claude_md_enabled-- if not _claude_md_enabled(repo_path):- return- status = _claude_md_stamp_status(repo_path, state)- if status is None:- return- ok, detail = status- if not ok:- console.print(f"[yellow]CLAUDE.md stamp drift:[/yellow] {detail}")+from ._types import DoctorCheck, _check, _status_markup+from .advisories import _advise_claude_md_stampasync def _decision_vector_ids(session, repository_id: str) -> set[str]:@@ -111,54 +39,6 @@ async def _decision_vector_ids(session, repository_id: str) -> set[str]:return {f"{DECISION_VECTOR_PREFIX}{r[0]}" for r in rows}-def _print_cli_version_status() -> None:- """Print a best-effort CLI update-check line.-- Advisory only: an outdated CLI is informational, not a broken repo, so this- never affects doctor's pass/fail outcome and never fails on network errors.- Runs once per invocation (the CLI version is global, not per-repo).- """- try:- from repowise.cli.update_check import get_cli_update_check-- check = get_cli_update_check()- except Exception:- return # never let the update check break doctor-- # Show the full running command and resolved path verbatim — they can- # differ (e.g. a stale shim on PATH vs the venv that launched this process),- # and surfacing that mismatch is the point of this row.- path_detail = check.resolved_executable or "not on PATH"- running = check.running_executable or "?"-- if check.latest_version is None:- status = "[green]OK[/green]"- detail = (- f"current {check.current_version}, could not check latest version, "- f"path {path_detail}, running {running}"- )- elif check.update_available:- status = "[yellow]WARN[/yellow]"- detail = (- f"current {check.current_version}, latest {check.latest_version}, "- f"path {path_detail}, running {running}"- )- else:- status = "[green]OK[/green]"- detail = f"current {check.current_version} (latest), path {path_detail}, running {running}"-- table = Table(show_header=False, box=None, pad_edge=False)- table.add_column(style="cyan")- table.add_column()- table.add_column()- table.add_row("CLI version", status, detail)- console.print(table)-- if check.update_available:- console.print(f" [yellow]Update available:[/yellow] {check.suggested_command}")- console.print(" [dim]Restart Claude/Codex/Cursor or any MCP client after updating.[/dim]")--def _run_repo_checks(repo_path: _DoctorPath, repair: bool, *, fmt: str = "table") -> tuple[bool, list[DoctorCheck]]:@@ -702,293 +582,3 @@ def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:checks.append(_check("Distill rewrite hook", True, f"Could not check: {exc}"))return checks--[email protected]("doctor")[email protected]("path", required=False, default=None)[email protected]("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")- "--workspace",- "-w",- is_flag=True,- default=False,- help="Force workspace mode (run checks against every repo in the workspace).",-)- "--no-workspace",- is_flag=True,- default=False,- help="Force single-repo mode even when invoked from a workspace.",-)- "--format",- "fmt",- default="table",- type=click.Choice(["table", "json"]),- help="Output format. json is read-only (incompatible with --repair) and exits "- "1 when any check fails.",-)-def doctor_command(- path: str | None,- repair: bool,- workspace: bool,- no_workspace: bool,- fmt: str,-) -> None:- """Run health checks on the wiki setup.-- Auto-detects workspace mode when invoked from a workspace root. In- workspace mode, runs the full check battery against each indexed repo- and prints a per-repo table plus a workspace-level summary.- """- if fmt != "table" and repair:- raise click.UsageError(- "--repair is not supported with --format json (json mode is read-only)."- )-- if fmt != "table":- silence_logs_for_machine_output()-- status = err_console if fmt != "table" else console-- target = resolve_command_target(- path=path,- workspace_flag=workspace,- no_workspace_flag=no_workspace,- )- target.notice(status, command="doctor")-- if fmt == "table":- # Advisory CLI update check, printed once above the repo check table(s).- _print_cli_version_status()-- if not target.is_workspace:- assert target.repo_path is not None- all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)- if fmt != "table":- payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}- click.echo(json.dumps(payload, indent=2))- if not all_ok:- raise SystemExit(1)- return-- # Workspace mode — iterate over every entry, run workspace-level- # validation, and report a summary table at the end so the user knows- # which repos need attention.- assert target.ws_root is not None and target.ws_config is not None- ws_root = target.ws_root- ws_config = target.ws_config-- ws_issues = _run_workspace_checks(ws_root, ws_config, repair=repair, fmt=fmt)-- overall_ok = True- not_indexed: list[str] = []- all_checks: list[DoctorCheck] = []- for entry in ws_config.repos:- abs_path = (ws_root / entry.path).resolve()- if not abs_path.is_dir():- continue- if not (abs_path / ".repowise").is_dir():- not_indexed.append(entry.alias)- continue- if fmt == "table":- console.print()- console.print(- f"[bold]── {entry.alias}[/bold] "- f"[dim]({entry.path})[/dim]"- + (- " [bold cyan](primary)[/bold cyan]"- if entry.alias == ws_config.default_repo- else ""- )- )- ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)- overall_ok = overall_ok and ok- all_checks.extend(DoctorCheck(f"{entry.alias}: {c.name}", c.ok, c.detail) for c in checks)-- if fmt != "table":- all_ok = overall_ok and not ws_issues and not not_indexed- payload = {- "ok": all_ok,- "checks": [c._asdict() for c in all_checks],- "workspace": {- "checked": True,- "issues": list(ws_issues),- "not_indexed": not_indexed,- },- }- click.echo(json.dumps(payload, indent=2))- if not all_ok:- raise SystemExit(1)- return-- console.print()- if not_indexed:- console.print(f"[yellow]Not indexed:[/yellow] {', '.join(not_indexed)}")- console.print(" Run [bold]repowise update --workspace[/bold] to index them.")- if ws_issues and not repair:- console.print(- f"[yellow]{len(ws_issues)} workspace-level issue(s); "- f"rerun with [bold]--repair[/bold] to attempt fixes.[/yellow]"- )-- workspace_clean = not ws_issues and overall_ok and not not_indexed- if workspace_clean:- console.print("[bold green]Workspace healthy.[/bold green]")- elif overall_ok and not ws_issues:- console.print("[bold yellow]All indexed repos healthy; some repos unindexed.[/bold yellow]")- else:- console.print("[bold yellow]Some checks failed across the workspace.[/bold yellow]")---def _run_workspace_checks(- ws_root: _DoctorPath,- ws_config,- *,- repair: bool,- fmt: str = "table",-) -> list[str]:- """Run workspace-level validation. Returns a list of issue strings.-- Covers:- - Per-entry directory existence & ``.git`` presence.- - State drift between ``WorkspaceConfig.last_commit_at_index`` and- each repo's ``.repowise/state.json``.- - MCP server registration (best-effort detection in claude config).- - ``--repair``: rebuild missing ``state.json``, drop dead workspace- entries (with a notice). Skipped when ``fmt != "table"``; callers- must not pass ``repair=True`` with a non-table format.- """- from repowise.core.workspace.update import (- read_state_commit,- sync_workspace_state_from_disk,- )-- rows: list[tuple[str, str, str]] = []- issues: list[str] = []-- dead_entries: list[str] = []- for entry in ws_config.repos:- abs_path = (ws_root / entry.path).resolve()-- # Dir & git presence- if not abs_path.is_dir():- rows.append((entry.alias, "[red]MISSING[/red]", f"directory not found: {entry.path}"))- dead_entries.append(entry.alias)- issues.append(f"{entry.alias}: missing directory")- continue- if not (abs_path / ".git").exists():- rows.append((entry.alias, "[yellow]WARN[/yellow]", "not a git repo"))- issues.append(f"{entry.alias}: not a git repo")-- # State drift- disk_commit = read_state_commit(abs_path)- cfg_commit = entry.last_commit_at_index- if disk_commit and cfg_commit and disk_commit != cfg_commit:- rows.append(- (- entry.alias,- "[yellow]DRIFT[/yellow]",- f"config={cfg_commit[:8]}, state.json={disk_commit[:8]}",- )- )- issues.append(f"{entry.alias}: workspace config / state.json drift")- elif disk_commit and not cfg_commit:- rows.append(- (- entry.alias,- "[yellow]DRIFT[/yellow]",- f"workspace config missing last_commit_at_index (state.json has {disk_commit[:8]})",- )- )- issues.append(f"{entry.alias}: workspace config missing commit pointer")- elif (abs_path / ".repowise").is_dir() and not disk_commit:- rows.append(- (- entry.alias,- "[yellow]WARN[/yellow]",- "state.json missing or empty (run `repowise update`)",- )- )- issues.append(f"{entry.alias}: missing state.json")- else:- rows.append((entry.alias, "[green]OK[/green]", entry.path))-- if fmt == "table":- table = Table(title="repowise Workspace Doctor")- table.add_column("Repo", style="cyan")- table.add_column("Status")- table.add_column("Detail")- for r in rows:- table.add_row(*r)- console.print(table)-- # MCP server registration: best-effort, advisory only.- _check_mcp_registered(ws_root)-- # --repair: sync the workspace config from disk and drop dead entries.- if repair:- changed = sync_workspace_state_from_disk(ws_root, ws_config)- if changed:- console.print(- f"[green]Repaired workspace config from disk for:[/green] {', '.join(changed)}"- )- if dead_entries:- console.print(- f"[yellow]Removing dead workspace entries:[/yellow] {', '.join(dead_entries)}"- )- for alias in dead_entries:- ws_config.remove_repo(alias)- ws_config.save(ws_root)- console.print("[green]Workspace config updated.[/green]")- if not changed and not dead_entries:- console.print("[green]No workspace-level repairs needed.[/green]")-- return issues---def _check_mcp_registered(ws_root: _DoctorPath) -> None:- """Best-effort check that a Claude MCP entry points at this workspace.-- The check is advisory: a missing entry is not an error, since the user- may use the HTTP server or a different MCP client. We just print a- helpful hint so the workspace can be wired up if the user wants it.- """- import json as _json- import os as _os-- candidates: list[_DoctorPath] = []- appdata = _os.environ.get("APPDATA")- if appdata:- candidates.append(_DoctorPath(appdata) / "Claude" / "claude_desktop_config.json")- home = _DoctorPath.home()- candidates.extend(- [- home / ".claude" / "claude_desktop_config.json",- home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",- home / ".config" / "Claude" / "claude_desktop_config.json",- ]- )-- found_paths: list[str] = []- for cfg in candidates:- if not cfg.is_file():- continue- try:- data = _json.loads(cfg.read_text(encoding="utf-8"))- except Exception:- continue- servers = data.get("mcpServers", {}) or {}- for name, spec in servers.items():- args = spec.get("args", []) if isinstance(spec, dict) else []- arg_str = " ".join(str(a) for a in args)- if str(ws_root) in arg_str or str(ws_root.resolve()) in arg_str:- found_paths.append(f"{cfg.name}:{name}")-- if found_paths:- console.print(f" [dim]MCP: registered ({', '.join(found_paths)})[/dim]")- else:- console.print(- " [dim]MCP: no claude_desktop_config.json entry found — run "- "`repowise hook install` to register.[/dim]"- )diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.pynew file mode 100644index 000000000..a6a27c19f--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/workspace_checks.py@@ -0,0 +1,162 @@+"""Workspace-level doctor checks (per-entry drift, MCP registration)."""++from __future__ import annotations++from pathlib import Path as _DoctorPath++from rich.table import Table++from repowise.cli.helpers import console+++def _run_workspace_checks(+ ws_root: _DoctorPath,+ ws_config,+ *,+ repair: bool,+ fmt: str = "table",+) -> list[str]:+ """Run workspace-level validation. Returns a list of issue strings.++ Covers:+ - Per-entry directory existence & ``.git`` presence.+ - State drift between ``WorkspaceConfig.last_commit_at_index`` and+ each repo's ``.repowise/state.json``.+ - MCP server registration (best-effort detection in claude config).+ - ``--repair``: rebuild missing ``state.json``, drop dead workspace+ entries (with a notice). Skipped when ``fmt != "table"``; callers+ must not pass ``repair=True`` with a non-table format.+ """+ from repowise.core.workspace.update import (+ read_state_commit,+ sync_workspace_state_from_disk,+ )++ rows: list[tuple[str, str, str]] = []+ issues: list[str] = []++ dead_entries: list[str] = []+ for entry in ws_config.repos:+ abs_path = (ws_root / entry.path).resolve()++ # Dir & git presence+ if not abs_path.is_dir():+ rows.append((entry.alias, "[red]MISSING[/red]", f"directory not found: {entry.path}"))+ dead_entries.append(entry.alias)+ issues.append(f"{entry.alias}: missing directory")+ continue+ if not (abs_path / ".git").exists():+ rows.append((entry.alias, "[yellow]WARN[/yellow]", "not a git repo"))+ issues.append(f"{entry.alias}: not a git repo")++ # State drift+ disk_commit = read_state_commit(abs_path)+ cfg_commit = entry.last_commit_at_index+ if disk_commit and cfg_commit and disk_commit != cfg_commit:+ rows.append(+ (+ entry.alias,+ "[yellow]DRIFT[/yellow]",+ f"config={cfg_commit[:8]}, state.json={disk_commit[:8]}",+ )+ )+ issues.append(f"{entry.alias}: workspace config / state.json drift")+ elif disk_commit and not cfg_commit:+ rows.append(+ (+ entry.alias,+ "[yellow]DRIFT[/yellow]",+ f"workspace config missing last_commit_at_index (state.json has {disk_commit[:8]})",+ )+ )+ issues.append(f"{entry.alias}: workspace config missing commit pointer")+ elif (abs_path / ".repowise").is_dir() and not disk_commit:+ rows.append(+ (+ entry.alias,+ "[yellow]WARN[/yellow]",+ "state.json missing or empty (run `repowise update`)",+ )+ )+ issues.append(f"{entry.alias}: missing state.json")+ else:+ rows.append((entry.alias, "[green]OK[/green]", entry.path))++ if fmt == "table":+ table = Table(title="repowise Workspace Doctor")+ table.add_column("Repo", style="cyan")+ table.add_column("Status")+ table.add_column("Detail")+ for r in rows:+ table.add_row(*r)+ console.print(table)++ # MCP server registration: best-effort, advisory only.+ _check_mcp_registered(ws_root)++ # --repair: sync the workspace config from disk and drop dead entries.+ if repair:+ changed = sync_workspace_state_from_disk(ws_root, ws_config)+ if changed:+ console.print(+ f"[green]Repaired workspace config from disk for:[/green] {', '.join(changed)}"+ )+ if dead_entries:+ console.print(+ f"[yellow]Removing dead workspace entries:[/yellow] {', '.join(dead_entries)}"+ )+ for alias in dead_entries:+ ws_config.remove_repo(alias)+ ws_config.save(ws_root)+ console.print("[green]Workspace config updated.[/green]")+ if not changed and not dead_entries:+ console.print("[green]No workspace-level repairs needed.[/green]")++ return issues+++def _check_mcp_registered(ws_root: _DoctorPath) -> None:+ """Best-effort check that a Claude MCP entry points at this workspace.++ The check is advisory: a missing entry is not an error, since the user+ may use the HTTP server or a different MCP client. We just print a+ helpful hint so the workspace can be wired up if the user wants it.+ """+ import json as _json+ import os as _os++ candidates: list[_DoctorPath] = []+ appdata = _os.environ.get("APPDATA")+ if appdata:+ candidates.append(_DoctorPath(appdata) / "Claude" / "claude_desktop_config.json")+ home = _DoctorPath.home()+ candidates.extend(+ [+ home / ".claude" / "claude_desktop_config.json",+ home / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json",+ home / ".config" / "Claude" / "claude_desktop_config.json",+ ]+ )++ found_paths: list[str] = []+ for cfg in candidates:+ if not cfg.is_file():+ continue+ try:+ data = _json.loads(cfg.read_text(encoding="utf-8"))+ except Exception:+ continue+ servers = data.get("mcpServers", {}) or {}+ for name, spec in servers.items():+ args = spec.get("args", []) if isinstance(spec, dict) else []+ arg_str = " ".join(str(a) for a in args)+ if str(ws_root) in arg_str or str(ws_root.resolve()) in arg_str:+ found_paths.append(f"{cfg.name}:{name}")++ if found_paths:+ console.print(f" [dim]MCP: registered ({', '.join(found_paths)})[/dim]")+ else:+ console.print(+ " [dim]MCP: no claude_desktop_config.json entry found — run "+ "`repowise hook install` to register.[/dim]"+ )diff --git a/tests/unit/cli/test_doctor_cli_version.py b/tests/unit/cli/test_doctor_cli_version.pyindex e8a4a6f09..8d7465576 100644--- a/tests/unit/cli/test_doctor_cli_version.py+++ b/tests/unit/cli/test_doctor_cli_version.py@@ -13,7 +13,7 @@ from repowise.cli.update_check import UpdateCheckdef _capture(monkeypatch: pytest.MonkeyPatch, check: UpdateCheck) -> str:buf = io.StringIO()- monkeypatch.setattr(doctor_cmd, "console", Console(file=buf, width=200))+ monkeypatch.setattr(doctor_cmd.advisories, "console", Console(file=buf, width=200))monkeypatch.setattr("repowise.cli.update_check.get_cli_update_check", lambda *a, **k: check)doctor_cmd._print_cli_version_status()return buf.getvalue()@@ -73,7 +73,7 @@ def test_latest_unknown_stays_neutral(monkeypatch: pytest.MonkeyPatch) -> None:def test_never_raises_when_check_errors(monkeypatch: pytest.MonkeyPatch) -> None:buf = io.StringIO()- monkeypatch.setattr(doctor_cmd, "console", Console(file=buf, width=200))+ monkeypatch.setattr(doctor_cmd.advisories, "console", Console(file=buf, width=200))def _boom(*a, **k):raise RuntimeError("unexpected")diff --git a/tests/unit/cli/test_freshness_stamp_fixes.py b/tests/unit/cli/test_freshness_stamp_fixes.pyindex a70a22881..6318aff96 100644--- a/tests/unit/cli/test_freshness_stamp_fixes.py+++ b/tests/unit/cli/test_freshness_stamp_fixes.py@@ -119,7 +119,7 @@ def test_advise_stamp_prints_on_drift(tmp_path, monkeypatch):_write_claude_md(tmp_path, "1c67e0a9")printed: list[str] = []monkeypatch.setattr(- doctor_cmd.console,+ doctor_cmd.advisories.console,"print",lambda *a, **k: printed.append(" ".join(str(x) for x in a)),)@@ -137,7 +137,7 @@ def test_advise_stamp_skips_when_claude_md_disabled(tmp_path, monkeypatch):)printed: list[str] = []monkeypatch.setattr(- doctor_cmd.console,+ doctor_cmd.advisories.console,"print",lambda *a, **k: printed.append(" ".join(str(x) for x in a)),)