npm package: @sun-asterisk/impact-analyzer
Description: Automated impact analysis for TypeScript/JavaScript projects
Latest version: 1.0.8

# Impact Analyzer

Automated impact analysis for TypeScript/JavaScript projects. Analyzes code changes and generates comprehensive impact reports.

## Quick Start

### Installation

```bash
npm install @sun-asterisk/impact-analyzer
```

### Usage

```bash
# Analyze last commit (simplest - uses HEAD~1 as base)
npx @sun-asterisk/impact-analyzer

# Analyze changes between branch and current
npx @sun-asterisk/impact-analyzer --base=origin/main

# Full options
npx @sun-asterisk/impact-analyzer --input=src --base=origin/main --output=report.md
```

## Features

- 📡 **API Impact** - Detect affected endpoints
- 💾 **Database Impact** - Track table and field changes
- 📄 **Component Impact** - Identify modified UI components
- 🔄 **Logic Impact** - Analyze function dependencies
- ✅ **Test Recommendations** - Suggest test cases

## Analysis Flow

```
┌─────────────────────────────────────────────────────────────────────┐
│                    1. GIT CHANGE DETECTION                          │
│  ┌──────────────┐      ┌─────────────┐      ┌──────────────┐      │
│  │ Git Diff     │ ───> │ Changed     │ ───> │ AST Parser   │      │
│  │ (base→head)  │      │ Files       │      │ (Symbols)    │      │
│  └──────────────┘      └─────────────┘      └──────────────┘      │
└─────────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│           2. METHOD-LEVEL CALL GRAPH (ts-morph)                     │
│  ┌──────────────┐      ┌─────────────┐      ┌──────────────┐      │
│  │ Parse TS/JS  │ ───> │ Extract     │ ───> │ Build Call   │      │
│  │ Files        │      │ Methods     │      │ Graph Maps   │      │
│  └──────────────┘      └─────────────┘      └──────────────┘      │
│                                                                     │
│  ⚡ OPTIMIZED: Only parses source files, skips loading all to RAM  │
│  • method → [methods it calls]      (forward map)                  │
│  • method → [callers]                (reverse map)                 │
│  • method → endpoint info            (HTTP decorators)             │
└─────────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    3. IMPACT DETECTION                              │
│                                                                     │
│  ┌────────────────────────┐        ┌───────────────────────┐      │
│  │  ENDPOINT DETECTOR     │        │  DATABASE DETECTOR    │      │
│  ├────────────────────────┤        ├───────────────────────┤      │
│  │ Changed Method         │        │ Changed Method        │      │
│  │        ↓               │        │        ↓              │      │
│  │ Traverse Call Graph ↑  │        │ Find Repository       │      │
│  │        ↓               │        │ Methods ↓             │      │
│  │ Find Callers           │        │ Detect DB Ops         │      │
│  │        ↓               │        │ (TypeORM/Prisma)      │      │
│  │ Filter @Get/@Post      │        │        ↓              │      │
│  │        ↓               │        │ Extract Tables/Fields │      │
│  │ 📡 Affected Endpoints  │        │ 💾 DB Impact          │      │
│  └────────────────────────┘        └───────────────────────┘      │
│                                                                     │
│  Flow: Repository → Service → Controller → @Endpoint               │
└─────────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│               4. LOGIC IMPACT ANALYSIS                              │
│  ┌──────────────┐      ┌─────────────┐      ┌──────────────┐      │
│  │ Direct       │ ───> │ Indirect    │ ───> │ Risk Level   │      │
│  │ Callers      │      │ Callers     │      │ Calculation  │      │
│  └──────────────┘      └─────────────┘      └──────────────┘      │
│                                                                     │
│  Uses method call graph for accurate caller tracking               │
└─────────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│               5. IMPACT SCORE CALCULATION                           │
│                                                                     │
│   Score = (Endpoints × 10) + (DB Tables × 5) +                     │
│           (Direct Callers × 3) + (Indirect Callers × 1)            │
│                                                                     │
│   Multipliers:                                                      │
│   • High Risk Logic: ×1.5                                           │
│   • DB Migration: +20                                               │
└─────────────────────────────────────────────────────────────────────┘
                                 │
                                 ▼
┌─────────────────────────────────────────────────────────────────────┐
│                  6. REPORT GENERATION                               │
│                                                                     │
│   Score → Severity: 🟢 LOW | 🟡 MEDIUM | 🟠 HIGH | 🔴 CRITICAL     │
│                                                                     │
│   ┌────────────┐   ┌────────────┐   ┌────────────┐                │
│   │ Console    │   │ Markdown   │   │ JSON       │                │
│   │ Report     │   │ Report     │   │ (CI/CD)    │                │
│   └────────────┘   └────────────┘   └────────────┘                │
└─────────────────────────────────────────────────────────────────────┘
```

### Architecture Highlights

**Layer-Aware Tracking**
```
Controller (@Get/@Post) ──┐
         ↑                │
      Service             │ Call Graph
         ↑                │ Traversal
    Repository            │
         ↑                │
    Database ─────────────┘
```

## Usage

### Quick Reference

```bash
# Show help
npx @sun-asterisk/impact-analyzer --help

# Basic usage (analyzes last commit)
npx @sun-asterisk/impact-analyzer

# Analyze between branches
npx @sun-asterisk/impact-analyzer --base=origin/main

# Full example with all options
npx @sun-asterisk/impact-analyzer \
  --input=src \
  --base=HEAD~3 \
  --output=report.md \
  --json=report.json \
  --verbose
```

