# PR Reviewer Tool - Documentation

## Overview

PR Reviewer Tool analyzes code changes (diff/patch) and provides structured code review with blocking issues, security findings, regression risks, and recommendations.

## Integration

### Tool Definition

Registered in `services/router/tool_manager.py`:

```python
{
    "type": "function",
    "function": {
        "name": "pr_reviewer_tool",
        "description": "🔍 Рев'ю коду з PR/diff...",
        "parameters": {...}
    }
}
```

### RBAC Configuration

Added to `FULL_STANDARD_STACK` in `services/router/agent_tools_config.py` - available to all agents.

## Request Format

### `POST /v1/tools/pr-review` (via gateway dispatcher)

```json
{
  "mode": "blocking_only | full_review",
  "context": {
    "repo": {
      "name": "microdao-daarion",
      "commit_base": "abc123",
      "commit_head": "def456"
    },
    "change_summary": "Added user authentication",
    "risk_profile": "default | security_strict | release_gate"
  },
  "diff": {
    "format": "unified",
    "text": "diff --git a/file.py b/file.py\n...",
    "max_files": 200,
    "max_chars": 400000
  },
  "options": {
    "include_tests_checklist": true,
    "include_deploy_risks": true,
    "include_migration_risks": true,
    "language_hint": "python"
  }
}
```

## Response Format

```json
{
  "status": "succeeded",
  "data": {
    "summary": "🚫 2 blocking issues found",
    "score": {
      "risk": 50,
      "maintainability": 50,
      "security": 40,
      "test_coverage": 30
    },
    "blocking_issues": [
      {
        "id": "PRR-001",
        "title": "Secret detected in diff",
        "severity": "critical",
        "file": "config.py",
        "lines": "L15",
        "evidence": "API_KEY=***",
        "why_it_matters": "Secrets in code can be exposed...",
        "fix_suggestion": "Use environment variables..."
      }
    ],
    "issues": [...],
    "regression_risks": [...],
    "security_findings": [...],
    "tests_checklist": [...],
    "deploy_checklist": [...],
    "questions_for_author": [...]
  }
}
```

## Modes

### `blocking_only`
- Returns only critical and high severity issues
- Fast feedback for quick gate decisions
- No non-blocking issues

### `full_review`
- Complete analysis with all issues
- Includes recommendations and checklists
- Slower but thorough

## Blocking Issue Categories

| Category | Severity | Description |
|----------|----------|-------------|
| SECRETS | Critical | API keys, tokens, passwords in diff |
| RCE | Critical | eval, exec, subprocess with shell=True |
| SQL_INJECTION | Critical | String concatenation in queries |
| AUTH_BYPASS | High | Disabled auth checks |
| HARDCODED_CREDS | High | Hardcoded credentials |
| SECURITY_DISABLED | High | Security checks commented out |
| BREAKING_API | High | API changes without versioning |

## Non-Blocking Issue Categories

| Category | Severity | Description |
|----------|----------|-------------|
| TODO | Medium | Technical debt markers |
| BROAD_EXCEPTION | Medium | Catching all exceptions |
| LOGGING | Low | Print statements |
| BLOCKING_SLEEP | Low | Synchronous sleep calls |

## Security Features

### Logging Policy
- **NEVER** logs `diff.text`
- Only logs: hash (first 16 chars), file count, line count, char count, mode

### Secret Masking
Evidence automatically masks:
- `api_key = sk-live-***`
- `token = ***`
- `password = ***`
- Private keys: `-----BEGIN PRIVATE KEY-----` → masked

### Limits Enforced
- `max_chars`: Default 400KB, max configurable
- `max_files`: Default 200 files
- Timeout: 30 seconds for analysis

## Example Usage

### Blocking Only (Quick Gate)
```json
{
  "mode": "blocking_only",
  "diff": {
    "text": "diff --git a/.env b/.env\n+API_KEY=sk-live-123\n"
  }
}
```

Expected: Returns blocking issue about secrets, evidence masked.

### Full Review (Complete Analysis)
```json
{
  "mode": "full_review",
  "context": {
    "repo": {"name": "microdao-daarion", "commit_base": "abc", "commit_head": "def"}
  },
  "diff": {
    "text": "diff --git a/services/api/main.py..."
  },
  "options": {
    "include_tests_checklist": true,
    "include_deploy_risks": true
  }
}
```

Expected: Full response with blocking issues, non-blocking issues, checklists, regression risks.

## Scoring

### Risk Score (0-100)
- 0-25: Low risk
- 26-50: Medium risk
- 51-75: High risk
- 76-100: Critical risk

Calculation: `min(100, blocking_issues * 25 + issues * 5)`

### Security Score (0-100)
- Starts at 100
- Subtracts 30 per security finding

## Integration with Other Tools

### With RepoTool
If diff text not provided, can use:
```json
{
  "source": "git_range",
  "base": "abc123",
  "head": "def456"
}
```
Tool will fetch diff via RepoTool or local git.

## Testing

```bash
pytest tools/pr_reviewer_tool/tests/test_pr_reviewer.py -v
```

Test coverage:
- Diff size limits enforced
- File count limits enforced
- Secrets detection + masking
- RCE pattern detection
- SQL injection detection
- Auth bypass detection
- blocking_only vs full_review modes
- Scoring calculation
- Checklist generation

## Error Responses

```json
{
  "status": "failed",
  "error": {
    "code": "diff_too_large",
    "message": "Diff too large: 500000 chars (max: 400000)",
    "retryable": false
  }
}
```
