Skip to content

Update event handling for pull request updates - #2637

Merged
IsmaelMartinez merged 8 commits into
The-PR-Agent:mainfrom
michaelwellsjr:fix/use-correct-bitbucket-webhook-event-key
Aug 26, 2026
Merged

IsmaelMartinez merged 8 commits into
The-PR-Agent:mainfrom
michaelwellsjr:fix/use-correct-bitbucket-webhook-event-key

Conversation

@michaelwellsjr

Copy link
Copy Markdown
Contributor

Use correct bitbucket eventKey "pr:from_ref_updated" so pr review triggers on updates being pushed to the pr.

Use correct bitbucket eventKey "pr:from_ref_updated"
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix Bitbucket PR update webhook eventKey handling

🐞 Bug fix 🕐 Less than 10 minutes

Grey Divider

AI Description

• Trigger PR automation on Bitbucket PR source-branch updates using pr:from_ref_updated.
• Stop relying on repo:refs_changed for PR update detection to ensure reviews run on new pushes.
Diagram

graph TD
  BB{{"Bitbucket Server"}} --> HW["handle_webhook()"] --> EK{"eventKey?"}
  EK -->|"pr:opened / pr:from_ref_updated"| ARS["apply_repo_settings"] --> CMD["Select commands"]
  EK -->|"pr:comment:added"| CMD
  CMD --> RUN["Run commands"] --> AG["PRAgent.handle_request"]

  subgraph Legend
    direction LR
    _ext{{"External"}} ~~~ _api["Handler/logic"] ~~~ _dec{"Decision"}
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Accept both event keys (compatibility mode)
  • ➕ More resilient across Bitbucket Server/DC versions or differing webhook configurations
  • ➕ Avoids breaking existing installs that still emit/expect repo:refs_changed semantics
  • ➖ Could re-introduce unwanted triggers if repo:refs_changed fires for non-PR pushes
  • ➖ Slightly more branching/maintenance and harder-to-reason trigger matrix
2. Make update-trigger event keys configurable
  • ➕ Allows admins to match their Bitbucket webhook payloads without code changes
  • ➕ Supports future Bitbucket eventKey changes safely
  • ➖ Adds configuration surface area and documentation burden
  • ➖ Misconfiguration can silently disable triggers

Recommendation: Using pr:from_ref_updated is the correct default if the intent is to trigger automation specifically when new commits are pushed to an existing PR. If you need to support heterogeneous Bitbucket installations, consider temporarily accepting both keys or making the update trigger configurable to reduce rollout risk.

Files changed (1) +1 / -1

Bug fix (1) +1 / -1
bitbucket_server_webhook.pyTrigger PR update automation on 'pr:from_ref_updated' events +1/-1

Trigger PR update automation on 'pr:from_ref_updated' events

• Updates the webhook event routing to treat 'pr:from_ref_updated' as the PR-update/push trigger instead of 'repo:refs_changed'. This ensures configured push-trigger commands (e.g., review) run when new commits are pushed to an existing pull request.

pr_agent/servers/bitbucket_server_webhook.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Dropped refs_changed support 🐞 Bug ≡ Correctness
Description
handle_webhook no longer accepts repo:refs_changed events; those requests will now fall through
to the default branch and return HTTP 400 "Unsupported event" instead of running the PR update
automation. This is a behavioral regression for any existing webhook configurations still sending
repo:refs_changed payloads (even when they include a pullRequest.id).
Code

pr_agent/servers/bitbucket_server_webhook.py[R165-166]

    if (data["eventKey"] == "pr:opened"
-            or (data["eventKey"] == "repo:refs_changed" and data.get("pullRequest", {}).get("id", -1) != -1)):  # push event; -1 for push unassigned to a PR: #Check auto commands for creation/updating
+            or (data["eventKey"] == "pr:from_ref_updated" and data.get("pullRequest", {}).get("id", -1) != -1)):  # push event; -1 for push unassigned to a PR: #Check auto commands for creation/updating
Evidence
The webhook handler’s accepted event list now includes only pr:opened, pr:from_ref_updated, and
pr:comment:added; all other eventKeys fall into the final else which returns HTTP 400. Since
repo:refs_changed was removed from the accepted condition, it will now be rejected as unsupported.

