Skip to content

Conversation

@lu11y0
Copy link
Contributor

@lu11y0 lu11y0 commented Dec 18, 2025

Related Issue

Closes #245

Summary

Create a diagnostic command that checks system readiness and suggests fixes.
Command: cortex doctor

Checks:

  • Python version and dependencies
  • GPU drivers installed and working
  • CUDA/ROCm availability
  • Ollama installed and running
  • API keys configured
  • Disk space available
  • Memory sufficient for models
  • Meets Acceptance Criteria

Screen.Recording.2025-12-18.120538.mp4

Checklist

  • Tests pass (pytest tests/test_doctor.py)
  • PR title format: [#XX] Description
  • MVP label added if closing MVP issue

Summary by CodeRabbit

  • New Features

    • Added a new doctor command that runs comprehensive system health checks (Python, dependencies, GPU/CUDA, Ollama, API keys, disk space, memory) and displays actionable fix suggestions with appropriate exit codes.
  • Tests

    • Added unit tests covering the health-check command behavior, reporting, and exit-code logic.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 18, 2025

Walkthrough

Adds a new cortex doctor command and a SystemDoctor utility that runs checks (Python, dependencies, GPU drivers, CUDA/ROCm, Ollama, API keys, disk, memory), aggregates results into passes/warnings/failures with suggestions, and returns exit codes; CLI wired via a new CortexCLI.doctor() method.

Changes

Cohort / File(s) Summary
CLI Command Integration
cortex/cli.py
Added doctor() method to CortexCLI, wired doctor into CLI parsing and main dispatch so the command invokes SystemDoctor.run_checks().
System Health Check Implementation
cortex/doctor.py
New SystemDoctor class and run_doctor() entry point implementing checks for Python/version, dependencies (requirements.txt), GPU drivers (NVIDIA/ROCm), CUDA/ROCm availability, Ollama install/runtime, API keys, disk space, and memory; aggregates results, prints Rich-based output, and maps health to exit codes.
Unit Tests
tests/test_doctor.py
Added tests for SystemDoctor: initialization, Python version classification, dependency checks (mocked requirements/imports), GPU driver detection, and exit-code behavior with mocked internal checks and I/O.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review focus:
    • cortex/doctor.py: validate version parsing, dependency import checks and name mappings, GPU/driver detection heuristics, CUDA/ROCm detection, Ollama probing, API-key detection, and disk/memory thresholds and messaging.
    • tests/test_doctor.py: ensure mocks accurately simulate environments and assertions match expected output/exit codes.
    • cortex/cli.py: confirm CLI wiring and help text integration.

Suggested reviewers

  • mikejmorgan-ai

Poem

🐰 I hopped through logs and system cheers,
Checked Python, drivers, and storage gears,
Warnings in amber, fixes in sight,
The doctor helped the stack sleep tight — good night! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.69% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: cortex doctor - System Health Check' accurately describes the main change: adding a new diagnostic command feature to check system health.
Linked Issues check ✅ Passed The implementation addresses all requirements from issue #245: Python/dependency checks, GPU driver detection, CUDA/ROCm availability, Ollama status, API key verification, disk space assessment, memory checks, color-coded output via Rich, fix suggestions, and exit codes reflecting health status with unit tests.
Out of Scope Changes check ✅ Passed All code changes directly support the cortex doctor feature scope: new SystemDoctor class in doctor.py, CLI integration via doctor() method in CortexCLI, and corresponding unit tests in test_doctor.py. No unrelated modifications detected.
Description check ✅ Passed PR description includes all required sections: Related Issue (#245), comprehensive Summary with implemented checks, and completed Checklist items.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
cortex/doctor.py (3)

141-152: Address UP036 lint error - add noqa comment or configure ruff.

The lint error UP036: Version block is outdated for minimum Python version fires because the project's minimum Python is already 3.10+, making this check always true at import time.

However, cortex doctor is explicitly designed to validate runtime environments and report issues to users. This check is intentional—it informs users about their Python version even when it passes. To silence the lint:

🔎 Apply this diff to suppress the lint warning:
-        if sys.version_info >= (3, 10):
+        if sys.version_info >= (3, 10):  # noqa: UP036
             self._print_check("PASS", f"Python {version}")

Alternatively, configure ruff.toml to ignore UP036 for this file if this is a project-wide pattern.


154-161: Relative path for requirements.txt may fail when run from different directories.

Using Path("requirements.txt") assumes the current working directory is the project root. If a user runs cortex doctor from a subdirectory or a different location, this check will incorrectly warn about missing requirements.

Consider using the package's installation location or searching upward for the project root:

🔎 Suggested approach:
     def _check_dependencies(self) -> None:
         """Check packages from requirements.txt."""
         missing: list[str] = []
-        requirements_path = Path("requirements.txt")
+        # Try to find requirements.txt relative to this module's location
+        module_dir = Path(__file__).parent.parent
+        requirements_path = module_dir / "requirements.txt"
+        
+        # Fallback to CWD if not found
+        if not requirements_path.exists():
+            requirements_path = Path("requirements.txt")

         if not requirements_path.exists():
             self._print_check("WARN", "No requirements.txt found")
             return

169-179: Version specifier parsing doesn't handle all pip formats.

The current parsing line.split("==")[0].split(">")[0].split("<")[0] works for common cases but fails on:

  • pkg[extra]>=1.0 → extracts pkg[extra instead of pkg
  • pkg~=1.0 → extracts pkg~ instead of pkg
  • pkg @ https://... → extracts full URL portion

Consider using packaging.requirements for robust parsing, or add bracket/tilde handling:

🔎 Quick fix without adding dependencies:
                     if line and not line.startswith("#"):
-                        raw_name = line.split("==")[0].split(">")[0].split("<")[0]
+                        # Strip version specifiers and extras
+                        raw_name = line.split("==")[0].split(">=")[0].split("<=")[0]
+                        raw_name = raw_name.split(">")[0].split("<")[0].split("~=")[0]
+                        raw_name = raw_name.split("[")[0].split("@")[0].split(";")[0]
+                        raw_name = raw_name.strip()
                         pkg_name = name_overrides.get(raw_name, raw_name)
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd77316 and d720aa6.

📒 Files selected for processing (3)
  • cortex/cli.py (4 hunks)
  • cortex/doctor.py (1 hunks)
  • tests/test_doctor.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Follow PEP 8 style guide
Type hints required in Python code
Docstrings required for all public APIs

Files:

  • cortex/cli.py
  • cortex/doctor.py
  • tests/test_doctor.py
tests/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Maintain >80% test coverage for pull requests

Files:

  • tests/test_doctor.py
🧬 Code graph analysis (3)
cortex/cli.py (1)
cortex/doctor.py (2)
  • SystemDoctor (20-448)
  • run_checks (47-93)
cortex/doctor.py (2)
cortex/validators.py (1)
  • validate_api_key (20-48)
cortex/cli.py (1)
  • doctor (175-179)
tests/test_doctor.py (1)
cortex/doctor.py (5)
  • SystemDoctor (20-448)
  • _check_python (141-152)
  • _check_dependencies (154-197)
  • _check_gpu_driver (199-234)
  • run_checks (47-93)
🪛 GitHub Actions: CI
cortex/doctor.py

[error] 145-145: ruff check failed. UP036 Version block is outdated for minimum Python version.

🪛 GitHub Actions: Cortex Automation
cortex/doctor.py

[error] 1-1: PythonVersionCheck WARN scenario did not produce the expected warning for Python 3.9.0. Test looked for a warning containing 'Python 3.9.0 (3.10+ required)' but none was found. Command: 'pytest tests/ -v --cov=cortex --cov-report=xml --cov-report=term-missing'.

tests/test_doctor.py

[error] 45-45: TestPythonVersionCheck: WARN scenario did not produce expected warning 'Python 3.9.0'. The test expected a warning about Python 3.9.0 (3.10+ required) but none was found.

🪛 GitHub Check: Lint
cortex/doctor.py

[failure] 145-145: Ruff (UP036)
cortex/doctor.py:145:12: UP036 Version block is outdated for minimum Python version

🔇 Additional comments (7)
cortex/cli.py (2)

174-179: LGTM! Clean integration of the doctor command.

The lazy import pattern keeps startup fast, and the method correctly delegates to SystemDoctor.run_checks() and returns its exit code. This aligns well with the CLI's existing patterns.


620-622: Subparser wiring looks correct.

The doctor subparser is properly registered and the command dispatch at lines 702-703 correctly routes to cli.doctor().

tests/test_doctor.py (1)

93-129: Good isolation strategy for exit code tests.

Mocking all individual check methods and then setting passes/warnings/failures directly is a clean way to test the exit code logic without depending on the real system state.

cortex/doctor.py (4)

451-463: LGTM! Clean public entry point.

The run_doctor() function provides a clean API entry point, and the __main__ block correctly propagates exit codes for direct script execution.


281-306: Ollama check implementation looks solid.

Good practices observed:

  • Lazy import of requests only when needed
  • Reasonable 2-second timeout for the API check
  • Clear messaging for installed-but-not-running vs not-installed states

199-234: GPU driver check is well-structured.

The check correctly:

  • Tries NVIDIA first, then AMD ROCm
  • Uses timeouts to prevent hangs
  • Treats missing GPU as a warning (not failure) since CPU-only mode is supported
  • Provides helpful suggestions

The broad except Exception is acceptable here for defensive error handling in a diagnostic tool.


314-319: Fix typo in suggestion: ANTHROPOL_API_KEYANTHROPIC_API_KEY.

The suggestion contains a typo that would mislead users trying to configure their API key.

🔎 Apply this diff:
         else:
             self._print_check(
                 "WARN",
                 "No API keys configured (required for cloud models)",
-                "Configure API key: export ANTHROPOL_API_KEY=sk-... " "or run 'cortex wizard'",
+                "Configure API key: export ANTHROPIC_API_KEY=sk-ant-... or run 'cortex wizard'",
             )

Note: Also updated sk-... to sk-ant-... to match the Anthropic key format validated in cortex/validators.py.

Likely an incorrect or invalid review comment.

Cortex Automation / test errors
Copy link
Member

@mikejmorgan-ai mikejmorgan-ai left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cortex doctor: System Health Check

2 participants