ax-consistency 0.1.0
AI-powered code consistency checker and fixer for multiple languages
License: MIT
Requires Python: >=3.8

# AX - AI-Powered Code Consistency Checker

> Keep your codebase consistent across multiple languages using AI and static analysis

AX is an intelligent code consistency checker and fixer that helps maintain consistent coding patterns across your entire project. It uses a hybrid approach combining AST-based analysis with AI-powered detection to identify inconsistencies, logical errors, security issues, and performance problems.

## Features

- **Cross-File Consistency Analysis**: Learns patterns from your project and ensures consistency
- **Multi-Language Support**: Python, JavaScript, TypeScript, Java, Go, Rust, and more
- **AI-Powered Detection**: Uses LLMs to detect complex inconsistencies and logical errors
- **Hybrid Analysis**: Combines fast AST analysis with deep AI understanding
- **Auto-Fix Capabilities**: Automatically fixes issues with configurable confidence thresholds
- **Logical Error Detection**: Finds bugs like missing operators, unreachable code, infinite loops
- **Security Scanning**: Detects hardcoded secrets, SQL injection risks, unsafe deserialization
- **Performance Analysis**: Identifies N+1 queries, inefficient loops, unnecessary conversions
- **Real-time Feedback**: IDE extensions for VS Code and Cursor
- **Interactive Fixes**: Review and approve fixes with diff preview
- **Project-Wide Learning**: Automatically detects and enforces your team's coding patterns

## What AX Checks

### Consistency Issues
- Naming conventions (snake_case vs camelCase)
- None/Null checking patterns (is None vs == None)
- Type hint usage consistency
- Error handling patterns (exceptions vs return values)
- Import styles
- String quote preferences
- Docstring conventions

### Logical Errors
- Missing augmented operators (x = x + 1 vs x += 1)
- Incorrect comparisons
- Unreachable code after return/raise
- Infinite loops without break
- Loop variable modifications
- Missing return statements
- Unused variables
- Off-by-one errors

### Security Issues
- Hardcoded secrets (API keys, passwords, tokens)
- SQL injection vulnerabilities
- Command injection risks
- Unsafe deserialization (pickle)
- Weak cryptography (MD5, SHA1)
- Unsafe eval/exec usage
- Missing file encoding

### Performance Problems
- N+1 query patterns
- Inefficient loops (list comprehension opportunities)
- Repeated expensive computations
- Inefficient string concatenation
- Unnecessary type conversions
- Missing caching opportunities

## Installation

### For Users (PyPI)

```bash
pip install ax-consistency
```

### For Development

```bash
# Clone the repository
git clone https://github.com/CAVELAB-HK/AX.git
cd AX

# Install in development mode
pip install -e .

# Install development dependencies
pip install -e ".[dev]"
```

## Quick Start

### 1. Setup AI Provider (Optional but Recommended)

AX can work with or without AI. For best results, configure an AI provider:

```bash
ax setup
```

Supported providers:
- Qwen (Alibaba Cloud)
- OpenAI (GPT-4, GPT-3.5)
- Anthropic (Claude)
- Google (Gemini)

### 2. Check Your Code

```bash
# Check a single file
ax check myfile.py

# Check entire project
ax check .

# Check with AI analysis
ax check --ai myfile.py

# Check and auto-fix
ax fix myfile.py
```

### 3. Use in Your IDE

Install the VS Code or Cursor extension for real-time feedback:

- **VS Code**: Search "AX Consistency" in the marketplace
- **Cursor**: See [extensions/cursor-ax/INSTALL_CURSOR.md](extensions/cursor-ax/INSTALL_CURSOR.md)

## Usage

### CLI Commands

```bash
# Check files
ax check <file_or_directory>
ax check --ai <file>              # Use AI analysis
ax check --strategy naming        # Use specific strategy

# Fix issues
ax fix <file>                     # Interactive fix
ax fix --auto <file>              # Auto-fix high-confidence issues
ax fix --ai <file>                # Use AI to generate fixes

# Watch for changes
ax watch <directory>              # Auto-check on file changes

# Configuration
ax setup                          # Configure AI provider
ax config                         # Show current configuration
```

### Python API

```python
from pathlib import Path
from ax.core.hybrid_pipeline import HybridPipeline

# Initialize pipeline
pipeline = HybridPipeline(use_cache=True, prefer_ai=True)

# Analyze a file
project_files = list(Path('.').rglob('*.py'))
result = pipeline.analyze_file(Path('myfile.py'), project_files)

# Generate fixes
fixes = pipeline.generate_fixes(
    Path('myfile.py'), 
    result['issues'],
    project_files
)

print(f"Found {result['issue_count']} issues")
print(f"Consistency score: {result.get('consistency_score', 1.0):.2%}")
```

### Configuration File

Create `.axconfig.toml` in your project root:

```toml
[analysis]
enabled_strategies = [
    "naming",
    "type_hints",
    "imports",
    "docstrings",
    "error_handling",
    "logical_errors",
    "security",
    "performance"
]
auto_fix_threshold = 0.9
interactive_threshold = 0.6
ignore_patterns = [
    "__pycache__/*",
    "*.pyc",
    ".git/*",
    "venv/*",
    "node_modules/*"
]

[llm]
enabled = true
provider = "qwen"
timeout = 30

[cache]
enabled = true
directory = ".ax_cache"

[output]
format = "terminal"
colors = true
verbose = false
```

## Examples

### Before AX

```python
def processData(data):
    if data == None:
        return
    total = 0
    password = "secret123"
    for item in items:
        total = total + item
    return total
```

### After AX Fix

```python
def process_data(data):
    if data is None:
        return
    total = 0
    password = os.getenv('PASSWORD')
    for item in items:
        total += item
    return total
```

## IDE Extensions

### VS Code Extension

1. Install from marketplace: "AX Consistency"
2. Or install manually: `code --install-extension extensions/vscode-ax/ax-consistency-1.0.0.vsix`
3. Configure in settings (Cmd/Ctrl + ,):
   - `ax.enabled`: Enable/disable extension
   - `ax.useAI`: Use AI-powered analysis
   - `ax.autoCheckOnSave`: Check files on save
   - `ax.aiProvider`: AI provider (qwen/openai/anthropic/gemini)

**Keyboard Shortcuts**:
- `Cmd/Ctrl + Shift + A`: Check current file
- `Cmd/Ctrl + Shift + F`: Fix current file

### Cursor Extension

See [extensions/cursor-ax/INSTALL_CURSOR.md](extensions/cursor-ax/INSTALL_CURSOR.md) for installation instructions.

## Architecture

AX uses a hybrid architecture:

1. **AST-Based Analysis** (Fast): Uses abstract syntax tree parsing for quick pattern detection
2. **AI-Powered Analysis** (Deep): Uses LLMs for complex consistency and logical error detection
3. **Pattern Learning**: Learns dominant patterns from your project automatically
4. **Smart Caching**: Caches results to avoid redundant analysis
5. **Strategy System**: Pluggable strategies for different types of checks

## Development

### Project Structure

```
AX/
├── ax/                      # Core package
│   ├── cli/                # CLI interface
│   ├── core/               # Core analysis engine
│   │   ├── pipeline.py     # AST-based pipeline
│   │   ├── ai_pipeline.py  # AI-powered pipeline
│   │   ├── hybrid_pipeline.py  # Hybrid approach
│   │   └── pattern_learner.py  # Pattern detection
│   ├── strategies/         # Analysis strategies
│   │   ├── naming.py
│   │   ├── logical_errors.py
│   │   ├── security.py
│   │   └── performance.py
│   └── services/           # External services
│       └── llm_service.py  # AI provider integration
├── extensions/             # IDE extensions
│   ├── vscode-ax/         # VS Code extension
│   └── cursor-ax/         # Cursor extension
└── tests/                 # Test suite
```

### Running Tests

```bash
pytest tests/
```

### Building Extensions

```bash
# VS Code extension
cd extensions/vscode-ax
npm install
npm run compile
npm run package

# Cursor extension
cd extensions/cursor-ax
npm install
npm run compile
```

## Publishing to PyPI

### First Time Setup

1. Create accounts on PyPI and TestPyPI
2. Install build tools:
   ```bash
   pip install build twine
   ```

### Publishing Process

```bash
# 1. Update version in pyproject.toml
# 2. Build distribution
python -m build

# 3. Test on TestPyPI (optional)
python -m twine upload --repository testpypi dist/*

# 4. Publish to PyPI
python -m twine upload dist/*
```

### After Publishing

Users can install with:
```bash
pip install ax-consistency
```

## Contributing

We welcome contributions! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests (`pytest`)
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

## Troubleshooting

### "AX CLI not found"

Make sure AX is installed and in your PATH:
```bash
pip install ax-consistency
# Or for development:
pip install -e /path/to/AX
```

### "Invalid API key"

Run setup again to reconfigure:
```bash
ax setup
```

### Extension Not Working

1. Check that AX CLI is installed: `ax --version`
2. Check extension settings in VS Code
3. Restart VS Code/Cursor
4. Check the extension output panel for errors

### Analysis Too Slow

1. Enable caching in `.axconfig.toml`
2. Use `--no-ai` flag for faster AST-only analysis
3. Add ignore patterns for large dependencies

## License

MIT License - see LICENSE file for details

## Authors

- CAVELAB-HK (contact@cavelab.dev)

## Links

- **GitHub**: https://github.com/CAVELAB-HK/AX
- **Issues**: https://github.com/CAVELAB-HK/AX/issues
- **Documentation**: https://github.com/CAVELAB-HK/AX/wiki
- **Discussions**: https://github.com/CAVELAB-HK/AX/discussions

## Contributing

Found a bug or have a feature request? Please open an issue on GitHub!

## Acknowledgments

AX is built with:
- Tree-sitter for language parsing
- Rich for beautiful terminal output
- Typer for CLI interface
- Various LLM providers for AI-powered analysis