Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

perf(setup): load the Setup page in about two seconds with doctor --quick and a stale-while-revalidate cache (#4699)

Raghav Chamadiya5f6d18990f6b
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index e06b49d13..e6f4ebbb0 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2056,6 +2056,7 @@ repowise doctor --workspace --repair
| `--repair` | Rebuild FTS, re-embed missing pages, sync workspace drift, drop dead workspace entries. | off |
| `--workspace` / `-w`, `--no-workspace` | Workspace table (dir exists, git repo, state.json ↔ config drift) then per-repo checks / single repo. | auto-detect |
| `--format` | `table` or `json`. | `table` |
+| `--quick` | Skip the slow checks: starting the MCP server (`mcp-responds`) and reconciling the vector and full-text stores (`vector-store-sync`, `fts-index-sync`, `coordinator-drift`). Not with `--repair`. | off |
- **`--format json`** prints `{"ok": bool, "checks": [...]}`. Each check carries a stable `id` (kebab case, such as
`post-commit-hook` or `mcp-responds`), a display `name`, a `level` (`ok`, `warn` or `fail`), `ok` (false only for
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.py
index d0de70238..001fe82d4 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/context.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/context.py
@@ -35,6 +35,10 @@ class CheckContext:
repo_path: Path
repowise_dir: Path
+ # ``doctor --quick``: skip starting the MCP server and reconciling the
+ # stores, the two checks that take seconds. The web Setup page runs this
+ # on every load and the full set in the background.
+ quick: bool = False
db_ok: bool = False
page_count: int = 0
state: dict = field(default_factory=dict)
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py
index 4374f4edd..010790340 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/integrations.py
@@ -17,7 +17,8 @@ def integration_checks(ctx: CheckContext) -> list[DoctorCheck]:
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())
+ if not ctx.quick:
+ 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)
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py
index 3b780b9f4..24f106299 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/_checks/stores.py
@@ -380,6 +380,8 @@ def _coordinator_row(ctx: CheckContext) -> DoctorCheck:
def store_checks(ctx: CheckContext) -> list[DoctorCheck]:
"""Checks 8-10, in order. Fills ``ctx.drift`` and the drift highlight."""
checks: list[DoctorCheck] = []
+ if ctx.quick:
+ return checks
if ctx.db_ok and ctx.page_count > 0:
checks.extend(_consistency_rows(ctx))
if ctx.db_ok:
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
index 0f71893b8..2556e1785 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/command.py
@@ -20,6 +20,16 @@ from .repo_checks import _run_repo_checks
from .workspace_checks import _run_workspace_checks
+def _check_repair_flags(fmt: str, quick: bool) -> None:
+ """``--repair`` writes, and needs the store drift ``--quick`` skips."""
+ if fmt != "table":
+ raise click.UsageError(
+ "--repair is not supported with --format json (json mode is read-only)."
+ )
+ if quick:
+ raise click.UsageError("--repair needs the store checks that --quick skips.")
+
+
@click.command("doctor")
@click.argument("path", required=False, default=None)
@click.option("--repair", is_flag=True, default=False, help="Attempt to fix detected mismatches.")
@@ -44,12 +54,20 @@ from .workspace_checks import _run_workspace_checks
help="Output format. json is read-only (incompatible with --repair) and exits "
"1 when any check fails.",
)
+ "--quick",
+ is_flag=True,
+ default=False,
+ help="Skip the slow checks: starting the MCP server and reconciling the "
+ "vector and full-text stores. Incompatible with --repair.",
+)
def doctor_command(
path: str | None,
repair: bool,
workspace: bool,
no_workspace: bool,
fmt: str,
+ quick: bool,
) -> None:
"""Run health checks on the wiki setup.
@@ -57,10 +75,8 @@ def doctor_command(
workspace mode, runs the full check battery against each indexed repo
and prints a per-repo table plus a workspace-level summary.
"""
- if fmt != "table" and repair:
- raise click.UsageError(
- "--repair is not supported with --format json (json mode is read-only)."
- )
+ if repair:
+ _check_repair_flags(fmt, quick)
silencer = silence_logs_for_machine_output() if fmt != "table" else contextlib.nullcontext()
with silencer:
@@ -79,7 +95,7 @@ def doctor_command(
if not target.is_workspace:
assert target.repo_path is not None
- all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt)
+ all_ok, checks = _run_repo_checks(target.repo_path, repair, fmt=fmt, quick=quick)
if fmt != "table":
payload = {"ok": all_ok, "checks": [c._asdict() for c in checks]}
click.echo(json.dumps(payload, indent=2))
@@ -117,7 +133,7 @@ def doctor_command(
else ""
)
)
- ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt)
+ ok, checks = _run_repo_checks(abs_path, repair, fmt=fmt, quick=quick)
overall_ok = overall_ok and ok
# The alias goes on the display name only; ids stay the check's own.
all_checks.extend(c._replace(name=f"{entry.alias}: {c.name}") for c in checks)
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py
index e47449df9..31e256add 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py
@@ -55,7 +55,10 @@ _TEARDOWN_ERRORS = (OSError, ValueError, subprocess.TimeoutExpired)
# before the process is reaped. Polling at that instant reports "still running"
# for a process that is already on its way out - which is the crash loop, the
# one case this check exists to name. Wait briefly for the exit status first.
+# Only then: a server still mute at the deadline is not about to exit, so it
+# gets the short grace, enough to reap one that died right at the deadline.
_EXIT_GRACE_S = 5.0
+_DEADLINE_EXIT_GRACE_S = 0.2
# The child having exited does not mean the stderr reader has consumed the
# pipe's last lines yet; on a busy runner the ring can still be empty when the
@@ -182,6 +185,7 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> D
child_env = {**os.environ, **{str(k): str(v) for k, v in env.items()}}
started = time.monotonic()
+ deadline = started + _SMOKE_TIMEOUT_S
try:
proc = subprocess.Popen(
[command, *args],
@@ -198,7 +202,7 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> D
stderr_ring, stderr_reader = _drain_stderr(proc)
try:
- response = _initialize(proc, started + _SMOKE_TIMEOUT_S)
+ response = _initialize(proc, deadline)
elapsed_ms = int((time.monotonic() - started) * 1000)
if response is not None and "result" in response:
@@ -218,8 +222,9 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> D
# and mute changes the remedy, so the detail says which.
exit_code = proc.poll()
if exit_code is None:
+ early = time.monotonic() < deadline
with contextlib.suppress(subprocess.TimeoutExpired):
- exit_code = proc.wait(timeout=_EXIT_GRACE_S)
+ exit_code = proc.wait(timeout=_EXIT_GRACE_S if early else _DEADLINE_EXIT_GRACE_S)
if exit_code is None:
return _check(
CHECK_NAME,
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.py
index 211174475..232352955 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
@@ -75,8 +75,12 @@ __all__ = [
]
-def _collect(repo_path: _DoctorPath) -> tuple[CheckContext, list[DoctorCheck]]:
- ctx = CheckContext(repo_path=repo_path, repowise_dir=get_repowise_dir(repo_path))
+def _collect(
+ repo_path: _DoctorPath, *, quick: bool = False
+) -> tuple[CheckContext, list[DoctorCheck]]:
+ ctx = CheckContext(
+ repo_path=repo_path, repowise_dir=get_repowise_dir(repo_path), quick=quick
+ )
checks: list[DoctorCheck] = []
for group in (core_checks, provider_checks, store_checks, integration_checks):
checks.extend(group(ctx))
@@ -94,7 +98,7 @@ def collect_repo_checks(repo_path: _DoctorPath) -> list[DoctorCheck]:
def _run_repo_checks(
- repo_path: _DoctorPath, repair: bool, *, fmt: str = "table"
+ repo_path: _DoctorPath, repair: bool, *, fmt: str = "table", quick: bool = False
) -> tuple[bool, list[DoctorCheck]]:
"""Run the standard health checks against one repo.
@@ -102,9 +106,9 @@ def _run_repo_checks(
over every repo without duplicating the full check body. When
``fmt != "table"`` the table and advisory lines are not printed (repair
is also skipped; callers must not pass ``repair=True`` with a
- non-table format).
+ non-table format). *quick* skips the slow checks (see ``CheckContext.quick``).
"""
- ctx, checks = _collect(repo_path)
+ ctx, checks = _collect(repo_path, quick=quick)
all_ok = all(c.ok for c in checks)
if fmt != "table":
diff --git a/packages/server/src/repowise/server/routers/setup.py b/packages/server/src/repowise/server/routers/setup.py
index 192e0149a..e9c1f2191 100644
--- a/packages/server/src/repowise/server/routers/setup.py
+++ b/packages/server/src/repowise/server/routers/setup.py
@@ -284,7 +284,7 @@ async def get_setup(
repo: Repository = Depends(resolve_local_repo),
session: AsyncSession = Depends(get_db_session),
) -> dict[str, Any]:
- """Everything the Setup page shows for one repo, cached for a few seconds."""
+ """Everything the Setup page shows for one repo; see ``setup_status`` for the caching."""
payload = await setup_status.setup_payload(session, repo)
return {
**payload,
diff --git a/packages/server/src/repowise/server/services/setup_cli.py b/packages/server/src/repowise/server/services/setup_cli.py
index d705888d4..f69a0daf1 100644
--- a/packages/server/src/repowise/server/services/setup_cli.py
+++ b/packages/server/src/repowise/server/services/setup_cli.py
@@ -78,19 +78,16 @@ def run_cli(args: list[str], *, cwd: Path, timeout: float) -> CliRun:
# -- reads -------------------------------------------------------------------
-def doctor_json(repo_path: Path) -> dict | None:
- """``repowise doctor --format json`` for this repo; it exits 1 on a failed check."""
- run = run_cli(
- [
- "doctor",
- str(repo_path),
- "--no-workspace",
- "--format",
- "json",
- ],
- cwd=repo_path,
- timeout=_READ_TIMEOUT_SECONDS,
- )
+def doctor_json(repo_path: Path, *, quick: bool = False) -> dict | None:
+ """``repowise doctor --format json`` for this repo; it exits 1 on a failed check.
+
+ *quick* adds ``--quick``, which skips starting the MCP server and
+ reconciling the stores: seconds instead of tens of seconds.
+ """
+ args = ["doctor", str(repo_path), "--no-workspace", "--format", "json"]
+ if quick:
+ args.append("--quick")
+ run = run_cli(args, cwd=repo_path, timeout=_READ_TIMEOUT_SECONDS)
payload = run.json()
return payload if isinstance(payload, dict) else None
diff --git a/packages/server/src/repowise/server/services/setup_status.py b/packages/server/src/repowise/server/services/setup_status.py
index f75c13e27..397b1b059 100644
--- a/packages/server/src/repowise/server/services/setup_status.py
+++ b/packages/server/src/repowise/server/services/setup_status.py
@@ -3,8 +3,14 @@
Agent, hook and doctor state come from the CLI's own JSON (see
:mod:`.setup_cli`); the rest is read here from the index, the savings ledger,
the coverage discovery and the provider settings the other routes already use.
-The payload is cached for a few seconds per repo, because doctor starts the MCP
-server once and a page load must not do that on every request.
+
+The index and stored-coverage reads hit the database on every request. The
+rest (the CLI runs and the file reads, a few seconds) is a cached *probe* per
+repo: a fresh one is served as is, an older one is served at once while a new
+one builds in the background, and only a repo with none waits for the build.
+The probe runs ``doctor --quick``; the full doctor (it starts the MCP server and
+reconciles the stores, tens of seconds) runs in the background after it, and
+its extra rows join the checks once it lands. Every write drops both.
"""
from __future__ import annotations
@@ -14,6 +20,8 @@ import json
import logging
import sqlite3
import time
+from collections.abc import Callable, Coroutine
+from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -27,60 +35,159 @@ from repowise.server.services import setup_cli
logger = logging.getLogger(__name__)
-#: How long one payload answers repeat requests for the same repo.
-SETUP_CACHE_SECONDS = 5.0
+#: A probe this young is served without a rebuild; an older one is served
+#: while a rebuild runs, up to the stale limit. The page fetches once and does
+#: not refetch, so past that limit a load waits for the rebuild (seconds).
+SETUP_CACHE_SECONDS = 60.0
+SETUP_STALE_SECONDS = 300.0
+#: How often the full doctor runs again for the same repo.
+FULL_CHECK_SECONDS = 300.0
#: Bounds on the lists the payload carries.
_PARSE_ERROR_FILES_LIMIT = 50
_DISCOVERED_REPORTS_LIMIT = 10
-_cache: dict[str, tuple[float, dict[str, Any]]] = {}
-_locks: dict[str, asyncio.Lock] = {}
+
+@dataclass(frozen=True)
+class _Probe:
+ """The CLI answers and file reads behind one payload."""
+
+ built_at: float
+ generated_at: str
+ doctor: dict | None
+ agents: dict | None
+ local: tuple[Any, Any, tuple[bool, dict[str, Any]]]
+
+
+_probes: dict[str, _Probe] = {}
+#: Rows from the last full doctor, by repo: ``(monotonic time, rows)``. A
+#: failed run keeps the old rows with a new time, so it is not retried on
+#: every rebuild.
+_full_checks: dict[str, tuple[float, list[dict[str, Any]]]] = {}
+#: Builds in flight, by ``(kind, repo_id)``, so concurrent loads share one.
+_inflight: dict[tuple[str, str], asyncio.Task] = {}
+#: Strong references until each task ends; the loop keeps only weak ones.
+_running: set[asyncio.Task] = set()
#: Bumped by every write, so a build that started before it is not cached.
_generation = 0
def invalidate(repo_id: str | None = None) -> None:
- """Drop the cached payload for *repo_id*, or every one when ``None``."""
+ """Drop the cached answers for *repo_id*, or every one when ``None``.
+
+ A build already running started before the write: it finishes uncached,
+ and the next request starts a new one. The full doctor's rows stay until
+ the next full run replaces them, so a failing row does not blink out for
+ the tens of seconds that run takes; they are only marked due.
+ """
global _generation
_generation += 1
if repo_id is None:
- _cache.clear()
+ _probes.clear()
else:
- _cache.pop(repo_id, None)
+ _probes.pop(repo_id, None)
+ for key, (_at, rows) in list(_full_checks.items()):
+ if repo_id is None or key == repo_id:
+ _full_checks[key] = (float("-inf"), rows)
+ for key in [k for k in _inflight if repo_id is None or k[1] == repo_id]:
+ del _inflight[key]
async def setup_payload(session: AsyncSession, repo: Repository) -> dict[str, Any]:
- """The cached payload for *repo*, built once per window even under concurrent loads."""
- lock = _locks.setdefault(repo.id, asyncio.Lock())
- async with lock:
- hit = _cache.get(repo.id)
- if hit is not None and time.monotonic() - hit[0] < SETUP_CACHE_SECONDS:
- return hit[1]
- started = _generation
- payload = await _build(session, repo)
- if started == _generation:
- _cache[repo.id] = (time.monotonic(), payload)
- return payload
-
-
-async def _build(session: AsyncSession, repo: Repository) -> dict[str, Any]:
- repo_path = Path(repo.local_path)
+ """The payload for *repo*; only a repo with no probe yet waits for one."""
+ probe = await _current_probe(repo.id, Path(repo.local_path))
index = await _index_section(session, repo)
- ingest_ok, coverage_ingested_at = await _coverage_ingested_at(session, repo.id)
+ coverage_stored = await _coverage_ingested_at(session, repo.id)
+ full = _full_checks.get(repo.id)
+ return _assemble(repo.id, probe, index, coverage_stored, full[1] if full else None)
+
+
+def _start(kind: str, repo_id: str, make: Callable[[], Coroutine[Any, Any, Any]]) -> asyncio.Task:
+ """The build of *kind* for *repo_id* in flight, started if there is none."""
+ key = (kind, repo_id)
+ task = _inflight.get(key)
+ if task is None:
+ task = asyncio.create_task(make())
+ _inflight[key] = task
+ _running.add(task)
+ task.add_done_callback(lambda t: _finished(key, t))
+ return task
+
+
+def _finished(key: tuple[str, str], task: asyncio.Task) -> None:
+ _running.discard(task)
+ if _inflight.get(key) is task:
+ del _inflight[key]
+ if not task.cancelled() and task.exception() is not None:
+ logger.warning("setup: %s build for %s failed", *key, exc_info=task.exception())
+
+
+async def _current_probe(repo_id: str, repo_path: Path) -> _Probe:
+ def build() -> Coroutine[Any, Any, _Probe]:
+ return _build_probe(repo_id, repo_path)
+
+ hit = _probes.get(repo_id)
+ age = time.monotonic() - hit.built_at if hit else None
+ if age is None or age >= SETUP_STALE_SECONDS:
+ # Shielded: a request that gives up must not cancel the build that
+ # the other loads are waiting on.
+ return await asyncio.shield(_start("probe", repo_id, build))
+ if age >= SETUP_CACHE_SECONDS:
+ _start("probe", repo_id, build)
+ return hit
+
+
+async def _build_probe(repo_id: str, repo_path: Path) -> _Probe:
+ started = _generation
doctor, agents, local = await asyncio.gather(
- asyncio.to_thread(setup_cli.doctor_json, repo_path),
+ asyncio.to_thread(setup_cli.doctor_json, repo_path, quick=True),
asyncio.to_thread(setup_cli.agents_json, repo_path),
- asyncio.to_thread(_local_sections, repo.id, repo_path),
+ asyncio.to_thread(_local_sections, repo_id, repo_path),
)
- checks = _checks(doctor)
- agent_calls, coverage_files, (model_ok, model) = local
- agent_rows, calls = _agents(agents, agent_calls or {})
+ probe = _Probe(time.monotonic(), datetime.now(UTC).isoformat(), doctor, agents, local)
+ if started == _generation:
+ _probes[repo_id] = probe
+ # After the probe, not beside it: on a cold load the two would
+ # compete for the same CPU and the page would wait longer.
+ full = _full_checks.get(repo_id)
+ if full is None or time.monotonic() - full[0] >= FULL_CHECK_SECONDS:
+ _start("full", repo_id, lambda: _build_full_checks(repo_id, repo_path))
+ return probe
+
+
+async def _build_full_checks(repo_id: str, repo_path: Path) -> None:
+ started = _generation
+ doctor = await asyncio.to_thread(setup_cli.doctor_json, repo_path)
+ if started != _generation:
+ return
+ if doctor is None:
+ logger.warning("setup: the full doctor run for %s gave no answer", repo_path)
+ previous = _full_checks.get(repo_id)
+ _full_checks[repo_id] = (time.monotonic(), previous[1] if previous else [])
+ return
+ _full_checks[repo_id] = (time.monotonic(), _checks(doctor))
+
+
+def _assemble(
+ repo_id: str,
+ probe: _Probe,
+ index: dict[str, Any],
+ coverage_stored: tuple[bool, str | None],
+ full_checks: list[dict[str, Any]] | None,
+) -> dict[str, Any]:
+ checks = _checks(probe.doctor)
+ if full_checks:
+ # Only the rows the quick run skips; the quick rows are as new or newer.
+ quick_ids = {c["id"] for c in checks}
+ checks += [c for c in full_checks if c["id"] not in quick_ids]
+ agent_calls, coverage_files, (model_ok, model) = probe.local
+ agent_rows, calls = _agents(probe.agents, agent_calls or {})
+ ingest_ok, coverage_ingested_at = coverage_stored
return {
- "repo_id": repo.id,
- "generated_at": datetime.now(UTC).isoformat(),
+ "repo_id": repo_id,
+ "generated_at": probe.generated_at,
"index": index,
- "agents_available": agents is not None,
+ "agents_available": probe.agents is not None,
"agents": agent_rows,
"calls_available": agent_calls is not None,
"calls": calls,
@@ -93,7 +200,7 @@ async def _build(session: AsyncSession, repo: Repository) -> dict[str, Any]:
},
"model_available": model_ok,
"model": model,
- "checks_available": doctor is not None,
+ "checks_available": probe.doctor is not None or bool(full_checks),
"checks": checks,
}
diff --git a/packages/web/src/components/setup/use-setup.ts b/packages/web/src/components/setup/use-setup.ts
index e8304605c..8ff6735da 100644
--- a/packages/web/src/components/setup/use-setup.ts
+++ b/packages/web/src/components/setup/use-setup.ts
@@ -23,7 +23,7 @@ import { deriveSetup, type SetupHook, type SetupView } from "./setup-rows";
export const setupKey = (repoId: string) => ["setup", repoId] as const;
export const ONBOARDING_KEY = "setup-onboarding";
-/** First load runs doctor (about 20s), so nothing here refetches on its own. */
+/** First load runs the quick doctor (a few seconds), so nothing here refetches on its own. */
const QUIET = {
revalidateOnFocus: false,
revalidateOnReconnect: false,
diff --git a/tests/unit/cli/test_doctor_check_order.py b/tests/unit/cli/test_doctor_check_order.py
index 44b377fa4..e1c1bd6e4 100644
--- a/tests/unit/cli/test_doctor_check_order.py
+++ b/tests/unit/cli/test_doctor_check_order.py
@@ -187,6 +187,32 @@ def test_healthy_store_rows_and_order(env, tmp_path) -> None:
assert env["printed"] == []
+def test_quick_skips_the_store_reconciliation_and_the_mcp_launch(
+ env, monkeypatch, tmp_path
+) -> None:
+ from repowise.cli.commands.doctor_cmd._checks import stores
+
+ def fail(*_a, **_k):
+ raise AssertionError("--quick must not open the stores")
+
+ monkeypatch.setattr(stores, "_reconcile", fail)
+ monkeypatch.setattr(stores, "_coordinator_health", fail)
+ repo = asyncio.run(_build(tmp_path))
+ _ok, checks = repo_checks._run_repo_checks(repo, repair=False, fmt="json", quick=True)
+ slow = {"SQL ↔ Vector Store", "SQL ↔ FTS Index", "Coordinator drift", "<mcp>"}
+ assert [c.name for c in checks] == [n for n in HEALTHY_ORDER if n not in slow]
+
+
+def test_quick_and_repair_is_a_usage_error(tmp_path) -> None:
+ from click.testing import CliRunner
+
+ from repowise.cli.commands.doctor_cmd import doctor_command
+
+ result = CliRunner().invoke(doctor_command, [str(tmp_path), "--quick", "--repair"])
+ assert result.exit_code == 2
+ assert "--quick" in result.output
+
+
def test_optional_rows_slot_in_after_the_hook(env, monkeypatch, tmp_path) -> None:
monkeypatch.setattr(
core, "_attribution_notes_check", lambda _p: _check("<notes>", True, "", check_id="notes")
diff --git a/tests/unit/cli/test_doctor_json.py b/tests/unit/cli/test_doctor_json.py
index d354b27eb..19d88fc54 100644
--- a/tests/unit/cli/test_doctor_json.py
+++ b/tests/unit/cli/test_doctor_json.py
@@ -78,7 +78,7 @@ class TestDoctorTableExitCode:
_git_init(tmp_path)
monkeypatch.setattr(
"repowise.cli.commands.doctor_cmd.command._run_repo_checks",
- lambda repo_path, repair, fmt="table": (True, []),
+ lambda repo_path, repair, fmt="table", quick=False: (True, []),
)
result = CliRunner().invoke(doctor_command, [str(tmp_path), "--no-workspace"])
diff --git a/tests/unit/cli/test_doctor_mcp_smoke.py b/tests/unit/cli/test_doctor_mcp_smoke.py
index c84ac9cce..c813c83da 100644
--- a/tests/unit/cli/test_doctor_mcp_smoke.py
+++ b/tests/unit/cli/test_doctor_mcp_smoke.py
@@ -89,6 +89,19 @@ def test_a_mute_server_fails_without_hanging_doctor(monkeypatch: pytest.MonkeyPa
assert "still running" in check.detail
+def test_a_mute_server_is_not_given_the_exit_grace(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The exit grace is for a server whose stdout closed early, not one still
+ mute at the deadline: waiting on that only delays the answer."""
+ import time
+
+ monkeypatch.setattr(mcp_smoke, "_SMOKE_TIMEOUT_S", 1.0)
+ monkeypatch.setattr(mcp_smoke, "_EXIT_GRACE_S", 30.0)
+ started = time.monotonic()
+ check = mcp_smoke_check(sys.executable, ["-c", _MUTE_SERVER])
+ assert "still running" in check.detail
+ assert time.monotonic() - started < 15.0
+
+
def test_an_error_response_fails() -> None:
server = (
"import sys, json;"
diff --git a/tests/unit/server/test_setup_route.py b/tests/unit/server/test_setup_route.py
index dccb3eeec..e617d5cc5 100644
--- a/tests/unit/server/test_setup_route.py
+++ b/tests/unit/server/test_setup_route.py
@@ -117,6 +117,15 @@ async def local(app, home: Path) -> AsyncClient:
async with AsyncClient(transport=transport, base_url="http://localhost:7337") as c:
yield c
setup_status.invalidate()
+ await _settle()
+
+
+async def _settle() -> None:
+ """Let the background builds a request started finish."""
+ import asyncio
+
+ while setup_status._running:
+ await asyncio.gather(*setup_status._running, return_exceptions=True)
@pytest.fixture
@@ -195,7 +204,161 @@ async def test_setup_payload_is_cached_between_page_loads(
) -> None:
await local.get(f"/api/repos/{repo['id']}/setup")
await local.get(f"/api/repos/{repo['id']}/setup")
- assert sum(1 for c in cli.calls if c[0] == "doctor") == 1
+ await _settle()
+ doctors = [c for c in cli.calls if c[0] == "doctor"]
+ # One quick run for the page, one full run behind it.
+ assert [("--quick" in c) for c in doctors] == [True, False]
+
+
+async def test_a_stale_payload_is_served_at_once_and_rebuilt_behind_it(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ first = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ await _settle()
+ monkeypatch.setattr(setup_status, "SETUP_CACHE_SECONDS", 0.0)
+ calls_before = len(cli.calls)
+
+ stale = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert stale["generated_at"] == first["generated_at"] # served without waiting
+ await _settle()
+ fresh = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert fresh["generated_at"] != first["generated_at"]
+ assert any("--quick" in c for c in cli.calls[calls_before:])
+
+
+async def test_a_write_makes_the_next_load_wait_for_a_new_probe(
+ local: AsyncClient, repo: dict, cli: FakeCli
+) -> None:
+ first = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ await _settle()
+ setup_status.invalidate(repo["id"])
+ after = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert after["generated_at"] != first["generated_at"]
+
+
+async def test_a_payload_past_the_stale_limit_waits_for_a_rebuild(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ first = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ await _settle()
+ monkeypatch.setattr(setup_status, "SETUP_STALE_SECONDS", 0.0)
+ after = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ assert after["generated_at"] != first["generated_at"]
+
+
+_MCP_FAIL = {"name": "MCP server responds", "ok": False, "detail": "server exited with code 1",
+ "id": "mcp-responds", "level": "fail", "fix": None}
+
+
+def _full_doctor_answers(cli: FakeCli, monkeypatch: pytest.MonkeyPatch, answers: list) -> None:
+ """The full (not --quick) doctor runs answer from *answers* in turn."""
+ original = cli.__call__
+
+ def answer(args, *, cwd, timeout):
+ if args[0] == "doctor" and "--quick" not in args:
+ answer = answers.pop(0)
+ return answer() if callable(answer) else answer
+ return original(args, cwd=cwd, timeout=timeout)
+
+ monkeypatch.setattr(setup_cli, "run_cli", answer)
+
+
+async def test_full_rows_outlive_a_write_until_the_next_full_run(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ failing = setup_cli.CliRun(1, json.dumps({"ok": False, "checks": [_MCP_FAIL]}), "")
+ passing = setup_cli.CliRun(0, json.dumps({"ok": True, "checks": [
+ {**_MCP_FAIL, "ok": True, "level": "ok", "detail": "initialised"}]}), "")
+ import threading
+
+ rerun = threading.Event()
+ _full_doctor_answers(cli, monkeypatch, [failing, lambda: rerun.wait(10) and passing])
+ url = f"/api/repos/{repo['id']}/setup"
+ await local.get(url)
+ await _settle()
+ setup_status.invalidate(repo["id"])
+
+ body = (await local.get(url)).json() # the full run is due again, not done yet
+ assert [c["level"] for c in body["checks"] if c["id"] == "mcp-responds"] == ["fail"]
+ rerun.set()
+ await _settle()
+ body = (await local.get(url)).json()
+ assert [c["level"] for c in body["checks"] if c["id"] == "mcp-responds"] == ["ok"]
+
+
+async def test_a_failed_full_run_is_not_retried_on_every_rebuild(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _full_doctor_answers(cli, monkeypatch, [setup_cli.CliRun(None, "", "timed out")])
+ monkeypatch.setattr(setup_status, "SETUP_CACHE_SECONDS", 0.0)
+ url = f"/api/repos/{repo['id']}/setup"
+ for _ in range(3):
+ await local.get(url)
+ await _settle()
+ # One full run (popping a second answer would raise); the quick rows stand.
+ body = (await local.get(url)).json()
+ assert body["checks_available"] is True
+ assert "mcp-responds" not in {c["id"] for c in body["checks"]}
+
+
+async def test_the_full_doctor_rows_join_the_quick_ones(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ mcp = {"name": "MCP server responds", "ok": False, "detail": "server exited with code 1",
+ "id": "mcp-responds", "level": "fail", "fix": None}
+ stale_hook = {**_DOCTOR["checks"][0], "detail": "not installed", "level": "warn"}
+ original = cli.__call__
+
+ def answer(args, *, cwd, timeout):
+ if args[0] == "doctor" and "--quick" not in args:
+ full = {"ok": False, "checks": [stale_hook, *_DOCTOR["checks"][1:], mcp]}
+ return setup_cli.CliRun(1, json.dumps(full), "")
+ return original(args, cwd=cwd, timeout=timeout)
+
+ monkeypatch.setattr(setup_cli, "run_cli", answer)
+ await local.get(f"/api/repos/{repo['id']}/setup")
+ await _settle()
+ body = (await local.get(f"/api/repos/{repo['id']}/setup")).json()
+ ids = [c["id"] for c in body["checks"]]
+ assert ids == ["post-commit-hook", "distill-rewrite-hook", "database", "mcp-responds"]
+ # A row both runs report comes from the quick one.
+ assert body["sync"]["installed"] is True
+
+
+async def test_concurrent_cold_loads_share_one_build_that_survives_a_dropped_request(
+ local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import asyncio
+ import threading
+
+ gate, entered = threading.Event(), threading.Event()
+ original = cli.__call__
+
+ def slow(args, *, cwd, timeout):
+ if args[0] == "doctor":
+ entered.set()
+ gate.wait(10)
+ return original(args, cwd=cwd, timeout=timeout)
+
+ monkeypatch.setattr(setup_cli, "run_cli", slow)
+ url = f"/api/repos/{repo['id']}/setup"
+ dropped = asyncio.create_task(local.get(url))
+ waiting = [asyncio.create_task(local.get(url)) for _ in range(2)]
+ await asyncio.to_thread(entered.wait, 10)
+ await asyncio.sleep(0.2) # the other loads reach the shared build
+ dropped.cancel() # the proxy gave up on this one
+ await asyncio.sleep(0.05)
+ gate.set()
+ bodies = [(await t).json() for t in waiting]
+ assert bodies[0]["generated_at"] == bodies[1]["generated_at"]
+ assert sum(1 for c in cli.calls if "--quick" in c) == 1
@pytest.mark.anyio
@@ -536,16 +699,17 @@ async def test_onboarding_write_never_replaces_a_file_it_cannot_read(
async def test_a_write_during_a_build_keeps_the_old_payload_out_of_the_cache(
local: AsyncClient, repo: dict, cli: FakeCli, monkeypatch: pytest.MonkeyPatch
) -> None:
- real_build = setup_status._build
-
- async def build_then_write(session, row):
- payload = await real_build(session, row)
- setup_status.invalidate(row.id) # a write lands while this build runs
- return payload
+ def doctor_then_write(args, **kw):
+ run = cli(args, **kw)
+ if args[0] == "doctor" and "--quick" in args:
+ setup_status.invalidate(repo["id"]) # a write lands while this build runs
+ return run
- monkeypatch.setattr(setup_status, "_build", build_then_write)
+ monkeypatch.setattr(setup_cli, "run_cli", doctor_then_write)
await local.get(f"/api/repos/{repo['id']}/setup")
- assert repo["id"] not in setup_status._cache
+ await _settle()
+ assert repo["id"] not in setup_status._probes
+ assert repo["id"] not in setup_status._full_checks
@pytest.mark.anyio
@@ -566,7 +730,7 @@ async def test_onboarding_rejects_a_malformed_repo_id(local: AsyncClient) -> Non
@pytest.mark.parametrize(
("command", "flags"),
[
- (["doctor"], ["--no-workspace", "--format"]),
+ (["doctor"], ["--no-workspace", "--format", "--quick"]),
(["agents", "add"], ["--target", "--format", "--yes"]),
(["agents", "remove"], ["--target", "--format"]),
(["hook", "install"], ["--no-workspace"]),