---
name: code-quality
description: "Detect complexity hotspots, duplication above threshold, cognitive complexity violations, and tech debt accumulation"
type: operational
cadence: weekly
---

# Code Quality Runbook

## Objetivo

Detect complexity hotspots, duplication above threshold, cognitive complexity violations,
and tech debt accumulation. Produce actionable work items for sprint planning.

## Precondiciones

- `ruff` installed (minimum version 0.4.0 for JSON output). Install via `uv tool install ruff`.
- `jq` installed for the fallback path (Step 6). Pre-installed on most CI runners.
- `gh` or `az` CLI authenticated for work item creation and deduplication.
- `ai-eng` CLI is optional. Step 5 replaces Steps 1-4 when available; Step 6 provides equivalent coverage via ruff alone.

## Procedimiento

### Step 1 -- Run Linter

Collect all lint findings with statistics and structured output for downstream parsing.

```bash
ruff check src/ tests/ --statistics --output-format=json
LINT_EXIT=$?
echo "ruff exit code: $LINT_EXIT"
```

Note: capture output in-memory for downstream steps. Do not redirect to a local file.

### Step 2 -- Detect Complexity Violations

Scan for functions exceeding cyclomatic (threshold: 10) and cognitive complexity
(threshold: 15). Ruff rules C901 and PLR0912 cover the primary signals.

```bash
ruff check src/ --select C901,PLR0912 --output-format=json
```

For each finding, extract file path, function name, and reported complexity value.

### Step 3 -- Detect Duplication

Identify similar code blocks across files using ruff's duplication rules.

```bash
ruff check src/ --select PLR0801 --output-format=json
```

Project-level duplication thresholds in `pyproject.toml` take precedence over the default 3%.

### Step 4 -- Check Function Length

Find functions exceeding max_function_lines (50 lines) via PLR0915 (too many statements).

```bash
ruff check src/ --select PLR0915 --output-format=json
```

Cross-reference with PLR0913 (too many arguments) to surface high-priority refactoring candidates.

### Step 5 -- Comprehensive Metrics (ai-eng Available)

When `ai-eng` is installed, use it for a unified quality assessment covering all manifest thresholds.

```bash
if command -v ai-eng &>/dev/null; then
  ai-eng verify quality --json
  echo "ai-eng quality report generated"
fi
```

### Step 6 -- Fallback (ai-eng Unavailable)

When `ai-eng` is unavailable, merge ruff outputs from Steps 1-4 and apply thresholds manually.

```bash
if ! command -v ai-eng &>/dev/null; then
  echo "ai-eng not available -- falling back to ruff + heuristics"

  # Merge all ruff findings from Steps 1-4 (captured in-memory) into a single dataset
  # Count unique files with violations
fi
```

### Step 7 -- Map findings and deduplicate via handler

Map each finding from Steps 1-6 to the Finding contract and route through the shared dedup handler.

**Finding mapping:**

```yaml
domain_label: "tech-debt"
title: "tech-debt: $FUNCTION_NAME exceeds $METRIC_NAME ($CURRENT_VALUE/$THRESHOLD)"
file_path: $FILE_PATH
rule_id: $RUFF_RULE
symbol: $FUNCTION_NAME
severity: based on threshold exceedance (>2x = high, >1.5x = medium, else low)
body: |
  ## Code Quality Finding

  | Field            | Value                    |
  |------------------|--------------------------|
  | File             | $FILE_PATH               |
  | Function         | $FUNCTION_NAME           |
  | Metric           | $METRIC_NAME             |
  | Current Value    | $CURRENT_VALUE           |
  | Threshold        | $THRESHOLD               |
  | Rule             | $RUFF_RULE               |

  ## Suggested Action

  $SUGGESTED_ACTION

  ---
  *Auto-generated by code-quality runbook. Lifecycle: triage.*
```

Follow `handlers/dedup-check.md` to process all findings through the dedup cascade (max 15 per run).

Each new issue is labeled `tech-debt` and enters the triage lifecycle phase.

### Step 9 -- Generate Report

Produce a summary report with hotspot map, worst offenders, and trend analysis.

```bash
echo "=== Code Quality Report ==="
echo "Run date: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo ""
echo "--- Hotspot Map ---"
# Group findings by file, sorted by finding count descending

echo ""
echo "--- Worst Offenders ---"
# Top 5 functions by complexity

echo ""
echo "--- Trend ---"
echo "New findings this run: $NEW_COUNT"
echo "Pre-existing (open issues): $EXISTING_COUNT"
echo "Total active: $((NEW_COUNT + EXISTING_COUNT))"
```

The report distinguishes new findings from pre-existing ones so the team can track
whether debt is growing or shrinking.

## Output

Summary report to stdout. Work items created for violations exceeding thresholds. No local files are written.

## Guardrails

- **Max mutations**: At most 15 work items per run. Overflow findings are logged but not filed.
- **Read-only analysis**: Never modifies source code. Output is limited to reports, comments,
  labels, and work item creation.
- **Protected labels**: Issues with `p1-critical` or `pinned` are never modified or closed.
- **Protected states**: `closed` / `resolved` issues are never reopened. Recurring findings
  create new issues instead.
- **Mutations enabled by default.** All qualifying findings are written immediately.
- **No destructive operations**: Never deletes issues, removes labels, or alters existing
  work item content. Append-only.