pr_agent/servers/bitbucket_server_webhook.py[165-196]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The webhook handler used to treat `repo:refs_changed` (when associated with a PR) as a push/update trigger. The PR changes the conditional to only accept `pr:from_ref_updated`, which means `repo:refs_changed` now returns a 400 Unsupported event and no longer triggers automation.

### Issue Context
If this change is meant to be backward compatible, the handler should accept both eventKeys (or make the accepted key configurable), at least for the same PR-associated guard.

### Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[165-196]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.
Tip of the day
💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (2) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Single-quoted command key 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new test uses single-quoted string literals in the _get_commands_list_from_settings lambda,
contrary to the repository's double-quote convention. Replace them with double-quoted literals.
Code

tests/unittest/test_webhook_logic_core.py[80]

+        lambda key: ["/review"] if key == "BITBUCKET_SERVER.PUSH_COMMANDS" else [],
Relevance

●● Moderate

Double-quote fixes were accepted in tests, but a recent similarly scoped quote-style finding was
rejected.

PR-#2569
PR-#2598

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist requires all newly changed Python string literals to use double quotes, except where
escaping makes single quotes preferable. The added comparison uses a simple string with no such
escaping requirement.

Rule 2694657: Use double quotes for all Python string literals
tests/unittest/test_webhook_logic_core.py[80-80]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The added lambda compares `key` to a single-quoted string, violating the project's Python string-literal convention.

## Issue Context
Keep the regression test behavior unchanged while matching the established formatting rule.

## Fix Focus Areas
- tests/unittest/test_webhook_logic_core.py[77-80]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Non-imperative stub docstring 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The newly added _StubRequest docstring begins with the descriptive phrase Minimal stand-in
rather than an imperative description of the class's behavior. Rewrite it as an imperative
instruction such as Expose only the Request members that handle_webhook reads.
Code

tests/unittest/test_webhook_logic_core.py[52]

+    """Minimal stand-in for a starlette Request, exposing only what handle_webhook reads."""
Relevance

●● Moderate

Imperative docstring fixes were recently accepted, but a recent test-docstring precedent was
rejected; team behavior is mixed.

PR-#2703
PR-#2661

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The added class docstring starts with Minimal stand-in for..., which is descriptive rather than an
imperative verb phrase such as Expose... or Provide....

Rule 2694688: Docstrings and comments must use imperative phrasing
tests/unittest/test_webhook_logic_core.py[51-52]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new `_StubRequest` docstring uses a descriptive noun phrase instead of imperative phrasing.

## Issue Context
The project checklist requires the first descriptive line of newly added docstrings to use imperative mood.

## Fix Focus Areas
- tests/unittest/test_webhook_logic_core.py[51-52]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Webhook condition exceeds line limit ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The modified condition and inline comment form a Python line longer than the configured
120-character maximum. This violates the Ruff line-length requirement and should be wrapped into
multiple lines.
Code

pr_agent/servers/bitbucket_server_webhook.py[166]

+            or (data["eventKey"] in ["pr:from_ref_updated", "repo:refs_changed"] and data.get("pullRequest", {}).get("id", -1) != -1)): # push event; -1 for push unassigned to a PR: #Check auto commands for creation/updating
Evidence
The checklist requires every logical line in changed Python files to be at most 120 characters. The
added line at pr_agent/servers/bitbucket_server_webhook.py:166 contains the full condition and
inline comment on one line and visibly exceeds that limit.

Rule 2694655: Enforce 120-character maximum line length in Python source per Ruff config
pr_agent/servers/bitbucket_server_webhook.py[166-166]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The modified webhook condition line exceeds the 120-character Python line-length limit.

## Issue Context
The line combines the event-key membership test, pull-request ID guard, and a long inline comment. Preserve the existing behavior while making every physical line no longer than 120 characters.

## Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[166-166]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
✅ Compliance rules (platform): 34 rules
Review mode: 🚀 Fast: This is a single, localized test-only annotation change with no runtime behavior or high-risk area, so one light review pass is sufficient.

Grey Divider

Tip of the day
💡 Did you know, you can start a comment with 'qodo' or '@qodo' to chat about any finding

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit 5317000

Results up to commit d378cd7 🚀 Fast


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 📜 Skill insights (0)


Remediation recommended
1. Webhook condition exceeds line limit ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The modified condition and inline comment form a Python line longer than the configured
120-character maximum. This violates the Ruff line-length requirement and should be wrapped into
multiple lines.
Code

pr_agent/servers/bitbucket_server_webhook.py[166]

