watchflow icon indicating copy to clipboard operation
watchflow copied to clipboard

feat: add /risk and /reviewers commands, closes #65

Open oleksii-quinta opened this issue 8 months ago • 12 comments

Summary - Issue https://github.com/warestack/watchflow/issues/65

This PR introduces reviewer recommendation and risk assessment as two new Watchflow capabilities, triggered via /reviewers and /risk slash commands on any pull request. Both features follow a rules-heavy approach: risk signals are derived by running the existing rule engine conditions against the PR, not by ad-hoc heuristics, keeping the governance model deterministic and auditable.

A new Reviewer Reasoning Agent (LLM-backed, single-responsibility) generates natural-language explanations for why each reviewer was selected, grounded in their expertise profile and the triggered risk signals. The agent gracefully degrades to mechanical scoring reasons if the LLM call fails.

Implementation Phases

Phase Status Notes
Phase 1 — Risk Assessment ✅ Complete RiskAssessmentProcessor + /risk command. Risk score computed via existing rule engine. Risk labels applied and breakdown posted as PR comment.
Phase 2 — Reviewer Recommendation ✅ Complete ReviewerRecommendationProcessor + /reviewers and /reviewers --force. Expertise profiles from CODEOWNERS + commit history + merged PR reviews in .watchflow/expertise.yaml. ReviewerReasoningAgent generates natural-language explanations.
Phase 3 — Load Balancing ✅ Complete Pending review counts fetched per candidate (15-min cache). Overloaded reviewers penalized. Reviewer count scales with risk level (1 low → 3 critical).

What was done

New processors:

  • ReviewerRecommendationProcessor — recommends reviewers based on a 3-tier scoring model: (1) CODEOWNERS + commit history, (2) expertise profiles from .watchflow/expertise.yaml, (3) review history and critical-owner rules. Resolves team CODEOWNERS (@org/team) to individual members. Applies load-balancing penalties and inactivity decay.
  • RiskAssessmentProcessor — evaluates PR risk level (low/medium/high/critical) by running signal evaluators that each filter rules by parameter key and execute them through the existing engine agent.

New agent:

  • ReviewerReasoningAgent — single-responsibility LLM agent with typed ReviewerReasoningInput/ReviewerReasoningOutput (Pydantic at boundaries). Produces one explanation per reviewer and short topic labels for matched global rules.

Expertise system:

  • Contributor expertise is stored in .watchflow/expertise.yaml in the repository's default branch, alongside rules.yaml. Each contributor profile contains: languages, commit_count, path_commit_counts (file-level ownership signal), last_active date, and reviews (bucketed by risk level: low/medium/high/critical).
  • A dedicated expertise_scheduler.py refreshes profiles via a layered strategy: (1) CODEOWNERS base layer, (2) commit history scan (full 1-year lookback on fresh build, incremental on update), (3) merged PR layer (file changes, per-path commits, review history). Layers merge using max() for numeric counts to avoid inflation across runs.
  • A GitHub Actions workflow (.github/workflows/refresh-expertise.yaml) triggers on a schedule defined in the workflow via OIDC-authenticated POST, requiring no user-configured secrets.
  • To keep expertise profiles current, users are expected to add the refresh-expertise.yaml workflow to their repository's .github/workflows/ directory (or have it generated automatically during the initial .watchflow/rules.yaml setup flow). Without this workflow, profiles are only updated opportunistically during reviewer recommendation runs.
  • A future direction for expertise storage is using GitHub Projects as a structured backing store — this would allow richer querying, manual overrides via the Projects UI, and integration with existing team planning workflows without committing machine-generated YAML to the default branch.

Command handling:

  • /reviewers and /reviewers --force — enqueue reviewer recommendation (with cache bypass on --force).
  • /risk — enqueue standalone risk assessment.
  • @watchflow help updated with new commands.

Bug fix — FilePatternCondition._get_changed_files:

  • The upstream FilePatternCondition._get_changed_files() method contained only a TODO placeholder that always returned [], making the pattern + condition_type parameters entirely inactive (upstream code). This PR implements the actual file extraction from the event's files / changed_files arrays, enabling FilePatternCondition to function for both files_match_pattern and files_not_match_pattern condition types.

Live demo

These features can be seen in action on the test repository: oleksii-quinta/watchflow-test-code. Open any PR there and comment /reviewers or /risk to trigger the processors and see the generated comments, risk labels, and reviewer recommendations with reasoning.

Rules-heavy approach

Risk signals are not computed via standalone heuristics — each signal evaluator loads PR rules from .watchflow/rules.yaml, filters to those containing relevant parameter keys, and executes them through the engine agent to produce Violation objects. Violations are then mapped to RiskSignal instances. This means:

  • Adding a new rule to rules.yaml (e.g., a require_tests rule) automatically surfaces a corresponding risk signal without any code changes.
  • The rule's severity field propagates into the risk signal, and the overall risk level is computed from the weighted sum of signal severities against the total rule weight.
  • Rules with file_patterns produce path-specific signals with semantic labels derived from the rule description.

Implemented without new rule parameters

This version ships using only the existing condition parameter keys (as documented in CONTRIBUTING.md: require_linked_issue, max_lines, require_code_owner_reviewers, no_force_push, etc.). No new rule parameters were introduced. However, the following signal-specific rules would significantly improve coverage and are planned:

Signal Current rule parameter(s) Planned additions
Size risk max_lines max_commits (limit commit count per PR), max_files (limit number of changed files)
Critical path critical_owners (bug: no resolver for the condition — owners listed but never matched against changed files) Replace with critical_path rule that uses file patterns to identify critical business paths
Test coverage require_tests (already functional)
Dependency changes diff_restricted_patterns -
Contributor history Enabled by default (checks author_association from GitHub API) first_time_contributor rule (new) to allow disabling this signal per repo
Reverts title_pattern (match "revert" in PR title) commit_messages_match (new) to detect revert commits in the diff
Security-sensitive security_patterns Use pattern + condition_type to match security-related file paths (e.g., *.env, **/secrets/**, **/auth/**)
Breaking changes pattern + condition_type for BREAKING paths, title_pattern for "BREAKING" in PR title commit_messages_match (new) to detect "BREAKING" in commit messages

Additional GitHub App permissions required

This PR requires two additional repository permissions to be granted by users installing the Watchflow GitHub App:

1. Contents — Read and Write

Previously the app only needed read access to repository contents (for loading rules.yaml and CODEOWNERS). The expertise refresh system now writes .watchflow/expertise.yaml back to the default branch via the Contents API. The specific endpoints requiring this permission:

Endpoint Used by Access
GET /repos/{owner}/{repo}/contents/{path} Reading expertise.yaml, rules.yaml, CODEOWNERS read
PUT /repos/{owner}/{repo}/contents/{path} Writing updated expertise.yaml to the default branch write
GET /repos/{owner}/{repo}/git/trees/{tree_sha} Fetching the full repository tree for stale-path pruning during expertise refresh read
GET /repos/{owner}/{repo}/commits Scanning commit history per file path to build contributor expertise profiles read
GET /repos/{owner}/{repo}/commits/{ref} Resolving tree SHA for a given branch ref read

Per GitHub docs — Repository permissions for "Contents": PUT /repos/{owner}/{repo}/contents/{path} requires Contents: write.

2. Workflows — Read and Write

If the app generates the .github/workflows/refresh-expertise.yaml workflow file during the initial rules setup flow (rather than the user adding it manually), it must write to a path under .github/workflows/. GitHub treats workflow files as a separate permission scope — the Contents permission alone is insufficient.

Endpoint Used by Access
PUT /repos/{owner}/{repo}/contents/{path} (where path is .github/workflows/*) Creating refresh-expertise.yaml during initial setup write

Per GitHub docs — Repository permissions for "Workflows": PUT /repos/{owner}/{repo}/contents/{path} additionally requires Workflows: write when the target path is a workflow file.

Known limitation: hardcoded severity in conditions

Not all rule conditions honour the severity declared in rules.yaml. For example, MaxPrLocCondition.evaluate() hardcodes severity=Severity.MEDIUM regardless of the rule's configured severity. The same applies to FilePatternCondition and TestCoverageCondition. This means a rule with severity: "high" in rules.yaml may still produce a MEDIUM violation at evaluation time, which in turn affects risk scoring. This should be addressed by passing the rule's severity through to the condition's evaluate() context.

Files changed (23 files, ~2,984 additions)

  • New: src/event_processors/reviewer_recommendation.py, src/event_processors/risk_assessment/, src/event_processors/expertise_scheduler.py, src/agents/reviewer_reasoning_agent/, src/core/utils/github_oidc.py, .github/workflows/refresh-expertise.yaml
  • Modified: src/integrations/github/api.py, src/presentation/github_formatter.py, src/webhooks/handlers/issue_comment.py, src/rules/conditions/filesystem.py, src/rules/utils/codeowners.py, src/agents/factory.py, src/event_processors/factory.py, src/api/scheduler.py
  • Tests: tests/unit/event_processors/test_risk_assessment_signals.py, tests/unit/rules/conditions/test_filesystem.py

Summary by CodeRabbit

  • New Features

    • Reviewer recommendation system with AI-generated per-reviewer explanations and risk-aware ranking
    • Risk assessment engine producing multi-signal risk comments and labels
    • Background expertise refresh workflow and POST /refresh-expertise API (OIDC-protected)
  • Bug Fixes

    • Fixed PR files pagination and retrieval
    • CODEOWNERS now matches nested paths
    • Improved changed-files extraction for rule evaluations
  • Chores

    • GitHub integration: label management, commits, teams, installations
  • Tests

    • Added unit tests for risk signal formatting and file-change handling

oleksii-quinta avatar Mar 26 '26 15:03 oleksii-quinta

Merging to main in this repository is managed by Trunk.

  • [ ] To merge this pull request, check the box to the left or comment /trunk merge below.

trunk-io[bot] avatar Mar 26 '26 15:03 trunk-io[bot]

🛡️ Watchflow Governance Checks

Status: ❌ 4 Violations Found

🟡 Medium Severity (4)

Checks PR description (body) and title for a linked issue reference (e.g. #123, Fixes #123, Closes #456). Use when the rule requires issue refs in either field.

PR does not reference a linked issue (e.g. #123 or closes #123 in body/title) How to fix: Add an issue reference in the PR title or description (e.g. Fixes #123).

Validates that total lines changed (additions + deletions) in a PR do not exceed a maximum; enforces a maximum LOC per pull request.

Pull request exceeds maximum lines changed (3003 > 500) How to fix: Reduce the size of this PR to at most 500 lines changed (additions + deletions).

Validates if the PR title matches a specific pattern

PR title 'Feat/issue 65' does not match required pattern '^feat|^fix|^docs|^style|^refactor|^test|^chore|^perf|^ci|^build|^revert' How to fix: Update the PR title to match the pattern: ^feat|^fix|^docs|^style|^refactor|^test|^chore|^perf|^ci|^build|^revert

Ensures PRs that modify source code also include a CHANGELOG or .changeset addition.

Source code was modified without a corresponding CHANGELOG update. How to fix: Add an entry to CHANGELOG.md or generate a new .changeset file describing your changes.


💡 Reply with @watchflow ack [reason] to override these rules, or @watchflow help for commands.

Thanks for using Watchflow! It's completely free for OSS and private repositories. You can also self-host it easily.

watchflow[bot] avatar Mar 26 '26 15:03 watchflow[bot]

📝 Walkthrough

Walkthrough

Adds reviewer recommendation and risk assessment features: new ReviewerReasoningAgent and models/prompts, two event processors, expertise refresh scheduler, GitHub OIDC verifier and API endpoint, GitHub client extensions, webhook commands, formatters, rules/CODEOWNERS updates, repository-analysis tweak, and tests.

Changes

Cohort / File(s) Summary
Reviewer Reasoning Agent
src/agents/reviewer_reasoning_agent/__init__.py, src/agents/reviewer_reasoning_agent/agent.py, src/agents/reviewer_reasoning_agent/models.py, src/agents/reviewer_reasoning_agent/prompts.py
New LLM-backed agent with Pydantic I/O models, prompt builders, structured output parsing, timeout/retry, and execute/generate APIs producing per-reviewer explanations and rule labels.
Agent Factory & Exports
src/agents/__init__.py, src/agents/factory.py
Exports ReviewerReasoningAgent and registers "reviewer_reasoning" in the agent factory.
Event Processors
src/event_processors/reviewer_recommendation.py, src/event_processors/risk_assessment/processor.py, src/event_processors/risk_assessment/signals.py, src/event_processors/factory.py
Adds ReviewerRecommendationProcessor and RiskAssessmentProcessor; risk signal evaluators, aggregation, labeling, and factory registration.
Expertise Scheduler
src/event_processors/expertise_scheduler.py
New scheduled/triggered refresher that builds/updates .watchflow/expertise.yaml from CODEOWNERS, commit history, and merged PRs.
API & OIDC
src/api/scheduler.py, src/core/utils/github_oidc.py
Adds POST /refresh-expertise endpoint requiring GitHub Actions OIDC verification and an async JWKS-backed verifier with repository-claim checking.
GitHub Client Extensions
src/integrations/github/api.py
Fixes PR files pagination URL, adds PR listing pagination, and new helpers: ensure_label, add_labels_to_issue, get_commits, get_repo_installation, get_team_members, list_app_installations, list_installation_repositories.
Presentation
src/presentation/github_formatter.py
Adds comment formatters for reviewer recommendations and risk assessments, plus mention-sanitization and TYPE_CHECKING typing adjustments.
Rules & CODEOWNERS
src/rules/conditions/filesystem.py, src/rules/utils/codeowners.py
Changed-file extraction now prefers event["files"] then changed_files; CODEOWNERS bare-path patterns now match nested paths.
Repository Analysis
src/agents/repository_analysis_agent/nodes.py
Includes FIRST_TIMER in first-time contributor detection used for hygiene metrics.
Webhook Handlers
src/webhooks/handlers/issue_comment.py
Adds /reviewers (with --force) and /risk slash-command handling that enqueues processors; uses payload= when enqueuing and updates help text.
Tests
tests/unit/event_processors/test_risk_assessment_signals.py, tests/unit/rules/conditions/test_filesystem.py
Adds unit tests for path-signal description formatting and FilePatternCondition changed-file extraction/validation.
Minor
src/event_processors/pull_request/processor.py
Whitespace-only formatting change.

Sequence Diagram(s)

sequenceDiagram
    participant Webhook
    participant Handler
    participant Queue
    participant Processor as ReviewerRecommendationProcessor
    participant GitHub as GitHub API
    participant Expertise as Expertise Store
    participant Rules as Rule Engine
    participant Scorer as Reviewer Scorer
    participant LLM as ReviewerReasoningAgent
    participant Cache as Cache Store

    Webhook->>Handler: /reviewers comment
    Handler->>Queue: enqueue task
    Queue->>Processor: process(task)
    Processor->>Cache: check cached result
    alt cache hit
        Cache-->>Processor: cached comment & labels
    else cache miss
        Processor->>GitHub: fetch PR files & metadata
        Processor->>GitHub: fetch open PRs (load)
        Processor->>Expertise: load .watchflow/expertise.yaml
        Processor->>Rules: load repository rules
        Processor->>Scorer: compute candidate scores
        Processor->>LLM: generate reviewer reasoning (optional)
        LLM-->>Processor: {explanations, rule_labels}
        Processor->>Cache: store generated comment & labels
    end
    Processor->>GitHub: post PR comment
    Processor->>GitHub: ensure & apply labels
    Processor-->>Queue: return ProcessingResult
sequenceDiagram
    participant Webhook
    participant Handler
    participant Queue
    participant Processor as RiskAssessmentProcessor
    participant GitHub as GitHub API
    participant Rules as Rule Engine
    participant Evaluators as Signal Evaluators

    Webhook->>Handler: /risk comment
    Handler->>Queue: enqueue task
    Queue->>Processor: process(task)
    Processor->>GitHub: fetch PR metadata
    Processor->>GitHub: fetch PR files
    Processor->>Rules: load & filter PR rules
    Processor->>Evaluators: evaluate_size, evaluate_critical_path, evaluate_test_coverage,...
    Evaluators-->>Processor: list[RiskSignal]
    Processor->>Processor: compute_risk (aggregate signals)
    Processor->>GitHub: post risk assessment comment
    Processor->>GitHub: ensure & apply risk label
    Processor-->>Queue: return ProcessingResult
sequenceDiagram
    participant API
    participant Handler as /refresh-expertise
    participant OIDC as OIDC Verifier
    participant Scheduler as Expertise Scheduler
    participant GitHub as GitHub API
    participant CODEOWNERS as CODEOWNERS Parser
    participant Contributors as Contributor Profiler

    API->>Handler: POST /refresh-expertise (Bearer token)
    Handler->>OIDC: verify_github_oidc_token(token, expected_repo)
    OIDC-->>Handler: decoded claims
    Handler->>Scheduler: refresh_expertise_by_repo_name(repo)
    Scheduler->>GitHub: fetch repo info & tree
    Scheduler->>CODEOWNERS: parse CODEOWNERS
    Scheduler->>Contributors: profile from commit history & merged PRs
    Scheduler->>GitHub: create_or_update_file(.watchflow/expertise.yaml)
    Scheduler-->>Handler: success
    Handler-->>API: {status: "Expertise refresh completed"}

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

  • warestack/watchflow#65: Implements reviewer recommendation and risk-assessment features matching the issue’s objectives.

Possibly related PRs

  • warestack/watchflow#59: Related — touches GitHub client behavior and overlaps with API/client changes.

Suggested labels

enhancement

Suggested reviewers

  • dkargatzis

Poem

🐰 Hopping through diffs with a curious twitch,

I stitched reviewer wisdom into every switch.
Risk sings its signal, expertise blooms anew,
Comments and labels now guide what to do.
Cheers from a rabbit — code tidy, clever, and true!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.90% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main additions: two new slash commands (/risk and /reviewers) that represent the primary feature in this PR, with an issue reference.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Mar 26 '26 15:03 coderabbitai[bot]

:warning: Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

:x: Patch coverage is 16.54581% with 1266 lines in your changes missing coverage. Please review.

:x: Your patch status has failed because the patch coverage (16.5%) is below the target coverage (80.0%). You can increase the patch coverage or adjust the target coverage. :x: Your project status has failed because the head coverage (63.9%) is below the target coverage (80.0%). You can increase the head coverage or adjust the target coverage. :exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality.

@@           Coverage Diff           @@
##            main     #67     +/-   ##
=======================================
- Coverage   70.0%   63.9%   -6.1%     
=======================================
  Files        172     182     +10     
  Lines      11744   13249   +1505     
=======================================
+ Hits        8229    8477    +248     
- Misses      3515    4772   +1257     

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 5e9d037...b23bfe9. Read the comment docs.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

codecov-commenter avatar Mar 26 '26 16:03 codecov-commenter

🛡️ Watchflow Governance Checks

Status: ❌ 3 Violations Found

🟡 Medium Severity (3)

Checks PR description (body) and title for a linked issue reference (e.g. #123, Fixes #123, Closes #456). Use when the rule requires issue refs in either field.

PR does not reference a linked issue (e.g. #123 or closes #123 in body/title) How to fix: Add an issue reference in the PR title or description (e.g. Fixes #123).

Validates that total lines changed (additions + deletions) in a PR do not exceed a maximum; enforces a maximum LOC per pull request.

Pull request exceeds maximum lines changed (3003 > 500) How to fix: Reduce the size of this PR to at most 500 lines changed (additions + deletions).

Ensures PRs that modify source code also include a CHANGELOG or .changeset addition.

Source code was modified without a corresponding CHANGELOG update. How to fix: Add an entry to CHANGELOG.md or generate a new .changeset file describing your changes.


💡 Reply with @watchflow ack [reason] to override these rules, or @watchflow help for commands.

Thanks for using Watchflow! It's completely free for OSS and private repositories. You can also self-host it easily.

watchflow[bot] avatar Mar 27 '26 12:03 watchflow[bot]

@oleksii-quinta Nice work on this PR! 👍 Could you please add a quick test or example showing this rule in action? That would help new users see how it works

nehaaprasad avatar Mar 30 '26 10:03 nehaaprasad

@nehaaprasad Hi! Thank you for your attention.
I have a live, working demo repository here: https://github.com/oleksii-quinta/watchflow-test-code

Please open the Pull Requests tab to see the bot in action.

Important note: The bot relies solely on existing Watchflow rules. This gives users a clear, fully customizable view of why the bot behaves the way it does.

oleksii-quinta avatar Mar 30 '26 12:03 oleksii-quinta

@dimalavrishin-qg could you please address the pre-commit issues?

dkargatzis avatar Mar 30 '26 15:03 dkargatzis

🛡️ Watchflow Governance Checks

Status: ❌ 3 Violations Found

🟡 Medium Severity (3)

Checks PR description (body) and title for a linked issue reference (e.g. #123, Fixes #123, Closes #456). Use when the rule requires issue refs in either field.

PR does not reference a linked issue (e.g. #123 or closes #123 in body/title) How to fix: Add an issue reference in the PR title or description (e.g. Fixes #123).

Validates that total lines changed (additions + deletions) in a PR do not exceed a maximum; enforces a maximum LOC per pull request.

Pull request exceeds maximum lines changed (2997 > 500) How to fix: Reduce the size of this PR to at most 500 lines changed (additions + deletions).

Ensures PRs that modify source code also include a CHANGELOG or .changeset addition.

Source code was modified without a corresponding CHANGELOG update. How to fix: Add an entry to CHANGELOG.md or generate a new .changeset file describing your changes.


💡 Reply with @watchflow ack [reason] to override these rules, or @watchflow help for commands.

Thanks for using Watchflow! It's completely free for OSS and private repositories. You can also self-host it easily.

watchflow[bot] avatar Mar 30 '26 16:03 watchflow[bot]

@dkargatzis sure, all pre-commit issues should be fixed right now.

dimalavrishin-qg avatar Mar 30 '26 16:03 dimalavrishin-qg

🛡️ Watchflow Governance Checks

Status: ❌ 2 Violations Found

🟡 Medium Severity (2)

Validates that total lines changed (additions + deletions) in a PR do not exceed a maximum; enforces a maximum LOC per pull request.

Pull request exceeds maximum lines changed (3001 > 500) How to fix: Reduce the size of this PR to at most 500 lines changed (additions + deletions).

Ensures PRs that modify source code also include a CHANGELOG or .changeset addition.

Source code was modified without a corresponding CHANGELOG update. How to fix: Add an entry to CHANGELOG.md or generate a new .changeset file describing your changes.


💡 Reply with @watchflow ack [reason] to override these rules, or @watchflow help for commands.

Thanks for using Watchflow! It's completely free for OSS and private repositories. You can also self-host it easily.

watchflow[bot] avatar Mar 30 '26 17:03 watchflow[bot]

🛡️ Watchflow Governance Checks

Status: ❌ 1 Violations Found

🟡 Medium Severity (1)

Validates that total lines changed (additions + deletions) in a PR do not exceed a maximum; enforces a maximum LOC per pull request.

Pull request exceeds maximum lines changed (3040 > 500) How to fix: Reduce the size of this PR to at most 500 lines changed (additions + deletions).


💡 Reply with @watchflow ack [reason] to override these rules, or @watchflow help for commands.

Thanks for using Watchflow! It's completely free for OSS and private repositories. You can also self-host it easily.

watchflow[bot] avatar Mar 30 '26 17:03 watchflow[bot]