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(doctor): split repo checks into check groups, repair and render (#3985)
Raghav Chamadiya3d9a7571cb23
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/__init__.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/__init__.pynew file mode 100644index 000000000..a972064ac--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/__init__.py@@ -0,0 +1,7 @@+"""The per-repo doctor check groups, run in order by ``repo_checks``.++* :mod:`.core`: git, ``.repowise/``, hooks, database, state, store format+* :mod:`.providers`: providers, hosted account, stale pages+* :mod:`.stores`: SQL, vector store and FTS consistency, coordinator drift+* :mod:`.integrations`: distill, Claude Code registration, agents+"""diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/context.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/context.pynew file mode 100644index 000000000..d0de70238--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/context.py@@ -0,0 +1,62 @@+"""State the doctor check groups share, plus the store opener they all use."""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path++from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort+++@dataclass+class StoreDrift:+ """What the three-store reconciliation found; ``--repair`` acts on it."""++ missing_from_vector: set[str] = field(default_factory=set)+ orphaned_vector: set[str] = field(default_factory=set)+ missing_from_fts: set[str] = field(default_factory=set)+ orphaned_fts: set[str] = field(default_factory=set)+ # An index on disk holding no vectors at all. Repairing that is a whole+ # reindex, which doctor does not start on a hosted embedder unasked.+ vector_store_empty: bool = False++ def has_mismatches(self) -> bool:+ return bool(+ self.missing_from_fts+ or self.orphaned_fts+ or self.missing_from_vector+ or self.orphaned_vector+ )+++@dataclass+class CheckContext:+ """Inputs one group reads from an earlier one, and results repair and render need."""++ repo_path: Path+ repowise_dir: Path+ db_ok: bool = False+ page_count: int = 0+ state: dict = field(default_factory=dict)+ state_ok: bool = False+ stale_counts: dict[str, int] = field(default_factory=dict)+ stale_count: int = 0+ drift: StoreDrift = field(default_factory=StoreDrift)+ coord_drift_color: str = "white"+ coord_drift_pct: str = "N/A"+ registration_wedged: bool = False+ agents_need_refresh: bool = False+++async def open_store(repo_path: Path):+ """Reconcile the schema, then return ``(engine, session_factory)``.++ Reconciled first so doctor reports the store's real state rather than a+ `no such column` failure on a store one repowise older.+ """+ from repowise.core.persistence import create_engine, create_session_factory++ url = get_db_url_for_repo(repo_path)+ await reconcile_schema_best_effort(url)+ engine = create_engine(url)+ return engine, create_session_factory(engine)diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.pynew file mode 100644index 000000000..53274c855--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/core.py@@ -0,0 +1,208 @@+"""Checks 1-4b: git, ``.repowise/``, hooks, database, state.json, store format."""++from __future__ import annotations++from pathlib import Path as _DoctorPath++from repowise.cli.helpers import db_configured, load_state, run_async++from .._types import DoctorCheck, _check+from .context import CheckContext, open_store+++async def _page_count(session: object, repo_id: str) -> int:+ """Count this repository's pages in SQL.++ Counted in the database rather than by measuring a fetched list. The+ previous spelling took ``len()`` of a ``list_pages`` page, whose ``limit``+ defaults to 100 and was passed 10000 here, so every repository with more+ than 10000 pages reported exactly 10000 — a plausible-looking number that+ never moves.+ """+ from sqlalchemy import func, select++ from repowise.core.persistence.models import Page++ result = await session.execute( # type: ignore[attr-defined]+ select(func.count()).select_from(Page).where(Page.repository_id == repo_id)+ )+ return int(result.scalar_one())+++def _repowise_dir_check(repowise_dir: _DoctorPath) -> DoctorCheck:+ """Exists and writable, probed with a real file: os.access lies on Windows."""+ if not repowise_dir.exists():+ return _check(".repowise/ directory", False, f"{repowise_dir} (run 'repowise init')")+ probe = repowise_dir / ".doctor-write-probe"+ try:+ probe.write_text("", encoding="utf-8")+ probe.unlink()+ except OSError as exc:+ return _check(+ ".repowise/ directory",+ False,+ f"{repowise_dir} is not writable ({exc.strerror or exc}); fix its permissions",+ )+ return _check(".repowise/ directory", True, str(repowise_dir))+++def _autosync_hook_check(repo_path: _DoctorPath) -> DoctorCheck:+ """Report the post-commit hook through hooks.status, which asks git for the+ real hooks directory, so worktrees and core.hooksPath read correctly."""+ try:+ from repowise.cli.hooks import status as _hook_status++ state = _hook_status(repo_path)+ except Exception as exc:+ return _check("Post-commit hook", True, f"could not read hook state ({exc})")+ if state.startswith("installed"):+ return _check("Post-commit hook", True, state)+ if state == "not installed":+ return _check(+ "Post-commit hook",+ True,+ "not installed; the index updates only when you run 'repowise update' "+ "('repowise hook install' turns auto-sync on)",+ )+ return _check("Post-commit hook", True, state)+++def _attribution_notes_check(repo_path: _DoctorPath) -> DoctorCheck | None:+ """At ``attribution.capture: notes``, whether notes travel with the repo.++ None at every other level. Notes reach teammates only through a fetch+ refspec and an explicit push, and survive a rebase only via+ ``notes.rewriteRef``; without them coverage is silently low elsewhere.+ """+ name = "Attribution notes"+ try:+ from repowise.core.attribution import load_attribution_settings++ if load_attribution_settings(repo_path).capture != "notes":+ return None+ from repowise.core.edit_capture.notes import FETCH_REFSPEC, NOTES_REF, refspec_status++ status = refspec_status(_DoctorPath(repo_path))+ except OSError as exc:+ return _check(name, True, f"could not read git config ({exc})")+ if not status["remote"]:+ return _check(name, True, "no origin remote, so notes stay on this machine")+ push = (+ "push refspec set"+ if status["push"]+ else f"share them with 'git push origin {NOTES_REF}'"+ )+ problems = []+ if not status["fetch"]:+ problems.append(f"run 'git config --add remote.origin.fetch \"{FETCH_REFSPEC}\"'")+ if not status["rewrite_ref"]:+ problems.append(f"run 'git config --add notes.rewriteRef {NOTES_REF}'")+ if problems:+ return _check(name, False, "; ".join([*problems, push]))+ return _check(name, True, f"fetch refspec and notes.rewriteRef set; {push}")+++def _events_config_check(repo_path: _DoctorPath) -> DoctorCheck | None:+ """The ``events:`` block, when it has values that fell back to defaults."""+ try:+ from repowise.core.events.store import load_event_settings++ errors = load_event_settings(repo_path).errors+ except Exception as exc:+ return _check("Events config", True, f"could not read it ({exc})")+ if not errors:+ return None+ return _check("Events config", False, "; ".join(errors) + " (defaults used)")+++def _git_check(repo_path: _DoctorPath) -> DoctorCheck:+ try:+ import git as gitpython++ gitpython.Repo(repo_path, search_parent_directories=True)+ return _check("Git repository", True, str(repo_path))+ except Exception:+ return _check("Git repository", False, "Not a git repo")+++def _hook_rows(repo_path: _DoctorPath) -> list[DoctorCheck]:+ # The post-commit hook is installed by init by default; not having it is a+ # choice (--no-hook), so its absence is informational, not a fail.+ rows = [_autosync_hook_check(repo_path)]+ for optional in (_attribution_notes_check(repo_path), _events_config_check(repo_path)):+ if optional is not None:+ rows.append(optional)+ return rows+++async def _count_pages(repo_path: _DoctorPath) -> int:+ from repowise.core.persistence import get_repository_by_path, get_session++ engine, sf = await open_store(repo_path)+ count = 0+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo:+ count = await _page_count(session, repo.id)+ await engine.dispose()+ return count+++def _database_rows(ctx: CheckContext) -> list[DoctorCheck]:+ """Sets ``ctx.db_ok`` and ``ctx.page_count`` for the later groups."""+ probed = (ctx.repowise_dir / "wiki.db").exists() or db_configured()+ if not probed:+ return [_check("Database", False, "wiki.db not found")]+ try:+ ctx.page_count = run_async(_count_pages(ctx.repo_path))+ ctx.db_ok = True+ except Exception as e:+ return [_check("Database", False, str(e))]+ return [_check("Database", True, f"{ctx.page_count} pages")]+++def _state_row(ctx: CheckContext) -> DoctorCheck:+ ctx.state = load_state(ctx.repo_path)+ ctx.state_ok = bool(ctx.state)+ return _check(+ "state.json",+ ctx.state_ok,+ f"last_sync: {(ctx.state.get('last_sync_commit') or '—')[:8]}"+ if ctx.state_ok+ else "Not found or empty",+ )+++def _store_format_row(repo_path: _DoctorPath) -> DoctorCheck:+ """Does this store predate a capability the current build offers?++ A REINDEX_RECOMMENDED migration never auto-runs, so doctor is where an+ un-upgraded store learns a re-index is available. Reported OK, not FAIL:+ the store works degraded, it is not broken, and failing every pre-upgrade+ store's doctor run would cry wolf. The row carries the exact command so it+ is actionable even after the once-per-store update nag was suppressed.+ """+ try:+ from repowise.cli.upgrade import assess_store++ verdict = assess_store(repo_path)+ if verdict.reindex_recommended and verdict.reindex_command:+ notice = verdict.user_notice or "A re-index adds new capabilities."+ return _check("Store format", True, f"{notice} Run: {verdict.reindex_command}")+ return _check("Store format", True, "Current")+ except Exception as e:+ return _check("Store format", True, f"Could not check: {e}")+++def core_checks(ctx: CheckContext) -> list[DoctorCheck]:+ """Checks 1-4b, in order. Fills the database and state fields of *ctx*."""+ checks = [_git_check(ctx.repo_path)]+ # The MCP server refuses to start on a .repowise/ it cannot write, so an+ # existence-only row would say OK for the one state that fails every call.+ checks.append(_repowise_dir_check(ctx.repowise_dir))+ checks.extend(_hook_rows(ctx.repo_path))+ checks.extend(_database_rows(ctx))+ checks.append(_state_row(ctx))+ if ctx.state_ok:+ checks.append(_store_format_row(ctx.repo_path))+ return checksdiff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.pynew file mode 100644index 000000000..a4806d4f2--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py@@ -0,0 +1,395 @@+"""Checks 11-13: distill, Claude Code MCP registration and launch, agents."""++from __future__ import annotations++import functools as _functools+from pathlib import Path as _DoctorPath++from .._types import DoctorCheck, _check+from .context import CheckContext+++def integration_checks(ctx: CheckContext) -> list[DoctorCheck]:+ """Checks 11-13, in order. Sets the two flags that drive ``--repair``."""+ checks = list(_distill_checks(ctx.repo_path))+ # 12. Static registration check: wedged-path detection.+ registration_check, ctx.registration_wedged = _claude_registration_check(ctx.repo_path)+ checks.append(registration_check)+ # 12b. Does that registration actually start? Separate row: a wired-up+ # server that dies on every invocation has a different fix than none.+ checks.append(_mcp_responds_check())+ # 13. Per-agent health, reported by each agent's own descriptor.+ agent_checks, ctx.agents_need_refresh = _agent_target_checks(ctx.repo_path)+ checks.extend(agent_checks)+ return checks+++def _agent_target_checks(+ repo_path: _DoctorPath | None = None,+) -> tuple[list[DoctorCheck], bool]:+ """One row per agent, reported by that agent's own descriptor.++ Nothing here knows what any particular agent's health means: each+ ``AgentTarget`` answers for itself, so a fourth agent gets a doctor row by+ being registered rather than by someone adding a branch to this function.++ Only ``broken`` fails the run, and the line is drawn there on purpose.+ ``not-installed`` is not a failure — an agent you do not use is not a+ problem with your setup — and neither is ``stale``, which is advisory in+ the same way the "Distill rewrite hook" row above it already is. A stale+ matcher is common, opt-in surfaces go stale routinely, and making it fail+ would turn ``repowise doctor`` non-zero in CI for a condition nobody asked+ the tool to guarantee. ``broken`` means a config file is damaged, which is+ a real fault in the setup being checked.++ Advisory does not mean quiet. The stale row is the reason this function+ exists: a hook whose matcher names a tool the host has since renamed is+ installed, parses, and will never fire, which is indistinguishable from+ working unless something says so out loud. It is also the agreed mitigation+ for gating the self-heal migrations on ``REPOWISE_SKIP_EDITOR_SETUP`` —+ someone who exports that permanently never gets the migration, so the+ staleness has to be visible somewhere. It is printed, and it drives+ ``--repair``; it just does not change the exit code.++ Returns ``(checks, needs_refresh)``; ``needs_refresh`` drives ``--repair``.+ """+ from repowise.cli.agent_targets.registry import all_targets++ checks: list[DoctorCheck] = []+ needs_refresh = False+ try:+ targets = all_targets()+ except Exception as exc: # pragma: no cover - a broken registry is a crash elsewhere+ return [_check("Agent integrations", True, f"Could not check: {exc}")], False++ for target in targets:+ name = f"Agent: {target.id}"+ try:+ report = target.doctor(repo_path=repo_path)+ except Exception as exc:+ checks.append(_check(name, True, f"Could not check: {exc}"))+ continue+ if report.status.value in ("ok", "not-installed"):+ detail = report.issues[0] if report.issues else "wired up"+ checks.append(_check(name, True, detail))+ continue+ # Only conditions the repair pass can actually resolve drive it. A+ # plugin the CLI cannot rewrite, or a fix that is a different command,+ # would otherwise buy a global config write that changes nothing and+ # then report advice for a condition the user does not have.+ needs_refresh = needs_refresh or report.repairable+ detail = "; ".join(report.issues)+ if report.fix_command:+ detail += f" (run: {report.fix_command})"+ checks.append(_check(name, report.status.value != "broken", detail))+ return checks, needs_refresh+++def _registered_mcp_entry() -> dict | None:+ """The Claude Code ``mcpServers.repowise`` entry, or None if there isn't one.++ Delegates to ``claude_config``, which owns reading this entry, so the two+ doctor checks and the registration writer cannot drift apart on what counts+ as registered. Both checks must judge the same entry: a smoke check that+ launched a *different* command than the one registered would give a clean+ bill of health to the broken thing.+ """+ from repowise.cli.editor_integrations.claude_config import (+ _claude_code_settings_path,+ _stored_repowise_entry,+ )++ return _stored_repowise_entry(_claude_code_settings_path())+++def _unregistered_detail() -> str:+ """Why there is no entry: absent, or present but unreadable.++ Those have different fixes, and collapsing them tells a user with a+ hand-broken settings.json to run ``init``, which will fail on the same+ file. Only reached when there is no entry, so it costs nothing normally.+ """+ from repowise.cli.editor_integrations.claude_config import (+ _claude_code_settings_path,+ load_existing_config,+ )++ settings_path = _claude_code_settings_path()+ if settings_path.exists():+ try:+ load_existing_config(settings_path)+ except Exception:+ return f"could not parse {settings_path}"+ return "not registered (repowise init registers it)"+++@_functools.cache+def _mcp_responds_check() -> DoctorCheck:+ """Launch the registered MCP server and complete one round trip.++ Reported separately from the registration row: registration answers "is it+ wired up", this answers "does it run". An install whose server dies on+ every invocation passes the first and fails this one, which is the whole+ point. Absence of a registration is informational, matching+ the registration check.++ Cached for the process because there is one global ``mcpServers.repowise``+ entry and this takes no repo argument, while workspace mode runs the repo+ checks once per entry. Without the cache a ten-repo workspace would launch+ the same server ten times and pay the startup cost for each.+ """+ from ..mcp_smoke import CHECK_NAME, mcp_smoke_check++ try:+ entry = _registered_mcp_entry()+ if entry is None:+ return _check(CHECK_NAME, True, "not registered - nothing to launch")+ command = entry.get("command")+ args = entry.get("args")+ if not isinstance(command, str) or not isinstance(args, list):+ return _check(CHECK_NAME, True, "registration is hand-shaped - not launching it")+ return mcp_smoke_check(command, [str(a) for a in args], entry.get("env"))+ except Exception as exc: # a doctor check must never be the crash+ return _check(CHECK_NAME, True, f"Could not check: {exc}")+++def _claude_registration_check(+ repo_path: _DoctorPath | None = None,+) -> tuple[DoctorCheck, bool]:+ """Detect a wedged Claude Code MCP registration (stale paths).++ The global ``~/.claude/settings.json`` entry can end up pointing at a+ directory that no longer exists (a moved repo, or a leaked temp path) or+ at a pinned command binary from a deleted venv; either way the MCP+ server silently fails to start in every Claude Code session. Returns+ ``(check, wedged)``; ``wedged`` drives the ``--repair`` re-registration.+ Absence of a registration is informational, never a failure.++ With *repo_path*, an entry serving a different repo gets an advisory note+ unless another Claude Code scope registers this repo. Advisory because the+ entry is not broken, and never repaired: repointing the one global entry+ would break the repo it serves.++ This is a *static* check. Whether the server actually starts is+ ``_mcp_responds_check``.+ """+ name = "Claude Code MCP entry"+ try:+ entry = _registered_mcp_entry()+ if entry is None:+ return _check(name, True, _unregistered_detail()), False++ problems: list[str] = []+ command = entry.get("command")+ # Bare command names resolve via PATH at session start; only a pinned+ # absolute path can go stale.+ if (+ isinstance(command, str)+ and ("/" in command or "\\" in command)+ and not _DoctorPath(command).exists()+ ):+ problems.append(f"command not found: {command}")+ target = _registration_target(entry)+ if target is not None and not _DoctorPath(target).is_dir():+ problems.append(f"registered path missing: {target}")+ if problems:+ return _check(name, False, "; ".join(problems) + " (rerun with --repair)"), True+ if target is not None and repo_path is not None and not _registers_repo(target, repo_path):+ detail = (+ f"serves {target}; this repo is not registered (run `repowise agents add "+ "--target=claude-code --scope=project` for a project entry)"+ )+ return _check(name, True, detail), False+ return _check(name, True, target or "registered"), False+ except Exception as exc:+ return _check(name, True, f"Could not check: {exc}"), False+++def _registers_repo(target: str, repo_path: _DoctorPath) -> bool:+ """Whether Claude Code serves *repo_path* from the global entry or another scope.++ The global *target* counts when it is what init registers for this repo+ (the workspace root inside a workspace). Otherwise a repowise entry naming+ this repo in ``.mcp.json`` (project scope) or ``~/.claude.json`` (user or+ local scope) counts; one copied from another repo does not.+ """+ from repowise.cli.agent_targets.targets.claude_code import project_mcp_config_path+ from repowise.cli.editor_integrations.claude_config import (+ _resolve_mcp_target,+ _stored_repowise_entry,+ )+ from repowise.cli.helpers import _same_path++ served = (repo_path, _resolve_mcp_target(repo_path))++ def serves(path: str) -> bool:+ # Claude Code starts a project server in the repo, so a relative path+ # is relative to it.+ return any(_same_path(repo_path / path, s) for s in served)++ def names_repo(entry: object) -> bool:+ path = _registration_target(entry) if isinstance(entry, dict) else None+ return path is not None and serves(path)++ if serves(target):+ return True+ other_scopes = [+ _stored_repowise_entry(project_mcp_config_path(repo_path)),+ *_claude_json_entries(repo_path),+ ]+ return any(names_repo(e) for e in other_scopes)+++def _claude_json_entries(repo_path: _DoctorPath) -> list[object]:+ """Repowise entries in ``~/.claude.json``: user scope, then this repo's local scope.++ Read here only, best effort: an unreadable file yields nothing, so the+ worst case is the advisory note above.+ """+ import json++ from repowise.cli.helpers import _same_path++ try:+ data = json.loads((_DoctorPath.home() / ".claude.json").read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return []+ if not isinstance(data, dict):+ return []+ scopes = [data]+ projects = data.get("projects")+ if isinstance(projects, dict):+ scopes += [+ v+ for k, v in projects.items()+ if isinstance(v, dict) and _same_path(_DoctorPath(k), repo_path)+ ]+ entries: list[object] = []+ for scope in scopes:+ servers = scope.get("mcpServers")+ if isinstance(servers, dict) and "repowise" in servers:+ entries.append(servers["repowise"])+ return entries+++def _registration_target(entry: dict) -> str | None:+ """The repo/workspace path a registration serves, or None if unrecognized.++ Registrations are shaped ``args: ["mcp", "<abs path>", "--transport",+ "stdio"]``; the target sits right after ``mcp``. Anything else (a flag+ in that slot, a hand-edited entry) returns None rather than guessing.+ """+ args = entry.get("args")+ if not isinstance(args, list) or args[:1] != ["mcp"] or len(args) < 2:+ return None+ target = args[1]+ if isinstance(target, str) and not target.startswith("-"):+ return target+ return None+++def _distill_config_row(repo_path: _DoctorPath) -> tuple[DoctorCheck, object]:+ """``(row, distill_cfg)``; the block is kept even when validating it fails."""+ distill_cfg = None+ try:+ from repowise.core.repo_config import load_repo_config++ distill_cfg = load_repo_config(repo_path).get("distill")+ from repowise.core.distill.config import validate_distill_config++ problems = validate_distill_config(distill_cfg)+ if problems:+ return _check("Distill config", False, "; ".join(problems)), distill_cfg+ detail = "valid" if distill_cfg else "defaults (no block)"+ return _check("Distill config", True, detail), distill_cfg+ except Exception as exc:+ return _check("Distill config", True, f"Could not check: {exc}"), distill_cfg+++def _omission_store_row(repo_path: _DoctorPath, distill_cfg: object) -> DoctorCheck:+ """TTL and cap are pruned on write, so a store far past its cap means+ pruning is not keeping up."""+ try:+ from repowise.core.distill.config import omission_store_settings++ _ttl_days, max_mb = omission_store_settings(distill_cfg)+ db_path = repo_path / ".repowise" / "omissions" / "omissions.db"+ if not db_path.is_file():+ return _check("Omission store", True, "not created yet")+ size_bytes = db_path.stat().st_size+ wal = db_path.with_name(db_path.name + "-wal")+ if wal.is_file():+ size_bytes += wal.stat().st_size+ size_mb = size_bytes / (1024 * 1024)+ ok = size_mb <= max_mb * 1.5 # WAL slack before checkpointing+ detail = f"{size_mb:.1f} MB (cap {max_mb:g} MB)"+ if not ok:+ detail += " — over cap; pruning happens on the next distill write"+ return _check("Omission store", ok, detail)+ except Exception as exc:+ return _check("Omission store", True, f"Could not check: {exc}")+++def _rewrite_hook_surfaces() -> list[tuple[str, object]]:+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter+ from repowise.cli.agent_adapters.codex import CodexAdapter++ surfaces = [("claude-code", ClaudeCodeAdapter())]+ codex = CodexAdapter()+ if codex.detect():+ surfaces.append(("codex", codex))+ from repowise.cli.agent_adapters.cursor import CursorAdapter++ cursor = CursorAdapter()+ if cursor.detect():+ surfaces.append(("cursor", cursor))+ return surfaces+++def _installed_rewrite_hooks(surfaces: list[tuple[str, object]]) -> list[str]:+ # Registered and live are different questions: an entry whose matcher+ # predates a tool rename is registered and fires on some or none of the+ # agent's shell tools. Say which, rather than calling all three "installed".+ installed_names = []+ for name, adapter in surfaces:+ status = adapter.rewrite_hook_status() # type: ignore[attr-defined]+ if not status.installed:+ continue+ if not status.unmatched:+ installed_names.append(name)+ else:+ misses = ", ".join(status.unmatched)+ installed_names.append(f"{name} (matcher misses {misses})")+ return installed_names+++def _rewrite_hook_row(distill_cfg: object) -> DoctorCheck:+ """Advisory: the rewrite hook is strictly opt-in."""+ try:+ installed_names = _installed_rewrite_hooks(_rewrite_hook_surfaces())+ if installed_names:+ commands_cfg = distill_cfg.get("commands") if isinstance(distill_cfg, dict) else None+ opted_out = isinstance(commands_cfg, dict) and commands_cfg.get("enabled") is False+ detail = ", ".join(installed_names)+ detail += " (this repo opted out)" if opted_out else ""+ detail = f"installed: {detail}"+ else:+ detail = "not installed (opt-in: repowise hook rewrite install)"+ return _check("Distill rewrite hook", True, detail)+ except Exception as exc:+ return _check("Distill rewrite hook", True, f"Could not check: {exc}")+++def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:+ """Distill feature health: config validity, store sizing, rewrite hook.++ The rewrite hook is opt-in, so its absence is informational, never a+ failure. Any unexpected error degrades to an advisory OK row — distill+ problems must not break doctor.+ """+ config_row, distill_cfg = _distill_config_row(repo_path)+ return [+ config_row,+ _omission_store_row(repo_path, distill_cfg),+ _rewrite_hook_row(distill_cfg),+ ]diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/providers.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/providers.pynew file mode 100644index 000000000..fbec6c558--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/providers.py@@ -0,0 +1,162 @@+"""Checks 5-7: providers, hosted account, stale pages."""++from __future__ import annotations++from pathlib import Path as _DoctorPath++from repowise.cli.helpers import run_async++from .._types import DoctorCheck, _check+from .context import CheckContext, open_store+++async def _stale_page_counts(session: object, repo_id: str) -> dict[str, int]:+ """Count stale pages by type without hydrating their rendered content."""+ from sqlalchemy import func, select++ from repowise.core.persistence.models import Page++ result = await session.execute( # type: ignore[attr-defined]+ select(Page.page_type, func.count())+ .where(+ Page.repository_id == repo_id,+ Page.freshness_status.in_(["stale", "expired"]),+ )+ .group_by(Page.page_type)+ )+ return {str(page_type): int(count) for page_type, count in result.all()}+++def _stale_page_guidance(counts: dict[str, int]) -> str:+ """Describe stale work by owner and name commands that can clear it."""+ from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPES++ total = sum(counts.values())+ model_written = sum(+ count for page_type, count in counts.items() if page_type in MODEL_WRITTEN_PAGE_TYPES+ )+ structural = total - model_written+ categories = []+ if model_written:+ categories.append(f"{model_written} model-written")+ if structural:+ categories.append(f"{structural} structural")++ detail = (+ f"{total} stale ({', '.join(categories)}) — content no longer matches its "+ "current inputs or generation selection."+ )+ if model_written:+ detail += (+ " `repowise generate --stale` is the cheaper refresh for model-written "+ "pages that are still selected."+ )+ detail += (+ " `repowise update --full` performs the authoritative reconciliation and "+ "retires pages no longer selected."+ )+ return detail + " `--repair` only fixes store drift."+++def _provider_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:+ """Report provider implementations, configuration errors, and usability.++ These are three distinct claims. In particular, an empty validation+ warning list means no configured key is malformed; it does not prove that+ an LLM provider will resolve for this repository.+ """+ checks: list[DoctorCheck] = []++ try:+ from repowise.core.providers import list_providers++ providers = list_providers()+ checks.append(+ _check(+ "Providers",+ bool(providers),+ f"Implementations loaded: {', '.join(providers)}",+ )+ )+ except Exception as exc:+ checks.append(_check("Providers", False, str(exc)))++ from repowise.cli.helpers import validate_provider_config++ config_warnings = validate_provider_config(repo_path=repo_path)+ config_ok = not config_warnings+ config_detail = "No misconfigured provider keys" if config_ok else "; ".join(config_warnings)+ checks.append(_check("Provider config", config_ok, config_detail))++ from repowise.core.providers.llm.registry import provider_available_for_repo++ llm_available = provider_available_for_repo(repo_path)+ llm_detail = (+ "Resolves for this repository"+ if llm_available+ else "None configured — prose degrades to a structural wiki; set a key or pass --provider"+ )+ # Keyless operation is supported, so this is informational rather than a+ # failing health check. The detail tells users what init will actually do.+ checks.append(_check("LLM provider", True, llm_detail))+ return checks+++def _hosted_account_check() -> DoctorCheck:+ """Informational: signed out is not a failure."""+ try:+ from repowise.cli.platform import auth, credentials++ creds = credentials.load()+ if creds is None:+ return _check(+ "Hosted account",+ True,+ "Not signed in (optional: repowise login). "+ "Publish this repo free: repowise publish",+ )+ if creds.get("stale"):+ return _check("Hosted account", False, "Session expired or revoked; run repowise login")+ account = auth.fetch_account()+ cached = (account or creds.get("account") or {}) or {}+ who = cached.get("github_username") or cached.get("email") or "unknown"+ tier = cached.get("tier") or "free"+ suffix = "" if account else " (offline, using cached identity)"+ return _check("Hosted account", True, f"{who} ({tier}){suffix}")+ except Exception as e:+ return _check("Hosted account", False, str(e))+++async def _read_stale_counts(repo_path: _DoctorPath) -> dict[str, int]:+ from repowise.core.persistence import get_repository_by_path, get_session++ engine, sf = await open_store(repo_path)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo:+ counts = await _stale_page_counts(session, repo.id)+ await engine.dispose()+ return counts+ await engine.dispose()+ return {}+++def _stale_pages_row(ctx: CheckContext) -> DoctorCheck:+ """Sets ``ctx.stale_counts`` and ``ctx.stale_count`` for ``--repair``."""+ try:+ ctx.stale_counts = run_async(_read_stale_counts(ctx.repo_path))+ ctx.stale_count = sum(ctx.stale_counts.values())+ if ctx.stale_count:+ return _check("Stale pages", False, _stale_page_guidance(ctx.stale_counts))+ return _check("Stale pages", True, "0 stale")+ except Exception:+ return _check("Stale pages", True, "Could not check")+++def provider_checks(ctx: CheckContext) -> list[DoctorCheck]:+ """Checks 5-7, in order."""+ checks = list(_provider_checks(ctx.repo_path))+ checks.append(_hosted_account_check())+ if ctx.db_ok and ctx.page_count > 0:+ checks.append(_stale_pages_row(ctx))+ return checksdiff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.pynew file mode 100644index 000000000..7fb4816ab--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py@@ -0,0 +1,349 @@+"""Checks 8-10: SQL vs vector store vs FTS consistency, and coordinator drift."""++from __future__ import annotations++import contextlib+from pathlib import Path as _DoctorPath+from typing import NamedTuple++from repowise.cli.helpers import run_async+from repowise.core.exclusion import build_exclude_spec, is_excluded++from .._types import DoctorCheck, _check+from .context import CheckContext, StoreDrift, open_store+++async def _decision_vector_ids(session, repository_id: str) -> set[str]:+ """Vector-store ids for this repo's decision records.++ Decisions are co-located in the *page* vector store under the+ ``decision:<record_id>`` namespace (no separate table). The store therefore+ legitimately holds page vectors *and* decision vectors, so any SQL↔vector+ reconciliation must count decisions on the SQL side — otherwise every+ decision embedding reads as an orphan.+ """+ from sqlalchemy import text as _sql_text++ from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX++ rows = await session.execute(+ _sql_text("SELECT id FROM decision_records WHERE repository_id = :rid"),+ {"rid": repository_id},+ )+ return {f"{DECISION_VECTOR_PREFIX}{r[0]}" for r in rows}+++def _is_stub_fallback_row(page) -> bool:+ """True when a ``Page`` row is a stub standing in for a failed model page.++ The generation-side predicate reads ``page.metadata``; the ORM row carries+ the same dict as the ``metadata_json`` text column, so the marker key is+ shared but the accessor is not.+ """+ import json++ from repowise.core.generation.models import STUB_FALLBACK_ERROR++ try:+ meta = json.loads(page.metadata_json or "{}")+ except (TypeError, ValueError):+ return False+ return isinstance(meta, dict) and STUB_FALLBACK_ERROR in meta+++async def _all_pages_for_reconciliation(session: object, repo_id: str) -> list:+ """Every page this repository has, for reconciling against the indexes.++ The reconciliation asks which store entries have no page behind them, so+ anything it cannot see it calls an orphan. It read the pages through+ ``list_pages(limit=10000)`` — a paginated listing helper whose ``limit``+ defaults to 100 — and treated that page-one result as the whole database.+ Every page past the 10000th was therefore invisible, and each one turned+ its vector and FTS row into a phantom orphan: on a 18900-page repository,+ 8900 of them. ``--repair`` deletes what this reports, so what it removed+ was the live index.++ A few columns rather than whole rows: the id to match against the stores,+ the content and digest for the information floor, metadata_json for the stub+ predicate, target_path to tell whether the file is excluded, and+ freshness_status to leave tombstones out. Nothing downstream reads any other field, and hydrating full+ ORM objects for every page only to discard them is what made a cap look+ necessary in the first place.+ """+ from sqlalchemy import select++ from repowise.core.persistence.models import Page++ result = await session.execute( # type: ignore[attr-defined]+ select(+ Page.id,+ Page.content,+ Page.digest,+ Page.metadata_json,+ Page.target_path,+ Page.freshness_status,+ ).where(Page.repository_id == repo_id)+ )+ return list(result.all())+++class _SqlSide(NamedTuple):+ """The SQL ids each store is compared against."""++ sql_ids: set[str]+ vector_sql_ids: set[str]+ indexable_ids: set[str]+ vector_indexable_ids: set[str]+ stub_count: int+++async def _sql_side(session, repo_path: _DoctorPath, repo_id: str) -> _SqlSide:+ from repowise.core.persistence.information_floor import meets_information_floor++ pages = await _all_pages_for_reconciliation(session, repo_id)+ # A tombstone (its file is gone) is taken out of both indexes by update,+ # so it is never missing, and a store row still holding one is an orphan+ # `--repair` deletes. Counting it as live sent `--repair` to re-index and+ # re-embed pages for deleted files.+ pages = [p for p in pages if p.freshness_status != "tombstone"]+ # ``Page``'s primary key is the column ``id``; there is no ``page_id``+ # attribute. The old spelling raised on every run, was swallowed, and left+ # both reconciliations reporting "Could not check".+ sql_ids = {p.id for p in pages}++ # The page vector store also holds decision embeddings under the+ # "decision:<id>" namespace, so they belong on the SQL side of the ORPHAN+ # check (but NOT FTS, which only indexes pages). They are deliberately+ # excluded from the MISSING check: a decision can legitimately have no+ # vector (empty match text, swallowed embed failure) and repair cannot+ # re-embed it, so flagging it would be permanent noise.+ vector_sql_ids = sql_ids | await _decision_vector_ids(session, repo_id)++ # MISSING side only, both exclusions below:+ # - A page below the information floor is held out of both indexes on+ # purpose, and `--repair` applies the same rule and declines, so+ # reporting it would be permanent noise. A stored vector for a page now+ # below the floor stays on the ORPHAN side: deleting it is a real repair.+ # - A page whose FILE the user excluded is absent because they asked for+ # that; `--repair`'s only remedy would index excluded content. Every other+ # read path filters here too (`core/exclusion.py` documents why: rows+ # outlive an `exclude_patterns` edit by design). Matched on the FILE: a+ # symbol page's target_path is `path::Name`, which no file pattern+ # matches. Deleting store entries for newly-excluded files would make+ # `--repair` delete on a rules edit, too sharp an edge to add here.+ exclude_spec = build_exclude_spec(repo_path)+ indexable_ids = {+ p.id+ for p in pages+ if meets_information_floor(p.content or "", digest=p.digest or "")+ and not is_excluded((p.target_path or "").split("::", 1)[0], exclude_spec)+ }+ # A stub standing in for a failed model page is held out of the vector+ # store on purpose: ``_seed_resume`` reads the store back as the ledger of+ # pages already written, so a vector here would tell the next+ # ``init --resume`` there is nothing left to write, and ``--repair`` would+ # embed the stub and quietly burn the retry. FTS still indexes the stub, so+ # this is the vector side only, and only MISSING.+ stub_ids = {p.id for p in pages if _is_stub_fallback_row(p)}+ return _SqlSide(+ sql_ids, vector_sql_ids, indexable_ids, indexable_ids - stub_ids, len(stub_ids)+ )+++async def _vector_ids(lance_dir: _DoctorPath) -> tuple[set[str], str | None]:+ """``(ids, error)``; a store that cannot be opened is named, not read as empty."""+ if not lance_dir.exists():+ return set(), None+ from repowise.core.persistence.vector_store import LanceDBVectorStore+ from repowise.core.providers.embedding.base import MockEmbedder++ try:+ vs = LanceDBVectorStore(str(lance_dir), embedder=MockEmbedder())+ ids = await vs.list_page_ids()+ await vs.close()+ return ids, None+ except Exception as exc:+ from repowise.core.persistence.vector_store.lancedb_store import store_open_fix_hint++ return set(), f"{type(exc).__name__}: {exc}; to fix: {store_open_fix_hint(exc)}"+++async def _fts_ids(engine) -> set[str]:+ from repowise.core.persistence import FullTextSearch++ try:+ return await FullTextSearch(engine).list_indexed_ids()+ except Exception:+ return set()+++async def _reconcile(+ repo_path: _DoctorPath, repowise_dir: _DoctorPath+) -> tuple[StoreDrift, int, str | None]:+ """``(drift, stub_count, vector_store_error)`` across SQL, vectors and FTS."""+ from repowise.core.persistence import get_repository_by_path, get_session++ engine, sf = await open_store(repo_path)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if not repo:+ await engine.dispose()+ return StoreDrift(), 0, None+ sql = await _sql_side(session, repo_path, repo.id)++ lance_dir = repowise_dir / "lancedb"+ vs_ids, vs_error = await _vector_ids(lance_dir)+ fts_ids = await _fts_ids(engine)+ await engine.dispose()+ return (+ StoreDrift(+ # An index on disk that holds none of the indexable pages is every+ # one of them missing. Only no index at all (fast mode, nothing+ # embedded yet) has nothing to compare.+ missing_from_vector=(+ sql.vector_indexable_ids - vs_ids if lance_dir.exists() else set()+ ),+ orphaned_vector=vs_ids - sql.vector_sql_ids,+ missing_from_fts=sql.indexable_ids - fts_ids if fts_ids else set(),+ orphaned_fts=fts_ids - sql.sql_ids if fts_ids else set(),+ vector_store_empty=lance_dir.exists() and vs_error is None and not vs_ids,+ ),+ sql.stub_count,+ vs_error,+ )+++def _drift_detail(missing: set[str], orphaned: set[str]) -> tuple[bool, str]:+ ok = not missing and not orphaned+ return ok, "in sync" if ok else f"{len(missing)} missing, {len(orphaned)} orphaned"+++def _consistency_rows(ctx: CheckContext) -> list[DoctorCheck]:+ """Sets ``ctx.drift`` for ``--repair``."""+ rows: list[DoctorCheck] = []+ try:+ ctx.drift, stub_count, vector_store_error = run_async(+ _reconcile(ctx.repo_path, ctx.repowise_dir)+ )+ drift = ctx.drift+ if vector_store_error is not None:+ rows.append(+ _check(+ "Vector store",+ False,+ f"cannot open .repowise/lancedb ({vector_store_error}); semantic "+ "search is off until it opens, then run `repowise reindex`",+ )+ )+ vec_ok, vec_detail = _drift_detail(drift.missing_from_vector, drift.orphaned_vector)+ # Held-back stubs are not drift, but the wiki has a page there no model+ # wrote, so say so rather than letting "in sync" imply it is complete.+ # Name the command: `--resume` exists only on `init`.+ if stub_count:+ vec_detail += f" · {stub_count} stub(s) awaiting `repowise init --resume`"+ rows.append(_check("SQL ↔ Vector Store", vec_ok, vec_detail))+ fts_ok, fts_detail = _drift_detail(drift.missing_from_fts, drift.orphaned_fts)+ rows.append(_check("SQL ↔ FTS Index", fts_ok, fts_detail))+ except Exception as exc:+ # Name the failure. "Could not check" is reported as OK, so a+ # reconciliation that raises on every run would look exactly like one+ # that had nothing to reconcile.+ rows.append(+ _check("Store consistency", True, f"Could not check: {type(exc).__name__}: {exc}")+ )+ return rows+++async def _decision_aware_drift(session, repo_path: _DoctorPath, result: dict, vector_store):+ """Recompute the coordinator's drift with decisions counted on the SQL side.++ The vector store also holds decision embeddings ("decision:<id>"), so+ without this every decision reads as drift. Only decisions that actually+ have a vector count: one can legitimately be unembedded, and counting it+ would bias drift positive (SQL > Vector) forever.+ """+ from repowise.core.persistence import get_repository_by_path++ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return+ dec_ids = await _decision_vector_ids(session, repo.id)+ decision_count = len(dec_ids)+ if vector_store is not None:+ with contextlib.suppress(Exception):+ store_ids = await vector_store.list_page_ids()+ decision_count = len(dec_ids & store_ids)+ sql_pages = result.get("sql_pages")+ vector_count = result.get("vector_count")+ if sql_pages is not None:+ adjusted_sql = sql_pages + decision_count+ result["sql_pages"] = adjusted_sql+ if vector_count is not None and vector_count != -1:+ result["drift"] = abs(adjusted_sql - vector_count) / max(adjusted_sql, 1)+++async def _coordinator_health(repo_path: _DoctorPath, repowise_dir: _DoctorPath) -> dict:+ from repowise.core.persistence import get_session+ from repowise.core.persistence.coordinator import AtomicStorageCoordinator+ from repowise.core.persistence.vector_store import LanceDBVectorStore+ from repowise.core.providers.embedding.base import MockEmbedder++ engine, sf = await open_store(repo_path)+ vector_store = None+ lance_dir = repowise_dir / "lancedb"+ if lance_dir.exists():+ with contextlib.suppress(Exception):+ vector_store = LanceDBVectorStore(str(lance_dir), embedder=MockEmbedder())++ async with get_session(sf) as session:+ coord = AtomicStorageCoordinator(session, graph_builder=None, vector_store=vector_store)+ result = await coord.health_check()+ await _decision_aware_drift(session, repo_path, result, vector_store)++ if vector_store is not None:+ with contextlib.suppress(Exception):+ await vector_store.close()+ await engine.dispose()+ return result+++def _drift_color(drift: float | None) -> str:+ if drift is None:+ return "white"+ if drift < 0.05:+ return "green"+ if drift < 0.15:+ return "yellow"+ return "red"+++def _coordinator_row(ctx: CheckContext) -> DoctorCheck:+ """Sets ``ctx.coord_drift_color``/``pct``, which the table highlights."""+ try:+ result = run_async(_coordinator_health(ctx.repo_path, ctx.repowise_dir))+ sql_pages = result.get("sql_pages")+ vector_count = result.get("vector_count")+ drift = result.get("drift")++ drift_pct = f"{drift * 100:.1f}%" if drift is not None else "N/A"+ drift_color = _drift_color(drift)+ vec_display = (+ str(vector_count) if vector_count != -1 and vector_count is not None else "unknown"+ )+ detail = f"SQL={sql_pages}, Vector={vec_display}, Drift={drift_pct}"+ row = _check("Coordinator drift", drift is None or drift < 0.05, detail)+ ctx.coord_drift_color = drift_color+ ctx.coord_drift_pct = drift_pct+ return row+ except Exception as exc:+ return _check("Coordinator drift", True, f"Could not check: {exc}")+++def store_checks(ctx: CheckContext) -> list[DoctorCheck]:+ """Checks 8-10, in order. Fills ``ctx.drift`` and the drift highlight."""+ checks: list[DoctorCheck] = []+ if ctx.db_ok and ctx.page_count > 0:+ checks.extend(_consistency_rows(ctx))+ if ctx.db_ok:+ checks.append(_coordinator_row(ctx))+ return checksdiff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_render.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_render.pynew file mode 100644index 000000000..0487d7a5d--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_render.py@@ -0,0 +1,37 @@+"""The doctor table and the pass/fail summary printed after it."""++from __future__ import annotations++from rich.table import Table++from repowise.cli.helpers import console++from ._checks.context import CheckContext+from ._types import DoctorCheck, _status_markup+from .advisories import _advise_claude_md_stamp+++def render_checks(ctx: CheckContext, checks: list[DoctorCheck], all_ok: bool) -> None:+ # The "Coordinator drift" row's detail gets its drift percentage colored+ # here, since that highlight is orthogonal to the row's own OK/FAIL status.+ table = Table(title=f"repowise Doctor — {ctx.repo_path.name}")+ table.add_column("Check", style="cyan")+ table.add_column("Status")+ table.add_column("Detail")+ pct, color = ctx.coord_drift_pct, ctx.coord_drift_color+ for c in checks:+ detail = c.detail+ if c.name == "Coordinator drift":+ detail = detail.replace(f"Drift={pct}", f"Drift=[{color}]{pct}[/{color}]")+ table.add_row(c.name, _status_markup(c.ok), detail)+ console.print(table)++ # CLAUDE.md freshness stamp: advisory, never fails the run. If editor-file+ # regeneration stops, the stamp freezes while the index moves on and agents+ # reading the stale "Last indexed" line distrust the tools.+ _advise_claude_md_stamp(ctx.repo_path, ctx.state)++ if all_ok:+ console.print("[bold green]All checks passed![/bold green]")+ else:+ console.print("[bold yellow]Some checks failed.[/bold yellow]")diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_repair.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_repair.pynew file mode 100644index 000000000..aa938ba7a--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_repair.py@@ -0,0 +1,217 @@+"""``repowise doctor --repair``: store drift, agent refresh, Claude Code re-registration."""++from __future__ import annotations++from pathlib import Path as _DoctorPath++from repowise.cli.helpers import console, run_async++from ._checks.context import CheckContext, StoreDrift, open_store+from ._checks.providers import _stale_page_guidance+++async def _repair_fts(engine, sf, drift: StoreDrift) -> int:+ """Re-index missing pages and delete orphans; returns entries repaired."""+ from repowise.core.persistence import FullTextSearch, get_session++ fts = FullTextSearch(engine)+ try:+ await fts.ensure_index()+ except Exception as exc:+ # The schema upgrade is not what was asked for, and it must not take+ # the repair down with it: it once refused on a drifted store with an+ # error telling the user to run this very command (issue #1309). Both+ # repairs below work on either column set, so say so and carry on.+ console.print(f" [yellow]Full-text index upgrade skipped: {exc}[/yellow]")+ repaired = 0+ # Orphans first, deliberately. Deleting one needs only its page_id, so it+ # works on any column set this class has ever written; re-indexing writes+ # every column and would raise there, taking the runnable repair with it.+ if drift.orphaned_fts:+ # One transaction for the lot: per-id deletes cost a write lock each.+ await fts.delete_many(list(drift.orphaned_fts))+ repaired += len(drift.orphaned_fts)+ if drift.missing_from_fts:+ async with get_session(sf) as session:+ from sqlalchemy import select++ from repowise.core.persistence.models import Page++ rows = await session.execute(+ select(Page).where(Page.id.in_(list(drift.missing_from_fts)))+ )+ # ORM rows key on ``id``, not ``page_id``, so they go to+ # index_many as tuples rather than to index_pages.+ batch = [+ (p.id, p.title, p.content, p.summary, p.target_path, p.digest)+ for p in rows.scalars().all()+ ]+ await fts.index_many(batch)+ repaired += len(batch)+ return repaired+++def _announce_embedding(drift: StoreDrift, embedder_name: str) -> bool:+ """Say what a re-embed will cost; True when doctor should leave it to reindex.++ A hosted embedder here is a charge on a command people run to diagnose,+ not to spend. It is bounded by the missing pages, not the wiki, unless the+ store is empty.+ """+ missing = drift.missing_from_vector+ reindex_instead = bool(missing) and embedder_name != "mock" and drift.vector_store_empty+ if reindex_instead:+ console.print(+ f" [yellow]The vector store is empty: {len(missing)} "+ f"page(s) need embedding with {embedder_name}. Not starting a "+ "paid re-embed of the whole wiki from doctor; run "+ "`repowise reindex` to do it.[/yellow]"+ )+ elif missing and embedder_name != "mock":+ console.print(+ f" [dim]Embedding {len(missing)} missing page(s) with {embedder_name}.[/dim]"+ )+ return reindex_instead+++async def _embed_missing(sf, vs, missing: set[str]):+ """Yield once per page embedded, so a later failure keeps the count so far."""+ from sqlalchemy import select++ from repowise.core.persistence import get_session+ from repowise.core.persistence.models import Page+ from repowise.core.persistence.vector_store import embed_item++ async with get_session(sf) as session:+ rows = await session.execute(select(Page).where(Page.id.in_(list(missing))))+ for page in rows.scalars().all():+ if not (page.title or "").strip():+ # A vector no search can reach by name is not a repair; leave+ # the page reported as missing.+ console.print(f" [yellow]Skipped {page.id}: no title to index it by.[/yellow]")+ continue+ # Same recipe as generation and ``reindex``, so a repaired page is+ # comparable with its neighbours.+ item = embed_item(+ page.id,+ title=page.title,+ page_type=page.page_type or "",+ target_path=page.target_path or "",+ summary=page.summary or "",+ content=page.content or "",+ page_metadata=page.metadata_json,+ digest=page.digest or "",+ )+ if item is None:+ # Below the information floor, so its absence is correct. Said+ # out loud so it does not read as the repair having failed.+ console.print(f" [dim]Left out {page.id}: too thin to index.[/dim]")+ continue+ await vs.embed_and_upsert(*item)+ yield page.id+++async def _repair_vectors(sf, repo_path: _DoctorPath, drift: StoreDrift) -> int:+ """Re-embed missing pages and delete orphans; returns entries repaired."""+ repaired = 0+ try:+ from repowise.cli.providers import (+ build_embedder,+ build_vector_store,+ resolve_embedder_for_repo,+ )++ # Repair with the embedder that built this store, not a hardcoded+ # mock: writing 8-wide mock vectors into a real table makes LanceDB+ # drop it. build_vector_store refuses that combination and returns None.+ embedder_name = resolve_embedder_for_repo(repo_path)+ embedder = build_embedder(embedder_name, repo_path)+ vs = build_vector_store(_DoctorPath(repo_path), embedder)+ if vs is None:+ raise RuntimeError(+ "no embedder available that can write this store; "+ "set an embedder key and run `repowise reindex`"+ )+ reindex_instead = _announce_embedding(drift, embedder_name)+ if drift.missing_from_vector and not reindex_instead:+ async for _page_id in _embed_missing(sf, vs, drift.missing_from_vector):+ repaired += 1+ for pid in drift.orphaned_vector:+ await vs.delete(pid)+ repaired += 1+ await vs.close()+ except Exception as exc:+ console.print(f"[yellow]Vector repair skipped: {exc}[/yellow]")+ return repaired+++async def _repair_stores(ctx: CheckContext) -> int:+ engine, sf = await open_store(ctx.repo_path)+ drift = ctx.drift+ repaired = 0+ if drift.missing_from_fts or drift.orphaned_fts:+ repaired += await _repair_fts(engine, sf, drift)+ lance_dir = ctx.repowise_dir / "lancedb"+ if lance_dir.exists() and (drift.missing_from_vector or drift.orphaned_vector):+ repaired += await _repair_vectors(sf, ctx.repo_path, drift)+ await engine.dispose()+ return repaired+++def _report_store_repair(ctx: CheckContext) -> None:+ has_mismatches = ctx.drift.has_mismatches()+ if has_mismatches:+ console.print("\n[bold]Repairing store mismatches...[/bold]")+ repaired_count = run_async(_repair_stores(ctx))+ console.print(f"[bold green]Repaired {repaired_count} entries.[/bold green]")+ if ctx.stale_count:+ console.print(f"[yellow]{_stale_page_guidance(ctx.stale_counts)}[/yellow]")+ elif not ctx.registration_wedged and not ctx.agents_need_refresh:+ if ctx.stale_count:+ console.print(+ f"[yellow]No store drift to repair. "+ f"{_stale_page_guidance(ctx.stale_counts)}[/yellow]"+ )+ else:+ console.print("[green]Nothing to repair.[/green]")+++def _refresh_agents(repo_path: _DoctorPath) -> None:+ from repowise.cli.commands.agents_cmd import refresh_wired_agents++ console.print("\n[bold]Refreshing agent integrations...[/bold]")+ payload = refresh_wired_agents(repo_path)+ for agent in payload["agents"]:+ for scope, write in agent["writes"].items():+ for entry in write["files"]:+ console.print(f" {agent['id']} [{scope}]: {entry['action']} {entry['path']}")+ if not payload["changed"]:+ console.print(+ "[yellow]Nothing moved. A hook whose matcher is stale needs "+ "[bold]repowise hook rewrite install[/bold]; a damaged config file "+ "has to be fixed or removed by hand.[/yellow]"+ )+++def _reregister_claude(repo_path: _DoctorPath) -> None:+ from repowise.cli.editor_integrations.claude_config import register_with_claude_code++ fixed = register_with_claude_code(repo_path)+ if fixed:+ console.print(+ f"[bold green]Re-registered the Claude Code MCP entry ({fixed}).[/bold green]"+ )+ else:+ console.print(+ "[yellow]Could not re-register the Claude Code MCP entry; "+ "run `repowise init` to redo editor setup.[/yellow]"+ )+++def run_repair(ctx: CheckContext) -> None:+ """Store drift first, then agent integrations, then the Claude Code entry."""+ _report_store_repair(ctx)+ if ctx.agents_need_refresh:+ _refresh_agents(ctx.repo_path)+ if ctx.registration_wedged:+ _reregister_claude(ctx.repo_path)diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.pyindex a3a90574d..703c9a798 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py@@ -1,298 +1,77 @@-"""Per-repo doctor checks: store consistency, drift, distill, and repair."""+"""Per-repo doctor checks: runs the check groups in order, then render and repair.++The checks live in :mod:`._checks`, the table in :mod:`._render` and+``--repair`` in :mod:`._repair`. Names they define are re-exported here so+existing imports keep working; patch them on their defining module.+"""from __future__ import annotations-import contextlib-import functools as _functoolsfrom pathlib import Path as _DoctorPath-from rich.table import Table+from repowise.cli.helpers import console, get_repowise_dir-from repowise.cli.helpers import (- console,- db_configured,- get_db_url_for_repo,- get_repowise_dir,- load_state,- reconcile_schema_best_effort,- run_async,+from ._checks.context import CheckContext+from ._checks.core import (+ _attribution_notes_check,+ _autosync_hook_check,+ _events_config_check,+ _page_count,+ _repowise_dir_check,+ core_checks,)-from repowise.core.exclusion import build_exclude_spec, is_excluded--from ._types import DoctorCheck, _check, _status_markup-from .advisories import _advise_claude_md_stamp---async def _decision_vector_ids(session, repository_id: str) -> set[str]:- """Vector-store ids for this repo's decision records.-- Decisions are co-located in the *page* vector store under the- ``decision:<record_id>`` namespace (no separate table). The store therefore- legitimately holds page vectors *and* decision vectors, so any SQL↔vector- reconciliation must count decisions on the SQL side — otherwise every- decision embedding reads as an orphan.- """- from sqlalchemy import text as _sql_text-- from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX-- rows = await session.execute(- _sql_text("SELECT id FROM decision_records WHERE repository_id = :rid"),- {"rid": repository_id},- )- return {f"{DECISION_VECTOR_PREFIX}{r[0]}" for r in rows}---def _is_stub_fallback_row(page) -> bool:- """True when a ``Page`` row is a stub standing in for a failed model page.-- The generation-side predicate reads ``page.metadata``; the ORM row carries- the same dict as the ``metadata_json`` text column, so the marker key is- shared but the accessor is not.- """- import json-- from repowise.core.generation.models import STUB_FALLBACK_ERROR-- try:- meta = json.loads(page.metadata_json or "{}")- except (TypeError, ValueError):- return False- return isinstance(meta, dict) and STUB_FALLBACK_ERROR in meta----async def _page_count(session: object, repo_id: str) -> int:- """Count this repository's pages in SQL.-- Counted in the database rather than by measuring a fetched list. The- previous spelling took ``len()`` of a ``list_pages`` page, whose ``limit``- defaults to 100 and was passed 10000 here, so every repository with more- than 10000 pages reported exactly 10000 — a plausible-looking number that- never moves.- """- from sqlalchemy import func, select-- from repowise.core.persistence.models import Page-- result = await session.execute( # type: ignore[attr-defined]- select(func.count()).select_from(Page).where(Page.repository_id == repo_id)- )- return int(result.scalar_one())---async def _stale_page_counts(session: object, repo_id: str) -> dict[str, int]:- """Count stale pages by type without hydrating their rendered content."""- from sqlalchemy import func, select-- from repowise.core.persistence.models import Page-- result = await session.execute( # type: ignore[attr-defined]- select(Page.page_type, func.count())- .where(- Page.repository_id == repo_id,- Page.freshness_status.in_(["stale", "expired"]),- )- .group_by(Page.page_type)- )- return {str(page_type): int(count) for page_type, count in result.all()}---def _stale_page_guidance(counts: dict[str, int]) -> str:- """Describe stale work by owner and name commands that can clear it."""- from repowise.core.generation.models import MODEL_WRITTEN_PAGE_TYPES-- total = sum(counts.values())- model_written = sum(- count for page_type, count in counts.items() if page_type in MODEL_WRITTEN_PAGE_TYPES- )- structural = total - model_written- categories = []- if model_written:- categories.append(f"{model_written} model-written")- if structural:- categories.append(f"{structural} structural")-- detail = (- f"{total} stale ({', '.join(categories)}) — content no longer matches its "- "current inputs or generation selection."- )- if model_written:- detail += (- " `repowise generate --stale` is the cheaper refresh for model-written "- "pages that are still selected."- )- detail += (- " `repowise update --full` performs the authoritative reconciliation and "- "retires pages no longer selected."- )- return detail + " `--repair` only fixes store drift."---async def _all_pages_for_reconciliation(session: object, repo_id: str) -> list:- """Every page this repository has, for reconciling against the indexes.-- The reconciliation asks which store entries have no page behind them, so- anything it cannot see it calls an orphan. It read the pages through- ``list_pages(limit=10000)`` — a paginated listing helper whose ``limit``- defaults to 100 — and treated that page-one result as the whole database.- Every page past the 10000th was therefore invisible, and each one turned- its vector and FTS row into a phantom orphan: on a 18900-page repository,- 8900 of them. ``--repair`` deletes what this reports, so what it removed- was the live index.-- A few columns rather than whole rows: the id to match against the stores,- the content and digest for the information floor, metadata_json for the stub- predicate, target_path to tell whether the file is excluded, and- freshness_status to leave tombstones out. Nothing downstream reads any other field, and hydrating full- ORM objects for every page only to discard them is what made a cap look- necessary in the first place.- """- from sqlalchemy import select-- from repowise.core.persistence.models import Page-- result = await session.execute( # type: ignore[attr-defined]- select(- Page.id,- Page.content,- Page.digest,- Page.metadata_json,- Page.target_path,- Page.freshness_status,- ).where(Page.repository_id == repo_id)- )- return list(result.all())---def _provider_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:- """Report provider implementations, configuration errors, and usability.-- These are three distinct claims. In particular, an empty validation- warning list means no configured key is malformed; it does not prove that- an LLM provider will resolve for this repository.- """- checks: list[DoctorCheck] = []-- try:- from repowise.core.providers import list_providers-- providers = list_providers()- checks.append(- _check(- "Providers",- bool(providers),- f"Implementations loaded: {', '.join(providers)}",- )- )- except Exception as exc:- checks.append(_check("Providers", False, str(exc)))-- from repowise.cli.helpers import validate_provider_config-- config_warnings = validate_provider_config(repo_path=repo_path)- config_ok = not config_warnings- config_detail = "No misconfigured provider keys" if config_ok else "; ".join(config_warnings)- checks.append(_check("Provider config", config_ok, config_detail))-- from repowise.core.providers.llm.registry import provider_available_for_repo-- llm_available = provider_available_for_repo(repo_path)- llm_detail = (- "Resolves for this repository"- if llm_available- else "None configured — prose degrades to a structural wiki; set a key or pass --provider"- )- # Keyless operation is supported, so this is informational rather than a- # failing health check. The detail tells users what init will actually do.- checks.append(_check("LLM provider", True, llm_detail))- return checks---def _repowise_dir_check(repowise_dir: _DoctorPath) -> DoctorCheck:- """Exists and writable, probed with a real file: os.access lies on Windows."""- if not repowise_dir.exists():- return _check(".repowise/ directory", False, f"{repowise_dir} (run 'repowise init')")- probe = repowise_dir / ".doctor-write-probe"- try:- probe.write_text("", encoding="utf-8")- probe.unlink()- except OSError as exc:- return _check(- ".repowise/ directory",- False,- f"{repowise_dir} is not writable ({exc.strerror or exc}); fix its permissions",- )- return _check(".repowise/ directory", True, str(repowise_dir))---def _autosync_hook_check(repo_path: _DoctorPath) -> DoctorCheck:- """Report the post-commit hook through hooks.status, which asks git for the- real hooks directory, so worktrees and core.hooksPath read correctly."""- try:- from repowise.cli.hooks import status as _hook_status-- state = _hook_status(repo_path)- except Exception as exc:- return _check("Post-commit hook", True, f"could not read hook state ({exc})")- if state.startswith("installed"):- return _check("Post-commit hook", True, state)- if state == "not installed":- return _check(- "Post-commit hook",- True,- "not installed; the index updates only when you run 'repowise update' "- "('repowise hook install' turns auto-sync on)",- )- return _check("Post-commit hook", True, state)---def _attribution_notes_check(repo_path: _DoctorPath) -> DoctorCheck | None:- """At ``attribution.capture: notes``, whether notes travel with the repo.-- None at every other level. Notes reach teammates only through a fetch- refspec and an explicit push, and survive a rebase only via- ``notes.rewriteRef``; without them coverage is silently low elsewhere.- """- name = "Attribution notes"- try:- from repowise.core.attribution import load_attribution_settings-- if load_attribution_settings(repo_path).capture != "notes":- return None- from repowise.core.edit_capture.notes import FETCH_REFSPEC, NOTES_REF, refspec_status-- status = refspec_status(_DoctorPath(repo_path))- except OSError as exc:- return _check(name, True, f"could not read git config ({exc})")- if not status["remote"]:- return _check(name, True, "no origin remote, so notes stay on this machine")- push = (- "push refspec set"- if status["push"]- else f"share them with 'git push origin {NOTES_REF}'"- )- problems = []- if not status["fetch"]:- problems.append(f"run 'git config --add remote.origin.fetch \"{FETCH_REFSPEC}\"'")- if not status["rewrite_ref"]:- problems.append(f"run 'git config --add notes.rewriteRef {NOTES_REF}'")- if problems:- return _check(name, False, "; ".join([*problems, push]))- return _check(name, True, f"fetch refspec and notes.rewriteRef set; {push}")---def _events_config_check(repo_path: _DoctorPath) -> DoctorCheck | None:- """The ``events:`` block, when it has values that fell back to defaults."""- try:- from repowise.core.events.store import load_event_settings-- errors = load_event_settings(repo_path).errors- except Exception as exc:- return _check("Events config", True, f"could not read it ({exc})")- if not errors:- return None- return _check("Events config", False, "; ".join(errors) + " (defaults used)")+from ._checks.integrations import (+ _agent_target_checks,+ _claude_json_entries,+ _claude_registration_check,+ _distill_checks,+ _mcp_responds_check,+ _registered_mcp_entry,+ _registers_repo,+ _registration_target,+ _unregistered_detail,+ integration_checks,+)+from ._checks.providers import (+ _provider_checks,+ _stale_page_counts,+ _stale_page_guidance,+ provider_checks,+)+from ._checks.stores import (+ _all_pages_for_reconciliation,+ _decision_vector_ids,+ _is_stub_fallback_row,+ store_checks,+)+from ._render import render_checks+from ._repair import run_repair+from ._types import DoctorCheck++__all__ = [+ "_agent_target_checks",+ "_all_pages_for_reconciliation",+ "_attribution_notes_check",+ "_autosync_hook_check",+ "_claude_json_entries",+ "_claude_registration_check",+ "_decision_vector_ids",+ "_distill_checks",+ "_events_config_check",+ "_is_stub_fallback_row",+ "_mcp_responds_check",+ "_page_count",+ "_provider_checks",+ "_registered_mcp_entry",+ "_registers_repo",+ "_registration_target",+ "_repowise_dir_check",+ "_run_repo_checks",+ "_stale_page_counts",+ "_stale_page_guidance",+ "_unregistered_detail",+ "console",+]def _run_repo_checks(@@ -306,1111 +85,16 @@ def _run_repo_checks(is also skipped; callers must not pass ``repair=True`` with anon-table format)."""+ ctx = CheckContext(repo_path=repo_path, repowise_dir=get_repowise_dir(repo_path))checks: list[DoctorCheck] = []-- # 1. Git repository?- try:- import git as gitpython-- gitpython.Repo(repo_path, search_parent_directories=True)- checks.append(_check("Git repository", True, str(repo_path)))- except Exception:- checks.append(_check("Git repository", False, "Not a git repo"))-- # 2. .repowise/ exists and takes a write? The MCP server refuses to start- # on a directory it cannot write, so an existence-only row would say OK- # for the one state that makes every tool call fail.- repowise_dir = get_repowise_dir(repo_path)- checks.append(_repowise_dir_check(repowise_dir))-- # 2b. Post-commit auto-sync hook. init installs it by default; not having- # it is a choice (--no-hook), so its absence is informational, not a fail.- checks.append(_autosync_hook_check(repo_path))- notes_check = _attribution_notes_check(repo_path)- if notes_check is not None:- checks.append(notes_check)- events_check = _events_config_check(repo_path)- if events_check is not None:- checks.append(events_check)-- # 3. Database connectable?- db_path = repowise_dir / "wiki.db"- probed = db_path.exists() or db_configured()- db_ok = False- page_count = 0- if probed:- try:-- async def _check_db():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_repository_by_path,- get_session,- )-- url = get_db_url_for_repo(repo_path)- # So doctor reports the store's real state rather than a- # `no such column` failure on a store one repowise older.- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)- count = 0- async with get_session(sf) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo:- count = await _page_count(session, repo.id)- await engine.dispose()- return count-- page_count = run_async(_check_db())- db_ok = True- except Exception as e:- checks.append(_check("Database", False, str(e)))- if db_ok:- checks.append(_check("Database", True, f"{page_count} pages"))- elif not probed:- checks.append(_check("Database", False, "wiki.db not found"))-- # 4. state.json valid?- state = load_state(repo_path)- state_ok = bool(state)- checks.append(- _check(- "state.json",- state_ok,- f"last_sync: {(state.get('last_sync_commit') or '—')[:8]}"- if state_ok- else "Not found or empty",- )- )-- # 4b. Store-format capability: does this store predate a capability the- # current build offers? A REINDEX_RECOMMENDED migration never auto-runs, so- # doctor is where an un-upgraded store learns a re-index is available. It is- # reported OK, not FAIL: the store works degraded, it is not broken, and- # failing every pre-upgrade store's doctor run would cry wolf. The row- # carries the exact command so the recommendation is actionable here even- # when the once-per-store update nag has already been shown and suppressed.- if state_ok:- try:- from repowise.cli.upgrade import assess_store-- verdict = assess_store(repo_path)- if verdict.reindex_recommended and verdict.reindex_command:- notice = verdict.user_notice or "A re-index adds new capabilities."- checks.append(- _check("Store format", True, f"{notice} Run: {verdict.reindex_command}")- )- else:- checks.append(_check("Store format", True, "Current"))- except Exception as e:- checks.append(_check("Store format", True, f"Could not check: {e}"))-- # 5-6. Provider implementations, configuration, and repo-level usability.- checks.extend(_provider_checks(repo_path))-- # 6b. Hosted account (informational: signed out is not a failure).- try:- from repowise.cli.platform import auth, credentials-- creds = credentials.load()- if creds is None:- checks.append(- _check(- "Hosted account",- True,- "Not signed in (optional: repowise login). "- "Publish this repo free: repowise publish",- )- )- elif creds.get("stale"):- checks.append(- _check("Hosted account", False, "Session expired or revoked; run repowise login")- )- else:- account = auth.fetch_account()- cached = (account or creds.get("account") or {}) or {}- who = cached.get("github_username") or cached.get("email") or "unknown"- tier = cached.get("tier") or "free"- suffix = "" if account else " (offline, using cached identity)"- checks.append(_check("Hosted account", True, f"{who} ({tier}){suffix}"))- except Exception as e:- checks.append(_check("Hosted account", False, str(e)))-- # 7. Stale page count- stale_count = 0- stale_counts: dict[str, int] = {}- if db_ok and page_count > 0:- try:-- async def _check_stale():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_repository_by_path,- get_session,- )-- url = get_db_url_for_repo(repo_path)- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)- async with get_session(sf) as session:- repo = await get_repository_by_path(session, str(repo_path))- if repo:- counts = await _stale_page_counts(session, repo.id)- await engine.dispose()- return counts- await engine.dispose()- return {}-- stale_counts = run_async(_check_stale())- stale_count = sum(stale_counts.values())- if stale_count:- checks.append(- _check(- "Stale pages",- False,- _stale_page_guidance(stale_counts),- )- )- else:- checks.append(_check("Stale pages", True, "0 stale"))- except Exception:- checks.append(_check("Stale pages", True, "Could not check"))-- # 8-9. Three-store consistency (SQL vs Vector Store vs FTS)- missing_from_vector: set[str] = set()- orphaned_vector: set[str] = set()- missing_from_fts: set[str] = set()- orphaned_fts: set[str] = set()- # An index on disk holding no vectors at all. Repairing that is a whole- # reindex, which doctor does not start on a hosted embedder unasked.- vector_store_empty = False-- if db_ok and page_count > 0:- try:-- async def _check_stores():- from repowise.core.persistence import (- FullTextSearch,- create_engine,- create_session_factory,- get_repository_by_path,- get_session,- )- from repowise.core.persistence.information_floor import (- meets_information_floor,- )- from repowise.core.persistence.vector_store import (- LanceDBVectorStore,- )- from repowise.core.providers.embedding.base import MockEmbedder-- url = get_db_url_for_repo(repo_path)- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)-- # Get all SQL page IDs- async with get_session(sf) as session:- repo = await get_repository_by_path(session, str(repo_path))- if not repo:- await engine.dispose()- return set(), set(), set(), set(), 0, None, False- pages = await _all_pages_for_reconciliation(session, repo.id)- # A tombstone (its file is gone) is taken out of both- # indexes by update, so it is never missing, and a store- # row still holding one is an orphan `--repair` deletes.- # Counting it as live sent `--repair` to re-index and- # re-embed pages for deleted files.- pages = [p for p in pages if p.freshness_status != "tombstone"]- sql_ids = {p.id for p in pages}- # ``Page``'s primary key is the column ``id``; there is no- # ``page_id`` attribute. The old spelling raised here on- # every run, was swallowed below, and left both store- # reconciliations reporting "Could not check" — so neither- # drift was ever detected and --repair never had anything- # to repair. The FTS repair block had the same defect and- # was fixed; this half was missed.-- # The page vector store also holds decision embeddings under- # the "decision:<id>" namespace, so they belong on the SQL- # side of the ORPHAN check (but NOT FTS, which only indexes- # pages). They are deliberately excluded from the MISSING- # check: a decision can legitimately have no vector (empty- # match text, swallowed embed failure) and repair cannot- # re-embed it, so flagging it would be permanent noise.- vector_sql_ids = sql_ids | await _decision_vector_ids(session, repo.id)- # A page below the information floor is held out of both- # indexes on purpose, so its absence is the correct state- # and not drift. Without this it is reported missing on- # every run and ``--repair`` cannot fix it, because the- # repair applies the same rule and declines — the same- # permanent-noise argument the decision namespace is- # excluded for, one line above. It stays on the ORPHAN- # side: a stored vector for a page now below the floor is- # real drift, and deleting it is a repair that works.- # A page whose FILE the user excluded is absent from both- # indexes because they asked for that, so reporting it as- # missing is drift no action can clear: `--repair`'s only- # remedy is to index content they excluded. Every other read- # path already filters here — `filter_graph_nodes`,- # `_node_id_is_excluded`, `_prose_symbols` — and- # `core/exclusion.py` documents why: rows outlive an- # `exclude_patterns` edit by design, so readers filter rather- # than force a reindex. This check was the one reader that did- # not, and on a repo excluding its generated sources that was- # 5015 of 5049 reported-missing rows.- #- # Matched on the FILE: a symbol page's target_path is- # `path::Name`, which no file pattern matches. Same split- # `_node_id_is_excluded` does, for the same reason.- #- # MISSING side only, like the floor and stub exclusions- # above. Whether a store entry for a newly-excluded file is- # itself drift worth deleting is a separate question, and- # answering it here would make `--repair` delete on a rules- # edit — too sharp an edge to add in passing.- exclude_spec = build_exclude_spec(repo_path)- indexable_ids = {- p.id- for p in pages- if meets_information_floor(p.content or "", digest=p.digest or "")- and not is_excluded(- (p.target_path or "").split("::", 1)[0], exclude_spec- )- }- # A stub standing in for a failed model page is held out of- # the vector store on purpose: ``_seed_resume`` reads the- # store back as the ledger of pages already written, so a- # vector here is what would tell the next ``init --resume``- # there is nothing left to write. Reporting it as drift sent- # people to ``--repair``, which embedded the stub and quietly- # burned the retry. Same permanent-noise argument as the two- # exclusions above, plus a real cost to "fixing" it. FTS- # still indexes the stub, so this applies to the vector side- # only, and only to MISSING — a leftover vector for a page- # that has since become a stub is real drift worth deleting.- stub_ids = {p.id for p in pages if _is_stub_fallback_row(p)}- vector_indexable_ids = indexable_ids - stub_ids-- # Check vector store- vs_ids: set[str] = set()- vs_error: str | None = None- lance_dir = repowise_dir / "lancedb"- if lance_dir.exists():- try:- embedder = MockEmbedder()- vs = LanceDBVectorStore(str(lance_dir), embedder=embedder)- vs_ids = await vs.list_page_ids()- await vs.close()- except Exception as exc:- # Named, not passed: a store that cannot be opened- # used to read as an empty one, and so as "in sync".- from repowise.core.persistence.vector_store.lancedb_store import (- store_open_fix_hint,- )-- vs_error = f"{type(exc).__name__}: {exc}; to fix: {store_open_fix_hint(exc)}"-- # An index on disk that holds none of the indexable pages is- # every one of them missing. Only no index at all (fast mode,- # nothing embedded yet) has nothing to compare.- m_vec = vector_indexable_ids - vs_ids if lance_dir.exists() else set()- o_vec = vs_ids - vector_sql_ids-- # Check FTS- fts = FullTextSearch(engine)- try:- fts_ids = await fts.list_indexed_ids()- except Exception:- fts_ids = set()- m_fts = indexable_ids - fts_ids if fts_ids else set()- o_fts = fts_ids - sql_ids if fts_ids else set()-- await engine.dispose()- empty = lance_dir.exists() and vs_error is None and not vs_ids- return m_vec, o_vec, m_fts, o_fts, len(stub_ids), vs_error, empty-- (- missing_from_vector,- orphaned_vector,- missing_from_fts,- orphaned_fts,- stub_count,- vector_store_error,- vector_store_empty,- ) = run_async(_check_stores())- if vector_store_error is not None:- checks.append(- _check(- "Vector store",- False,- f"cannot open .repowise/lancedb ({vector_store_error}); semantic "- "search is off until it opens, then run `repowise reindex`",- )- )-- vec_ok = not missing_from_vector and not orphaned_vector- vec_detail = (- "in sync"- if vec_ok- else (f"{len(missing_from_vector)} missing, {len(orphaned_vector)} orphaned")- )- # Held-back stubs are not drift, but they are also not nothing: the- # wiki has a page there that no model wrote. Say so on the same row- # rather than letting "in sync" imply the wiki is complete.- # Name the command, not just the flag. `--resume` exists only on- # `init`, so a reader who takes this advice tries `generate- # --resume` first — 0.48.0 answers "No such option '--resume'. Did- # you mean '--yes'?" — and has to guess which command was meant. A- # health report is the worst place to make someone guess.- if stub_count:- vec_detail += f" · {stub_count} stub(s) awaiting `repowise init --resume`"- checks.append(_check("SQL ↔ Vector Store", vec_ok, vec_detail))-- fts_ok = not missing_from_fts and not orphaned_fts- fts_detail = (- "in sync"- if fts_ok- else (f"{len(missing_from_fts)} missing, {len(orphaned_fts)} orphaned")- )- checks.append(_check("SQL ↔ FTS Index", fts_ok, fts_detail))- except Exception as exc:- # Name the failure. "Could not check" is reported as OK, so a- # reconciliation that raises on every run looks exactly like one- # that had nothing to reconcile — which is how a plain attribute- # error stayed hidden here across releases.- checks.append(- _check(- "Store consistency",- True,- f"Could not check: {type(exc).__name__}: {exc}",- )- )-- # 10. AtomicStorageCoordinator drift check- coord_drift: float | None = None- coord_sql_pages: int | None = None- coord_vector_count: int | None = None- coord_drift_color = "white"- coord_drift_pct = "N/A"- if db_ok:- try:-- async def _check_coordinator():- from repowise.core.persistence import (- create_engine,- create_session_factory,- get_repository_by_path,- get_session,- )- from repowise.core.persistence.coordinator import AtomicStorageCoordinator- from repowise.core.persistence.vector_store import LanceDBVectorStore- from repowise.core.providers.embedding.base import MockEmbedder-- url = get_db_url_for_repo(repo_path)- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)-- vector_store = None- lance_dir = repowise_dir / "lancedb"- if lance_dir.exists():- try:- embedder = MockEmbedder()- vector_store = LanceDBVectorStore(str(lance_dir), embedder=embedder)- except Exception:- pass-- async with get_session(sf) as session:- coord = AtomicStorageCoordinator(- session, graph_builder=None, vector_store=vector_store- )- result = await coord.health_check()-- # The coordinator's drift compares wiki_pages count against- # the vector count, but the vector store also holds decision- # embeddings ("decision:<id>" namespace). Without counting- # decisions on the SQL side, every decision reads as drift.- # Recompute drift with a decision-aware SQL count so a- # consistent store reports ~0% rather than a false FAIL.- # Count only decisions that actually have a vector: a- # decision can legitimately be unembedded (empty match- # text, swallowed embed failure), and counting it would- # bias drift positive (SQL > Vector) forever.- repo = await get_repository_by_path(session, str(repo_path))- if repo is not None:- dec_ids = await _decision_vector_ids(session, repo.id)- decision_count = len(dec_ids)- if vector_store is not None:- with contextlib.suppress(Exception):- store_ids = await vector_store.list_page_ids()- decision_count = len(dec_ids & store_ids)- sql_pages = result.get("sql_pages")- vector_count = result.get("vector_count")- if sql_pages is not None:- adjusted_sql = sql_pages + decision_count- result["sql_pages"] = adjusted_sql- if vector_count is not None and vector_count != -1:- denom = max(adjusted_sql, 1)- result["drift"] = abs(adjusted_sql - vector_count) / denom-- if vector_store is not None:- with contextlib.suppress(Exception):- await vector_store.close()- await engine.dispose()- return result-- coord_result = run_async(_check_coordinator())- coord_sql_pages = coord_result.get("sql_pages")- coord_vector_count = coord_result.get("vector_count")- coord_drift = coord_result.get("drift")-- drift_pct = f"{coord_drift * 100:.1f}%" if coord_drift is not None else "N/A"- if coord_drift is None:- drift_color = "white"- elif coord_drift < 0.05:- drift_color = "green"- elif coord_drift < 0.15:- drift_color = "yellow"- else:- drift_color = "red"-- vec_display = (- str(coord_vector_count)- if coord_vector_count != -1 and coord_vector_count is not None- else "unknown"- )- drift_detail = f"SQL={coord_sql_pages}, Vector={vec_display}, Drift={drift_pct}"- coord_ok = coord_drift is None or coord_drift < 0.05- checks.append(_check("Coordinator drift", coord_ok, drift_detail))- coord_drift_color = drift_color- coord_drift_pct = drift_pct- except Exception as exc:- checks.append(_check("Coordinator drift", True, f"Could not check: {exc}"))-- # 11. Distill — config block, omission store, rewrite hook (advisory)- checks.extend(_distill_checks(repo_path))-- # 12. Claude Code MCP registration: wedged-path detection- registration_check, registration_wedged = _claude_registration_check(repo_path)- checks.append(registration_check)-- # 12b. Does that registration actually start? Reported separately, because- # a wired-up server that dies on every invocation is a different problem- # with a different fix than one that is not wired up at all.- checks.append(_mcp_responds_check())-- # 13. Per-agent health, reported by each agent's own descriptor- agent_checks, agents_need_refresh = _agent_target_checks(repo_path)- checks.extend(agent_checks)-+ for group in (core_checks, provider_checks, store_checks, integration_checks):+ checks.extend(group(ctx))all_ok = all(c.ok for c in checks)if fmt != "table":return all_ok, checks- # Display: the "Coordinator drift" row's detail gets its drift- # percentage colored here, since that highlight is orthogonal to the- # row's own OK/FAIL status.- table = Table(title=f"repowise Doctor — {repo_path.name}")- table.add_column("Check", style="cyan")- table.add_column("Status")- table.add_column("Detail")- for c in checks:- detail = c.detail- if c.name == "Coordinator drift":- detail = detail.replace(- f"Drift={coord_drift_pct}",- f"Drift=[{coord_drift_color}]{coord_drift_pct}[/{coord_drift_color}]",- )- table.add_row(c.name, _status_markup(c.ok), detail)- console.print(table)-- # CLAUDE.md freshness stamp — advisory, never fails the run. The managed- # ".claude/CLAUDE.md" block stamps the commit it was generated against; if- # editor-file regeneration stops, the stamp freezes while the index moves- # on and agents reading the stale "Last indexed" line distrust the tools.- _advise_claude_md_stamp(repo_path, state)-- if all_ok:- console.print("[bold green]All checks passed![/bold green]")- else:- console.print("[bold yellow]Some checks failed.[/bold yellow]")-- # --repair: fix detected mismatches- has_mismatches = missing_from_fts or orphaned_fts or missing_from_vector or orphaned_vector- if repair and has_mismatches:- console.print("\n[bold]Repairing store mismatches...[/bold]")-- async def _repair():- from repowise.core.persistence import (- FullTextSearch,- create_engine,- create_session_factory,- get_session,- )-- url = get_db_url_for_repo(repo_path)- await reconcile_schema_best_effort(url)- engine = create_engine(url)- sf = create_session_factory(engine)- repaired = 0-- # Repair FTS: re-index missing pages, delete orphaned- if missing_from_fts or orphaned_fts:- fts = FullTextSearch(engine)- try:- await fts.ensure_index()- except Exception as exc:- # The schema upgrade is not what was asked for, and it must- # not take the repair down with it. It used to: the upgrade- # refused on a drifted store and the error it raised told- # the user to run this very command (issue #1309), so the- # only command that could fix the drift was the one the- # drift killed. Both repairs below work on either column- # set, so say what failed and carry on.- console.print(- f" [yellow]Full-text index upgrade skipped: {exc}[/yellow]"- )- # Orphans first, deliberately. Deleting one needs nothing but- # its page_id, so it works on any column set this class has- # ever written — including the one an upgrade just failed to- # leave behind. Re-indexing a missing page writes every column- # and would raise there, taking the repair that *can* run down- # with it.- if orphaned_fts:- # One transaction for the lot. Per-id deletes cost a write- # lock each, and the store that needs this most is the one- # with thousands of them.- await fts.delete_many(list(orphaned_fts))- repaired += len(orphaned_fts)- if missing_from_fts:- # Fetch full page data for missing pages- async with get_session(sf) as session:- from sqlalchemy import select-- from repowise.core.persistence.models import Page-- # Page's natural primary key is the column `id`; there- # is no `page_id` attribute, so the old spelling raised- # AttributeError and no repair ever ran.- rows = await session.execute(- select(Page).where(Page.id.in_(list(missing_from_fts)))- )- # ORM rows key on ``id``, not ``page_id``, so they go- # to index_many as tuples rather than to index_pages.- batch = [- (p.id, p.title, p.content, p.summary, p.target_path, p.digest)- for p in rows.scalars().all()- ]- await fts.index_many(batch)- repaired += len(batch)-- # Repair vector store: re-embed missing pages, delete orphaned- lance_dir = repowise_dir / "lancedb"- if lance_dir.exists() and (missing_from_vector or orphaned_vector):- try:- from repowise.cli.providers import (- build_embedder,- build_vector_store,- resolve_embedder_for_repo,- )-- # Repair with the embedder that built this store, not a- # hardcoded mock. The mock was chosen to avoid API costs,- # but writing its 8-wide vectors into a real table makes- # LanceDB drop the table: a repair that deletes the index- # it was asked to fix. build_vector_store refuses that- # combination and returns None, so a repo whose embedder is- # unavailable is left alone instead of wrecked.- embedder_name = resolve_embedder_for_repo(repo_path)- embedder = build_embedder(embedder_name, repo_path)- vs = build_vector_store(_DoctorPath(repo_path), embedder)- if vs is None:- raise RuntimeError(- "no embedder available that can write this store; "- "set an embedder key and run `repowise reindex`"- )- # This repair has never actually run (it raised on a column- # that does not exist), so a hosted embedder here is a new- # charge on a command people run to diagnose, not to spend.- # Say so. It is bounded by the missing pages, not the wiki.- reindex_instead = (- bool(missing_from_vector) and embedder_name != "mock" and vector_store_empty- )- if reindex_instead:- console.print(- f" [yellow]The vector store is empty: {len(missing_from_vector)} "- f"page(s) need embedding with {embedder_name}. Not starting a "- "paid re-embed of the whole wiki from doctor; run "- "`repowise reindex` to do it.[/yellow]"- )- elif missing_from_vector and embedder_name != "mock":- console.print(- f" [dim]Embedding {len(missing_from_vector)} missing "- f"page(s) with {embedder_name}.[/dim]"- )-- if missing_from_vector and not reindex_instead:- async with get_session(sf) as session:- from sqlalchemy import select-- from repowise.core.persistence.models import Page- from repowise.core.persistence.vector_store import embed_item-- rows = await session.execute(- select(Page).where(Page.id.in_(list(missing_from_vector)))- )- for page in rows.scalars().all():- if not (page.title or "").strip():- # A repair that writes an unfindable row is- # not a repair. Leave it reported as missing- # rather than filling the gap with a vector- # no search can reach by name.- console.print(- f" [yellow]Skipped {page.id}: no title to "- f"index it by.[/yellow]"- )- continue- # Same recipe as generation and ``reindex``, so a- # repaired page is comparable with its neighbours- # instead of being embedded on different terms.- item = embed_item(- page.id,- title=page.title,- page_type=page.page_type or "",- target_path=page.target_path or "",- summary=page.summary or "",- content=page.content or "",- page_metadata=page.metadata_json,- digest=page.digest or "",- )- if item is None:- # Below the information floor, so its absence- # from the store is correct and there is- # nothing to repair. Said out loud, because a- # page silently left missing by the repair- # reads as the repair having failed on it.- console.print(- f" [dim]Left out {page.id}: too thin to index.[/dim]"- )- continue- await vs.embed_and_upsert(*item)- repaired += 1-- for pid in orphaned_vector:- await vs.delete(pid)- repaired += 1-- await vs.close()- except Exception as exc:- console.print(f"[yellow]Vector repair skipped: {exc}[/yellow]")-- await engine.dispose()- return repaired-- repaired_count = run_async(_repair())- console.print(f"[bold green]Repaired {repaired_count} entries.[/bold green]")- if stale_count:- console.print(f"[yellow]{_stale_page_guidance(stale_counts)}[/yellow]")- elif repair and not has_mismatches and not registration_wedged and not agents_need_refresh:- if stale_count:- console.print(- f"[yellow]No store drift to repair. "- f"{_stale_page_guidance(stale_counts)}[/yellow]"- )- else:- console.print("[green]Nothing to repair.[/green]")-- if repair and agents_need_refresh:- from repowise.cli.commands.agents_cmd import refresh_wired_agents-- console.print("\n[bold]Refreshing agent integrations...[/bold]")- payload = refresh_wired_agents(repo_path)- for agent in payload["agents"]:- for scope, write in agent["writes"].items():- for entry in write["files"]:- console.print(f" {agent['id']} [{scope}]: {entry['action']} {entry['path']}")- if not payload["changed"]:- console.print(- "[yellow]Nothing moved. A hook whose matcher is stale needs "- "[bold]repowise hook rewrite install[/bold]; a damaged config file "- "has to be fixed or removed by hand.[/yellow]"- )-- if repair and registration_wedged:- from repowise.cli.editor_integrations.claude_config import register_with_claude_code-- fixed = register_with_claude_code(repo_path)- if fixed:- console.print(- f"[bold green]Re-registered the Claude Code MCP entry ({fixed}).[/bold green]"- )- else:- console.print(- "[yellow]Could not re-register the Claude Code MCP entry; "- "run `repowise init` to redo editor setup.[/yellow]"- )-+ render_checks(ctx, checks, all_ok)+ if repair:+ run_repair(ctx)return all_ok, checks---def _agent_target_checks(- repo_path: _DoctorPath | None = None,-) -> tuple[list[DoctorCheck], bool]:- """One row per agent, reported by that agent's own descriptor.-- Nothing here knows what any particular agent's health means: each- ``AgentTarget`` answers for itself, so a fourth agent gets a doctor row by- being registered rather than by someone adding a branch to this function.-- Only ``broken`` fails the run, and the line is drawn there on purpose.- ``not-installed`` is not a failure — an agent you do not use is not a- problem with your setup — and neither is ``stale``, which is advisory in- the same way the "Distill rewrite hook" row above it already is. A stale- matcher is common, opt-in surfaces go stale routinely, and making it fail- would turn ``repowise doctor`` non-zero in CI for a condition nobody asked- the tool to guarantee. ``broken`` means a config file is damaged, which is- a real fault in the setup being checked.-- Advisory does not mean quiet. The stale row is the reason this function- exists: a hook whose matcher names a tool the host has since renamed is- installed, parses, and will never fire, which is indistinguishable from- working unless something says so out loud. It is also the agreed mitigation- for gating the self-heal migrations on ``REPOWISE_SKIP_EDITOR_SETUP`` —- someone who exports that permanently never gets the migration, so the- staleness has to be visible somewhere. It is printed, and it drives- ``--repair``; it just does not change the exit code.-- Returns ``(checks, needs_refresh)``; ``needs_refresh`` drives ``--repair``.- """- from repowise.cli.agent_targets.registry import all_targets-- checks: list[DoctorCheck] = []- needs_refresh = False- try:- targets = all_targets()- except Exception as exc: # pragma: no cover - a broken registry is a crash elsewhere- return [_check("Agent integrations", True, f"Could not check: {exc}")], False-- for target in targets:- name = f"Agent: {target.id}"- try:- report = target.doctor(repo_path=repo_path)- except Exception as exc:- checks.append(_check(name, True, f"Could not check: {exc}"))- continue- if report.status.value in ("ok", "not-installed"):- detail = report.issues[0] if report.issues else "wired up"- checks.append(_check(name, True, detail))- continue- # Only conditions the repair pass can actually resolve drive it. A- # plugin the CLI cannot rewrite, or a fix that is a different command,- # would otherwise buy a global config write that changes nothing and- # then report advice for a condition the user does not have.- needs_refresh = needs_refresh or report.repairable- detail = "; ".join(report.issues)- if report.fix_command:- detail += f" (run: {report.fix_command})"- checks.append(_check(name, report.status.value != "broken", detail))- return checks, needs_refresh---def _registered_mcp_entry() -> dict | None:- """The Claude Code ``mcpServers.repowise`` entry, or None if there isn't one.-- Delegates to ``claude_config``, which owns reading this entry, so the two- doctor checks and the registration writer cannot drift apart on what counts- as registered. Both checks must judge the same entry: a smoke check that- launched a *different* command than the one registered would give a clean- bill of health to the broken thing.- """- from repowise.cli.editor_integrations.claude_config import (- _claude_code_settings_path,- _stored_repowise_entry,- )-- return _stored_repowise_entry(_claude_code_settings_path())---def _unregistered_detail() -> str:- """Why there is no entry: absent, or present but unreadable.-- Those have different fixes, and collapsing them tells a user with a- hand-broken settings.json to run ``init``, which will fail on the same- file. Only reached when there is no entry, so it costs nothing normally.- """- from repowise.cli.editor_integrations.claude_config import (- _claude_code_settings_path,- load_existing_config,- )-- settings_path = _claude_code_settings_path()- if settings_path.exists():- try:- load_existing_config(settings_path)- except Exception:- return f"could not parse {settings_path}"- return "not registered (repowise init registers it)"---@_functools.cache-def _mcp_responds_check() -> DoctorCheck:- """Launch the registered MCP server and complete one round trip.-- Reported separately from the registration row: registration answers "is it- wired up", this answers "does it run". An install whose server dies on- every invocation passes the first and fails this one, which is the whole- point. Absence of a registration is informational, matching- the registration check.-- Cached for the process because there is one global ``mcpServers.repowise``- entry and this takes no repo argument, while workspace mode runs the repo- checks once per entry. Without the cache a ten-repo workspace would launch- the same server ten times and pay the startup cost for each.- """- from .mcp_smoke import CHECK_NAME, mcp_smoke_check-- try:- entry = _registered_mcp_entry()- if entry is None:- return _check(CHECK_NAME, True, "not registered - nothing to launch")- command = entry.get("command")- args = entry.get("args")- if not isinstance(command, str) or not isinstance(args, list):- return _check(CHECK_NAME, True, "registration is hand-shaped - not launching it")- return mcp_smoke_check(command, [str(a) for a in args], entry.get("env"))- except Exception as exc: # a doctor check must never be the crash- return _check(CHECK_NAME, True, f"Could not check: {exc}")---def _claude_registration_check(- repo_path: _DoctorPath | None = None,-) -> tuple[DoctorCheck, bool]:- """Detect a wedged Claude Code MCP registration (stale paths).-- The global ``~/.claude/settings.json`` entry can end up pointing at a- directory that no longer exists (a moved repo, or a leaked temp path) or- at a pinned command binary from a deleted venv; either way the MCP- server silently fails to start in every Claude Code session. Returns- ``(check, wedged)``; ``wedged`` drives the ``--repair`` re-registration.- Absence of a registration is informational, never a failure.-- With *repo_path*, an entry serving a different repo gets an advisory note- unless another Claude Code scope registers this repo. Advisory because the- entry is not broken, and never repaired: repointing the one global entry- would break the repo it serves.-- This is a *static* check. Whether the server actually starts is- ``_mcp_responds_check``.- """- name = "Claude Code MCP entry"- try:- entry = _registered_mcp_entry()- if entry is None:- return _check(name, True, _unregistered_detail()), False-- problems: list[str] = []- command = entry.get("command")- # Bare command names resolve via PATH at session start; only a pinned- # absolute path can go stale.- if (- isinstance(command, str)- and ("/" in command or "\\" in command)- and not _DoctorPath(command).exists()- ):- problems.append(f"command not found: {command}")- target = _registration_target(entry)- if target is not None and not _DoctorPath(target).is_dir():- problems.append(f"registered path missing: {target}")- if problems:- return _check(name, False, "; ".join(problems) + " (rerun with --repair)"), True- if target is not None and repo_path is not None and not _registers_repo(target, repo_path):- detail = (- f"serves {target}; this repo is not registered (run `repowise agents add "- "--target=claude-code --scope=project` for a project entry)"- )- return _check(name, True, detail), False- return _check(name, True, target or "registered"), False- except Exception as exc:- return _check(name, True, f"Could not check: {exc}"), False---def _registers_repo(target: str, repo_path: _DoctorPath) -> bool:- """Whether Claude Code serves *repo_path* from the global entry or another scope.-- The global *target* counts when it is what init registers for this repo- (the workspace root inside a workspace). Otherwise a repowise entry naming- this repo in ``.mcp.json`` (project scope) or ``~/.claude.json`` (user or- local scope) counts; one copied from another repo does not.- """- from repowise.cli.agent_targets.targets.claude_code import project_mcp_config_path- from repowise.cli.editor_integrations.claude_config import (- _resolve_mcp_target,- _stored_repowise_entry,- )- from repowise.cli.helpers import _same_path-- served = (repo_path, _resolve_mcp_target(repo_path))-- def serves(path: str) -> bool:- # Claude Code starts a project server in the repo, so a relative path- # is relative to it.- return any(_same_path(repo_path / path, s) for s in served)-- def names_repo(entry: object) -> bool:- path = _registration_target(entry) if isinstance(entry, dict) else None- return path is not None and serves(path)-- if serves(target):- return True- other_scopes = [- _stored_repowise_entry(project_mcp_config_path(repo_path)),- *_claude_json_entries(repo_path),- ]- return any(names_repo(e) for e in other_scopes)---def _claude_json_entries(repo_path: _DoctorPath) -> list[object]:- """Repowise entries in ``~/.claude.json``: user scope, then this repo's local scope.-- Read here only, best effort: an unreadable file yields nothing, so the- worst case is the advisory note above.- """- import json-- from repowise.cli.helpers import _same_path-- try:- data = json.loads((_DoctorPath.home() / ".claude.json").read_text(encoding="utf-8"))- except (OSError, ValueError):- return []- if not isinstance(data, dict):- return []- scopes = [data]- projects = data.get("projects")- if isinstance(projects, dict):- scopes += [- v- for k, v in projects.items()- if isinstance(v, dict) and _same_path(_DoctorPath(k), repo_path)- ]- entries: list[object] = []- for scope in scopes:- servers = scope.get("mcpServers")- if isinstance(servers, dict) and "repowise" in servers:- entries.append(servers["repowise"])- return entries---def _registration_target(entry: dict) -> str | None:- """The repo/workspace path a registration serves, or None if unrecognized.-- Registrations are shaped ``args: ["mcp", "<abs path>", "--transport",- "stdio"]``; the target sits right after ``mcp``. Anything else (a flag- in that slot, a hand-edited entry) returns None rather than guessing.- """- args = entry.get("args")- if not isinstance(args, list) or args[:1] != ["mcp"] or len(args) < 2:- return None- target = args[1]- if isinstance(target, str) and not target.startswith("-"):- return target- return None---def _distill_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:- """Distill feature health: config validity, store sizing, rewrite hook.-- The rewrite hook is opt-in, so its absence is informational, never a- failure. Any unexpected error degrades to an advisory OK row — distill- problems must not break doctor.- """- checks: list[DoctorCheck] = []-- # Config block valid?- distill_cfg = None- try:- from repowise.core.repo_config import load_repo_config-- distill_cfg = load_repo_config(repo_path).get("distill")- from repowise.core.distill.config import validate_distill_config-- problems = validate_distill_config(distill_cfg)- if problems:- checks.append(_check("Distill config", False, "; ".join(problems)))- else:- checks.append(- _check("Distill config", True, "valid" if distill_cfg else "defaults (no block)")- )- except Exception as exc:- checks.append(_check("Distill config", True, f"Could not check: {exc}"))-- # Omission store sizing (TTL + cap are pruned opportunistically on write,- # so a store far past its cap means pruning is not keeping up).- try:- from repowise.core.distill.config import omission_store_settings-- _ttl_days, max_mb = omission_store_settings(distill_cfg)- db_path = repo_path / ".repowise" / "omissions" / "omissions.db"- if not db_path.is_file():- checks.append(_check("Omission store", True, "not created yet"))- else:- size_bytes = db_path.stat().st_size- wal = db_path.with_name(db_path.name + "-wal")- if wal.is_file():- size_bytes += wal.stat().st_size- size_mb = size_bytes / (1024 * 1024)- ok = size_mb <= max_mb * 1.5 # WAL slack before checkpointing- detail = f"{size_mb:.1f} MB (cap {max_mb:g} MB)"- if not ok:- detail += " — over cap; pruning happens on the next distill write"- checks.append(_check("Omission store", ok, detail))- except Exception as exc:- checks.append(_check("Omission store", True, f"Could not check: {exc}"))-- # Rewrite hook (advisory: strictly opt-in).- try:- from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter- from repowise.cli.agent_adapters.codex import CodexAdapter-- surfaces = [("claude-code", ClaudeCodeAdapter())]- codex = CodexAdapter()- if codex.detect():- surfaces.append(("codex", codex))- from repowise.cli.agent_adapters.cursor import CursorAdapter-- cursor = CursorAdapter()- if cursor.detect():- surfaces.append(("cursor", cursor))- # Registered and live are different questions: an entry whose matcher- # predates a tool rename is registered and fires on some or none of- # the agent's shell tools. Say which, rather than calling all three- # "installed".- installed_names = []- for name, adapter in surfaces:- status = adapter.rewrite_hook_status()- if not status.installed:- continue- if not status.unmatched:- installed_names.append(name)- else:- misses = ", ".join(status.unmatched)- installed_names.append(f"{name} (matcher misses {misses})")- if installed_names:- commands_cfg = distill_cfg.get("commands") if isinstance(distill_cfg, dict) else None- opted_out = isinstance(commands_cfg, dict) and commands_cfg.get("enabled") is False- detail = ", ".join(installed_names)- detail += " (this repo opted out)" if opted_out else ""- detail = f"installed: {detail}"- else:- detail = "not installed (opt-in: repowise hook rewrite install)"- checks.append(_check("Distill rewrite hook", True, detail))- except Exception as exc:- checks.append(_check("Distill rewrite hook", True, f"Could not check: {exc}"))-- return checksdiff --git a/tests/unit/cli/test_doctor_check_order.py b/tests/unit/cli/test_doctor_check_order.pyindex e1db1dd21..c7f126a92 100644--- a/tests/unit/cli/test_doctor_check_order.py+++ b/tests/unit/cli/test_doctor_check_order.py@@ -16,7 +16,8 @@ from pathlib import Pathimport pytest-from repowise.cli.commands.doctor_cmd import repo_checks+from repowise.cli.commands.doctor_cmd import _render, repo_checks+from repowise.cli.commands.doctor_cmd._checks import core, integrations, providersfrom repowise.cli.commands.doctor_cmd._types import _checkfrom ._real_call_guard import guard_real_calls@@ -100,23 +101,23 @@ async def _build(def env(monkeypatch) -> dict:"""Stub machine-dependent rows and record console output in order."""st: dict = {"printed": [], "wedged": False, "refresh": False}- monkeypatch.setattr(repo_checks, "_autosync_hook_check", lambda _p: _check("<hook>", True, ""))- monkeypatch.setattr(repo_checks, "_attribution_notes_check", lambda _p: None)- monkeypatch.setattr(repo_checks, "_events_config_check", lambda _p: None)- monkeypatch.setattr(repo_checks, "_provider_checks", lambda _p: [_check("<provider>", True, "")])- monkeypatch.setattr(repo_checks, "_distill_checks", lambda _p: [_check("<distill>", True, "")])+ monkeypatch.setattr(core, "_autosync_hook_check", lambda _p: _check("<hook>", True, ""))+ monkeypatch.setattr(core, "_attribution_notes_check", lambda _p: None)+ monkeypatch.setattr(core, "_events_config_check", lambda _p: None)+ monkeypatch.setattr(providers, "_provider_checks", lambda _p: [_check("<provider>", True, "")])+ monkeypatch.setattr(integrations, "_distill_checks", lambda _p: [_check("<distill>", True, "")])monkeypatch.setattr(- repo_checks,+ integrations,"_claude_registration_check",lambda _p: (_check("<registration>", not st["wedged"], ""), st["wedged"]),)- monkeypatch.setattr(repo_checks, "_mcp_responds_check", lambda: _check("<mcp>", True, ""))+ monkeypatch.setattr(integrations, "_mcp_responds_check", lambda: _check("<mcp>", True, ""))monkeypatch.setattr(- repo_checks,+ integrations,"_agent_target_checks",lambda _p: ([_check("<agent>", not st["refresh"], "")], st["refresh"]),)- monkeypatch.setattr(repo_checks, "_advise_claude_md_stamp", lambda *_a: st["printed"].append("<stamp>"))+ monkeypatch.setattr(_render, "_advise_claude_md_stamp", lambda *_a: st["printed"].append("<stamp>"))monkeypatch.setattr("repowise.cli.platform.credentials.load", lambda: None)monkeypatch.setattr(repo_checks.console, "print", lambda *a, **_k: st["printed"].append(" ".join(map(str, a)))@@ -173,10 +174,10 @@ def test_healthy_store_rows_and_order(env, tmp_path) -> None:def test_optional_rows_slot_in_after_the_hook(env, monkeypatch, tmp_path) -> None:monkeypatch.setattr(- repo_checks, "_attribution_notes_check", lambda _p: _check("<notes>", True, "")+ core, "_attribution_notes_check", lambda _p: _check("<notes>", True, ""))monkeypatch.setattr(- repo_checks, "_events_config_check", lambda _p: _check("<events>", False, "")+ core, "_events_config_check", lambda _p: _check("<events>", False, ""))repo = asyncio.run(_build(tmp_path))names = [r[0] for r in _rows(repo)]@@ -186,7 +187,7 @@ def test_optional_rows_slot_in_after_the_hook(env, monkeypatch, tmp_path) -> Nondef test_unindexed_repo_rows(env, monkeypatch, tmp_path) -> None:import git as gitpython- monkeypatch.setattr(repo_checks, "db_configured", lambda: False)+ monkeypatch.setattr(core, "db_configured", lambda: False)repo = tmp_path / "bare"repo.mkdir()gitpython.Repo.init(repo)@@ -241,7 +242,7 @@ def test_stale_pages_row(env, monkeypatch, tmp_path) -> None:async def _stale(_s, _r):return {"file_page": 2}- monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)+ monkeypatch.setattr(providers, "_stale_page_counts", _stale)repo = asyncio.run(_build(tmp_path))ok, detail = _by_name(_rows(repo))["Stale pages"]assert ok is False@@ -308,7 +309,7 @@ def test_repair_without_drift_names_stale_pages(env, monkeypatch, tmp_path) -> Nasync def _stale(_s, _r):return {"file_page": 1}- monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)+ monkeypatch.setattr(providers, "_stale_page_counts", _stale)repo = asyncio.run(_build(tmp_path))_repair(repo)assert _texts(env)[-1].startswith("[yellow]No store drift to repair. 1 stale")@@ -341,7 +342,7 @@ def test_repair_reports_stale_after_store_repair(env, monkeypatch, tmp_path) ->async def _stale(_s, _r):return {"file_page": 1}- monkeypatch.setattr(repo_checks, "_stale_page_counts", _stale)+ monkeypatch.setattr(providers, "_stale_page_counts", _stale)repo = asyncio.run(_build(tmp_path, fts=(KEPT, GHOST)))_repair(repo)out = _texts(env)diff --git a/tests/unit/cli/test_doctor_store_reconciliation.py b/tests/unit/cli/test_doctor_store_reconciliation.pyindex 8606bf49b..e62ab29f5 100644--- a/tests/unit/cli/test_doctor_store_reconciliation.py+++ b/tests/unit/cli/test_doctor_store_reconciliation.py@@ -18,6 +18,7 @@ import asynciofrom pathlib import Pathfrom repowise.cli.commands.doctor_cmd import repo_checks+from repowise.cli.commands.doctor_cmd._checks import storesPAGE_IN_BOTH = "file_page:kept.py"PAGE_MISSING = "file_page:dropped.py"@@ -120,16 +121,16 @@ def test_a_failed_reconciliation_no_longer_passes_as_a_bare_note(tmp_path: Path)# break has to be inside this check and nowhere else — the earlier# database row shares most of the same calls, and failing that one first# means the reconciliation never runs at all.- original = repo_checks._decision_vector_ids+ original = stores._decision_vector_idsasync def _boom(*_a: object, **_kw: object):raise RuntimeError("store unreadable")- repo_checks._decision_vector_ids = _boom+ stores._decision_vector_ids = _boomtry:broken = _rows(repo_path)finally:- repo_checks._decision_vector_ids = original+ stores._decision_vector_ids = originalassert "Store consistency" in broken_ok, detail = broken["Store consistency"]