+            or (data["eventKey"] in ["pr:from_ref_updated", "repo:refs_changed"] and data.get("pullRequest", {}).get("id", -1) != -1)): # push event; -1 for push unassigned to a PR: #Check auto commands for creation/updating
Evidence
The checklist requires every logical line in changed Python files to be at most 120 characters. The
added line at pr_agent/servers/bitbucket_server_webhook.py:166 contains the full condition and
inline comment on one line and visibly exceeds that limit.

Rule 2694655: Enforce 120-character maximum line length in Python source per Ruff config
pr_agent/servers/bitbucket_server_webhook.py[166-166]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The modified webhook condition line exceeds the 120-character Python line-length limit.

## Issue Context
The line combines the event-key membership test, pull-request ID guard, and a long inline comment. Preserve the existing behavior while making every physical line no longer than 120 characters.

## Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[166-166]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit e0324f8

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified: merges clean, full suite passes at 2031. The change is right, and the old code proves it - the else branch comment already said "Has to be: pr:from_ref_updated", but the condition above it only ever matched pr:opened or repo:refs_changed, so for that event the branch was unreachable.

Could you add a test? tests/unittest/ has webhook tests to copy from, and this is the kind of event-routing fix that quietly regresses.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 80ce524

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding the test.

Your pr:from_ref_updated case is doing its job: it goes red against main's source and green against yours, so the change itself is right.

The rewritten import block is the problem, and build-and-test is now failing on it. Suggestion inline.

Comment on lines 1 to 11
import copy
import importlib
from types import SimpleNamespace
import json

import pytest
from starlette.testclient import TestClient
from starlette.background import BackgroundTasks
from starlette_context import request_cycle_context

import pr_agent.servers.bitbucket_server_webhook as bitbucket_server_webhook
from pr_agent.config_loader import get_settings
from pr_agent.identity_providers.identity_provider import Eligibility
from pr_agent.servers import bitbucket_server_webhook, github_app


Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This drops SimpleNamespace, TestClient, Eligibility and github_app, which are still used from line 251 to 408, so 15 existing tests in this file fail. Restoring them, plus the blank line the rewrite removed, gives 34 of 34 here and keeps ruff clean.

Suggested change
import copy
import importlib
from types import SimpleNamespace
import json
import pytest
from starlette.testclient import TestClient
from starlette.background import BackgroundTasks
from starlette_context import request_cycle_context
import pr_agent.servers.bitbucket_server_webhook as bitbucket_server_webhook
from pr_agent.config_loader import get_settings
from pr_agent.identity_providers.identity_provider import Eligibility
from pr_agent.servers import bitbucket_server_webhook, github_app
import copy
import importlib
import json
from types import SimpleNamespace
import pytest
from starlette.background import BackgroundTasks
from starlette.testclient import TestClient
from starlette_context import request_cycle_context
from pr_agent.config_loader import get_settings
from pr_agent.identity_providers.identity_provider import Eligibility
from pr_agent.servers import bitbucket_server_webhook, github_app

# push event; -1 for push unassigned to a PR: Check auto commands for creation/updating
if (data["eventKey"] == "pr:opened"
or (data["eventKey"] == "repo:refs_changed" and data.get("pullRequest", {}).get("id", -1) != -1)): # push event; -1 for push unassigned to a PR: #Check auto commands for creation/updating
or (data["eventKey"] in ["pr:from_ref_updated", "repo:refs_changed"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trailing whitespace here; the repo has an active trailing-whitespace pre-commit hook.

Suggested change
or (data["eventKey"] in ["pr:from_ref_updated", "repo:refs_changed"]
or (data["eventKey"] in ["pr:from_ref_updated", "repo:refs_changed"]

The import block rewrite removed SimpleNamespace, TestClient, Eligibility and
github_app, which the GitHub and GitLab draft-setting tests still use, so 15
tests in the file failed. Also drops the trailing whitespace on the new
eventKey line.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit f7a5bc5

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed the import restore rather than leave you another round, plus the trailing whitespace on the new eventKey line. That file is back to 34 of 34 and build-and-test is green.

Thanks for adding the test, that is the part that made this easy to confirm.

The CI image installs from pyproject.toml and then deletes it, so
asyncio_mode = "auto" is not in effect there and an unmarked async test is
skipped as unsupported. Every other async test in this file carries the
marker for the same reason.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 5317000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants