Skip to content

Conversation

@Sahilbhatane
Copy link
Collaborator

@Sahilbhatane Sahilbhatane commented Nov 14, 2025

Summary

  • expand InstallationCoordinator with plan-based initialization, richer logging, and automatic rollback registration
  • modernize Docker installation workflow to use signed keyrings and provide concrete verification and rollback steps
  • relocate coordinator tests, add run_all_tests.py runner, and extend coverage for plan parsing plus CUDA sample plan

Testing

  • python -m unittest test.test_coordinator
  • python test/run_all_tests.py

this satisfy everything mentioned.

Summary by CodeRabbit

  • New Features

    • Added interactive CLI tool for AI-assisted software installation with dry-run and execute modes.
    • Added installation coordination framework supporting multi-step execution, progress tracking, rollback capabilities, and verification.
  • Tests

    • Added comprehensive test suites for CLI and installation coordination.
  • Chores

    • Added Python .gitignore configuration.
    • Updated package manifest and setup configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 14, 2025

Walkthrough

This PR introduces cortex-linux, a Python project featuring an AI-powered CLI tool for software installation. It includes packaging configuration, a core package with CLI and installation coordination subsystems, comprehensive test coverage with mocks, and updates to existing test imports.

Changes

Cohort / File(s) Summary
Project Packaging
.gitignore, MANIFEST.in, setup.py
Adds standard Python .gitignore exclusions for build/cache artifacts; configures package manifest to include README, LICENSE, and source files; defines setup.py with console entry point cortex=cortex.cli:main, metadata, Python >=3.8 requirement, and dynamic dependency resolution from LLM/requirements.txt.
Core cortex Package
cortex/__init__.py, cortex/cli.py
Exposes main CLI entry point and version "0.1.0" from package; implements CortexCLI class with install method accepting software, execute, and dry_run flags; orchestrates API key retrieval, provider selection (OpenAI/Anthropic), CommandInterpreter invocation, progress feedback with spinner, command display, and optional execution via InstallationCoordinator.
Installation Coordinator
cortex/coordinator.py
Introduces InstallationStep and InstallationResult data models; implements InstallationCoordinator for orchestrating multi-step installations with timeout, stop_on_error, rollback support, logging, and progress callbacks; provides from_plan() classmethod, add_rollback_command(), execute(), verify_installation(), get_summary(), and export_log() methods; includes helper functions install_docker() and example_cuda_install_plan().
Test Infrastructure
test/run_all_tests.py, test/test_cli.py, test/test_coordinator.py
Adds test runner discovering and executing test_*.py modules; comprehensive test suite for CortexCLI covering API key retrieval, provider selection, status output, and installation workflows (dry-run, execute, error handling); extensive test suite for InstallationCoordinator validating step creation, execution with timeouts, rollback behavior, logging, verification, and Docker installation scenario.
Test Import Updates
LLM/test_interpreter.py
Updates patch targets from interpreter.OpenAI/interpreter.Anthropic to openai.OpenAI/anthropic.Anthropic; adjusts sys.path for importing from LLM.interpreter module.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as CortexCLI
    participant Interpreter as CommandInterpreter
    participant Coordinator as InstallationCoordinator
    participant System as OS/Subprocess

    User->>CLI: install(software, execute=True)
    CLI->>CLI: _get_api_key() [OpenAI/Anthropic]
    CLI->>CLI: _get_provider()
    
    rect rgba(200, 220, 255, 0.3)
        Note over CLI: Planning Phase
        CLI->>Interpreter: generate_commands(software)
        Interpreter-->>CLI: list of commands
        CLI->>CLI: _print_status("Analyzing...")
    end
    
    rect rgba(220, 255, 220, 0.3)
        Note over CLI,Coordinator: Execution Phase
        CLI->>Coordinator: execute()
        
        loop For each command
            Coordinator->>System: subprocess.run(command, timeout)
            System-->>Coordinator: stdout, stderr, return_code
            Coordinator->>Coordinator: update InstallationStep status
            Coordinator->>CLI: progress_callback(step_index, total, step)
            CLI->>CLI: _print_status(command progress)
        end
        
        Coordinator-->>CLI: InstallationResult
    end
    
    CLI->>CLI: _print_success(duration)
    CLI-->>User: exit code 0
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45–60 minutes

  • cortex/coordinator.py: Dense logic with multiple data models, complex execution flow, timeout handling, rollback orchestration, and state transitions requiring careful validation
  • cortex/cli.py: Multi-stage CLI workflow with error paths, API provider selection, and integration of CommandInterpreter and InstallationCoordinator
  • test/test_coordinator.py & test/test_cli.py: Comprehensive test coverage with extensive mocking; verify correctness of CLI and coordinator across success/failure/edge cases
  • setup.py: Requires verification of entry points, dependency resolution, and metadata configuration

Key areas requiring attention:

  • Rollback logic correctness and order of execution in InstallationCoordinator
  • Timeout and subprocess handling under various failure scenarios
  • Progress callback invocation timing and parameter correctness
  • CLI error handling and exit code consistency across all paths
  • Mock coverage alignment with actual API calls in CLI tests

Poem

🐰 A CLI hops forth with AI's might,
Installing software left and right,
Commands orchestrated with care,
Rollbacks standing by, just there,
From cortex springs a stable flight!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.95% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: addition of a multi-step structured installation coordinator with plan support, and directly references the fixed issue.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@sonarqubecloud
Copy link

@Sahilbhatane
Copy link
Collaborator Author

@dhvll as you suggested I closed previous pull requests and creating new pull request each for specific for that issue on new branch. please review it. if any changes @ me here or mention me on discord ;)

@Sahilbhatane Sahilbhatane requested a review from dhvll November 14, 2025 15:41
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: 0

🧹 Nitpick comments (7)
LLM/test_interpreter.py (1)

4-9: Consider using relative imports or package installation.

While the sys.path manipulation works, consider either:

  • Using relative imports (from ..interpreter import ...)
  • Installing the package in development mode (pip install -e .)

This would make the tests more maintainable and align with the new setup.py configuration.

test/test_coordinator.py (1)

4-15: Consider using package installation for imports.

Similar to the test_interpreter.py file, consider installing the package in development mode (pip install -e .) instead of manipulating sys.path. This aligns better with the new setup.py configuration.

cortex/cli.py (3)

8-8: Consider removing sys.path manipulation.

Modifying sys.path at import time is an anti-pattern for installed packages. Since the project includes setup.py for proper package installation, the imports should resolve correctly without this manipulation. This line may cause issues in production environments or when the package is installed via pip.

Apply this diff to remove the sys.path manipulation:

-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
-
 from LLM.interpreter import CommandInterpreter

66-68: Consider extracting spinner iteration count.

The hard-coded value 10 for spinner animation iterations could be extracted as a class constant or configuration parameter for better maintainability.

Apply this diff to extract the magic number:

 class CortexCLI:
     def __init__(self):
         self.spinner_chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
         self.spinner_idx = 0
+        self.spinner_iterations = 10

Then use it in the install method:

-            for _ in range(10):
+            for _ in range(self.spinner_iterations):
                 self._animate_spinner("Analyzing system requirements...")

131-133: Catching bare Exception can hide unexpected errors.

The broad Exception catch at line 131 can mask unexpected errors and make debugging difficult. Consider either catching more specific exception types or at least logging the full exception traceback for debugging purposes.

Apply this diff to add logging for unexpected errors:

         except Exception as e:
-            self._print_error(f"Unexpected error: {str(e)}")
+            import traceback
+            self._print_error(f"Unexpected error: {str(e)}")
+            if os.environ.get('DEBUG'):
+                traceback.print_exc()
             return 1

Based on static analysis hints

test/test_cli.py (2)

6-6: Consider removing sys.path manipulation.

Similar to the CLI module, this sys.path manipulation should not be necessary if the package is properly installed for testing (e.g., with pip install -e .).

Apply this diff:

-sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
-
 from cortex.cli import CortexCLI, main

42-56: Strengthen print method test assertions.

These tests patch stdout/stderr but don't verify the actual output or that the print functions were called correctly. The assertions self.assertTrue(True) and self.assertTrue(mock_stdout.write.called or print) are weak and don't validate behavior.

Apply this diff to improve the tests:

     @patch('sys.stdout')
     def test_print_status(self, mock_stdout):
-        self.cli._print_status("🧠", "Test message")
-        self.assertTrue(mock_stdout.write.called or print)
+        with patch('builtins.print') as mock_print:
+            self.cli._print_status("🧠", "Test message")
+            mock_print.assert_called_once_with("🧠 Test message")
     
-    @patch('sys.stderr')
-    def test_print_error(self, mock_stderr):
-        self.cli._print_error("Test error")
-        self.assertTrue(True)
+    def test_print_error(self):
+        with patch('builtins.print') as mock_print:
+            self.cli._print_error("Test error")
+            mock_print.assert_called_once()
+            args, kwargs = mock_print.call_args
+            self.assertIn("Test error", args[0])
+            self.assertEqual(kwargs.get('file'), sys.stderr)
     
-    @patch('sys.stdout')
-    def test_print_success(self, mock_stdout):
-        self.cli._print_success("Test success")
-        self.assertTrue(True)
+    def test_print_success(self):
+        with patch('builtins.print') as mock_print:
+            self.cli._print_success("Test success")
+            mock_print.assert_called_once_with("✅ Test success")

Based on static analysis hints

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90236f7 and 6a3049d.

📒 Files selected for processing (10)
  • .gitignore (1 hunks)
  • LLM/test_interpreter.py (10 hunks)
  • MANIFEST.in (1 hunks)
  • cortex/__init__.py (1 hunks)
  • cortex/cli.py (1 hunks)
  • cortex/coordinator.py (1 hunks)
  • setup.py (1 hunks)
  • test/run_all_tests.py (1 hunks)
  • test/test_cli.py (1 hunks)
  • test/test_coordinator.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
LLM/test_interpreter.py (1)
LLM/interpreter.py (3)
  • CommandInterpreter (12-158)
  • APIProvider (7-9)
  • parse (131-145)
test/test_cli.py (3)
cortex/cli.py (8)
  • CortexCLI (14-133)
  • _get_api_key (19-24)
  • _get_provider (26-31)
  • _print_status (33-34)
  • _print_error (36-37)
  • _print_success (39-40)
  • install (52-133)
  • _animate_spinner (42-46)
LLM/interpreter.py (1)
  • parse (131-145)
cortex/coordinator.py (1)
  • execute (202-249)
test/test_coordinator.py (1)
cortex/coordinator.py (12)
  • InstallationCoordinator (44-300)
  • InstallationStep (19-32)
  • StepStatus (10-15)
  • install_docker (303-357)
  • example_cuda_install_plan (360-385)
  • duration (29-32)
  • from_plan (78-124)
  • execute (202-249)
  • add_rollback_command (198-200)
  • verify_installation (251-273)
  • get_summary (275-296)
  • export_log (298-300)
cortex/coordinator.py (1)
cortex/cli.py (1)
  • progress_callback (86-93)
cortex/__init__.py (1)
cortex/cli.py (1)
  • main (136-172)
cortex/cli.py (2)
LLM/interpreter.py (2)
  • CommandInterpreter (12-158)
  • parse (131-145)
cortex/coordinator.py (3)
  • InstallationCoordinator (44-300)
  • StepStatus (10-15)
  • execute (202-249)
🪛 Ruff (0.14.4)
LLM/test_interpreter.py

82-82: Unused method argument: mock_openai

(ARG002)

test/test_cli.py

28-28: Unused method argument: mock_stderr

(ARG002)


48-48: Unused method argument: mock_stderr

(ARG002)


53-53: Unused method argument: mock_stdout

(ARG002)

cortex/coordinator.py

65-65: Avoid specifying long messages outside the exception class

(TRY003)


102-102: Avoid specifying long messages outside the exception class

(TRY003)


134-135: try-except-pass detected, consider logging the exception

(S110)


134-134: Do not catch blind exception: Exception

(BLE001)


144-144: subprocess call with shell=True identified, security issue

(S602)


173-173: Do not catch blind exception: Exception

(BLE001)


177-177: Use explicit conversion flag

Replace with conversion flag

(RUF010)


189-189: subprocess call with shell=True identified, security issue

(S602)


195-195: Do not catch blind exception: Exception

(BLE001)


196-196: Use explicit conversion flag

Replace with conversion flag

(RUF010)


259-259: subprocess call with shell=True identified, security issue

(S602)


269-269: Do not catch blind exception: Exception

(BLE001)


271-271: Use explicit conversion flag

Replace with conversion flag

(RUF010)

cortex/cli.py

123-123: Consider moving this statement to an else block

(TRY300)


129-129: Use explicit conversion flag

Replace with conversion flag

(RUF010)


131-131: Do not catch blind exception: Exception

(BLE001)


132-132: Use explicit conversion flag

Replace with conversion flag

(RUF010)

🔇 Additional comments (27)
MANIFEST.in (1)

1-5: LGTM!

The packaging manifest correctly includes documentation, package code, and dependencies. This aligns well with the setup.py configuration.

test/run_all_tests.py (1)

6-17: LGTM!

The test runner correctly discovers and executes all test modules with appropriate verbosity and exit code handling.

LLM/test_interpreter.py (1)

17-225: LGTM!

The updated patch targets (openai.OpenAI and anthropic.Anthropic) are more precise and correctly match the actual import paths used in the implementation.

Note: The static analysis hint about unused mock_openai argument on line 82 is a false positive—the decorator requires this parameter.

.gitignore (1)

1-30: LGTM!

The .gitignore file includes comprehensive and standard Python-specific exclusions for build artifacts, caches, virtual environments, and distribution files.

cortex/coordinator.py (14)

