# Quality Lens CLI

A standalone CLI tool for running quality lenses (ESLint, Jest, TypeScript, Knip, Git, Alexandria) on codebases in CI/CD pipelines.

## Installation

```bash
npm install -g @principal-ai/quality-lens-cli
```

## Quick Start

```bash
# 1. Install the CLI
npm install -g @principal-ai/quality-lens-cli

# 2. See what quality tools are available in your project
quality-lens list

# 3. Set up the GitHub Action
quality-lens init

# 4. Commit and push to start tracking quality
git add .github/workflows/quality-lens.yml
git commit -m "Add Quality Lens workflow"
git push
```

## Usage

### Initialize GitHub Action

```bash
# Set up the workflow in current directory
quality-lens init

# Set up in specific directory
quality-lens init /path/to/repo

# Overwrite existing workflow
quality-lens init --force
```

### List available lenses

```bash
# See what lenses are available and what's missing
quality-lens list

# Example output:
# @my-project/core:
#   Available: eslint, typescript, test, prettier
#   Missing: knip, alexandria
```

### Run quality lenses

```bash
# Run all available lenses in current directory
quality-lens run

# Run on specific directory
quality-lens run /path/to/repo

# Run specific lenses only
quality-lens run --lenses eslint,jest,typescript,alexandria

# Output to JSON file
quality-lens run --output results.json --format json

# Console output (default)
quality-lens run --format console
```

## Options

- `--output, -o`: Output file path for results (JSON format)
- `--lenses`: Comma-separated list of lenses to run (eslint,jest,typescript,knip,git,alexandria)
- `--format`: Output format - `json` or `console` (default: console)

## GitHub Actions Integration

Create `.github/workflows/quality-lens.yml`:

```yaml
name: Quality Lens Analysis

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  analyze:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build CLI
        run: npm run build

      - name: Run quality lenses
        run: |
          node bin/quality-lens.js run . \
            --output results.json \
            --format json \
            --lenses eslint,typescript,knip,test,alexandria
        continue-on-error: true

      - name: Upload results artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: quality-lens-results-${{ github.sha }}
          path: results.json
          if-no-files-found: warn

      - name: Comment PR with results
        if: github.event_name == 'pull_request' && always()
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            if (!fs.existsSync('results.json')) return;

            const results = JSON.parse(fs.readFileSync('results.json', 'utf8'));
            const analysisResults = results.results || [];

            let passed = 0, failed = 0, details = [];
            analysisResults.forEach(result => {
              if (result.execution?.success) passed++;
              else failed++;

              const icon = result.execution?.success ? '✅' : '❌';
              const pkg = result.package?.name || 'unknown';
              const lens = result.lens?.id || 'unknown';
              const duration = result.execution?.duration || 0;

              details.push(`${icon} **${pkg}** - ${lens} (${duration}ms)`);
            });

            const body = `## 🔍 Quality Lens Analysis Results

            **Summary:**
            - Total Checks: ${passed + failed}
            - Passed: ✅ ${passed}
            - Failed: ❌ ${failed}

            **Details:**
            ${details.join('\n')}`;

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });
```

### What the Workflow Does

The workflow will:

- Run quality lenses on push and pull requests
- Upload results as artifacts
- Automatically comment on PRs with analysis summary
- Continue workflow execution even if quality checks fail

## Retrieving Artifacts from GitHub Actions

For detailed instructions on retrieving quality analysis artifacts from GitHub Actions and integrating them with your UI (e.g., Quality Hexagon visualization), see the [Artifact Retrieval Guide](./ARTIFACT_RETRIEVAL_GUIDE.md).

The guide covers:

- Authentication setup (fine-grained tokens, classic tokens, GitHub Apps)
- Retrieval methods (GitHub CLI, REST API, Octokit)
- Integration examples for Electron apps
- Quality Hexagon visualization integration
- Best practices for caching and error handling

## Output Format

### JSON Output

```json
{
  "metadata": {
    "timestamp": "2025-10-16T20:00:00.000Z",
    "version": "1.0.0",
    "totalPackages": 2,
    "totalLenses": 6,
    "git": {
      "commit": "1741fd5abc123def456789",
      "branch": "main",
      "repository": "owner/repo"
    }
  },
  "results": [
    {
      "package": {
        "name": "my-package",
        "path": "packages/my-package"
      },
      "lens": {
        "id": "eslint",
        "command": "npm run lint"
      },
      "execution": {
        "success": true,
        "exitCode": 0,
        "duration": 1234,
        "timestamp": 1697486400000
      },
      "issues": [],
      "metrics": {},
      "qualityContext": {}
    }
  ],
  "qualityMetrics": {
    "hexagon": {
      "tests": 100,
      "deadCode": 98.5,
      "formatting": 95,
      "linting": 85,
      "types": 100,
      "documentation": 70
    }
  }
}
```

### Console Output

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Quality Lens Results
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📦 my-package
  ✓ eslint: npm run lint (1234ms)
  ✓ jest: npm run test (5678ms)
  ✓ typescript: npm run typecheck (2345ms)

Summary:
  Total: 3
  Passed: 3
  Failed: 0
```

## Development

```bash
# Install dependencies
npm install

# Build
npm run build

# Run locally
./bin/quality-lens.js run .

# Lint
npm run lint

# Type check
npm run typecheck
```

## License

MIT
