Skip to content

API Reference parrot.bots.github_reviewer

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.bots.github_reviewer

View source

GitHub Code Reviewer agent.

Reviews GitHub artefacts against the acceptance criteria of the linked Jira ticket. Today the agent only handles pull requests; future revisions are expected to layer additional code-review duties on top of the same class. Designed to be subclassed per repository (mirrors the :class:~parrot.bots.jira_specialist.JiraSpecialist pattern).

Workflow:

  • On github.pr_opened / pr_reopened / pr_synchronize events emitted by :class:~parrot.core.hooks.github_webhook.GitHubWebhookHook, :meth:handle_hook_event is invoked by the orchestrator. It extracts the NAV-xxx (or any configured project prefix) key from the PR head branch / title (never the PR body), pulls the ticket from Jira, fetches the PR diff, asks the LLM for a structured comparison and either submits a REQUEST_CHANGES review with Telegram alerts (when discrepancies are found) or posts an APPROVE review (when all acceptance criteria are satisfied). Re-deliveries with the same head_sha are deduplicated in-memory so pushing multiple commits to a still-failing PR does not produce a storm of reviews and alerts.
  • :meth:report_stale_pull_requests is decorated with :func:schedule_daily_report so it runs once a day and reports every open PR older than 24h to a public Telegram channel.

Authentication, toolkit wiring and the LLM model selection follow the same pattern as :class:JiraSpecialist so a deployment that already runs JiraSpecialist needs no extra plumbing beyond a new @register_agent subclass per watched repository.

Class Discrepancy

Single mismatch between the PR and the Jira acceptance criteria.

Fields:

Field Type Default Description
criterion str The acceptance criterion or ticket requirement not met.
issue str What the PR misses, contradicts or deviates from.
severity Literal['minor', 'major', 'blocker'] Severity. 'blocker' = MUST fix before merge, 'major' = should fix, 'minor' = nice-to-have.

Class GitHubReviewer

Reviews GitHub PRs against linked Jira ticket acceptance criteria.

Like :class:JiraSpecialist, this class is abstract by convention: deployments should subclass it (one subclass per repository) and apply @register_agent on the subclass.

