DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(cli): add setup doctor command (#959)
pederbe9be3b0cf590f
diff --git a/deeptutor/services/doctor.py b/deeptutor/services/doctor.pynew file mode 100644index 000000000..7a038fada--- /dev/null+++ b/deeptutor/services/doctor.py@@ -0,0 +1,450 @@+"""Local and opt-in online diagnostics for the DeepTutor CLI."""++from __future__ import annotations++from collections.abc import Awaitable, Callable, Mapping+from dataclasses import asdict, dataclass+from pathlib import Path+import re+import tempfile+from typing import Any, Literal+from urllib.parse import urlsplit, urlunsplit++from deeptutor.services.llm.utils import is_local_llm_server, sanitize_url+from deeptutor.services.provider_registry import find_by_name++CheckStatus = Literal["pass", "fail", "skip"]+++@dataclass(frozen=True)+class DoctorCheck:+ """One diagnostic result shown by ``deeptutor doctor``."""++ key: str+ label: str+ status: CheckStatus+ detail: str+ required: bool = True++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++@dataclass(frozen=True)+class DoctorReport:+ """Complete diagnostic report."""++ online: bool+ checks: list[DoctorCheck]++ @property+ def ok(self) -> bool:+ return all(check.status != "fail" for check in self.checks if check.required)++ def to_dict(self) -> dict[str, Any]:+ return {+ "ok": self.ok,+ "online": self.online,+ "checks": [check.to_dict() for check in self.checks],+ }+++def _safe_endpoint(raw_url: str | None) -> tuple[bool, str]:+ if not raw_url:+ return False, "No provider endpoint is configured."++ normalized = sanitize_url(raw_url)+ try:+ parsed = urlsplit(normalized)+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:+ return False, "The configured provider endpoint is not a valid HTTP(S) URL."+ host = parsed.hostname+ if ":" in host and not host.startswith("["):+ host = f"[{host}]"+ port = f":{parsed.port}" if parsed.port is not None else ""+ display_url = urlunsplit((parsed.scheme, f"{host}{port}", "", "", ""))+ except (ValueError, TypeError):+ return False, "The configured provider endpoint is not a valid HTTP(S) URL."+ return True, display_url.rstrip("/")+++def _has_authentication_header(headers: Any) -> bool:+ if not isinstance(headers, Mapping):+ return False++ exact_names = {+ "authorization",+ "proxy-authorization",+ "api-key",+ "x-api-key",+ "x-goog-api-key",+ }+ auth_suffixes = (+ "-authorization",+ "-auth",+ "-api-key",+ "-apikey",+ "-access-token",+ "-auth-token",+ )+ for name, value in headers.items():+ normalized_name = re.sub(r"[_\s]+", "-", str(name).strip().lower())+ if str(value or "").strip() and (+ normalized_name in exact_names or normalized_name.endswith(auth_suffixes)+ ):+ return True+ return False+++def _credentials_check(config: Any) -> DoctorCheck:+ provider_name = str(getattr(config, "provider_name", "") or "")+ provider_mode = str(getattr(config, "provider_mode", "") or "")+ api_key = str(getattr(config, "api_key", "") or "")+ endpoint = str(+ getattr(config, "effective_url", None) or getattr(config, "base_url", None) or ""+ )+ extra_headers = getattr(config, "extra_headers", None) or {}+ provider = find_by_name(provider_name)+ placeholders = {"", "no-key", "sk-no-key-required"}++ if provider_mode == "oauth" or (provider and provider.is_oauth):+ return DoctorCheck(+ key="llm_credentials",+ label="LLM credentials",+ status="pass",+ detail=f"{provider_name or 'Selected provider'} uses provider-managed OAuth.",+ )+ if (+ provider_mode == "local"+ or (provider and provider.is_local)+ or is_local_llm_server(endpoint)+ ):+ return DoctorCheck(+ key="llm_credentials",+ label="LLM credentials",+ status="pass",+ detail="The selected local provider does not require an API key.",+ )+ if api_key not in placeholders or _has_authentication_header(extra_headers):+ return DoctorCheck(+ key="llm_credentials",+ label="LLM credentials",+ status="pass",+ detail=f"Credentials are configured for {provider_name or 'the selected provider'}.",+ )+ if provider and provider.is_direct and provider.name != "azure_openai":+ return DoctorCheck(+ key="llm_credentials",+ label="LLM credentials",+ status="skip",+ detail=(+ "No recognized credential is configured for this custom endpoint. "+ "Use --online to verify whether it accepts unauthenticated requests."+ ),+ required=False,+ )+ return DoctorCheck(+ key="llm_credentials",+ label="LLM credentials",+ status="fail",+ detail=f"No credentials are configured for {provider_name or 'the selected provider'}.",+ )+++def _llm_checks(config: Any) -> list[DoctorCheck]:+ model = str(getattr(config, "model", "") or "")+ provider_name = str(getattr(config, "provider_name", "") or "")+ provider_mode = str(getattr(config, "provider_mode", "") or "")+ endpoint = getattr(config, "effective_url", None) or getattr(config, "base_url", None)++ checks = [+ DoctorCheck(+ key="llm_config",+ label="LLM configuration",+ status="pass" if model else "fail",+ detail=(+ f"Active model: {model} ({provider_name or 'unknown provider'})."+ if model+ else "No active LLM model is configured."+ ),+ ),+ _credentials_check(config),+ ]++ provider = find_by_name(provider_name)+ if provider_mode == "oauth" or (provider and provider.is_oauth):+ checks.append(+ DoctorCheck(+ key="llm_endpoint",+ label="LLM endpoint",+ status="pass",+ detail="The OAuth provider manages its endpoint.",+ )+ )+ else:+ endpoint_ok, detail = _safe_endpoint(endpoint)+ checks.append(+ DoctorCheck(+ key="llm_endpoint",+ label="LLM endpoint",+ status="pass" if endpoint_ok else "fail",+ detail=detail,+ )+ )+ return checks+++def _storage_check(data_root: Path) -> DoctorCheck:+ try:+ data_root.mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ prefix=".deeptutor-doctor-",+ dir=data_root,+ delete=True,+ ) as handle:+ handle.write("ok")+ handle.flush()+ except OSError as exc:+ return DoctorCheck(+ key="storage",+ label="Runtime storage",+ status="fail",+ detail=f"Cannot write to {data_root}: {exc}",+ )+ return DoctorCheck(+ key="storage",+ label="Runtime storage",+ status="pass",+ detail=f"Writable: {data_root}",+ )+++def _rag_check(+ config: dict[str, Any],+ preflight: Callable[[str], dict[str, Any]],+) -> DoctorCheck:+ knowledge_bases = config.get("knowledge_bases", {})+ if not isinstance(knowledge_bases, dict) or not knowledge_bases:+ return DoctorCheck(+ key="rag",+ label="RAG prerequisites",+ status="skip",+ detail="No knowledge bases are configured.",+ required=False,+ )++ defaults = config.get("defaults", {})+ default_provider = (+ str(defaults.get("rag_provider", "llamaindex"))+ if isinstance(defaults, dict)+ else "llamaindex"+ )+ from deeptutor.services.rag.factory import (+ LIGHTRAG_SERVER_PROVIDER,+ normalize_provider_name,+ )++ providers: set[str] = set()+ failures: list[str] = []+ for kb_name, entry in knowledge_bases.items():+ if not isinstance(entry, dict):+ continue+ provider = normalize_provider_name(str(entry.get("rag_provider") or default_provider))+ providers.add(provider)+ if provider != LIGHTRAG_SERVER_PROVIDER:+ continue++ from deeptutor.services.rag.pipelines.lightrag_server.config import (+ config_from_entry,+ )++ try:+ server_config = config_from_entry(entry)+ endpoint_ok, _ = _safe_endpoint(server_config.base_url)+ if not endpoint_ok:+ failures.append(f"{kb_name}: invalid LightRAG server URL")+ except Exception as exc:+ failures.append(f"{kb_name}: {_redact_error(exc, None)}")++ for provider in sorted(providers - {LIGHTRAG_SERVER_PROVIDER}):+ try:+ report = preflight(provider)+ for check in report.get("checks", []):+ if not check.get("ok") and not check.get("optional", False):+ failures.append(f"{provider}: {check.get('label', 'requirement failed')}")+ except Exception as exc:+ failures.append(f"{provider}: preflight could not run ({_redact_error(exc, None)})")++ if failures:+ return DoctorCheck(+ key="rag",+ label="RAG prerequisites",+ status="fail",+ detail="; ".join(failures),+ required=False,+ )+ return DoctorCheck(+ key="rag",+ label="RAG prerequisites",+ status="pass",+ detail=f"Ready for configured provider(s): {', '.join(sorted(providers))}.",+ required=False,+ )+++def _redact_error(exc: Exception, config: Any) -> str:+ message = str(exc).strip() or type(exc).__name__+ extra_headers = getattr(config, "extra_headers", None) or {}+ header_values = (+ [str(value or "") for value in extra_headers.values()]+ if isinstance(extra_headers, Mapping)+ else []+ )+ secrets = [+ str(getattr(config, "api_key", "") or ""),+ str(getattr(config, "effective_url", "") or ""),+ str(getattr(config, "base_url", "") or ""),+ *header_values,+ ]+ for secret in secrets:+ if secret and secret not in {"no-key", "sk-no-key-required"}:+ message = message.replace(secret, "[redacted]")+ message = re.sub(r"\bsk-[A-Za-z0-9_-]{4,}\b", "[redacted]", message)+ message = re.sub(+ r"(?i)((?:api[_-]?key|authorization|token|password)\s*[:=]\s*)[^\s,;]+",+ r"\1[redacted]",+ message,+ )+ return message+++async def _probe_provider(config: Any) -> None:+ from deeptutor.services.llm import complete++ response = await complete(+ model=str(config.model),+ prompt="Reply with OK.",+ system_prompt="Reply with only OK.",+ binding=str(config.binding),+ api_key=str(config.api_key or ""),+ base_url=str(config.effective_url or config.base_url or ""),+ api_version=config.api_version,+ temperature=0,+ extra_headers=config.extra_headers,+ reasoning_effort=config.reasoning_effort,+ max_retries=0,+ allow_image_fallback=False,+ max_tokens=64,+ )+ if not (response or "").strip():+ raise RuntimeError("The model returned an empty response.")+++async def run_diagnostics(+ *,+ online: bool = False,+ resolve_llm: Callable[[], Any] | None = None,+ data_root: Path | None = None,+ load_rag_config: Callable[[], dict[str, Any]] | None = None,+ rag_preflight: Callable[[str], dict[str, Any]] | None = None,+ online_probe: Callable[[Any], Awaitable[None]] | None = None,+) -> DoctorReport:+ """Run setup diagnostics without network access unless ``online`` is set."""+ if resolve_llm is None:+ from deeptutor.services.config import resolve_llm_runtime_config++ resolve_llm = resolve_llm_runtime_config+ if data_root is None:+ from deeptutor.services.path_service import get_path_service++ data_root = get_path_service().get_user_root()+ if load_rag_config is None:+ from deeptutor.services.config import get_kb_config_service++ load_rag_config = get_kb_config_service().get_all_configs+ if rag_preflight is None:+ from deeptutor.services.rag.preflight import engine_preflight++ rag_preflight = engine_preflight+ if online_probe is None:+ online_probe = _probe_provider++ checks: list[DoctorCheck] = []+ config = None+ llm_ready = False+ try:+ config = resolve_llm()+ llm_checks = _llm_checks(config)+ checks.extend(llm_checks)+ llm_ready = all(check.status != "fail" for check in llm_checks if check.required)+ except Exception as exc:+ checks.append(+ DoctorCheck(+ key="llm_config",+ label="LLM configuration",+ status="fail",+ detail=f"Could not resolve active LLM settings: {_redact_error(exc, None)}",+ )+ )++ checks.append(_storage_check(data_root))+ try:+ checks.append(_rag_check(load_rag_config(), rag_preflight))+ except Exception as exc:+ checks.append(+ DoctorCheck(+ key="rag",+ label="RAG prerequisites",+ status="fail",+ detail=f"Could not inspect RAG settings: {_redact_error(exc, None)}",+ required=False,+ )+ )++ if not online:+ checks.append(+ DoctorCheck(+ key="online",+ label="Provider response",+ status="skip",+ detail="Not requested. Use --online to send a small model request.",+ required=False,+ )+ )+ elif config is None or not llm_ready:+ checks.append(+ DoctorCheck(+ key="online",+ label="Provider response",+ status="skip",+ detail="Skipped because local LLM checks failed.",+ required=False,+ )+ )+ else:+ try:+ await online_probe(config)+ checks.append(+ DoctorCheck(+ key="online",+ label="Provider response",+ status="pass",+ detail="The model returned a response.",+ )+ )+ except Exception as exc:+ checks.append(+ DoctorCheck(+ key="online",+ label="Provider response",+ status="fail",+ detail=_redact_error(exc, config),+ )+ )++ return DoctorReport(online=online, checks=checks)+++__all__ = ["DoctorCheck", "DoctorReport", "run_diagnostics"]diff --git a/deeptutor_cli/doctor.py b/deeptutor_cli/doctor.pynew file mode 100644index 000000000..a2d94124d--- /dev/null+++ b/deeptutor_cli/doctor.py@@ -0,0 +1,66 @@+"""Setup diagnostics for the DeepTutor CLI."""++from __future__ import annotations++import asyncio+import json++from rich.table import Table+import typer++from deeptutor.services.doctor import DoctorReport, run_diagnostics++from .common import console+++def _render_rich(report: DoctorReport) -> None:+ table = Table(title="DeepTutor setup diagnostics")+ table.add_column("Status", no_wrap=True)+ table.add_column("Check")+ table.add_column("Details")+ for check in report.checks:+ if check.status == "pass":+ status = "[green]PASS[/green]"+ elif check.status == "fail" and not check.required:+ status = "[yellow]WARN[/yellow]"+ elif check.status == "fail":+ status = "[red]FAIL[/red]"+ else:+ status = "[dim]SKIP[/dim]"+ table.add_row(status, check.label, check.detail)+ console.print(table)+ if report.ok:+ console.print("[green]Required checks passed.[/green]")+ else:+ console.print("[red]One or more required checks failed.[/red]")+++def register(app: typer.Typer) -> None:+ @app.command("doctor")+ def doctor(+ online: bool = typer.Option(+ False,+ "--online",+ help="Send a small request to the configured model provider.",+ ),+ fmt: str = typer.Option(+ "rich",+ "--format",+ "-f",+ help="Output format: rich | json.",+ ),+ ) -> None:+ """Check whether DeepTutor is ready to start a session."""+ if fmt not in {"rich", "json"}:+ raise typer.BadParameter("must be 'rich' or 'json'", param_hint="--format")++ report = asyncio.run(run_diagnostics(online=online))+ if fmt == "json":+ console.print_json(json.dumps(report.to_dict()))+ else:+ _render_rich(report)+ if not report.ok:+ raise typer.Exit(code=1)+++__all__ = ["register"]diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.pyindex d722f1422..4f39acf7e 100644--- a/deeptutor_cli/main.py+++ b/deeptutor_cli/main.py@@ -13,6 +13,7 @@ from .book import register as register_bookfrom .chat import register as register_chatfrom .common import build_turn_request, console, maybe_runfrom .config_cmd import register as register_config+from .doctor import register as register_doctorfrom .init_cmd import register as register_initfrom .kb import register as register_kbfrom .memory import register as register_memory@@ -69,6 +70,7 @@ register_session(session_app)register_notebook(notebook_app)register_provider(provider_app)register_book(book_app)+register_doctor(app)register_init(app)diff --git a/tests/cli/test_doctor_cli.py b/tests/cli/test_doctor_cli.pynew file mode 100644index 000000000..d574856e3--- /dev/null+++ b/tests/cli/test_doctor_cli.py@@ -0,0 +1,470 @@+"""Tests for the ``deeptutor doctor`` command."""++from __future__ import annotations++import json+from types import SimpleNamespace++import pytest+from typer.testing import CliRunner++from deeptutor.services.doctor import DoctorCheck, DoctorReport, run_diagnostics+from deeptutor_cli.main import app++runner = CliRunner()+++def _llm_config(**overrides):+ values = {+ "model": "gpt-4o-mini",+ "provider_name": "openai",+ "provider_mode": "standard",+ "binding": "openai",+ "api_key": "sk-test-secret",+ "base_url": "https://api.openai.com/v1",+ "effective_url": "https://api.openai.com/v1",+ "api_version": None,+ "extra_headers": {},+ "reasoning_effort": None,+ }+ values.update(overrides)+ return SimpleNamespace(**values)+++async def test_local_diagnostics_pass_without_contacting_provider(tmp_path) -> None:+ online_calls = []++ async def online_probe(config) -> None:+ online_calls.append(config)++ report = await run_diagnostics(+ online=False,+ resolve_llm=lambda: _llm_config(),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ online_probe=online_probe,+ )++ assert report.ok is True+ assert online_calls == []+ assert {check.key: check.status for check in report.checks} == {+ "llm_config": "pass",+ "llm_credentials": "pass",+ "llm_endpoint": "pass",+ "storage": "pass",+ "rag": "skip",+ "online": "skip",+ }+++async def test_missing_required_llm_settings_fail_diagnostics(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(model="", api_key=""),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ checks = {check.key: check for check in report.checks}+ assert report.ok is False+ assert checks["llm_config"].status == "fail"+ assert checks["llm_credentials"].status == "fail"+++async def test_storage_probe_failure_is_reported(tmp_path) -> None:+ file_instead_of_directory = tmp_path / "blocked"+ file_instead_of_directory.write_text("occupied", encoding="utf-8")++ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(),+ data_root=file_instead_of_directory,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ storage = next(check for check in report.checks if check.key == "storage")+ assert storage.status == "fail"+ assert report.ok is False+++async def test_diagnostics_never_render_credentials_or_endpoint_secrets(tmp_path) -> None:+ api_key = "sk-top-secret-value"+ endpoint = "https://user:[email protected]/v1/path-secret?api_key=query-secret"++ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(+ api_key=api_key,+ base_url=endpoint,+ effective_url=endpoint,+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ rendered = json.dumps(report.to_dict())+ assert "https://example.com" in rendered+ for secret in (api_key, "user", "password", "path-secret", "query-secret"):+ assert secret not in rendered+++async def test_online_probe_failure_is_required_and_redacted(tmp_path) -> None:+ api_key = "sk-online-secret"++ async def failing_probe(config) -> None:+ raise RuntimeError(f"Provider rejected {config.api_key}")++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(api_key=api_key),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ online_probe=failing_probe,+ )++ online = next(check for check in report.checks if check.key == "online")+ assert online.status == "fail"+ assert online.required is True+ assert api_key not in online.detail+ assert report.ok is False+++async def test_online_failure_redacts_configured_header_values(tmp_path) -> None:+ header_secret = "header-secret-value"++ async def failing_probe(config) -> None:+ raise RuntimeError(f"Provider rejected {config.extra_headers['X-Custom-Auth']}")++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(+ extra_headers={"X-Custom-Auth": header_secret},+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ online_probe=failing_probe,+ )++ online = next(check for check in report.checks if check.key == "online")+ assert online.status == "fail"+ assert header_secret not in online.detail+++async def test_online_probe_success_is_reported(tmp_path) -> None:+ probed_models = []++ async def successful_probe(config) -> None:+ probed_models.append(config.model)++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ online_probe=successful_probe,+ )++ online = next(check for check in report.checks if check.key == "online")+ assert online.status == "pass"+ assert probed_models == ["gpt-4o-mini"]+ assert report.ok is True+++async def test_online_probe_passes_one_bounded_token_parameter(monkeypatch, tmp_path) -> None:+ import deeptutor.services.llm as llm++ captured = {}++ async def fake_complete(**kwargs):+ captured.update(kwargs)+ return "OK"++ monkeypatch.setattr(llm, "complete", fake_complete)++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(+ model="gpt-5-mini",+ provider_name="openrouter",+ provider_mode="gateway",+ binding="openrouter",+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ assert report.ok is True+ assert captured["max_tokens"] == 64+ assert "max_completion_tokens" not in captured+++async def test_online_probe_preserves_empty_custom_endpoint_api_key(monkeypatch, tmp_path) -> None:+ import deeptutor.services.llm as llm++ captured = {}++ async def fake_complete(**kwargs):+ captured.update(kwargs)+ return "OK"++ monkeypatch.setattr(llm, "complete", fake_complete)++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(+ provider_name="custom",+ provider_mode="direct",+ binding="custom",+ api_key="",+ base_url="https://models.example.com/v1",+ effective_url="https://models.example.com/v1",+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ assert report.ok is True+ assert captured["api_key"] == ""+++async def test_online_probe_is_skipped_when_local_llm_checks_fail(tmp_path) -> None:+ online_calls = []++ async def online_probe(config) -> None:+ online_calls.append(config)++ report = await run_diagnostics(+ online=True,+ resolve_llm=lambda: _llm_config(model="", api_key=""),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ online_probe=online_probe,+ )++ online = next(check for check in report.checks if check.key == "online")+ assert online_calls == []+ assert online.status == "skip"+ assert report.ok is False+++async def test_local_provider_does_not_require_placeholder_api_key(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(+ provider_name="ollama",+ provider_mode="local",+ binding="ollama",+ api_key="sk-no-key-required",+ base_url="http://localhost:11434/v1",+ effective_url="http://localhost:11434/v1",+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ credentials = next(check for check in report.checks if check.key == "llm_credentials")+ assert credentials.status == "pass"+ assert report.ok is True+++async def test_unrecognized_headers_do_not_count_as_cloud_credentials(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(+ api_key="",+ extra_headers={"X-Trace-ID": "diagnostic-trace"},+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ credentials = next(check for check in report.checks if check.key == "llm_credentials")+ assert credentials.status == "fail"+ assert report.ok is False+++async def test_remote_custom_endpoint_without_credentials_is_advisory(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(+ provider_name="custom",+ provider_mode="direct",+ binding="custom",+ api_key="",+ base_url="https://models.example.com/v1",+ effective_url="https://models.example.com/v1",+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ credentials = next(check for check in report.checks if check.key == "llm_credentials")+ assert credentials.status == "skip"+ assert credentials.required is False+ assert report.ok is True+++async def test_custom_auth_header_counts_as_custom_endpoint_credentials(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(+ provider_name="custom",+ provider_mode="direct",+ binding="custom",+ api_key="",+ extra_headers={"X-Custom-Auth": "custom-secret"},+ base_url="https://models.example.com/v1",+ effective_url="https://models.example.com/v1",+ ),+ data_root=tmp_path,+ load_rag_config=lambda: {"defaults": {}, "knowledge_bases": {}},+ )++ credentials = next(check for check in report.checks if check.key == "llm_credentials")+ assert credentials.status == "pass"+ assert report.ok is True+++async def test_configured_rag_backend_reports_advisory_preflight_failure(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(),+ data_root=tmp_path,+ load_rag_config=lambda: {+ "defaults": {"rag_provider": "llamaindex"},+ "knowledge_bases": {"notes": {"rag_provider": "llamaindex"}},+ },+ rag_preflight=lambda provider: {+ "ok": False,+ "checks": [+ {+ "label": "Active embedding model",+ "ok": False,+ "optional": False,+ }+ ],+ },+ )++ rag = next(check for check in report.checks if check.key == "rag")+ assert rag.status == "fail"+ assert rag.required is False+ assert "Active embedding model" in rag.detail+ assert report.ok is True+++async def test_lightrag_server_checks_per_kb_connection_without_engine_preflight(tmp_path) -> None:+ preflight_calls = []++ def preflight(provider):+ preflight_calls.append(provider)+ raise AssertionError("server-backed RAG should not use engine_preflight")++ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(),+ data_root=tmp_path,+ load_rag_config=lambda: {+ "defaults": {"rag_provider": "llamaindex"},+ "knowledge_bases": {+ "remote-notes": {+ "rag_provider": "lightrag-server",+ "server_url": "https://rag.example.com",+ }+ },+ },+ rag_preflight=preflight,+ )++ rag = next(check for check in report.checks if check.key == "rag")+ assert preflight_calls == []+ assert rag.status == "pass"+ assert "lightrag-server" in rag.detail+++async def test_lightrag_server_reports_missing_connection_as_advisory(tmp_path) -> None:+ report = await run_diagnostics(+ resolve_llm=lambda: _llm_config(),+ data_root=tmp_path,+ load_rag_config=lambda: {+ "defaults": {},+ "knowledge_bases": {+ "remote-notes": {"rag_provider": "lightrag-server"},+ },+ },+ rag_preflight=lambda provider: pytest.fail(f"unexpected engine preflight for {provider}"),+ )++ rag = next(check for check in report.checks if check.key == "rag")+ assert rag.status == "fail"+ assert rag.required is False+ assert "remote-notes" in rag.detail+ assert "no server URL configured" in rag.detail+ assert report.ok is True+++def test_doctor_json_exits_nonzero_for_required_failure(monkeypatch) -> None:+ async def fake_run_diagnostics(*, online: bool):+ assert online is False+ return DoctorReport(+ online=False,+ checks=[+ DoctorCheck(+ key="llm_config",+ label="LLM configuration",+ status="fail",+ detail="No active LLM model is configured.",+ )+ ],+ )++ monkeypatch.setattr("deeptutor_cli.doctor.run_diagnostics", fake_run_diagnostics)++ result = runner.invoke(app, ["doctor", "--format", "json"])++ assert result.exit_code == 1, result.output+ assert json.loads(result.output) == {+ "ok": False,+ "online": False,+ "checks": [+ {+ "key": "llm_config",+ "label": "LLM configuration",+ "status": "fail",+ "detail": "No active LLM model is configured.",+ "required": True,+ }+ ],+ }+++def test_doctor_online_rich_output_succeeds(monkeypatch) -> None:+ async def fake_run_diagnostics(*, online: bool):+ assert online is True+ return DoctorReport(+ online=True,+ checks=[+ DoctorCheck(+ key="online",+ label="Provider response",+ status="pass",+ detail="The model returned a response.",+ )+ ],+ )++ monkeypatch.setattr("deeptutor_cli.doctor.run_diagnostics", fake_run_diagnostics)++ result = runner.invoke(app, ["doctor", "--online"])++ assert result.exit_code == 0, result.output+ assert "PASS" in result.output+ assert "Provider response" in result.output