10-16: LGTM!

The StepStatus enum provides clear state tracking for installation steps.


18-32: LGTM!

The InstallationStep dataclass is well-designed with appropriate fields for tracking command execution, timing, and results.


35-41: LGTM!

The InstallationResult dataclass provides a comprehensive summary of the installation process with all necessary fields.


47-75: LGTM!

The constructor is well-designed with appropriate validation of inputs and clear initialization logic. The static analysis hint about exception message length (line 65) is overly pedantic for this context.


77-124: LGTM!

The from_plan classmethod provides an elegant way to construct a coordinator from structured plans, with intelligent defaults for rollback behavior based on plan content. The static analysis hint about exception message length (line 102) is overly pedantic.


126-135: LGTM!

The logging method correctly handles file operations with timestamps. The broad exception handling with pass (lines 134-135) is acceptable here since logging failures shouldn't interrupt the installation process.


137-178: LGTM with security context.

The command execution logic is robust with proper timeout handling and error capture. The use of shell=True (line 144) is flagged by static analysis but is appropriate here since:

  • The tool's purpose is to execute shell commands
  • Commands come from user input or curated plans, not arbitrary external sources
  • Shell features (pipes, redirects) are needed for the Docker installation workflow

The broad exception handling (line 173) provides necessary resilience for command execution.


180-196: LGTM!

The rollback logic correctly executes commands in reverse order and handles failures gracefully. The broad exception handling (line 195) ensures rollback failures don't crash the coordinator.


198-200: LGTM!

Simple and clear method for registering rollback commands.


202-249: LGTM!

The execute method provides comprehensive orchestration with proper progress tracking, error handling, rollback triggering, and structured result reporting.


251-273: LGTM!

The verification method provides a clean way to validate installations with per-command success tracking.


275-300: LGTM!

The summary and export methods provide clear ways to retrieve and persist installation results.


303-357: LGTM!

The Docker installation function demonstrates best practices:

  • Modern signed keyring approach using /etc/apt/keyrings/docker.gpg (lines 314-326)
  • Proper rollback commands for service management
  • Post-installation verification

This is a solid reference implementation.


360-385: LGTM!

The example CUDA plan provides a good template for complex installation workflows with verification steps.

cortex/__init__.py (1)

1-2: LGTM!

The package initialization correctly exposes the CLI entry point and version, aligning with the setup.py configuration.

setup.py (1)

1-43: LGTM!

The setup.py configuration is well-structured with:

  • Dynamic reading of README and requirements
  • Proper metadata and classifiers
  • Console script entry point matching the package structure
  • Support for package data via MANIFEST.in
test/test_coordinator.py (4)

18-32: LGTM!

The InstallationStep tests provide good coverage of creation and duration calculation.


35-255: LGTM!

Comprehensive test coverage for coordinator initialization, execution modes, error handling, callbacks, logging, and rollback functionality. The mocking strategy is appropriate and the tests are well-structured.


257-333: LGTM!

Excellent coverage of verification, summary, export, and timing functionality with proper resource cleanup for temporary files.


336-372: LGTM!

Good integration tests for the Docker installation workflow and CUDA plan structure validation.

cortex/cli.py (1)

136-173: LGTM! Well-structured CLI entry point.

The main function provides comprehensive help text, clear examples, and proper argument handling. The subcommand structure allows for future extensibility.

test/test_cli.py (2)

16-41: LGTM! Comprehensive API key and provider tests.

These tests properly cover the environment variable lookup logic for both OpenAI and Anthropic API keys, including the missing key scenario.


57-203: LGTM! Comprehensive installation flow tests.

These tests provide excellent coverage of the installation workflow including:

  • API key validation
  • Dry-run and execution modes
  • Success and failure scenarios
  • Exception handling (ValueError, RuntimeError, generic Exception)
  • CLI argument parsing and command dispatch
  • Spinner animation behavior

The proper use of mocks prevents actual API calls and command execution during testing.

@mikejmorgan-ai mikejmorgan-ai merged commit 95342d8 into cortexlinux:main Nov 14, 2025
2 checks passed
@Sahilbhatane Sahilbhatane deleted the issue-8 branch November 14, 2025 18:18
@mikejmorgan-ai
Copy link
Member

🎯 Closing for MVP Focus

This issue is being closed to help the team focus on MVP-critical features (#1-45).

This is NOT abandoned - it's an important feature we'll revisit after MVP completion.

Timeline:

Want to work on this anyway?
Comment below and we can discuss! We're always open to great contributions.

Tracking: Labeled as post-mvp for easy filtering when we reopen.

Thanks for understanding! 🚀

— Mike (@mikejmorgan-ai)

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.

2 participants