Parameter Type Default Description
repository str Target GitHub repository in "owner/name" format.
jira_project str 'NAV' Jira project key whose tickets the PRs reference (default "NAV"). Used to build the regex that extracts the ticket key from the PR head branch / title.
sdd_feature_prefix str 'FEAT' Prefix used to extract SDD feature identifiers from PR head branches and titles. Defaults to "FEAT".
enable_sdd_spec_fallback bool True Whether later review integration may use an SDD specification when no Jira key is present. Defaults to True.
max_spec_scan_files int 500 Positive upper bound on specification candidate files inspected during a lookup. Defaults to 500.
alert_chat_ids Optional[List[ChatId]] None Telegram chat IDs that should receive a private alert when a discrepancy is found.
public_channel_id Optional[ChatId] None Telegram chat / channel ID that receives the daily summary of stale (>24h) open PRs.
management_chat_id Optional[ChatId] None Telegram chat / channel ID that receives the management reports — :meth:today_pr, :meth:report_weekly_activity and :meth:report_jira_tickets. Defaults to public_channel_id so those reports keep arriving when it is not configured.
webhook_public_url Optional[str] None Public HTTPS URL of the GitHub webhook endpoint (e.g. https://parrot.example.com/api/v1/hooks/github). When set, :meth:post_configure calls :meth:GitToolkit.ensure_webhook to register it.
webhook_secret Optional[str] None Shared secret GitHub will use to sign deliveries. Required for HMAC verification on the receiving end.
stale_after_hours int 24 How long an open PR must be unattended before being included in :meth:report_stale_pull_requests. Defaults to 24.
max_diff_bytes int 50000 How much of the diff to feed the LLM. Larger diffs are truncated; the prompt instructs the LLM to acknowledge it.
max_ticket_bytes int 20000 Per-field clamp applied to the Jira description and acceptance criteria text before they are spliced into the LLM prompt. Prevents one oversized ticket from blowing the context window. Defaults to 20_000.
silent_weeks_threshold int 3
top_n_contributors int 10
use_llm_summary bool False
max_review_tool_calls Optional[int] None
min_check_pass_ratio Optional[float] None Share of a PR's COMPLETED CI checks that must be green for :meth:review_pr to approve it — "all OK, or a great part of them". Clamped to [0, 1]; defaults to GITHUB_REVIEW_MIN_CHECK_PASS_RATIO (0.8).
require_checks Optional[bool] None Makes test evidence mandatory. By default CI is an OPTIONAL gate — only a FAILING pipeline refuses a PR, while one that is absent or unreadable is a non-blocking warning, because "no CI" is not "CI failed". Turn this on and missing evidence (no checks declared, or a CI nobody could read) becomes a blocking reason too. Defaults to GITHUB_REVIEW_REQUIRE_CHECKS (False).
google_api_key Optional[str] None Google credential this agent bills its LLM traffic to, so reviewer usage can be metered and rotated apart from the process-wide key. Defaults to GITHUB_REVIEW_GOOGLE_API_KEY; when neither is set the Google client falls back to GOOGLE_API_KEY as before.
**kwargs Any {}

Attributes:

Attribute Type Description
WEBHOOK_APP_KEY str
WEBHOOK_LISTENERS_KEY str
WEBHOOK_TASKS_KEY str
alert_chat_ids List[ChatId]
configured_management_chat_id Optional[ChatId]
min_check_pass_ratio float
require_checks bool
git_toolkit Optional[GitToolkit]
jira_toolkit Optional[JiraToolkit]
management_chat_is_fallback bool True when the management reports ride on the public channel. That is, when no GITHUB_MANAGEMENT_TELEGRAM_CHAT_ID was configured and :attr:management_chat_id resolved to :attr:public_channel_id instead. A management chat explicitly pointed at that same chat is configured, not a fallback — the resolved value is identical in both cases, which is why :attr:configured_management_chat_id is kept.
allowed_repositories Optional[Sequence[str]]

Method GitHubReviewer.setup_webhook_route

Register the aiohttp route that receives GitHub webhook deliveries.

Call this from the synchronous application setup phase (e.g. Main.configure() in a Navigator app) — before aiohttp freezes its router on on_startup. Adding routes from :meth:post_configure is too late and will raise RuntimeError: Cannot register a resource into frozen router.

Idempotent: subsequent calls return the existing hook stored in app[WEBHOOK_APP_KEY]. Multiple agent instances share one hook and one route; each agent appends its :meth:handle_hook_event as a listener during :meth:post_configure, and the dispatcher fans every delivery out to all listeners. handle_hook_event already filters by payload.repository, so cross-repo noise is dropped per agent.

The dispatcher answers first and reviews afterwards. GitHub abandons a delivery after about 10 seconds, while a real review (ticket + diff + LLM) takes a minute — 66s measured on a live PR — so the listeners run in a background task and the route replies 202 at once. Without that, every delivery is recorded as failed even when the review succeeded, and GitHub retries a SHA whose review is already running. In-flight reviews are tracked in app[WEBHOOK_TASKS_KEY] and awaited by an on_cleanup handler (:meth:drain_webhook_reviews), so a shutdown does not kill a review halfway through.

Auth integration: GitHub signs deliveries with HMAC-SHA256 (verified by :class:GitHubWebhookHook), not with Bearer tokens. If your app uses an auth middleware (e.g. navigator-auth) you must whitelist the returned hook's url so deliveries are not rejected with a 401::

github_hook = GitHubReviewer.setup_webhook_route(app)
auth.setup(app)
auth.add_exclude_list(github_hook.url)

setup_webhook_route(app: Any, *, url: str = '/api/v1/hooks/github', secret: Optional[str] = None, name: str = 'github_review_hook') -> GitHubWebhookHook

Parameter Type Default Description
app Any The aiohttp web.Application.
url str '/api/v1/hooks/github' The route path. Must match what GitHub points its webhook at; default "/api/v1/hooks/github".
secret Optional[str] None HMAC-SHA256 shared secret used to verify deliveries. Falls back to :data:parrot.conf.GITHUB_REVIEW_WEBHOOK_SECRET when None. Pass an explicit empty string to disable verification (not recommended).
name str 'github_review_hook' Logical name of the hook instance, surfaced in logs.

Returns: GitHubWebhookHook — The shared :class:GitHubWebhookHook instance.

Method GitHubReviewer.drain_webhook_reviews

Await every review still running from a webhook delivery.

Registered on app.on_cleanup by :meth:setup_webhook_route, so a shutdown does not kill a review mid-flight; also the seam tests use to wait for a dispatch they deliberately did not await.

drain_webhook_reviews(app: Any) -> int

Parameter Type Default Description
app Any

Returns: int — How many in-flight reviews it waited for.

Method GitHubReviewer.set_wrapper

Called by :class:TelegramAgentWrapper so the agent can push proactive messages over the Telegram Bot it shares with the wrapper.

set_wrapper(wrapper) -> None

Parameter Type Default Description
wrapper

Method GitHubReviewer.post_configure

Wire :class:GitToolkit and :class:JiraToolkit once self.app is attached. Auth selection mirrors :class:JiraSpecialist, with the important difference that per-user OAuth is rejected (no caller).

Also attaches :meth:handle_hook_event to the shared :class:GitHubWebhookHook that :meth:setup_webhook_route registered during sync setup. If setup_webhook_route was never called the agent logs a clear warning — the bot still works for manually-triggered reviews, but GitHub deliveries land on a 404 until the route is registered before the aiohttp router freezes.

Re-entrant (FEAT-721): toolkits already served by the ToolManager are adopted, so a second pass opens no second authenticated client and self.git_toolkit/self.jira_toolkit always name the registered instances.

post_configure() -> None

Method GitHubReviewer.shutdown

Stop the owned background tasks before the inherited agent shutdown.

shutdown(**kwargs: Any) -> None

Parameter Type Default Description
**kwargs Any {}

Method GitHubReviewer.handle_hook_event

Route :class:HookEvent instances from :class:GitHubWebhookHook.

handle_hook_event(event: HookEvent) -> Optional[Dict[str, Any]]

Parameter Type Default Description
event HookEvent

Returns: Optional[Dict[str, Any]]

Method GitHubReviewer.review_pull_request

Run a single PR review and return a summary dict.

Used both by :meth:handle_hook_event (via webhook) and as a public entry point for manual triggering / tests.

review_pull_request(payload: Dict[str, Any]) -> Dict[str, Any]

Parameter Type Default Description
payload Dict[str, Any] Mapping with at least pr_number, pr_title, pr_url, repository and head_sha; head_ref (the PR branch) is the preferred source of the ticket / feature id.

Returns: Dict[str, Any] — A dict with status and the relevant artifacts (jira key, review id, alert results). On the unhappy path status is one of "no_ticket", "ticket_not_found", "already_reviewed" or "error".

Method GitHubReviewer.strict_review_pull_request

Review a PR and enforce the verdict on GitHub.

The same review pipeline as :meth:review_pull_request — ticket lookup, diff, wiki-assisted LLM comparison against the acceptance criteria — plus an optional CI gate and the consequences:

  • mergeable → an APPROVE review, whose footer discloses the CI picture (including "no test evidence could be verified", when the checks were absent or unreadable — that warns, it does not refuse).
  • deferred (checks still RUNNING) → a COMMENT review; the PR is left untouched.
  • not mergeable → the PR is converted to a draft, a comment explains why, and the assignee is notified privately and in the public channel.

The webhook path deliberately keeps its own, gentler orchestration (:meth:review_pull_request never drafts a PR), so this method does not reuse it; both share every underlying helper.

strict_review_pull_request(payload: Dict[str, Any]) -> Dict[str, Any]

Parameter Type Default Description
payload Dict[str, Any] Review payload — repository, pr_number, pr_title, head_ref, pr_url, head_sha, author.

Returns: Dict[str, Any] — {"status": ..., ...} where status is approved, deferred, blocked, no_ticket, ticket_not_found or error.

Method GitHubReviewer.review_pr

Answer /review_pr <pull request link>.

Runs the full gate on demand: code review against the Jira ticket and its acceptance criteria, plus an optional CI/test check. A PR that complies is approved; one that does not is converted to a draft, commented on, and its assignee is pinged privately and in the public channel.

CI only refuses a PR when it FAILS. A pipeline that is absent or unreadable is reported as a non-blocking note and the ticket comparison decides alone (see :attr:require_checks to make the evidence mandatory); a pipeline still running defers the verdict.

review_pr(target: str = '', **kwargs: Any) -> str

Parameter Type Default Description
target str '' The PR to review — a GitHub PR URL, owner/repo#123, or a bare 123 for the configured repository. Telegram hands the whole argument string through (parse_mode="raw") so a pasted URL survives intact.
**kwargs Any {}

Returns: str — A Markdown summary of the verdict, which the channel wrapper delivers to whoever asked. Failures come back as a one-line notice, never as an exception.

Method GitHubReviewer.pr_review

Fetch a PR, run the full review, and return the chat reply.

pr_review(target: str = '', jira_key: Optional[str] = None, auto_draft: bool = False, dry_run: bool = False, **kwargs: Any) -> str

Parameter Type Default Description
target str ''
jira_key Optional[str] None
auto_draft bool False
dry_run bool False
**kwargs Any {}

Returns: str

Method GitHubReviewer.full_review_pull_request

Review with isolated reads, then perform only explicitly guarded GitHub writes.

full_review_pull_request(payload: Dict[str, Any], *, jira_key: Optional[str] = None, auto_draft: bool = False, dry_run: bool = False) -> Dict[str, Any]

Parameter Type Default Description
payload Dict[str, Any]
jira_key Optional[str] None
auto_draft bool False
dry_run bool False

Returns: Dict[str, Any]

Method GitHubReviewer.report_stale_pull_requests

Scan open PRs on the configured repo and announce stale ones.

A PR is "stale" when its created_at is older than :attr:stale_after_hours (defaults to 24h). All stale PRs are announced to :attr:public_channel_id in a SINGLE digest message (split into as few messages as fit only when the digest would exceed Telegram's 4096-char limit). Returns a small dict with counts (useful for tests and scheduler logs).

Scheduled by :func:schedule_daily_report; override the run time per deployment via {AGENT_ID}_DAILY_REPORT env var (HH:MM UTC).

report_stale_pull_requests() -> Dict[str, Any]

Returns: Dict[str, Any]

Method GitHubReviewer.today_pr

Announce every PR opened in the last window_hours as one message.

Only PRs that are still open are reported: one opened and already closed or merged inside the window is left out, because the digest is a review queue, not an activity log.

When no open PR was created inside the window — or the repo has no PRs at all — the method terminates silently: nothing is sent to Telegram and the returned dict carries today_count: 0.

Scheduled by :func:schedule_daily_report, so it fires at the same {AGENT_ID}_DAILY_REPORT time (HH:MM UTC) as the stale-PR report, as its own APScheduler job (auto_<bot>_today_pr).

today_pr(window_hours: Optional[int] = None) -> Dict[str, Any]

Parameter Type Default Description
window_hours Optional[int] None How far back to look. Defaults to :attr:_TODAY_PR_WINDOW_HOURS (24h).

Returns: Dict[str, Any] — A status dict with status, repository, window_hours, today_count, announced (PRs covered by a successful send), messages_sent and today (the PR entries).

Method GitHubReviewer.report_jira_tickets

Digest the review project's tickets by assignee and state.

Counterpart of :meth:report_stale_pull_requests on the Jira side: one JQL search over self.jira_project (the project the reviewer already resolves PR tickets against), bucketed per assignee into open / in progress / closed via each ticket's statusCategory, and reported in two columns — the last recent_hours and the last window_days.

Scope is activity, not backlog: the JQL is updated >= -{window_days}d, so a ticket nobody has touched in that window does not appear in either column, and the 24h column is the subset of those tickets updated in the last recent_hours (derived locally — no second Jira call).

When the project had no activity in the window — or Jira returns nothing — the method terminates silently like :meth:today_pr: nothing is sent and the returned dict carries ticket_count: 0.

Scheduled daily at 10:00 America/New_York (DST-aware), on its own cron job rather than the {AGENT_ID}_DAILY_REPORT tick the other reports share — see the decorator above.

report_jira_tickets(recent_hours: Optional[int] = None, window_days: Optional[int] = None) -> Dict[str, Any]

Parameter Type Default Description
recent_hours Optional[int] None Width of the short column. Defaults to :attr:_TICKET_RECENT_HOURS (24h).
window_days Optional[int] None Width of the long column, and of the JQL window. Defaults to :attr:_TICKET_WINDOW_DAYS (14 days).

Returns: Dict[str, Any] — A status dict with status, project, jql, recent_hours, window_days, ticket_count, assignees, totals, announced (assignee rows covered by a successful send) and messages_sent.

Method GitHubReviewer.report_resolved_tickets

List the tickets that moved to Resolved or Closed, and send it.

The named counterpart of :meth:report_jira_tickets: that one counts a project by assignee, this one names the tickets that actually crossed the finish line in the last window_hours — what got done, with a link per ticket — and posts the list to :attr:management_chat_id (GITHUB_MANAGEMENT_TELEGRAM_CHAT_ID, falling back to the public channel).

Scope is the transition, not the current state: the JQL asks status CHANGED TO (Resolved, Closed) AFTER -{window_hours}h, so a ticket that has sat in Closed for a month is absent however often it was touched, while one that moved to Closed and was reopened the same day is present — it did get resolved, and its row shows the status it sits in now.

When nothing moved — or Jira returns nothing — the method terminates silently like the other digests: no message goes out and the returned dict carries ticket_count: 0.

Scheduled daily at 10:00 America/New_York (DST-aware); it is equally dispatchable on demand, which is what /call report_resolved_tickets does.

report_resolved_tickets(window_hours: Optional[int] = None) -> Dict[str, Any]

Parameter Type Default Description
window_hours Optional[int] None Width of the window. Defaults to :attr:_RESOLVED_WINDOW_HOURS (24h).

Returns: Dict[str, Any] — A status dict with status, project, jql, window_hours, ticket_count, tickets (bare keys), announced (tickets covered by a successful send) and messages_sent. tickets carries keys rather than the rendered rows on /call <method> echoes a method's return value back into the chat through Telegram's legacy Markdown parser, which a ticket summary holding _ or * breaks (the digest itself is sent as HTML and is unaffected). Telemetry stays printable; :meth:_collect_resolved_tickets is where a caller that wants the full rows goes.

Method GitHubReviewer.monthly_jira_tickets

Answer /monthly_jira_tickets with a per-assignee pie chart.

The same JQL and bucketing as :meth:report_jira_tickets, over 30 days instead of 14, drawn as each assignee's share of the month's ticket activity — scope is activity, not backlog, so a ticket nobody touched this month is in neither the pie nor the table.

The reply is returned, not sent: the channel wrapper reads :class:ChartReply and delivers it (Telegram as a photo with the ranking as its message), so this method never has to know which chat asked. It is therefore equally dispatchable from a schedule or another agent — the caller decides where the chart lands.

monthly_jira_tickets(window_days: Optional[int] = None, **kwargs: Any) -> ChartReply

Parameter Type Default Description
window_days Optional[int] None Width of the window in days, default 30. Telegram passes command arguments as strings (/monthly_jira_tickets window_days=60), so the value is coerced; anything unparseable or non-positive falls back to the default.
**kwargs Any {}

Returns: ChartReply — class:ChartReply with the ranking text and, when PNG export worked, one pie-chart attachment. Jira failures come back as a one-line notice, not an exception.

Method GitHubReviewer.report_monthly_jira_tickets

Send the monthly ticket pie to the management channel.

The scheduled twin of :meth:monthly_jira_tickets: same numbers, same chart, but it delivers them itself — on the 1st of the month to :attr:management_chat_id (GITHUB_MANAGEMENT_TELEGRAM_CHAT_ID, falling back to the public channel), alongside the other reports people read to follow the project.

The table rides as the photo's caption when it fits Telegram's 1024-character limit, so the chat shows one item instead of two; otherwise the digest goes as its own message. Without a PNG (no vl-convert-python) only that message goes out — a missing chart never costs the report.

report_monthly_jira_tickets(window_days: Optional[int] = None) -> Dict[str, Any]

Parameter Type Default Description
window_days Optional[int] None Width of the window in days; defaults to :attr:_TICKET_MONTH_DAYS (30).

Returns: Dict[str, Any] — A status dict with status, project, window_days, ticket_count, wedges, chart (the PNG's name or None) and messages_sent.

Method GitHubReviewer.report_weekly_activity

Compose and send the weekly contributor-activity digest.

Scheduled by :func:schedule_weekly_report. Override the firing day/time per deployment via {AGENT_ID}_WEEKLY_REPORT=DDD HH:MM (UTC, default MON 09:00).

report_weekly_activity() -> Dict[str, Any]

Returns: Dict[str, Any] — A status dict with keys: status, repository, period_start, period_end, active, silent, rendered_via, telegram_sent, partial (True when code_frequency never became ready and the digest went out without its week-over-week line totals).

Class PRReviewResult

LLM-produced summary of a PR review.

Fields:

Field Type Default Description
jira_key Optional[str] None The Jira issue key referenced by the PR, if any.
requirement_source Literal['jira', 'sdd_spec'] 'jira'
discrepancies List[Discrepancy] Discrepancies found between the PR and the ticket.
summary str One-paragraph human summary of the review.
approve bool True if the PR satisfies every acceptance criterion.

Class WeeklyActivitySummary

Structured input to the templated/LLM renderer for the weekly digest.

Fields:

Field Type Default Description
repository str Repository name in owner/name format.
period_start datetime Sunday 00:00 UTC that begins the reporting week.
period_end datetime Sunday 00:00 UTC that begins the FOLLOWING week (exclusive upper bound).
contributors_active List[_ContributorWindowSummary] Contributors with at least one commit in the reporting week, sorted by commits desc then additions+deletions desc then login.
contributors_silent List[_ContributorWindowSummary] Contributors whose last weeks_silent >= threshold consecutive weeks all had zero commits. Sorted by weeks_silent desc then login. Uncapped.
total_commits int Sum of commits across all contributors in the current week.
total_additions int Sum of additions across all contributors in the current week.
total_deletions int Sum of deletions across all contributors in the current week.
prev_total_commits int Total commits in the week immediately before the reporting window (from code_frequency data, 0 if not available).
prev_total_additions int Total additions in the previous week (from code_frequency, 0 if missing).
prev_total_deletions int Total deletions in the previous week (from code_frequency, 0 if missing).
code_freq_available bool True False when the previous week's code_frequency slice was missing — a cold /stats cache (persistent 202) or a repo without that much history. The prev_total_additions / prev_total_deletions zeros are then unknown, not measured, so renderers must not derive a line delta from them. prev_total_commits is unaffected: it is summed from the contributor slices, never from code_frequency.

Class WeeklyLLMSummarizationError

Raised when the LLM summarizer fails; caller falls back to templated output.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally