watchflow icon indicating copy to clipboard operation
watchflow copied to clipboard

feat: add conditional rule logic via <code>when:</code> block (issue #73, PR 1/3)

Open codesensei-tushar opened this issue 7 months ago β€’ 6 comments

feat: add conditional rule logic via when: block (issue #73, PR 1/3)

Part of #73

Summary

Rules in .watchflow/rules.yaml can now declare a when: block that gates evaluation. If the predicates don't match, the rule is skipped before any validator or LLM work runs (skip reason is logged).

rules:
  - description: Require Changelog (first-time contributors only)
    event_types: [pull_request]
    parameters:
      changelog_required: true
    when:
      contributor: first_time
      files_match: "src/auth/**"

Supported Predicates (v1)

All optional. Multiple predicates combine with AND.

Predicate Example Semantics
contributor: first_time when: { contributor: first_time } Zero prior merged PRs
contributor: trusted when: { contributor: trusted } β‰₯1 prior merged PR
pr_count_below: N when: { pr_count_below: 3 } Fewer than N merged PRs
files_match when: { files_match: "src/auth/**" } Changed file matches glob (string or list)

Expression parser (and / or / comparisons) and extended predicates (risk.level, contributor.role, …) are deferred to PRs 2/3 and 3/3.

Summary by CodeRabbit

  • New Features
    • Rules can be conditionally applied using a top-level when: block with predicates: contributor status (first_time | trusted), pr_count_below, and files_match globs/lists. All predicates must hold to apply a rule; skipped rules are logged at debug. Contributor context (login, merged PR count, is_first_time, trusted) is enriched via the GitHub Search API; missing data defaults to permissive (fail-open).
  • Documentation
    • Changelog entry added describing when: support and known future enhancements.

codesensei-tushar avatar Apr 17 '26 14:04 codesensei-tushar

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.

After your PR is submitted to the merge queue, this comment will be automatically updated with its status. If the PR fails, failure details will also be posted here

trunk-io[bot] avatar Apr 17 '26 14:04 trunk-io[bot]

No actionable comments were generated in the recent review. πŸŽ‰

ℹ️ Recent review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: eecbfea0-aad6-42cd-8359-88e6f2ab1a73

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between d58ae8fe1f6cebf57997f26e6bebc59a816576dc and 8251dc89015de2da8d81462de3ba16fadddda8d8.

πŸ“’ Files selected for processing (1)
  • src/rules/when_evaluator.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/rules/when_evaluator.py

πŸ“ Walkthrough

Walkthrough

Adds a structured when: predicate block to rules, enriches PR events with contributor context via the GitHub Search API, introduces predicate evaluation (contributor, pr_count_below, files_match) with fail-open semantics, integrates predicate checks into the rule engine to skip non-matching rules and log skip reasons at debug level, and includes unit tests and changelog entry.

Changes

Cohort / File(s) Summary
Core models
src/rules/models.py, src/agents/engine_agent/models.py
Added RuleWhen Pydantic model and an optional `when: RuleWhen
Rule loader
src/rules/loaders/github_loader.py
Parse optional top-level when block into RuleWhen when present; log and ignore invalid when content.
When evaluator
src/rules/when_evaluator.py
New should_apply_rule(when, event_data) implementing contributor, pr_count_below, and files_match checks with fail-open behavior and explanatory skip reasons.
Engine integration
src/agents/engine_agent/agent.py, src/agents/engine_agent/nodes.py
Propagate when into RuleDescription; analyze_rule_descriptions calls should_apply_rule and skips rules that do not apply, logging reason at DEBUG and appending analysis steps.
PR enrichment & GitHub client
src/event_processors/pull_request/enricher.py, src/integrations/github/api.py
Enricher builds contributor_context (login, merged_pr_count, is_first_time, trusted) using new GitHubClient.search_merged_pr_count; added search method that queries GitHub Search API and returns total_count or None.
Tests
tests/unit/rules/test_loader_when_block.py, tests/unit/rules/test_when_evaluator.py, tests/unit/agents/test_engine_agent.py, tests/unit/event_processors/pull_request/test_enricher.py, tests/unit/integrations/github/test_api.py
Added comprehensive tests for loader parsing, evaluator semantics (including fail-open cases), engine skipping/logging, enricher behavior, and GitHub Search API interactions.
Docs / Changelog
CHANGELOG.md
Added Unreleased β†’ Added entry documenting conditional when: block, supported predicates, and planned future extensions.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Event Source
    participant Enricher as PR Enricher
    participant GitHub as GitHub API
    participant Engine as Rule Engine
    participant Evaluator as When Evaluator

    Client->>Enricher: enrich_event_data(event)
    Enricher->>GitHub: search_merged_pr_count(repo, author)
    GitHub-->>Enricher: merged_pr_count (or None)
    Enricher->>Enricher: attach contributor_context to event_data
    Enricher-->>Client: enriched event_data

    Client->>Engine: analyze_rule_descriptions(state with event_data)
    Engine->>Engine: filter rules by event_type
    Engine->>Evaluator: should_apply_rule(rule.when, event_data)
    Evaluator->>Evaluator: evaluate contributor, pr_count_below, files_match
    Evaluator-->>Engine: (applies: bool, reason: str)

    alt applies == true
        Engine->>Engine: add rule to applicable_rules
    else applies == false
        Engine->>Engine: log "Rule \"<desc>\" skipped: <reason>" (DEBUG)
        Engine->>Engine: append analysis_steps entry
    end

    Engine-->>Client: applicable_rules

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • warestack/watchflow#73 β€” Matches implemented conditional rule-gating, contributor lookup, pr_count checks, and file-glob gating described in the issue.

Possibly related PRs

  • warestack/watchflow#59 β€” Touches GitHub API and PR enrichment codepaths; related by overlapping changes to PR enrichment and file fetching.
  • warestack/watchflow#43 β€” Overlaps on rule model and engine evaluation pipeline changes (Rule/RuleDescription/engine nodes integration).

Suggested reviewers

  • dkargatzis

Poem

🐰
I hop through rules with a curious twitch,
When blocks now guide which checks to stitch.
Contributor tales and globs in play,
I skip or run with a joyous swayβ€”
Watchflow clearer with every twitch.

πŸš₯ Pre-merge checks | βœ… 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% 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
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title accurately describes the main change: adding conditional rule logic via a when: block, and correctly references the issue (#73) and PR sequence (1/3).

✏️ 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 Apr 17 '26 14:04 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 99.15730% with 3 lines in your changes missing coverage. Please review.

:x: Your project status has failed because the head coverage (73.8%) 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     #75     +/-   ##
=======================================
+ Coverage   73.0%   73.8%   +0.8%     
=======================================
  Files        181     184      +3     
  Lines      13481   13831    +350     
=======================================
+ Hits        9851   10221    +370     
+ Misses      3630    3610     -20     

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 60ae336...8251dc8. 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 Apr 19 '26 14:04 codecov-commenter

πŸ›‘οΈ 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 (751 > 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 Apr 19 '26 14:04 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 (753 > 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 Apr 20 '26 04:04 watchflow[bot]

when: block β€” end-to-end sandbox validation

Validated conditional rule applicability on this branch against a live GitHub App installation. All three
predicate families (contributor, pr_count_below, files_match) behave as designed, including the AND
composition of multiple predicates.

Test repo: codesensei-tushar/watchflow-sandbox

Setup

A 7-rule .watchflow/rules.yaml covering every predicate permutation (first-time, trusted, pr_count_below,
single glob, list of globs, combined AND). Two contributors differing only in their per-repo merged-PR count:

  • tushar-u (burner, PR from fork): merged_pr_count = 0 β†’ is_first_time = true
  • codesensei-tushar (repo owner): flipped 0 β†’ 1 mid-test via a clean merge (PR #5) to become trusted, then further bumped 1 β†’ 3 via PR #8 and PR #9 to cross the pr_count_below: 3 threshold

Test matrix

Case PR Author state Result
Green baseline, small first-time edit #4
first-time pass, 0 violations β€” 3 of 7 rules applicable, rest correctly skipped
Clean trusted-flip PR (merged) #5
first-time β†’ trusted pass, 0 violations, merged
"Break everything" from owner #6 trusted
fail, 4 violations β€” first-time rules skipped, trusted CHANGELOG rule fired
"Break everything" from burner #7
first-time fail, 5 violations β€” first-time rules fired, trusted rule skipped
Large clean PR after merged_pr_count = 3
#10 trusted, 3 merged pass, 0 violations β€”
max_pr_loc rule skipped by when: pr_count_below: 3 despite 600 LOC

Side-by-side proof

PRs #6 and
#7 have identical change surfaces (600-line src/big.py, non-conventional title, 3-char body, .github/workflows/* + docs/* additions). The only
difference is the author's per-repo merged_pr_count. Violations diverge precisely where when: contributor gates it. PR #10 adds a third column showing the pr_count_below: 3 gate closing once the author has 3 merged PRs.

Rule PR #7 (first-time, 0 merged) PR #6 (trusted, 1 merged) PR #10 (trusted, 3 merged)
require_linked_issue (no when:) fired fired applied, passed
First-time title + desc (when: contributor: first_time) fired skipped skipped
Trusted CHANGELOG (when: contributor: trusted) skipped fired applied, passed
max_pr_loc (when: pr_count_below: 3) fired fired skipped
docs/* title (when: files_match: docs/*) fired fired skipped (no docs/ changes)
src/** codeowner (when: files_match: [...]) applied, passed applied, passed applied, passed
Combined first_time + src/** applied, passed skipped skipped

The diagonal inversion (rows 2 and 3) is the direct observable signal that contributor: gating works
end-to-end through the enricher β†’ when_evaluator β†’ condition pipeline. Row 4 proves the same for
pr_count_below: β€” server logs for PR #10 show exactly 3 rules marked applicable, with max_pr_loc absent from the applicability list before condition evaluation ever ran.

Verdict

when: block on feat/first-time-contributor-rules is functionally correct. All three predicate types and
their AND composition behave exactly as documented in src/rules/when_evaluator.py.

codesensei-tushar avatar Apr 20 '26 12:04 codesensei-tushar