Skip to content

Latest commit

 

History

History
272 lines (208 loc) · 9.6 KB

File metadata and controls

272 lines (208 loc) · 9.6 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

AI Shell Command Generator: A cross-platform CLI tool that translates natural language queries into executable shell commands using AI providers (OpenAI, Anthropic Claude, and Ollama). Features risk assessment, teaching mode, and supports multiple shells (bash, PowerShell, cmd).

Entry Points:

  • ai_shell_command_generator/main.py - Package initialization and environment setup
  • ai_shell_command_generator/cli/commands.py - Main CLI command handler using Click

Published to PyPI as ai-shell-command-generator with aliases ai-shell and aisc

Architecture

Provider Pattern (Plugin-based)

The codebase uses a factory pattern for AI providers. All providers implement BaseProvider abstract class.

Key files:

  • providers/base.py - Abstract base class defining provider interface
  • providers/factory.py - ProviderFactory.create_provider() instantiates providers
  • providers/anthropic_provider.py - Claude implementation
  • providers/openai_provider.py - GPT implementation
  • providers/ollama_provider.py - Local AI implementation
  • providers/models.py - ModelRegistry - centralized model definitions and validation

Provider responsibilities:

  1. generate_command() - Generate shell command from natural language
  2. generate_teaching_response() - Generate command + educational breakdown
  3. assess_risk() - Analyze command for safety concerns (deletion, permissions, etc.)
  4. list_available_models() - Return supported models

Adding a new provider:

  1. Create providers/new_provider.py extending BaseProvider
  2. Implement all abstract methods
  3. Add factory method in factory.py
  4. Register models in models.py ModelRegistry

Configuration System

core/config.py contains dataclasses for configuration:

  • CommandConfig - Main config (provider, shell, mode flags)
  • ProviderConfig - Per-provider settings (API keys, models)
  • TeachingConfig - Teaching mode detail levels

Configuration flows: CLI args → Environment variables → Defaults

API Key Loading Priority (see main.py:12-27):

  1. Environment variables (e.g., OPENAI_API_KEY)
  2. ./.env in current directory (project-specific)
  3. ~/.ai-shell-env in home directory (user-specific)
  4. Interactive prompt with save option (only for Anthropic/OpenAI)

Two Operating Modes

Interactive Mode (default):

  • User selects provider/model via prompts (cli/prompts.py)
  • Shell auto-detection with confirmation
  • Interactive query loop with teaching/explanation options
  • Implemented in run_interactive_mode() in commands.py:133

Non-Interactive Mode (with -q flag):

  • All parameters required via CLI flags
  • Shell MUST be specified explicitly for safety (commands.py:148-156)
  • Direct command output for scripting/CI/CD
  • Implemented in run_non_interactive_mode() in commands.py:92

Teaching Mode

Two-phase educational system:

Phase 1: Generate teaching response

  • Providers parse structured sections (COMMAND, BREAKDOWN, OS NOTES, SAFER APPROACH, WHAT YOU LEARNED)
  • Common parser in teaching/formatter.py:parse_teaching_response()
  • Providers use structured prompts (see _build_teaching_prompt() in each provider)

Phase 2: Interactive teaching loop

  • teaching/interactive.py:teaching_loop() - handles Q&A, examples, alternatives
  • Options: ask questions, see examples, explore alternatives, ready to use
  • User can clarify, request variations, or request different approaches

Display and Output

All user-facing output goes through cli/display.py:

  • display_command() - Show generated command
  • display_risk_warning() - Color-coded risk levels (HIGH/MEDIUM/LOW)
  • display_teaching_output() - Formatted teaching sections
  • display_provider_info() - Show current provider/model

Risk Assessment Colors:

  • HIGH (red) - Destructive operations, data loss risk
  • MEDIUM (yellow) - Permission changes, system modifications
  • LOW (green) - Safe operations

Shell Support

core/os_detection.py - Platform and shell detection

  • Supported shells: bash, powershell, cmd
  • Detects OS-specific command variants (BSD vs GNU)
  • Generates platform-appropriate commands (e.g., Get-ChildItem for PowerShell vs find for bash)

Development Commands

Setup

# Clone and create virtual environment
git clone https://github.com/codingthefuturewithai/ai-shell-command-generator.git
cd ai-shell-command-generator

# Install with all dependencies
uv pip install -e ".[dev]"

Testing

# Run all tests
uv run pytest tests/ -v

# Run specific test category
uv run pytest tests/unit/ -v
uv run pytest tests/integration/ -v

# Run with coverage
uv run pytest tests/ -v --cov=ai_shell_command_generator --cov-report=html

# Run single test file
uv run pytest tests/unit/test_providers.py -v

# Run single test
uv run pytest tests/unit/test_providers.py::test_specific_function -v

Test Structure:

  • tests/unit/ - Unit tests for individual components
  • tests/integration/ - Integration tests requiring API keys (optional)
  • tests/integration/conftest.py - Shared fixtures, API key validation

Integration tests require:

  • Real API keys in environment or ~/.ai-shell-env
  • Skip with markers if keys not available
  • Use @pytest.mark.integration decorator

Building and Publishing

# Build package
uv build

# Check package
twine check dist/*

# Upload to PyPI (requires credentials)
twine upload dist/*

# Upload to TestPyPI first (recommended)
twine upload --repository testpypi dist/*

Running Locally

# Interactive mode
uv run python -m ai_shell_command_generator.main

# Non-interactive with Ollama (no API key needed)
uv run python -m ai_shell_command_generator.main -p ollama -s bash -q "find large files"

# With teaching mode
uv run python -m ai_shell_command_generator.main --teach -p ollama -s bash -q "backup documents"

# List models
uv run python -m ai_shell_command_generator.main --list-models anthropic

Debugging

# Enable debug logging
export LOG_LEVEL=DEBUG
uv run python -m ai_shell_command_generator.main -p anthropic -s bash -q "test"

# Check logs in provider files for API request/response details
# All providers log: model, tokens, prompt, response via utils/logger.py

Important Implementation Details

Prompt Engineering

Each provider has three prompt builders:

  • _build_command_prompt() - Simple command generation (max_tokens: 300)
  • _build_teaching_prompt() - Structured teaching response (max_tokens: 1500)
  • _build_risk_prompt() - JSON-formatted risk assessment (max_tokens: 200)

Critical: OpenAI uses system messages to reduce reasoning token usage (see openai_provider.py:172-185). Anthropic uses only user messages with instructions inline.

Risk Assessment

Providers return risk dict: {"is_risky": bool, "severity": "low/medium/high", "reason": str}

Assessment checks for:

  • Data deletion (rm -rf, dd, destructive operations)
  • Permission changes (chmod, chown, setfacl)
  • System modifications (network settings, system files, services)
  • Recursive operations (widespread changes)
  • Network exposure (opening ports, firewall changes)

Command Cleaning

BaseProvider._clean_command() removes markdown formatting only:

  • Strips markdown code blocks (bash ... )
  • Preserves actual shell syntax (pipes, redirects, quotes)
  • Does NOT interpret or validate shell semantics

Teaching Response Format

Structured sections parsed from AI output:

COMMAND:
[command]

BREAKDOWN:
[explanation]

OS NOTES:
[platform specifics]

SAFER APPROACH:
[preview/alternative]

WHAT YOU LEARNED:
[key concepts]

Parsing handled by teaching/formatter.py:parse_teaching_response()

API Key Management

Ollama requires no API key (local). OpenAI and Anthropic prompt interactively if missing:

  • cli/prompts.py:prompt_for_api_key() - Interactive prompt
  • Option to save to ~/.ai-shell-env permanently
  • Saved keys loaded on next run via main.py initialization

Code Style

  • Type hints: Use throughout (Python 3.10+ syntax)
  • Docstrings: Google style for classes/methods
  • Line length: 88 characters (Black formatter)
  • Imports: Standard lib → Third party → Local (separated by blank lines)
  • Error handling: Specific exceptions, user-friendly messages via cli/display.py

Critical Safety Requirements

  1. Shell validation in non-interactive mode - MUST require -s flag explicitly. See config.py:148-156
  2. Risk assessment opt-in - Default enabled, user can disable with --no-risk-check
  3. Command cleaning - Only remove markdown, never modify shell syntax
  4. API key security - Never log API keys, use environment variables
  5. Cross-platform testing - Test on Windows/macOS/Linux when changing shell-specific code

Common Tasks

Adding a new model

  1. Add to providers/models.py ModelRegistry dictionaries
  2. Update provider's list_available_models() if needed
  3. Test with --list-models flag

Modifying prompts

  1. Edit provider's _build_*_prompt() methods
  2. Test with debug logging: LOG_LEVEL=DEBUG
  3. Verify token usage (logged in response)
  4. Update integration tests if behavior changes

Adding CLI options

  1. Add Click option in cli/commands.py:main() decorator
  2. Add field to CommandConfig in core/config.py
  3. Update CommandConfig.from_cli_args() to handle new option
  4. Update help text and README.md

Debugging provider issues

  1. Enable debug logging: export LOG_LEVEL=DEBUG
  2. Check provider logs for API calls (request/response)
  3. Verify prompt format matches provider expectations
  4. Test with simple query first: -q "list files"