### CLI Options

| Option | Description | Default | Example |
|--------|-------------|---------|---------|
| `--input=<path>` | Source directory to analyze | `src` | `--input=backend/src` |
| `--base=<ref>` | Base git reference for comparison | `HEAD~1` | `--base=origin/main` |
| `--head=<ref>` | Head git reference | Working directory | `--head=HEAD` |
| `--exclude=<paths>` | Comma-separated paths to exclude | `node_modules,dist,build,specs,coverage` | `--exclude=test,coverage` |
| `--output=<file>` | Markdown report output | `impact-report.md` | `--output=report.md` |
| `--json=<file>` | JSON report output (optional) | - | `--json=report.json` |
| `--max-depth=<n>` | Maximum call graph depth | `3` | `--max-depth=5` |
| `--include-tests` | Include test files in analysis | `false` | `--include-tests` |
| `--verbose` | Show verbose output | `false` | `--verbose` |
| `--no-fail` | Don't exit with error on critical | `false` | `--no-fail` |
| `--help`, `-h` | Show help message | - | `--help` |

### Examples

**Analyze last commit (default behavior)**
```bash
npx @sun-asterisk/impact-analyzer
# Compares HEAD~1 (previous commit) with current working directory
```

**Analyze changes between main branch and current**
```bash
npx @sun-asterisk/impact-analyzer --base=origin/main
```

**Analyze last 5 commits**
```bash
npx @sun-asterisk/impact-analyzer --base=HEAD~5
```

**Compare two specific commits**
```bash
npx @sun-asterisk/impact-analyzer --base=abc123 --head=def456
```

**Full analysis with reports**
```bash
npx @sun-asterisk/impact-analyzer \
  --input=src \
  --base=origin/main \
  --output=impact-report.md \
  --json=impact-report.json \
  --verbose
```

**Analyze different directory**
```bash
npx @sun-asterisk/impact-analyzer --input=backend/src
```

**Include test files in analysis**
```bash
npx @sun-asterisk/impact-analyzer --include-tests
```

## CI/CD Integration

### GitHub Actions (Recommended)

**Simple - Analyze last commit in PR**
```yaml
name: Impact Analysis
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Fetch full history for branch comparison

      - uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: Run Impact Analysis
        run: |
          npx @sun-asterisk/impact-analyzer \
            --base=origin/${{ github.event.pull_request.base.ref }} \
            --output=impact-report.md \
            --json=impact-report.json

      - name: Upload Reports
        uses: actions/upload-artifact@v4
        with:
          name: impact-reports
          path: |
            impact-report.md
            impact-report.json
          retention-days: 30
```

**Advanced - With PR Comment**
```yaml
      - name: Comment PR with Impact Report
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const report = fs.readFileSync('impact-report.md', 'utf8');
            
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: report
            });
```

### GitLab CI

```yaml
impact-analysis:
  stage: test
  image: node:18
  variables:
    GIT_DEPTH: 0  # Fetch full history
  script:
    - npx @sun-asterisk/impact-analyzer
        --base=origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME
        --output=impact-report.md
        --json=impact-report.json
  artifacts:
    paths:
      - impact-report.md
      - impact-report.json
    expire_in: 30 days
  only:
    - merge_requests
```

### Jenkins

```groovy
pipeline {
    agent any
    stages {
        stage('Impact Analysis') {
            steps {
                sh '''
                    npx @sun-asterisk/impact-analyzer \
                        --base=origin/main \
                        --output=impact-report.md \
                        --json=impact-report.json
                '''
                
                archiveArtifacts artifacts: 'impact-report.*', fingerprint: true
            }
        }
    }
}
```

### Severity Levels

- 🟢 **LOW** (0-20) - Minor changes
- 🟡 **MEDIUM** (21-50) - Moderate impact
- 🟠 **HIGH** (51-100) - Significant impact
- 🔴 **CRITICAL** (100+) - Major changes

### Impact Score Calculation

- Endpoints: +10 each
- DB Tables: +5 each
- Direct Callers: +3 each
- Indirect Callers: +1 each
- High Risk Logic: ×1.5
- DB Migration: +20

## Troubleshooting

### Common Issues

**"Source directory does not exist"**
```bash
# Check if directory exists
ls -la src

# Use correct path
npx @sun-asterisk/impact-analyzer --input=backend/src
```

**"Base ref does not exist"**
```bash
# Fetch latest branches
git fetch origin

# Verify branch exists
git show origin/main

# Or use commit SHA
npx @sun-asterisk/impact-analyzer --base=abc123
```

**"No changes detected"**
```bash
# Check if there are actual differences
git diff HEAD~1 HEAD

# Or compare with branch
git diff origin/main HEAD
```

**Need more details?**
```bash
# Enable verbose mode for detailed logs
npx @sun-asterisk/impact-analyzer --verbose

# Show help
npx @sun-asterisk/impact-analyzer --help
```

### Getting Help

```bash
# Show comprehensive help guide
npx @sun-asterisk/impact-analyzer --help
```

### References

- **Architecture**: `.specify/plans/architecture.md` - System design and flow
- **Coding Rules**: `.github/copilot-instructions.md` - Development standards
- **Tasks**: `.specify/tasks/` - Implementation tasks and specifications

## License

MIT