# AI Developer Assistant

A modular, open-source AI Developer Assistant designed to automate, accelerate, and improve the software development lifecycle. This command-line tool helps developers review, understand, document, refactor, test, and secure code using AI models while maintaining privacy, extensibility, and open access.

## Features

### Core Capabilities
- **Code Review & Analysis**: Identify logical errors, style issues, and missing documentation
- **Code Understanding**: Explain commits, diffs, or functions in plain English
- **Code Improvement**: Suggest refactoring improvements and cleaner structures
- **Testing Automation**: Generate test case templates and suggest missing edge cases
- **Security Scanning**: Detect common vulnerabilities and security issues
- **Documentation Generation**: Auto-generate docstrings, changelogs, and API documentation
- **Developer Mentorship**: Provide constructive feedback on code quality and maintainability

### Language-Specific Intelligence
- **Automatic Language Detection**: Detects programming languages from file extensions
- **Framework Auto-Selection**: Chooses appropriate testing frameworks for each language
- **Language-Specific Analysis**: Tailored code analysis and suggestions per language
- **Multi-Language Support**: Dart, TypeScript, JavaScript, Python, Java, C#, Go, Rust, and more
- **Beautiful Output**: Colorized, formatted output with language-specific syntax highlighting

### Key Benefits
- **Privacy-First**: Supports both local (offline) and remote LLMs
- **Modular Architecture**: Cleanly layered, technology-agnostic using Hexagonal Architecture
- **Extensible**: Plugin-ready system for custom adapters and integrations
- **CLI-First**: Optimized for command-line workflows with potential IDE extensions
- **File-Pattern Support**: Analyze specific files or file types with `--file-patterns`
- **Beautiful Output**: Colorized, structured output with JSON parsing and formatting
- **Multi-LLM Support**: OpenAI, Ollama (local), and Google Gemini integration

## Quick Start

### Installation

```bash
# Clone the repository
git clone https://github.com/kg6-oss/kg6-codex.git
cd ai-developer-assistant

# Install dependencies
npm install

# Build the project
npm run build

# Install globally (optional)
npm install -g .
```

### Configuration

1. Copy the example configuration:
```bash
cp env.example .env
```

2. Configure your AI provider:
```bash
# For OpenAI
export OPENAI_API_KEY="your-openai-api-key"

# For Ollama (local)
export OLLAMA_BASE_URL="http://localhost:11434"

# For Gemini (Google)
export GEMINI_API_KEY="your-gemini-api-key"
```

3. Create a configuration file:
```bash
cp ai-dev.config.yaml ai-dev.config.local.yaml
# Edit ai-dev.config.local.yaml with your preferences
```

### Basic Usage

```bash
# Review your latest changes
ai-dev review

# Review specific files (auto-detects language)
ai-dev review --file-patterns "lib/**/*.dart"
ai-dev review --file-patterns "src/**/*.ts"

# Explain what changed in your last commit
ai-dev explain

# Generate a commit message
ai-dev commit-msg

# Suggest test cases for new code (auto-detects language & framework)
ai-dev test-suggest
ai-dev test-suggest --file-patterns "lib/**/*.dart"  # Generates Dart/Flutter tests
ai-dev test-suggest --file-patterns "src/**/*.ts"   # Generates TypeScript/Jest tests

# Scan for security issues
ai-dev security-scan
ai-dev security-scan --file-patterns "*.py"  # Python-specific security scan

# Generate documentation
ai-dev docs
ai-dev docs --file-patterns "lib/**/*.dart" --doc-type "api"  # Dart API docs
```

### Advanced File Pattern Usage

The AI Developer Assistant supports powerful file pattern matching for targeted analysis:

```bash
# Analyze specific file types across your project
ai-dev review --file-patterns "src/**/*.ts" --exclude-patterns "*test*"
ai-dev security-scan --file-patterns "*.py" --severity "high"
ai-dev test-suggest --file-patterns "lib/**/*.dart" --test-type "integration"

# Multi-language project analysis
ai-dev review --file-patterns "frontend/**/*.{ts,tsx}"  # Frontend TypeScript
ai-dev review --file-patterns "backend/**/*.py"        # Backend Python
ai-dev review --file-patterns "mobile/**/*.dart"       # Mobile Dart/Flutter

# Comprehensive analysis with verbose output
ai-dev review --file-patterns "src/**/*.{ts,js}" --verbose --format "markdown"
ai-dev docs --file-patterns "*.dart" --doc-type "api" --include-examples --include-parameters
```

## Command Reference

### Code Review
```bash
ai-dev review [options]
```
Analyze and review code changes with AI-powered feedback.

**Options:**
- `--staged`: Review staged changes only
- `--unstaged`: Review unstaged changes only
- `--base <ref>`: Base reference for comparison
- `--head <ref>`: Head reference for comparison
- `--file-patterns <patterns>`: Review specific files (auto-detects language)
- `--exclude-patterns <patterns>`: Exclude files from review
- `--post-github`: Post review comments to GitHub PR
- `--format <format>`: Output format (console, markdown, json)
- `--verbose`: Show detailed output

**Examples:**
```bash
# Review all changes
ai-dev review

# Review specific Dart files
ai-dev review --file-patterns "lib/**/*.dart"

# Review TypeScript files with verbose output
ai-dev review --file-patterns "src/**/*.ts" --verbose

# Review Python files, exclude test files
ai-dev review --file-patterns "*.py" --exclude-patterns "*test*"
```

### Code Explanation
```bash
ai-dev explain [options]
```
Explain commits or functions in plain English.

**Options:**
- `--level <level>`: Explanation depth (basic, detailed, expert)
- `--include-examples`: Include code examples
- `--style <style>`: Explanation style (formal, casual, technical)

### Commit Message Generation
```bash
ai-dev commit-msg [options]
```
Generate commit message suggestions based on changes.

**Options:**
- `--style <style>`: Commit message style (conventional, simple, detailed)
- `--max-length <length>`: Maximum message length
- `--include-body`: Include commit body

### Refactoring Suggestions
```bash
ai-dev refactor [options]
```
Suggest refactoring improvements for cleaner code.

**Options:**
- `--focus <focus>`: Focus area (performance, readability, maintainability)
- `--severity <severity>`: Minimum suggestion severity (low, medium, high)

### Test Generation
```bash
ai-dev test-suggest [options]
```
Generate test case templates and suggestions with automatic language and framework detection.

**Options:**
- `--framework <framework>`: Test framework (auto-detected from file language)
- `--test-type <type>`: Test type (unit, integration, e2e, performance, security)
- `--language <language>`: Programming language (auto-detected from file extension)
- `--file-patterns <patterns>`: Generate tests for specific files
- `--exclude-patterns <patterns>`: Exclude files from test generation
- `--coverage-target <target>`: Target coverage percentage
- `--include-setup`: Include test setup code
- `--include-teardown`: Include test teardown code
- `--verbose`: Show detailed output

**Language & Framework Auto-Detection:**
- **Dart** → Flutter Test Framework (generic)
- **TypeScript/JavaScript** → Jest
- **Python** → pytest (generic)
- **Java** → JUnit (generic)
- **C#** → NUnit (generic)
- **Go** → Go Testing (generic)
- **Rust** → Cargo Test (generic)

**Examples:**
```bash
# Auto-detect language and generate appropriate tests
ai-dev test-suggest --file-patterns "lib/**/*.dart"     # Dart/Flutter tests
ai-dev test-suggest --file-patterns "src/**/*.ts"      # TypeScript/Jest tests
ai-dev test-suggest --file-patterns "*.py"             # Python tests
ai-dev test-suggest --file-patterns "src/**/*.java"    # Java tests

# Generate specific test types
ai-dev test-suggest --file-patterns "*.dart" --test-type "integration"
ai-dev test-suggest --file-patterns "*.ts" --test-type "e2e"

# Include setup and teardown code
ai-dev test-suggest --file-patterns "*.py" --include-setup --include-teardown
```

### Security Scanning
```bash
ai-dev security-scan [options]
```
Detect vulnerabilities and security issues with language-specific analysis.

**Options:**
- `--severity <severity>`: Minimum severity level (low, medium, high, critical)
- `--categories <categories>`: Security categories to scan
- `--file-patterns <patterns>`: Scan specific files (auto-detects language)
- `--exclude-patterns <patterns>`: Exclude files from security scan
- `--include-dependencies`: Scan dependency vulnerabilities
- `--verbose`: Show detailed output

**Examples:**
```bash
# Scan all files for security issues
ai-dev security-scan

# Scan specific file types
ai-dev security-scan --file-patterns "*.py"                    # Python security scan
ai-dev security-scan --file-patterns "src/**/*.ts"             # TypeScript security scan
ai-dev security-scan --file-patterns "lib/**/*.dart"           # Dart security scan

# Scan with specific severity levels
ai-dev security-scan --file-patterns "*.js" --severity "high"
```

### Documentation Generation
```bash
ai-dev docs [options]
```
Generate documentation for code with language-specific formatting.

**Options:**
- `--format <format>`: Documentation format (markdown, jsdoc, tsdoc, asciidoc, rst)
- `--doc-type <type>`: Documentation type (function, class, interface, module, api, readme, changelog, architecture)
- `--file-patterns <patterns>`: Generate docs for specific files (auto-detects language)
- `--exclude-patterns <patterns>`: Exclude files from documentation generation
- `--include-examples`: Include code examples
- `--include-parameters`: Include parameter documentation
- `--include-return-types`: Include return type documentation
- `--include-see-also`: Include "see also" references
- `--style <style>`: Documentation style (formal, casual, technical, beginner)
- `--verbose`: Show detailed output

**Examples:**
```bash
# Generate documentation for all files
ai-dev docs

# Generate API documentation for specific languages
ai-dev docs --file-patterns "lib/**/*.dart" --doc-type "api"     # Dart API docs
ai-dev docs --file-patterns "src/**/*.ts" --doc-type "function"  # TypeScript function docs
ai-dev docs --file-patterns "*.py" --doc-type "class"            # Python class docs

# Generate different documentation types
ai-dev docs --file-patterns "*.ts" --doc-type "readme"
ai-dev docs --file-patterns "*.dart" --doc-type "changelog"
ai-dev docs --file-patterns "*.py" --doc-type "architecture"

# Include comprehensive documentation
ai-dev docs --file-patterns "*.ts" --include-examples --include-parameters --include-return-types
```

### PR Summary
```bash
ai-dev pr-summary [options]
```
Summarize pull request changes.

**Options:**
- `--pr <number>`: Pull request number
- `--include-metrics`: Include change metrics
- `--style <style>`: Summary style (brief, detailed, technical)

### Developer Mentorship
```bash
ai-dev mentor [options]
```
Get educational feedback on code quality and best practices.

**Options:**
- `--level <level>`: Experience level (beginner, intermediate, advanced)
- `--focus <focus>`: Focus areas (clean-code, patterns, performance)
- `--include-resources`: Include learning resources

## Language-Specific Features

### Automatic Language Detection

The AI Developer Assistant automatically detects programming languages from file extensions and provides tailored analysis:

| Language | File Extensions | Test Framework | Documentation Style |
|----------|----------------|----------------|-------------------|
| **Dart** | `.dart` | Flutter Test | Flutter-specific |
| **TypeScript** | `.ts`, `.tsx` | Jest | TypeScript/JSDoc |
| **JavaScript** | `.js`, `.jsx` | Jest | JSDoc |
| **Python** | `.py` | pytest | Python docstrings |
| **Java** | `.java` | JUnit | JavaDoc |
| **C#** | `.cs` | NUnit | XML Documentation |
| **Go** | `.go` | Go Testing | Go Documentation |
| **Rust** | `.rs` | Cargo Test | Rust Documentation |
| **PHP** | `.php` | PHPUnit | PHPDoc |
| **Ruby** | `.rb` | RSpec | RDoc |
| **Swift** | `.swift` | XCTest | Swift Documentation |
| **Kotlin** | `.kt` | JUnit | KDoc |

### Smart Framework Selection

When generating tests, the system automatically selects the most appropriate testing framework:

```bash
# These commands automatically detect language and select framework
ai-dev test-suggest --file-patterns "lib/**/*.dart"     # → Flutter Test
ai-dev test-suggest --file-patterns "src/**/*.ts"      # → Jest
ai-dev test-suggest --file-patterns "tests/**/*.py"    # → pytest
ai-dev test-suggest --file-patterns "src/**/*.java"    # → JUnit
```

### Language-Specific Code Analysis

Each language receives tailored analysis and suggestions:

- **Dart/Flutter**: Flutter best practices, widget testing, state management patterns
- **TypeScript/JavaScript**: ES6+ features, async/await patterns, type safety
- **Python**: PEP 8 compliance, async patterns, type hints
- **Java**: Spring patterns, JVM best practices, enterprise patterns
- **C#**: .NET patterns, async programming, LINQ usage
- **Go**: Go idioms, concurrency patterns, error handling
- **Rust**: Ownership patterns, memory safety, performance optimization

### Beautiful Output Formatting

All commands now provide colorized, structured output with:
- **Syntax Highlighting**: Language-specific code highlighting
- **Structured Reports**: Organized sections for different types of feedback
- **Severity Indicators**: Color-coded severity levels (low, medium, high, critical)
- **Actionable Suggestions**: Clear, implementable recommendations

## Architecture

The AI Developer Assistant follows **Hexagonal Architecture** (Ports & Adapters) principles:

```
┌─────────────────────┐
│   CLI / IDE / API   │  ← Driving Adapters
│  (Inbound Ports)    │
└─────────┬───────────┘
          │
┌─────────▼───────────┐
│  Application Core   │  ← Domain Entities + Use Cases
│ (Domain Layer)      │
└─────────┬───────────┘
          │
┌─────────▼───────────┐
│ Infrastructure      │  ← Git, LLM, GitHub, Output
│   Adapters          │    (Outbound Adapters)
└─────────────────────┘
```

### Domain Layer
- **Entities**: `Diff`, `ReviewComment`, `ReviewReport`, `CodeBlock`, `TestSuggestion`, `SecurityIssue`, `DocSuggestion`
- **Ports**: Interfaces for external dependencies (`DiffProviderPort`, `LLMPort`, `OutputPort`, etc.)
- **Use Cases**: Business logic (`ReviewCodeUseCase`, `ExplainCodeUseCase`, etc.)

### Adapters Layer
- **Inbound**: CLI commands, VS Code Extension, HTTP API
- **Outbound**: Git (simple-git), LLM (OpenAI/Ollama), GitHub (Octokit), Output (console/markdown)

## Configuration

### Environment Variables

```bash
# LLM Configuration
OPENAI_API_KEY=your-openai-api-key
OPENAI_BASE_URL=https://api.openai.com/v1
OLLAMA_BASE_URL=http://localhost:11434
GEMINI_API_KEY=your-gemini-api-key

# GitHub Integration
GITHUB_TOKEN=your-github-token
GITHUB_BASE_URL=https://api.github.com

# Output Configuration
AI_DEV_OUTPUT_FORMAT=console
AI_DEV_VERBOSE=true
AI_DEV_COLORIZE=true
```

### Configuration File (`ai-dev.config.yaml`)

```yaml
llm:
  provider: "openai"  # or "ollama" or "gemini"
  model: "gpt-4"
  temperature: 0.7
  maxTokens: 2000

openai:
  apiKey: "${OPENAI_API_KEY}"
  baseUrl: "https://api.openai.com/v1"

ollama:
  enabled: true
  baseUrl: "http://localhost:11434"
  model: "llama2"

gemini:
  apiKey: "${GEMINI_API_KEY}"
  model: "gemini-2.0-flash"
  temperature: 0.7
  maxTokens: 2000

github:
  token: "${GITHUB_TOKEN}"
  baseUrl: "https://api.github.com"

output:
  format: "console"
  colorize: true
  verbose: false

security:
  enabled: true
  severity: ["medium", "high", "critical"]
  categories: ["injection", "authentication", "authorization"]

test:
  enabled: true
  framework: "jest"
  coverageTarget: 80

documentation:
  enabled: true
  format: "markdown"
  includeExamples: true
```

## Extensibility

### Custom Adapters

The system is designed to be easily extensible. You can create custom adapters by implementing the domain ports:

```typescript
// Custom LLM Provider
export class CustomLLMProvider implements LLMProvider {
  async generateResponse(messages: LLMMessage[]): Promise<LLMResponse> {
    // Your custom implementation
  }
}

// Custom Output Format
export class CustomOutputAdapter implements OutputPort {
  async displayReviewReport(report: ReviewReport): Promise<void> {
    // Your custom output logic
  }
}
```

### Plugin System

```typescript
// Register custom adapters
const llmAdapter = new LLMAdapter(config);
llmAdapter.registerProvider('custom', new CustomLLMProvider());

const outputAdapter = new OutputAdapter();
outputAdapter.registerFormat('custom', new CustomOutputAdapter());
```

## Testing

```bash
# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run specific test suite
npm test -- --testPathPattern=GitAdapter

# Run tests in watch mode
npm run test:watch
```

## Docker Support

### Using Docker

```bash
# Build the Docker image
docker build -t ai-dev-assistant .

# Run with Ollama
docker-compose up -d ollama
docker-compose up ai-dev-assistant

# Run with environment variables
docker run -e OPENAI_API_KEY=your-key ai-dev-assistant review
```

### Docker Compose

```yaml
version: '3.8'
services:
  ollama:
    image: ollama/ollama
    ports:
      - "11434:11434"
    volumes:
      - ollama_data:/root/.ollama

  ai-dev-assistant:
    build: .
    depends_on:
      - ollama
    environment:
      - OLLAMA_BASE_URL=http://ollama:11434
    volumes:
      - .:/workspace
    working_dir: /workspace
```

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone and install
git clone https://github.com/kg6-oss/kg6-codex.git
cd ai-developer-assistant
npm install

# Run in development mode
npm run dev

# Build and test
npm run build
npm test
```

### Project Structure

```
src/
├── domain/           # Core business logic
│   ├── entities/     # Domain entities
│   ├── ports/        # Interface definitions
│   └── usecases/     # Business use cases
├── adapters/         # External integrations
│   ├── inbound/      # CLI, API adapters
│   └── outbound/     # Git, LLM, GitHub adapters
├── config/           # Configuration management
└── utils/            # Utility functions
```

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Built with TypeScript and Node.js
- Uses [Commander.js](https://github.com/tj/commander.js) for CLI
- Integrates with [OpenAI](https://openai.com) and [Ollama](https://ollama.ai)
- Inspired by modern development practices and clean architecture principles

## Support

- [Documentation](https://github.com/kg6-oss/kg6-codex/wiki)
- [Issue Tracker](https://github.com/kg6-oss/kg6-codex/issues)
- [Discussions](https://github.com/kg6-oss/kg6-codex/discussions)
- [Email Support](mailto:support@ai-dev-assistant.com)

---

**Made with ❤️ by the kg6 team**