diffscope 0.5.3

A composable code review engine with smart analysis, confidence scoring, and professional reporting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# DiffScope

A composable code review engine for automated diff analysis.

## Features

- **Model Agnostic**: Works with OpenAI, Anthropic Claude 4, Ollama, and any OpenAI-compatible API
- **Git Integration**: Review uncommitted, staged, or branch changes directly
- **PR Reviews**: Analyze and comment on GitHub pull requests with interactive commands
- **Smart Prompting**: Advanced prompt engineering with examples, XML structure, and chain-of-thought
- **Commit Messages**: AI-powered commit message suggestions following conventional commits
- **Composable Architecture**: Modular components that work together
- **Plugin System**: Extensible pre-analyzers and post-processors
- **Multiple Outputs**: JSON, patch, or markdown formats
- **CI/CD Ready**: GitHub Action, GitLab CI, and Docker support
- **Smart Review**: Enhanced analysis with confidence scoring, fix effort estimation, and executive summaries
- **Path-Based Configuration**: Customize review behavior for different parts of your codebase
- **Changelog Generation**: Generate changelogs and release notes from git history
- **Interactive Commands**: Respond to PR comments with @diffscope commands

## Quick Start

### Install Pre-built Binary (Recommended)

#### Linux/macOS
```bash
curl -sSL https://raw.githubusercontent.com/haasonsaas/diffscope/main/install.sh | sh
```

#### Windows (PowerShell)
```powershell
iwr -useb https://raw.githubusercontent.com/haasonsaas/diffscope/main/install.ps1 | iex
```

#### Manual Download
Download the latest binary for your platform from the [releases page](https://github.com/haasonsaas/diffscope/releases/latest):
- Linux: `diffscope-x86_64-unknown-linux-musl`
- macOS Intel: `diffscope-x86_64-apple-darwin`
- macOS Apple Silicon: `diffscope-aarch64-apple-darwin`
- Windows: `diffscope-x86_64-pc-windows-msvc.exe`

### Install via Package Managers

#### Homebrew (macOS/Linux)
```bash
brew tap haasonsaas/diffscope
brew install diffscope
```

#### Cargo (requires Rust)
```bash
cargo install diffscope
```

### Docker
```bash
# Pull the latest image
docker pull ghcr.io/haasonsaas/diffscope:latest

# Run with current directory mounted
docker run --rm -v $(pwd):/workspace ghcr.io/haasonsaas/diffscope:latest review --diff /workspace/pr.diff

# Create an alias for convenience
alias diffscope='docker run --rm -v $(pwd):/workspace ghcr.io/haasonsaas/diffscope:latest'
```

## Usage

### Basic Usage
```bash
# Review your current changes
git diff | diffscope review

# Review a specific file diff
diffscope review --diff patch.diff

# Get enhanced analysis with smart review
git diff | diffscope smart-review
```

### Git Integration
```bash
# Review what you're about to commit
diffscope git staged

# Review all uncommitted changes  
diffscope git uncommitted

# Compare your branch to main
diffscope git branch main

# Get AI-powered commit message suggestions
diffscope git suggest
```

### Pull Request Review
```bash
# Review the current PR
diffscope pr

# Review a specific PR number
diffscope pr --number 123

# Post review comments directly to GitHub
diffscope pr --post-comments
```

### Smart Review (Enhanced Analysis)
```bash
# Get professional-grade analysis with confidence scoring
git diff | diffscope smart-review

# Generate executive summary report
diffscope smart-review --diff changes.patch --output report.md

# Review with specific AI model
git diff | diffscope smart-review --model claude-3-5-sonnet-20241022
```

### AI Model Configuration
```bash
# OpenAI (default)
export OPENAI_API_KEY=your-key
git diff | diffscope review --model gpt-4o

# Anthropic Claude
export ANTHROPIC_API_KEY=your-key  
git diff | diffscope review --model claude-3-5-sonnet-20241022

# Local Ollama
git diff | diffscope review --model ollama:codellama
```

### Supported Models

**OpenAI**: gpt-4o, gpt-4-turbo, gpt-3.5-turbo

**Anthropic**: 
- Claude 4: claude-opus-4-20250514, claude-sonnet-4-20250514
- Claude 3.5: claude-3-5-sonnet-20241022, claude-3-5-haiku-20240307
- Claude 3: claude-3-opus-20240229, claude-3-haiku-20240307

**Ollama**: Any locally installed model (codellama, llama3.2, mistral, etc.)

### Output Formats
```bash
# JSON output (default)
git diff | diffscope review --output-format json

# Markdown report  
git diff | diffscope review --output-format markdown > review.md

# Inline patch comments
git diff | diffscope review --output-format patch
```

## GitHub Action

```yaml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: haasonsaas/diffscope@v1
        with:
          model: gpt-4o
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          post-comments: true
```

## Configuration

Create a `.diffscope.yml` file in your repository:

```yaml
model: gpt-4o
temperature: 0.2
max_tokens: 4000
system_prompt: "Focus on security vulnerabilities, performance issues, and best practices"
```

## Plugin Development

Create custom analyzers:

```typescript
export interface PreAnalyzer {
  id: string
  run(diff: UnifiedDiff, repoPath: string): Promise<LLMContextChunk[]>
}

export interface PostProcessor {
  id: string
  run(comments: Comment[], repoPath: string): Promise<Comment[]>
}
```

## Architecture

```mermaid
graph LR
  A[git diff] --> B(core-engine)
  subgraph core-engine
    B1[Diff Parser]
    B2[Context Fetcher]
    B3[Prompt Builder]
    B4[LLM Adapter]
    B5[Comment Synthesizer]
  end
  B -->|JSON| C(output)
```

## License

Apache-2.0 License. See [LICENSE](LICENSE) for details.

## Example Output

### Standard Review
```json
[
  {
    "file_path": "src/auth.py",
    "line_number": 42,
    "content": "Potential SQL injection vulnerability",
    "severity": "Error",
    "category": "Security",
    "suggestion": "Use parameterized queries instead of string interpolation"
  }
]
```

### Smart Review Output
```markdown
# šŸ¤– Smart Review Analysis Results

## šŸ“Š Executive Summary

🟔 **Code Quality Score:** 8.2/10
šŸ“ **Total Issues Found:** 4
🚨 **Critical Issues:** 1
šŸ“ **Files Analyzed:** 3

### šŸŽÆ Priority Actions
1. Address 1 security issue(s) immediately
2. Consider performance optimization for database queries

---

## šŸ” Detailed Analysis

### šŸ”“ Critical Issues (Fix Immediately)

#### šŸ”’ **src/auth.py:42** - šŸ”“ Significant Effort Security
**Confidence:** 95% | **Tags:** `security`, `sql`, `injection`

SQL injection vulnerability detected. User input is directly interpolated into query string without proper sanitization.

**šŸ’” Recommended Fix:**
Use parameterized queries to prevent SQL injection attacks.

**šŸ”§ Code Example:**
```diff
- query = f"SELECT * FROM users WHERE username='{username}'"
+ query = "SELECT * FROM users WHERE username=%s"
+ cursor.execute(query, (username,))
```

### 🟔 High Priority Issues

#### ⚔ **src/models.py:28** - 🟔 Moderate Effort Performance
**Confidence:** 87% | **Tags:** `performance`, `n+1-query`

N+1 query problem detected in user retrieval loop.

**šŸ’” Recommended Fix:**
Use eager loading or bulk queries to reduce database calls.
```

### Commit Message Suggestion
```
feat(auth): add JWT-based authentication system
```

## Author

Jonathan Haas <jonathan@haas.holdings>

## Advanced CI/CD Integration

### Enterprise GitHub Actions Workflow

Here's an example of how large organizations use diffscope in production CI/CD pipelines:

```yaml
name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize]
    branches: [main]

jobs:
  ai-code-review:
    name: AI Code Review with DiffScope
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - name: Checkout PR
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event.pull_request.head.sha }}

      - name: Install DiffScope with Cache
        uses: actions/cache@v4
        with:
          path: ~/.cargo/bin
          key: ${{ runner.os }}-diffscope-${{ hashFiles('**/Cargo.lock') }}
      
      - run: |
          if ! command -v diffscope &> /dev/null; then
            cargo install diffscope
          fi

      - name: Generate PR Diff
        run: |
          git diff origin/${{ github.event.pull_request.base.ref }}...HEAD > pr.diff

      - name: Run AI Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          diffscope review --model claude-3-5-sonnet-20241022 \
            --diff pr.diff --output-format json > review.json

      - name: Post Review Comments
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            
            let body = '## šŸ¤– AI Code Review\n\n';
            if (review.length === 0) {
              body += 'āœ… **No issues found!** Code looks good!';
            } else {
              body += review.map((item, i) => 
                `**${i+1}.** \`${item.file_path}:${item.line_number}\`\n` +
                `${item.content}\n` +
                (item.suggestion ? `\nšŸ’” **Suggestion:** ${item.suggestion}\n` : '')
              ).join('\n---\n');
            }
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });
```

### Enterprise Configuration Example

For a large Python/FastAPI application at a company like Acme Inc:

**.diffscope.yml**
```yaml
# Acme Inc DiffScope Configuration
model: "claude-3-5-sonnet-20241022"
temperature: 0.1  # Low for consistent reviews
max_tokens: 4000

system_prompt: |
  You are reviewing Python code for a production FastAPI application.
  
  Critical focus areas:
  - SQL injection and security vulnerabilities
  - Async/await correctness
  - Resource leaks and memory issues
  - API contract consistency
  - Production deployment concerns
  
  Prioritize by severity: Security > Performance > Maintainability

# File filters for monorepo
include_patterns:
  - "src/**/*.py"
  - "tests/**/*.py"
  - "alembic/versions/*.py"
  - "*.yml"
  - "Dockerfile*"

exclude_patterns:
  - "**/__pycache__/**"
  - "**/venv/**"
  - "**/.pytest_cache/**"
  - "**/node_modules/**"

# Review configuration
max_diff_size: 10000
context_lines: 3
```

### Integration with Other CI Tools

**GitLab CI Example:**
```yaml
code-review:
  stage: review
  image: rust:alpine
  only:
    - merge_requests
  script:
    - apk add --no-cache git
    - cargo install diffscope
    - git diff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD > mr.diff
    - diffscope smart-review --diff mr.diff --output review.md
  artifacts:
    reports:
      codequality: review.md
```

**Jenkins Pipeline:**
```groovy
stage('AI Code Review') {
  steps {
    sh '''
      curl -sSL https://sh.rustup.rs | sh -s -- -y
      source $HOME/.cargo/env
      cargo install diffscope
      
      git diff origin/${env.CHANGE_TARGET}...HEAD > pr.diff
      diffscope review --diff pr.diff --output-format json > review.json
    '''
    
    publishHTML([
      allowMissing: false,
      alwaysLinkToLastBuild: true,
      keepAll: true,
      reportDir: '.',
      reportFiles: 'review.json',
      reportName: 'AI Code Review'
    ])
  }
}
```

### Best Practices for CI/CD Integration

1. **Cache Installation**: Cache cargo/diffscope binaries to speed up CI runs
2. **API Key Management**: Use secure secret storage for API keys
3. **Diff Size Limits**: Set max diff size to avoid timeouts on large PRs
4. **Custom Prompts**: Tailor system prompts to your tech stack and standards
5. **Output Parsing**: Handle both empty reviews and JSON parsing errors gracefully
6. **Conditional Runs**: Skip reviews on draft PRs or specific file types

## New Features in v0.5.0

### šŸ”„ Changelog Generation

Generate professional changelogs and release notes from your git history:

```bash
# Generate changelog from a specific tag to HEAD
diffscope changelog --from v0.4.0 --to HEAD

# Generate release notes for a new version
diffscope changelog --release v0.5.0 --from v0.4.0

# Output to file
diffscope changelog --from v0.4.0 --output CHANGELOG.md
```

The changelog generator:
- Parses conventional commits automatically
- Groups changes by type (features, fixes, etc.)
- Highlights breaking changes
- Shows contributor statistics
- Generates both changelogs and release notes formats

### šŸŽÆ Path-Based Configuration

Customize review behavior for different parts of your codebase:

**.diffscope.yml**
```yaml
# Global configuration
model: gpt-4o
temperature: 0.2
max_tokens: 4000

# Exclude patterns
exclude_patterns:
  - "**/*.generated.*"
  - "**/node_modules/**"

# Path-specific rules
paths:
  # API endpoints need security focus
  "src/api/**":
    focus:
      - security
      - validation
      - authentication
    severity_overrides:
      security: error  # All security issues become errors
    system_prompt: |
      Focus on SQL injection, auth bypass, and input validation

  # Test files have different standards
  "tests/**":
    focus:
      - coverage
      - assertions
    severity_overrides:
      style: suggestion  # Style issues are just suggestions

  # Database migrations are critical
  "migrations/**":
    severity_overrides:
      bug: error  # Any bug in migrations is critical
```

### šŸ’¬ Interactive PR Commands

Respond to pull request comments with interactive commands:

```
@diffscope review                 # Re-review the changes
@diffscope review security        # Focus review on security
@diffscope ignore src/generated/  # Ignore specific paths
@diffscope explain line 42        # Explain specific code
@diffscope generate tests         # Generate unit tests
@diffscope help                   # Show all commands
```

### šŸ“Š PR Summary Generation

Generate executive summaries for pull requests:

```bash
# Generate PR summary with statistics
diffscope pr --summary

# Generate and post to GitHub
diffscope pr --number 123 --summary --post-comments
```

The summary includes:
- Change statistics and impact analysis
- Key modifications by category
- Risk assessment
- Review recommendations

## Contributing

Contributions are welcome! Please open an issue first to discuss what you would like to change.

## Supported Platforms

DiffScope provides pre-built binaries for the following platforms:

| Platform | Architecture | Binary |
|----------|-------------|---------|
| Linux | x86_64 | `diffscope-x86_64-unknown-linux-musl` (static, works on all distros) |
| Linux | x86_64 | `diffscope-x86_64-unknown-linux-gnu` |
| Linux | ARM64 | `diffscope-aarch64-unknown-linux-gnu` |
| macOS | Intel (x86_64) | `diffscope-x86_64-apple-darwin` |
| macOS | Apple Silicon (ARM64) | `diffscope-aarch64-apple-darwin` |
| Windows | x86_64 | `diffscope-x86_64-pc-windows-msvc.exe` |

All binaries are automatically built and uploaded with each release.

## Support

- GitHub Issues: [github.com/Haasonsaas/diffscope/issues]https://github.com/Haasonsaas/diffscope/issues