Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(review_hog): project rules, repository ownership and sparse settings (#113788)

Julian Bezf11b6d027b73
diff --git a/.github/workflows/review-hog.yml b/.github/workflows/review-hog.yml
deleted file mode 100644
index 6aa901ccc84e..000000000000
--- a/.github/workflows/review-hog.yml
+++ /dev/null
@@ -1,88 +0,0 @@
-# ReviewHog label trigger.
-#
-# When the `reviewhog` label is added to a non-fork PR — by a maintainer, or by stamphog[bot] handing
-# off a refused/escalated PR — this makes ONE authenticated call to the PostHog `review_hog` trigger
-# endpoint, which starts the review Temporal workflow server-side and publishes the review back to the
-# PR. One label add = one review: pushes and ready-for-review deliberately do NOT re-trigger —
-# re-reviewing is an explicit gesture (remove and re-add the label), so a labeled PR can keep evolving
-# without burning a review per event. Unlike Stamphog, the agent does NOT run in CI: there is no
-# checkout, no app token, no Anthropic key here — the only secret is the shared trigger token.
-# Publishing happens server-side via the PostHog GitHub App installation token.
-#
-# Safety: `pull_request_target` always runs the base branch's version of this file, so a PR cannot
-# edit its own trigger, and it fires even when the PR has merge conflicts. It does expose secrets to
-# fork PRs, so the `if:` hard-gates forks — safe because this job never checks out or runs PR code.
-name: ReviewHog
-
-# Sanctioned use — no job checks out or runs PR code; see the Safety note above.
-# nosemgrep: github-actions-pull-request-target
-on:
- pull_request_target:
- types: [labeled]
-
-# No GitHub permissions by default — the trigger job only makes an outbound authenticated request;
-# the review is fetched and published server-side via the PostHog GitHub App installation token.
-permissions: {}
-
-concurrency:
- group: reviewhog-${{ github.event.pull_request.number }}
- cancel-in-progress: true
-
-jobs:
- trigger:
- name: Trigger ReviewHog review
- runs-on: ubuntu-24.04
- timeout-minutes: 5
- # Run when the `reviewhog` label lands on a non-fork PR from an allowed labeler: a human, or
- # stamphog[bot] handing off a refused/escalated PR. Other bots are skipped below. Any author
- # (drafts and bots included); the label is the explicit review request.
- if: >-
- github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
- && github.event.label.name == 'reviewhog'
- && (github.event.sender.type != 'Bot' || github.event.sender.login == 'stamphog[bot]')
- steps:
- - name: Trigger ReviewHog review
- env:
- REVIEWHOG_TRIGGER_TOKEN: ${{ secrets.REVIEWHOG_TRIGGER_TOKEN }}
- ENDPOINT: ${{ vars.REVIEWHOG_ENDPOINT_URL || 'https://us.posthog.com/api/review_hog/trigger/' }}
- REPO: ${{ github.repository }}
- PR_NUMBER: ${{ github.event.pull_request.number }}
- run: |
- if [ -z "$REVIEWHOG_TRIGGER_TOKEN" ]; then
- echo "::error::REVIEWHOG_TRIGGER_TOKEN secret is not set." >&2
- exit 1
- fi
- payload="$(jq -n --arg repo "$REPO" --argjson pr "$PR_NUMBER" '{repo: $repo, pr_number: $pr}')"
- # Retries are safe: the trigger dedups via Temporal USE_EXISTING, so a
- # double-delivered trigger joins the in-flight review instead of starting another.
- curl --fail-with-body --silent --show-error \
- --retry 3 --retry-delay 2 --max-time 30 --connect-timeout 10 \
- -X POST "$ENDPOINT" \
- -H "Authorization: Bearer $REVIEWHOG_TRIGGER_TOKEN" \
- -H "Content-Type: application/json" \
- -d "$payload"
-
- # The trigger job skips bot-applied labels silently (stamphog[bot] excepted — it hands off
- # refused PRs and is routed above); explain why and strip the label so a human can re-add it.
- bot-labeler-skip:
- name: Explain skipped bot label
- runs-on: ubuntu-24.04
- timeout-minutes: 5
- permissions:
- issues: write
- if: >-
- github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
- && github.event.sender.type == 'Bot'
- && github.event.sender.login != 'stamphog[bot]'
- && github.event.label.name == 'reviewhog'
- steps:
- - name: Comment and strip label
- env:
- GH_TOKEN: ${{ github.token }}
- REPO: ${{ github.repository }}
- PR_NUMBER: ${{ github.event.pull_request.number }}
- run: |
- set -euo pipefail
- gh api -X POST "repos/$REPO/issues/$PR_NUMBER/comments" \
- -f body="ReviewHog reviews start only when a human adds the \`reviewhog\` label, so this bot-applied label was removed. Re-add it yourself to start a review."
- gh api -X DELETE "repos/$REPO/issues/$PR_NUMBER/labels/reviewhog"
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 39eec27468b6..23e6d8519e58 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -345,10 +345,15 @@ rules:
|ReplayVisionLearnedRuleset
|Repo
|RepoRoutingRule
+ |ReviewInstallationClaim
+ |ReviewProjectSettings
|ReviewReport
|ReviewReportArtefact
+ |ReviewRepository
+ |ReviewRepositoryPerson
|ReviewSkillConfig
|ReviewUserSettings
+ |ReviewUserRepositoryChoice
|SandboxCustomImage
|SandboxEnvironment
|SandboxSession
@@ -788,10 +793,15 @@ rules:
|ReplayVisionLearnedRuleset
|Repo
|RepoRoutingRule
+ |ReviewInstallationClaim
+ |ReviewProjectSettings
|ReviewReport
|ReviewReportArtefact
+ |ReviewRepository
+ |ReviewRepositoryPerson
|ReviewSkillConfig
|ReviewUserSettings
+ |ReviewUserRepositoryChoice
|SandboxCustomImage
|SandboxEnvironment
|SandboxSession
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index d74d64e0748d..7c98b6b933fa 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -237,11 +237,13 @@ The property identifies the active environment: explicitly include every environ
access. A parent project's flag does not enable its child environments, even though ReviewHog stores
their settings and reviews under the shared parent project.
-Newly enabled projects get manual review and resolution. The first `REVIEWHOG_TEAM_IDS` entry retains
-Flash and all automation UI (`show_internal_features`); other projects do not query Stamphog.
+Newly enabled projects get manual Full reviews. The `review-hog-internal` flag, set up the same way per
+project, adds the internal-only parts: automatic Flash reviews, the `reviewhog` label trigger, manual
+Flash, resolution, Inbox reviews, the tiered review models, and the Stamphog Inbox switch.
Existing Inbox or Stamphog opt-ins remain visible in other projects until the user switches them off.
Each project needs a GitHub App integration covering the repository; review skills seed automatically.
-Existing automation routing and label secrets stay unchanged.
+Automatic reviews and the label trigger also need the project to claim the repository in the Code review
+settings. No environment variable or shared secret picks the project.
Use resolution only for explicitly enabled trusted projects reviewing repositories their teams own.
Ownership does not authenticate commenters: operators must assess repository and comment trust before
@@ -250,10 +252,8 @@ missing commenter authorization and the post-push path check. Public or untruste
[ReviewHog's architecture](../../products/review_hog/ARCHITECTURE.md#status--next).
ReviewHog Flash uses `gpt-6-luna` for review, blind-spot checks, and validation.
-The configured internal project's **ReviewHog Flash - Experimental** subsection under **What gets reviewed** groups the automatic Flash review toggle and **Flash strength** setting.
-These settings apply only to Flash reviews.
-**Flash strength** selects **Medium** (`medium`, the default) or **Extra high** (`xhigh`) for all of your Flash reviews, including automatic, UI, and CLI requests.
-Each turn saves the effort it starts with, so a settings change applies to later turns.
+The configured internal project's **ReviewHog Flash - Experimental** subsection under **What gets reviewed** holds the automatic Flash review toggle.
+Flash reviews use the medium reasoning effort.
The shared `FLASH_ARM` and `flash_arm_for_effort` in `products/review_hog/backend/reviewer/constants.py` pin the Codex runtime and `full-access` permission mode.
Flash uses the existing `review_hog` model allowance.
Both review modes instruct the agent to fetch pinned review and validation skills through the PostHog MCP with `skill-get`.
@@ -263,27 +263,16 @@ Flash requests preserve an existing report's review tier, including when they jo
Flash marks its status comment header as `PostHog Review (flash)`, skips the clean-review media, and never starts comment resolution.
**Review all your PRs in Flash mode** is off by default and shown only on the configured internal project.
-Turn it on in Code review to review PRs you author in `PostHog/posthog` when they open or receive new commits, including drafts.
-The head branch must belong to `PostHog/posthog`; fork PRs are excluded.
+Turn it on in Code review to review PRs you author in the repositories your project reviews when they open or receive new commits, including drafts.
+The head branch must belong to the PR's own repository; fork PRs are excluded.
Enabling it does not review existing PRs immediately; an existing PR becomes eligible on its next push.
Only one review runs per PR, and pushes during a review coalesce into a follow-up for the latest head.
An explicit Full request also runs after an active Flash review when that head still needs a Full review.
Turning the setting off stops future and pending automatic starts; a running review finishes.
Automatic Flash uses your existing severity threshold and never resolves comments or changes the PR branch.
-To change this setting from the CLI for a selected user:
-
-```bash
-.codex/with-flox python manage.py enable_authored_pr_reviews \
- --team-id 1 --user-ids 1 --effort medium
-.codex/with-flox python manage.py disable_authored_pr_reviews \
- --team-id 1 --user-ids 1
-```
-
-Use `--effort xhigh` to select Extra high; omitting `--effort` preserves the saved choice.
-Disabling automatic reviews also preserves that choice for manual Flash reviews.
-Both commands accept `--dry-run`.
-Omitting `--user-ids` changes every active member of the team's organization.
+The switch sets your `default_review_mode` preference to `flash` or `follow` through `PATCH /api/projects/<project_id>/review_hog/settings/`.
+Project admins choose which repositories the project reviews, and who gets automatic Flash there, through the `review_hog/project_settings`, `review_hog/installation_claims`, and `review_hog/repositories` endpoints.
To run Flash locally, use `run_review --review-mode flash` from the repository root:
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e7efe2a4c1c2..05d946bfc19d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14453,9 +14453,9 @@ snapshots:
scenes-code-review--flag-disabled-for-staff--light:
hash: v1.k794b7964.a71251e301794f51a0a9140ab1442fada37b1cc0fb54095a5eb19499e0cb1b34.3GhhJCqNfLkY2WdBTTn0LHJifxiCqyEJ7viaHaoCoGA
scenes-code-review--internal-features--dark:
- hash: v1.k794b7964.e84a6c63912f44c738093a89d3eea936cca9b21de73d762a882aae8e256dacbb.JJa8Hduge6S_I_pzqD0Zyd9EDIHiMVSwr5QWz3jYb5g
+ hash: v1.k794b7964.d9a19def03194e6034b2e789d152aa7fa3a4800c71844ee4048bf9da0bde65cf.OScd4AhOSHEMklEIfhxY4X6T6tI3Ldy-P0HrR-X-J80
scenes-code-review--internal-features--light:
- hash: v1.k794b7964.622b0984cc4e8829103680ae3df80d6a239417ef9a1dfd71d720aa8cdd92b9ff.TRm24CiiDu0FsAlLjbh6U4upXsXq7WUumJUFnIp_0TI
+ hash: v1.k794b7964.bcf88d581a51854f65fbd28871f3ea415206c6d4411c7193c67950e7253e3b7c.1wk9q4e_YatldElhcW76JX2q5P0d_UoCmQevhDGM35Y
scenes-code-review--narrow--dark:
hash: v1.k794b7964.35849f88cd28db56cb71ca5beaf1cf0c8817abf8714f4035113a75f1aa1a7def.w8ZUBwj8pOSIMaqaxNfLstA4-2GD7_oPox7tm2lrG5o
scenes-code-review--narrow--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 5ef30fefe62d..28fe60587ef9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -537,6 +537,7 @@ export const FEATURE_FLAGS = {
REVAMPED_PY_NOTEBOOKS: 'revamped-py-notebooks', // owner: #team-data-tools
REVENUE_FIELDS_IN_POWER_USERS_TABLE: 'revenue-fields-in-power-users-table', // owner: @arthurdedeus #team-customer-analytics
REVIEW_HOG: 'review-hog', // owner: #team-devex, gates the Code review menu entry, scene, and API access
+ REVIEW_HOG_INTERNAL: 'review-hog-internal', // owner: #team-devex, gates ReviewHog automation, Flash, resolution, and Inbox reviews per project
SCENE_MENU_BAR: 'scene-menu-bar', // owner: @adamleithp #team-platform-ux, gates the per-scene MenuBar above SceneTitleSection
SCHEMA_ENFORCEMENT_REJECT: 'schema-enforcement-reject', // owner: @aspicer, gates the ability to set schema enforcement mode to "reject"
SCHEMA_MANAGEMENT: 'schema-management', // owner: @aspicer
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index b52e19d4088c..e10437959cf0 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6236,6 +6236,9 @@ export enum ActivityScope {
SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
SIGNAL_TEAM_CONFIG = 'SignalTeamConfig',
STAMPHOG_REPO_CONFIG = 'StamphogRepoConfig',
+ REVIEW_REPOSITORY = 'ReviewRepository',
+ REVIEW_PROJECT_SETTINGS = 'ReviewProjectSettings',
+ REVIEW_INSTALLATION_CLAIM = 'ReviewInstallationClaim',
}
export type CommentType = {
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index dfdd8a7321bd..f563c8cbd18d 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -134,6 +134,9 @@ ActivityScope = Literal[
"Billing",
"Loop",
"StamphogRepoConfig",
+ "ReviewRepository",
+ "ReviewProjectSettings",
+ "ReviewInstallationClaim",
]
ChangeAction = Literal[
"changed", "created", "deleted", "merged", "split", "exported", "revoked", "logged_in", "logged_out", "copied"
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 290d2e55d31e..52cddbfbc3cc 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -150,25 +150,10 @@ TASKS_AGENT_PROXY_INTERNAL_URL: str | None = os.getenv("TASKS_AGENT_PROXY_INTERN
# agent-proxy in production; unset (local/CI) disables the check.
AGENT_PROXY_CALLBACK_SECRET: str | None = os.getenv("AGENT_PROXY_CALLBACK_SECRET") or None
-# ReviewHog production label trigger. The trigger endpoint (POST /api/review_hog/trigger) authenticates
-# CI by comparing the request's bearer token to REVIEWHOG_TRIGGER_TOKEN (a shared secret provisioned to
-# both Django and the GitHub Action). Unset fails closed outside local dev/test. REVIEWHOG_TEAM_ID is a
-# comma-separated list of team ids using tiered review models; the FIRST id is the team that receives
-# label-triggered and automatic authored-PR reviews and sees internal UI features. Manual UI/API access
-# uses the review-hog feature flag. REVIEWHOG_RUN_USER_ID is the user the label-triggered sandbox tasks
-# run as (falls back to the team's GitHub integration creator when unset).
-REVIEWHOG_TRIGGER_TOKEN: str | None = os.getenv("REVIEWHOG_TRIGGER_TOKEN") or None
-# The env var stays singular (production charts provision it by that name); a single id parses to [id].
-REVIEWHOG_TEAM_IDS: list[int] = get_from_env(
- "REVIEWHOG_TEAM_ID",
- default=[],
- type_cast=lambda raw: [int(part) for part in str(raw).split(",") if part.strip()],
-)
-REVIEWHOG_RUN_USER_ID: int | None = get_from_env("REVIEWHOG_RUN_USER_ID", optional=True, type_cast=int)
# The GitHub App's bot login (`<app slug>[bot]`) ReviewHog posts as. When set, the marker-based
# idempotency scans only trust comments/reviews authored by this exact identity — otherwise any
# installed bot could paste a public marker and suppress a publish (or get its comment PATCHed).
-# Unset falls back to trusting any Bot-typed author.
+# Unset trusts no author in production, and any Bot-typed author in local development and tests.
REVIEWHOG_GITHUB_BOT_LOGIN: str = get_from_env("REVIEWHOG_GITHUB_BOT_LOGIN", "")
# These are legacy values only kept around for backwards compatibility with self hosted versions
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index f88885bc6c16..8d371caaec67 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -44,6 +44,10 @@ model_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_
model_activity:products.managed_migrations.backend.activity_logging.handle_batch_import_change
model_activity:products.replay_vision.backend.activity_logging.handle_replay_scanner_change
model_activity:products.replay_vision.backend.activity_logging.handle_vision_alert_change
+model_activity:products.review_hog.backend.activity_logging.handle_review_installation_claim_change
+model_activity:products.review_hog.backend.activity_logging.handle_review_project_settings_change
+model_activity:products.review_hog.backend.activity_logging.handle_review_repository_change
+model_activity:products.review_hog.backend.activity_logging.handle_review_repository_person_change
model_activity:products.signals.backend.activity_logging.handle_signal_scout_config_change
model_activity:products.signals.backend.activity_logging.handle_signal_team_config_change
model_activity:products.stamphog.backend.activity_logging.handle_stamphog_repo_config_change
@@ -106,6 +110,7 @@ post_delete:products.feature_flags.backend.local_evaluation.feature_flag_changed
post_delete:products.managed_warehouse.backend.models._observe_duckgres_server_delete
post_delete:products.replay_vision.backend.media_expiry.expire_media_asset
post_delete:products.replay_vision.backend.search_suggestion_cleanup.forget_team_suggestions_from_deleted_scanner
+post_delete:products.review_hog.backend.ownership._invalidate_owned_repositories_on_delete
post_delete:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_change
post_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deleted
post_delete:products.signals.backend.receivers.sync_report_latest_actionability_on_delete
@@ -220,6 +225,7 @@ post_save:products.feature_flags.backend.models.organization_feature_flags_confi
post_save:products.feature_flags.backend.session_recording_links.relink_teams_on_key_change
post_save:products.managed_warehouse.backend.models._observe_duckgres_server_save
post_save:products.posthog_ai.backend.receivers.mark_conversation_sandbox_on_first_run
+post_save:products.review_hog.backend.ownership._invalidate_owned_repositories_on_save
post_save:products.review_hog.backend.receivers.handle_task_run_saved
post_save:products.signals.backend.receivers.arm_pending_checks_when_report_resolved
post_save:products.signals.backend.receivers.capture_status_change_analytics
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 9acd65058e59..d2966dfd8bfc 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1481,6 +1481,9 @@ export type ActivityLogListParams = {
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
+ * * `ReviewRepository` - ReviewRepository
+ * * `ReviewProjectSettings` - ReviewProjectSettings
+ * * `ReviewInstallationClaim` - ReviewInstallationClaim
* @minLength 1
*/
scope?: ActivityLogListScope
@@ -1586,6 +1589,9 @@ export const ActivityLogListScope = {
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
+ ReviewRepository: 'ReviewRepository',
+ ReviewProjectSettings: 'ReviewProjectSettings',
+ ReviewInstallationClaim: 'ReviewInstallationClaim',
} as const
/**
@@ -1678,6 +1684,9 @@ export const ActivityLogListScope = {
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
+ * * `ReviewRepository` - ReviewRepository
+ * * `ReviewProjectSettings` - ReviewProjectSettings
+ * * `ReviewInstallationClaim` - ReviewInstallationClaim
*/
export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyof typeof ActivityLogListScopesItem]
@@ -1771,6 +1780,9 @@ export const ActivityLogListScopesItem = {
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
+ ReviewRepository: 'ReviewRepository',
+ ReviewProjectSettings: 'ReviewProjectSettings',
+ ReviewInstallationClaim: 'ReviewInstallationClaim',
} as const
export type AdvancedActivityLogsListParams = {
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index c73a9225ec92..a0f8442a29dc 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -69,8 +69,8 @@ against the hard-floor **path backstop** (`commit_restricted_paths`): one touchi
dependency manifests delivers a human-review warning instead of the link and never auto-resolves either.
**TODO (BLOCKING public release): the three remaining injection-surface hardening items from the July e2e
-GO conditions.** Manual review and resolution are available to explicitly enabled projects for
-repositories their teams own. This is a limited rollout; the feature flag does not establish repository or
+GO conditions.** Manual review is available to explicitly enabled projects. Resolution is limited to
+projects with the `review-hog-internal` flag, for repositories their teams own. This is a limited rollout; the feature flag does not establish repository or
comment trust. Operators must assess both before enabling resolution. DECISIONS.md Stage 7 records the
2026-09-30 decision to accept the existing risks for this limited manual rollout. The path backstop above is built; these
are deliberately deferred (maintainer decisions 2026-08-06 and 2026-08-10, recorded in DECISIONS.md Stage 7)
@@ -96,12 +96,16 @@ and MUST land before public release or resolution on untrusted PRs or repositori
the Tasks facade threading the policy in, plus a sandbox image rebuild), which is why it is a gate rather
than a fix in this repo.
-**Full reviews can include resolving**: a published Full review chains into the stage when the acting user's
-`resolve_comments` setting is on (default on; the toggle sits with the trigger opt-outs on the Code review scene,
-which also carries a single-active resolution-criteria skill block and a split Review button with
-review-without-resolving / resolve-only side actions). Standalone entry: `POST /api/review_hog/resolve`, the
-`run_resolution` command, or the UI's resolve-only action. Standalone runs without a pinned acting user apply
-the PR author's resolution criteria (canonical for unmapped authors). Design + decision record: DECISIONS.md
+**Full reviews can include resolving**: a published Full review chains into the stage when the **PR owner**
+opted in (`resolve_comments`, default off), whoever triggered the review, and the project has the
+`review-hog-internal` flag (`review_request_rules.ResolutionGate`). The owner (`backend/pr_owner.py`) is the
+author when the GitHub login maps to an active member; for a self-driving PR that the PostHog GitHub App opened, it
+is the Inbox report's canonical reviewer; otherwise nobody, and a PR without an owner never gets writes. Flash never
+resolves. The chained run applies the owner's resolution criteria. Standalone entry: the `run_resolution` command or
+the UI / MCP resolve-only action, which answers 409 `resolution_not_opted_in` unless the owner opted in;
+`_prepare_run` checks the same gate again before any write. Before every push the stage also holds on a protected
+head branch (`CommitHold.BRANCH_PROTECTED`, read from GitHub's branch API; a failed read raises), next to the merge
+queue and stacked-PR holds. Design + decision record: DECISIONS.md
Stage 7; vocabulary: CONTEXT.md; the live-e2e qualification plan (the resolver fixes its own PR):
`eval/experiments/2026-07-resolution-e2e/PLAN.md`.
@@ -133,7 +137,7 @@ outcome, and everything else skips at zero cost. What's missing is the **trigger
run when the reply lands, so today the conversation only advances when someone runs `run_resolution` / the
resolve-only action. Build the comment trigger — a `pull_request_review_comment` (created) event → the existing
trigger API → `start_resolution_workflow` for that PR (debounced; skip when the commenter is ReviewHog itself,
-mirroring the label-trigger Action) — so replying to an escalation gets an actual answer: implement on a go-ahead,
+mirroring the label trigger) — so replying to an escalation gets an actual answer: implement on a go-ahead,
decline-and-say-why on a disagreement, re-escalate with the new context otherwise. Mind the known blind spot: the
work-list only fetches **unresolved** threads, so replies on already-resolved (FIXED) threads are invisible —
the trigger should either unresolve-on-human-reply or the fetch must include threads with comments newer than
@@ -558,7 +562,7 @@ never the reverse; a resolve-only run upserts the same row but does not lift (`l
person's Full trigger that lands while the report's review is still running signals the existing queue and preserves a pending Full request.
The trigger endpoints write the lift themselves (`lift_review_tier_for_joined_trigger`) and answer
`joined_running_review`; remaining Full units and later Full turns use the human tier, while an active Flash turn keeps its Flash arm.
-The cheaper arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood gate; other teams record their tier
+The cheaper arms are rolled out per project through the `review-hog-internal` flag; other projects record their tier
but run the default arm. `load_review_arm` → `resolve_review_arm` honors a persisted arm only while it stays a
registry-supported combo — anything else falls back to the default (full-strength) pins and stamps
`review_arm_fallback` on the run's analytics events. Chunking, dedup, and the validator stay on Claude at fixed
@@ -792,17 +796,6 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
An explicit `--review-mode` must match the stored mode.
- **Reset local state:** `DEBUG=1 python manage.py reset_review_hog [--dry-run] [--yes]` wipes all ReviewHog rows
across every team (DEBUG-only; GitHub comments untouched).
-- **Turn a per-user toggle on or off in bulk:** `python manage.py {enable,disable}_inbox_reviews --team-id <id>
-[--user-ids <id> ...] [--dry-run]` sets `review_inbox_prs` on every active org member's `ReviewUserSettings`
- (or only the listed users, each of whom must be an org member). `{enable,disable}_stamphog_inbox_reviews` is
- the same pair for `stamphog_review_inbox_prs`, and `{enable,disable}_comment_resolution` for `resolve_comments`.
- `{enable,disable}_authored_pr_reviews` controls `review_authored_prs`, the default-off automatic Flash setting.
- `enable_authored_pr_reviews` also accepts `--effort medium` or `--effort xhigh` to set the user's effort for all Flash requests; omitting it preserves the saved choice.
- Disabling automatic reviews preserves the effort preference and lets running reviews finish while stopping future and pending automatic starts.
- Each command changes only its named toggle and any explicit effort choice. A run creates rows only when the requested value differs from the
- field's default (a missing row already reads as the default) and otherwise flips existing rows. A deliberate
- operator action because the per-user defaults are the budget and posture gates; members who join later keep
- the default until a re-run. Shared logic: `backend/settings_toggles.py`.
- **Lint:** `ruff check products/review_hog/ --fix && ruff format products/review_hog/`
- **Tests:** the product's `backend:test` script covers **both** `backend/tests` and `backend/reviewer/tests`
(sandbox calls mocked, fixtures under `reviewer/tests/fixtures/`; persistence/model tests hit the test DB). Verify
@@ -831,47 +824,93 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
sandbox tasks run as. They are threaded as **explicit activity inputs** (no ContextVar identity); the team's
`kind="github"` `Integration` is validated up front by `validate_github_integration_activity`.
The sandbox `repository` is the PR's own `owner/repo`, derived from the PR URL.
-- **Prod label trigger** (settings, `posthog/settings/access.py`) — `REVIEWHOG_TRIGGER_TOKEN` (shared secret),
- the first `REVIEWHOG_TEAM_IDS` entry from the `REVIEWHOG_TEAM_ID` environment variable (the run team),
- and `REVIEWHOG_RUN_USER_ID` (optional; falls back to the integration creator).
- Enabling manual project access requires no changes to these settings or the shared secret.
-- **Automatic authored-PR trigger** uses the first `REVIEWHOG_TEAM_IDS` entry and requires a matching GitHub installation on that team.
- The PR author's linked GitHub identity must map to an active member of the team's organization with `review_authored_prs` enabled.
-- **Internal UI features** use `show_internal_features` in the settings response, true only for the first
- `REVIEWHOG_TEAM_IDS` entry. That project retains Flash and all automation controls. Other enabled projects
- show manual review and resolution without Flash or automation controls, except that saved Inbox or
- Stamphog opt-ins remain visible until switched off. Their settings reads do not query Stamphog.
- Existing automation routing and its configuration remain separate from the flag.
+- **Settings storage** — personal preferences live in `ReviewUserSettings.preferences`, a sparse JSON dict typed by
+ `backend/preferences.py`: an absent key inherits, unknown keys and invalid values are ignored on read, and a write
+ equal to the inherited value removes the key. `urgency_threshold` and `celebrate_clean_reviews` inherit from the
+ project defaults in `ReviewProjectSettings.preferences`, then from the code defaults; the other keys
+ (`default_review_mode` follow/flash/off, `resolve_comments` default off, the two Inbox opt-ins) inherit from code
+ only. Read them with `ReviewUserSettings.load_preferences[_many]`. The older boolean and choice columns on
+ `ReviewUserSettings` are unused. A GET creates no row; the first PATCH does.
+- **Repository ownership** (`backend/ownership.py`) — a repository belongs to at most one project, like GitHub's
+ install picker. A `ReviewInstallationClaim` per (project, installation) is `all` (every repository no other
+ project selected, at most one project per installation) or `selected`. A `ReviewRepository` row is either
+ selected into its project or a repository exception (`flash_for`); a repository has one row across all
+ projects. Ownership: a selected row (or a row in the project that claims all) → that project; else the `all`
+ claim → that project; else nobody, so no automatic review and the label trigger answers "not set up". The
+ webhook prefilter (`OwnedRepositoryPrefilter`) caches a per-installation summary and fails open. Repository
+ lookups match GitHub's repository id first and then the name, and backfill both. The installation id is not part
+ of a repository's identity (a reinstall gets a new one), so rows and personal choices are unique by name and id. The repository list in the
+ settings comes from the core GitHub integration's cached repository list (`repository_overview`), which the
+ core `installation_repositories` webhook keeps fresh. A repository write must match a name and id in that list,
+ so a project cannot reserve a repository id the installation does not report.
+- **Label trigger** — the PostHog GitHub App's own `pull_request` `labeled` delivery (`backend/label_reviews.py`).
+ No GitHub Action, shared secret, or environment variable is involved. See the triggers paragraph below.
+- **Automatic authored-PR trigger** runs in the owning project and requires that project's GitHub integration for
+ the delivery's installation. The rules in `backend/automatic_review_rules.py` decide, highest first: the
+ author's choice for the repository (`ReviewUserRepositoryChoice`, flash/off, stored only when it differs from
+ the inherited result), the author's `default_review_mode` unless `follow`, the repository exception, then the
+ project rule (`ReviewProjectSettings.flash_for`: everyone except the excepted people, the listed people, or
+ opt-in only, the default). Bot authors and authors who map to no active member get automatic Flash only when the
+ project sets `bot_prs=run`; the review then runs as the user who connected the installation, with default
+ settings and no resolution. The owning project also needs the `review-hog-internal` flag. No per-deploy team id
+ picks the project for any trigger.
+- **Internal features** (`backend/internal_features.py::has_internal_features`) — the `review-hog-internal`
+ feature flag, evaluated per project with the project group the same way as `review-hog` (set it up the same way).
+ It gates automatic Flash reviews, the label trigger, resolution, manual Flash, the tiered review arms, and the
+ scene's Flash, Inbox, and Stamphog controls (`FEATURE_FLAGS.REVIEW_HOG_INTERNAL`). Saved Inbox or Stamphog
+ opt-ins stay visible without it until switched off, and settings reads without it do not query Stamphog. A flag
+ service failure reads as off.
+- **`REVIEWHOG_GITHUB_BOT_LOGIN`** (`posthog/settings/access.py`) names the app's `<slug>[bot]` login per region.
+ `is_app_bot_author` trusts only that login; unset, it trusts no author in production (local development and tests
+ fall back to any `Bot`-typed author).
+
+**Customer setup path.** Nothing in ReviewHog's behavior depends on a per-deploy team id, so any project can enable it:
+
+1. Turn on the `review-hog` flag for the project (and `review-hog-internal` for the internal-only parts).
+2. Connect GitHub through the core GitHub integration (the PostHog GitHub App installation).
+3. In the Code review settings, claim the installation: all repositories (at most one project per installation) or
+ only selected repositories.
+4. Set the project rule (automatic Flash for everyone, for listed people, or opt-in only) and the bot rule.
**Triggers.** Six entry points feed the same per-PR `ReviewPRQueueWorkflow`: the `run_review` CLI (manual / eval), the
-`reviewhog` **label** on a `PostHog/posthog` or `PostHog/ai-gateway` PR (a thin GitHub Action → `POST /api/review_hog/trigger`), a **UI**
+`reviewhog` **label** on a PR in a repository that a project reviews (the GitHub App's own `labeled` delivery), a **UI**
"Review this PR" field in the Code review scene (any installation-accessible PR; its split button's `run_mode`
-also carries the review-without-resolving and resolve-only variants; the configured internal project also shows
+also carries the review-without-resolving and resolve-only variants; projects with `review-hog-internal` also see
**Flash**, which pins resolution off), an **inbox** trigger (a
`TaskRun` receiver auto-reviews self-driving Signals implementations once their PR exists — a pushed branch without
a PR is not reviewed, and the PR must sit in the task's own repository because `output.pr_url` is written by
whoever controls the run, the sandbox agent included), **MCP tools**
(`review-hog-reviews-{trigger,list,get}`, defined in `products/review_hog/mcp/tools.yaml` and gated on the
`review-hog` feature flag) that drive the same reviews viewset with a personal API key or OAuth token, and **automatic authored-PR Flash reviews**.
-The automatic trigger consumes signed GitHub `pull_request` deliveries through `review_hog_authored_prs` and queues a Celery task for identity and opt-in checks.
-It accepts `opened` and `synchronize` for open `PostHog/posthog` PRs whose head and base belong to that repository, including drafts.
+The automatic trigger consumes signed GitHub `pull_request` deliveries through `review_hog_authored_prs` and queues a Celery task for the ownership, identity, and rule checks.
+It accepts `opened` and `synchronize` for open PRs whose head and base belong to the delivery's repository, including drafts.
+The webhook handler reads only the cached ownership summary, so the task checks ownership again.
Enabling the setting performs no backfill; existing PRs become eligible on their next push.
-The turn rechecks the author's opt-in before starting and uses their saved severity threshold; Flash never starts resolution.
+The turn rechecks ownership and the rules before starting. Flash publishes every kept finding (it records `consider` as the turn's threshold) and never starts resolution.
+**No Flash after Full:** once a PR has a published Full review, automatic dispatch skips it (`full_review_published`), the turn's recheck refuses it, and a manual Flash request answers 409 `flash_after_full`.
+The same `review_hog_authored_prs` consumer (the name is the dedup key, so it stays) routes by action through `facade/github.py::accept_pull_request_event` (`backend/pull_request_events.py`): `labeled` with the `reviewhog` label queues `process_label_event`.
+That task finds the owning project, requires `review-hog-internal`, and accepts a person or `stamphog[bot]` (Stamphog's hand-off) as the labeler; another bot's label gets an explaining comment and is removed with the app token.
+The review runs as the PR owner, else as the user who connected the installation (`Integration.created_by`) with default settings and no resolution; the workflow removes the label when the run ends, and a running resolution leaves the label for a later retry.
+Counters: `posthog_review_hog_authored_pr_review_total` and `posthog_review_hog_label_review_total`, keyed by outcome.
+`facade/github.py::owning_team_id(installation_id, repository)` answers the same ownership question for other products, for example a PR comment command dispatcher.
The UI and MCP paths are one surface: the viewset carries the grantable `review_hog` scope (`review_hog:read` for list /
retrieve / perspective_stats, `review_hog:write` for trigger). Both require the `review-hog` feature flag,
and the trigger action checks the URL, GitHub App access, fork status, and open state regardless of caller.
-It refuses `run_mode=flash` with a 403 outside the project that has `show_internal_features`.
+It refuses `run_mode=flash` and `resolve_only` with a 403 (`internal_feature`) without the `review-hog-internal` flag.
+The trigger action and the `@posthog review` comment (`facade/reviews.py`) both call `requested_reviews.request_pr_review()`, which applies the owner rule for resolution and the no-Flash-after-Full refusal.
+Settings: an automatic review follows the owner's rules (Flash reads no personal settings), the UI / MCP Review button
+and the comment follow the person who asks, the label follows the owner, and an Inbox review follows the report's reviewer.
See [DECISIONS.md](./DECISIONS.md) for each trigger's auth / scope / identity rules.
The `review-pr-queue` workflow keeps the existing per-PR workflow ID and records requests through signals.
It has at most one pending request each for Full, manual Flash, and automatic Flash, taking explicit requests before automatic ones.
It waits for an active resolution stage and runs each review in a `review-pr` child workflow with the existing retry and comment behavior.
An explicit Full request remains pending during an active Flash turn and runs if that head still needs a Full review.
-Automatic pushes coalesce to the latest head; turning off the authored-PR setting prevents pending automatic reviews from starting without canceling a running turn.
+Automatic pushes coalesce to the latest head; a rule change that stops the author's automatic review prevents pending automatic reviews from starting without canceling a running turn.
`automatic_reviewed_head_sha` advances only after publication succeeds or finds nothing to publish, so a failed publication can retry and an empty review does not repeat.
An automatic follow-up turn (one with an `automatic_reviewed_head_sha`) first runs the push gate (`reviewer/push_gate.py`) on the PR's own commits since that head.
-Its rules, in order: `no_new_commits` (the PR gained no commit and its full diff is unchanged; a force-push that drops commits runs the review), `merge_only` (the PR's full diff against its base is unchanged, as after a base merge or a rebase), `docs_only` (the new own commits touch only docs, lockfiles, snapshots, images, or generated files), and `system_one_below_threshold` (System One rates the own code patches below `SYSTEM_ONE_SKIP_BELOW`).
-Each rule has a `SKIP_*` switch. `no_new_commits` and `merge_only` skip; `docs_only` and System One only record a shadow decision until production data confirms them.
+Its rules, in order: `no_new_commits` (the PR gained no commit and its full diff is unchanged; a force-push that drops commits runs the review), `reviewhog_commits_only` (the ReviewHog app authored every new commit, such as resolution fixes; this includes the PostHog app's commits on self-driving PRs, which share the app identity), `merge_only` (the PR's full diff against its base is unchanged, as after a base merge or a rebase), `docs_only` (the new own commits touch only docs, lockfiles, snapshots, images, or generated files), and `system_one_below_threshold` (System One rates the own code patches below `SYSTEM_ONE_SKIP_BELOW`).
+Each rule has a `SKIP_*` switch. `no_new_commits`, `reviewhog_commits_only`, and `merge_only` skip; `docs_only` and System One only record a shadow decision until production data confirms them.
A skipped turn posts no status comment and leaves `automatic_reviewed_head_sha` in place, so the next push is judged against the last reviewed head.
Any gate failure reviews the push. Each decision emits `reviewhog_push_gate_decided` with `skipped`, `would_skip`, the reason, and the System One probability and model.
The first automatic review and every label, UI, inbox, and manual trigger never reach the gate.
diff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.md
index b2f639d3318f..37ddc80375aa 100644
--- a/products/review_hog/CONTEXT.md
+++ b/products/review_hog/CONTEXT.md
@@ -32,7 +32,7 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no
- **Review cycle** — one review turn plus its chained resolution, taken as a unit: the span from review start until the resolution stage finishes settling that review's comments. Two Temporal workflows implement it (see ADR 0001), but users reason about the cycle — "the PR is being worked on" — not the stages.
- **Busy-guard** — the explicit cross-stage check that refuses to start a new review while the PR's `resolve-pr` workflow is running, and refuses to start a standalone resolution while its `review-pr` workflow is running (the chained hand-off is exempt: it fires only after publish). Needed because Temporal's same-id joining cannot see across the two workflows.
- **Resolution etiquette** — triage and fixing logic is identical for every thread regardless of author; only the _resolve_ action is author-gated. Human-authored threads: reply as the bot with the outcome (fix + commit link, or the decline/escalate reasoning), **never resolve** — the human keeps the final word on their own thread. Bot-authored threads: reply and resolve on terminal outcomes. ESCALATE never resolves, for any author. (Autonomous adaptation of the triage skill's "bot threads: reply + resolve; human threads: hand back" invariant — the bot now speaks as itself, but resolution of human threads still belongs to humans.)
-- **Entry points** — the durable interface is a trigger-style endpoint (mirroring `ReviewHogTriggerViewSet`: shared-secret bearer, server-side team/user resolution, unscoped mount), callable by API clients (other products, e.g. self-driving) and by a thin label-driven GitHub Action. Chained mode — `ReviewPRWorkflow` dispatching the stage after publish — is an internal dispatch, not an HTTP hop, and it is the **default**: reviewing includes resolving, gated by the acting user's `resolve_comments` setting (on unless they opt out; snapshotted at acting-user resolution like the other gates), with the workflow input as a per-run override only the Code review scene uses (its split Review button offers "review without resolving", "resolve only", and "flash" — the Luna medium review that never resolves). A `run_resolution` management command mirrors `run_review` for dev/test. Deterministic skip gates run before any sandbox: closed/merged PR, fork (hard refuse — this stage writes), empty work-list after the pre-filter. One run per PR at a time via a deterministic workflow ID.
+- **Entry points** — the UI / MCP resolve-only action and the `run_resolution` command start a standalone run. Chained mode — `ReviewPRWorkflow` dispatching the stage after publish — is an internal dispatch, not an HTTP hop, and it is the **default**: reviewing includes resolving, gated by the **PR owner's** `resolve_comments` opt-in (off by default; snapshotted at acting-user resolution like the other gates; the owner is the mapped author, or the Inbox reviewer of a self-driving PR) and the `review-hog-internal` flag, with the workflow input as a per-run switch-off only the Code review scene uses (its split Review button offers "review without resolving", "resolve only", and "flash" — the Luna medium review that never resolves). A `run_resolution` management command mirrors `run_review` for dev/test. Deterministic skip gates run before any sandbox: closed/merged PR, fork (hard refuse — this stage writes), empty work-list after the pre-filter. One run per PR at a time via a deterministic workflow ID.
- **Writing mechanics** — one signed commit per FIXED thread (a signed commit is inherently remote — the harness creates commits via the GitHub API, so commit cadence _is_ push cadence), with that thread's reply/resolve posted right after its commit is visible. On a mid-run race (author pushed; signed commit refuses because the remote advanced): sync onto the new head once, re-verify, retry; if the branch moves again, yield gracefully — done threads keep their outcomes, the rest wait for the next run.
- **CI boundary** — the resolution stage handles review threads only; it never waits on, chases, or fixes PR checks. CI babysitting already exists (the Tasks CI follow-up loop). Known seam to close on the Tasks side: `_should_run_ci_follow_up` also fires on new unresolved threads and `DEFAULT_CI_MESSAGE` mandates comment-addressing — narrow that to checks-only (or skip its thread trigger) where the resolution stage is active, so two bots never fix the same comment.
- **Run budget** — a run resolves at most **20** threads, priority-ordered; the binding constraint is the warm session's context window (every turn accumulates, and fix quality degrades as it fills), not just sandbox cost. Overflow is always named in the run summary ("handled 20, N remain") and the next run continues — never silent truncation. Session/turn timeouts are inherited from the Tasks runner. Fix _size_ is deliberately not a numeric cap — proportionality in the criteria skill is the guard. Model/effort pinned by `RESOLUTION_*` constants (validator's Claude default to start).
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index d834684b8835..f1b97452e651 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -312,6 +312,61 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)
- **Caveats.** Each thread and arm ran once, and no tests ran in the trial. Production runs one warm session per PR,
not one session per thread. Watch the resolution outcomes on the dashboard after the change.
+### ✅ BUILT 2026-10-09 — settings rework: project rules, repository ownership, the PR owner rule, and first-class enablement
+
+Decided with the maintainer on 2026-10-09 (settings audit and settings mockup). Built in two layers: the data model
+and API (storage, ownership, the Flash decision), then the behavior rules. The record of the settled spec:
+
+- **Storage.** Personal preferences live in `ReviewUserSettings.preferences`, a sparse JSON dict typed in
+ `backend/preferences.py`: an absent key inherits, unknown keys and invalid values are ignored on read, and a write
+ equal to the inherited value removes the key. Keys: `default_review_mode` (follow / flash / off), `resolve_comments`
+ (default off, personal only), `urgency_threshold` and `celebrate_clean_reviews` (Full only, layered code default →
+ project default → user value), and the two Inbox opt-ins. The old columns stay on the model, unused. A GET creates no
+ row. Project rules live in `ReviewProjectSettings`: `flash_for` (everyone / listed / off, default off = opt-in only),
+ `bot_prs` (skip / run), and the two project defaults. People lists are `ReviewRepositoryPerson` rows; a row without
+ a repository belongs to the project rule.
+- **Ownership.** A repository belongs to at most one project, like GitHub's install picker: a
+ `ReviewInstallationClaim` per (project, installation) is `all` (at most one project per installation) or
+ `selected`, and a selected `ReviewRepository` row (unique across projects, matched by GitHub repository id, then by
+ name) wins over another project's `all` claim. Global uniqueness, not one project per GitHub organization, because
+ several projects often share one installation. The repository list in the settings reads the core GitHub
+ integration's cached repository list; the core `installation_repositories` webhook refreshes it.
+- **Flash decision**, highest first: the user's choice for the repository → the user's default unless follow → the
+ repository exception → the project rule. Bots and authors without an active member follow `bot_prs` only; a bot
+ review runs as the user who connected the installation, with default settings and no writes.
+- **PR owner** (`backend/pr_owner.py`): the author when the login maps to an active member; a self-driving PR (opened
+ by the PostHog app) belongs to its Inbox report's canonical reviewer; else nobody.
+- **Whose settings shape a review.** Automatic: the owner's rules (Flash reads no personal settings). Review button
+ and MCP: the person who asks. Label: the owner, else the connector with default settings. Inbox: the report
+ reviewer. The `review_labeled_prs` opt-out is gone: a label always runs.
+- **Resolution** runs only after a Full review, only when the owner opted in, whoever triggered, and only with the
+ `review-hog-internal` flag (`review_request_rules.ResolutionGate`). No owner, no writes. The resolve-only action
+ answers 409 `resolution_not_opted_in`, and `_prepare_run` checks the gate again. Guards: a protected head branch
+ holds the stage before any push (`CommitHold.BRANCH_PROTECTED`), and `is_app_bot_author` fails closed in production
+ when `REVIEWHOG_GITHUB_BOT_LOGIN` is unset.
+- **Flash vs Full.** Flash ignores `urgency_threshold`: it publishes every kept finding and records `consider` in
+ `published_urgency_thresholds`. No Flash after Full: once a PR has a published Full review, automatic dispatch, the
+ turn's recheck, and manual Flash requests (API, MCP) refuse it (`flash_after_full`). Full may resolve Flash threads.
+- **Push gate.** New rule `reviewhog_commits_only`: an automatic follow-up skips when the ReviewHog app authored every
+ new commit since the last automatically reviewed head (resolution fixes). It emits `reviewhog_push_gate_decided`
+ like the other rules.
+- **First-class enablement.** No per-deploy team constant decides behavior: `REVIEWHOG_TEAM_IDS`,
+ `REVIEWHOG_RUN_USER_ID`, and `REVIEWHOG_TRIGGER_TOKEN` are gone. One feature flag, `review-hog-internal`, evaluated
+ per project like `review-hog`, gates the internal-only parts: automatic reviews, the label trigger, resolution, manual
+ Flash, the tiered review arms, and the Inbox and Stamphog controls. The `review-hog` flag stays the product switch.
+ The label trigger moved from the GitHub Action (deleted) to the GitHub App's own `labeled` delivery through the
+ existing `review_hog_authored_prs` consumer, which now routes by action (`accept_pull_request_event`). A person or
+ `stamphog[bot]` may label; another bot's label gets the explaining comment and is removed with the app token. The
+ shared-secret `/api/review_hog/trigger` and `/resolve` endpoints are removed, because nothing else called them. No
+ migration seeds a claim: a project admin sets the claim in the settings UI. Customer setup: enable the flag →
+ connect GitHub → claim the installation → set the project rule.
+- **Facade.** `facade/github.py::owning_team_id(installation_id, repository)` exposes ownership, so a PR comment
+ command dispatcher can pick the project.
+- **One request entry.** `requested_reviews.request_pr_review()` serves the UI, MCP and the `@posthog review` comment,
+ and applies the owner rule, the resolution gate and the Flash-after-Full check for all of them. A comment run
+ follows the same owner rule.
+- **Open follow-ups.** Claims and rows of an uninstalled installation are not cleaned up yet.
+
### ✅ BUILT 2026-10-08 — inline finding comments: one P-level heading and one paragraph
- **What.** An inline comment is `**P{n} · {title}**`, then one paragraph with the issue and its fix, then the hidden
diff --git a/products/review_hog/backend/activity_logging.py b/products/review_hog/backend/activity_logging.py
new file mode 100644
index 000000000000..e1742b742209
--- /dev/null
+++ b/products/review_hog/backend/activity_logging.py
@@ -0,0 +1,233 @@
+"""Activity-log receivers for the project-wide ReviewHog settings.
+
+Project admins decide which repositories a project reviews and who gets automatic reviews, so every
+change needs a visible author. A change to a people list is logged on its owner, the repository or
+the project settings, because a reader looks for "who changed this rule", not for list rows.
+"""
+
+from typing import Any
+from uuid import UUID
+
+from django.db import models
+
+from posthog.models.activity_logging.activity_log import AuditableScope, Change, Detail, changes_between, log_activity
+from posthog.models.integration import Integration
+from posthog.models.signals import model_activity_signal, mutable_receiver
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.review_hog.backend.models import (
+ ReviewInstallationClaim,
+ ReviewProjectSettings,
+ ReviewRepository,
+ ReviewRepositoryPerson,
+)
+
+PROJECT_SETTINGS_NAME = "Project settings"
+
+
+def _organization_id_for_team(team_id: int) -> UUID | None:
+ return Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()
+
+
+def installation_account_name(installation_id: str) -> str:
+ """The GitHub account of an installation, as the core GitHub integration stores it."""
+ name = (
+ Integration.objects.filter(kind="github", integration_id=installation_id)
+ .values_list("config__account__name", flat=True)
+ .first()
+ )
+ return name if isinstance(name, str) and name else installation_id
+
+
+def _log_model_change(
+ instance: models.Model,
+ *,
+ team_id: int,
+ name: str,
+ scope: AuditableScope,
+ before_update: models.Model | None,
+ after_update: models.Model | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool,
+) -> None:
+ log_activity(
+ organization_id=_organization_id_for_team(team_id),
+ team_id=team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.pk,
+ scope=scope,
+ activity=activity,
+ detail=Detail(name=name, changes=changes_between(scope, previous=before_update, current=after_update)),
+ )
+
+
+@mutable_receiver(model_activity_signal, sender=ReviewRepository)
+def handle_review_repository_change(
+ sender: type[ReviewRepository],
+ scope: AuditableScope,
+ before_update: ReviewRepository | None,
+ after_update: ReviewRepository | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ if instance is None:
+ return
+ _log_model_change(
+ instance,
+ team_id=instance.team_id,
+ name=instance.full_name,
+ scope=scope,
+ before_update=before_update,
+ after_update=after_update,
+ activity=activity,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+
+
+@mutable_receiver(model_activity_signal, sender=ReviewProjectSettings)
+def handle_review_project_settings_change(
+ sender: type[ReviewProjectSettings],
+ scope: AuditableScope,
+ before_update: ReviewProjectSettings | None,
+ after_update: ReviewProjectSettings | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ if instance is None:
+ return
+ _log_model_change(
+ instance,
+ team_id=instance.team_id,
+ name=PROJECT_SETTINGS_NAME,
+ scope=scope,
+ before_update=before_update,
+ after_update=after_update,
+ activity=activity,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+
+
+@mutable_receiver(model_activity_signal, sender=ReviewInstallationClaim)
+def handle_review_installation_claim_change(
+ sender: type[ReviewInstallationClaim],
+ scope: AuditableScope,
+ before_update: ReviewInstallationClaim | None,
+ after_update: ReviewInstallationClaim | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ if instance is None:
+ return
+ _log_model_change(
+ instance,
+ team_id=instance.team_id,
+ name=installation_account_name(instance.installation_id),
+ scope=scope,
+ before_update=before_update,
+ after_update=after_update,
+ activity=activity,
+ user=user,
+ was_impersonated=was_impersonated,
+ )
+
+
+@mutable_receiver(model_activity_signal, sender=ReviewRepositoryPerson)
+def handle_review_repository_person_change(
+ sender: type[ReviewRepositoryPerson],
+ scope: AuditableScope,
+ before_update: ReviewRepositoryPerson | None,
+ after_update: ReviewRepositoryPerson | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ # A person row has no editable field, so only an add and a remove are changes.
+ if activity not in ("created", "deleted"):
+ return
+ instance = after_update or before_update
+ if instance is None:
+ return
+ owner_scope: AuditableScope
+ owner_name: str | None
+ if instance.repository_id is None:
+ owner_scope, owner_name = "ReviewProjectSettings", PROJECT_SETTINGS_NAME
+ owner_id = ReviewProjectSettings.objects.for_team(instance.team_id).values_list("id", flat=True).first()
+ else:
+ owner_scope, owner_id = "ReviewRepository", instance.repository_id
+ owner_name = (
+ ReviewRepository.objects.for_team(instance.team_id)
+ .filter(id=instance.repository_id)
+ .values_list("full_name", flat=True)
+ .first()
+ )
+ person_email = User.objects.filter(id=instance.user_id).values_list("email", flat=True).first()
+ added = activity == "created"
+ log_activity(
+ organization_id=_organization_id_for_team(instance.team_id),
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=owner_id,
+ scope=owner_scope,
+ activity="updated",
+ detail=Detail(
+ name=owner_name,
+ changes=[
+ Change(
+ type=owner_scope,
+ action="created" if added else "deleted",
+ field=f"{instance.kind}_people",
+ before=None if added else person_email,
+ after=person_email if added else None,
+ )
+ ],
+ ),
+ )
+
+
+def log_repository_taken(*, claim: ReviewInstallationClaim, full_name: str, taken_by_team_id: int, user: User) -> None:
+ """Tell the project that takes all repositories of an installation that another project took one.
+
+ The taking project logs its own row through the receiver above, so both projects can see the move.
+ """
+ organization_id = _organization_id_for_team(claim.team_id)
+ taker = Team.objects.filter(id=taken_by_team_id).values("name", "organization_id").first() or {}
+ # Project names and their admins stay inside their organization.
+ same_organization = taker.get("organization_id") == organization_id
+ taken_by = taker.get("name") if same_organization else "A project in another organization"
+ log_activity(
+ organization_id=organization_id,
+ team_id=claim.team_id,
+ user=user if same_organization else None,
+ was_impersonated=False,
+ item_id=claim.id,
+ scope="ReviewInstallationClaim",
+ activity="updated",
+ detail=Detail(
+ name=installation_account_name(claim.installation_id),
+ changes=[
+ Change(
+ type="ReviewInstallationClaim",
+ action="changed",
+ field="repository_taken_by_another_project",
+ before=full_name,
+ after=taken_by,
+ )
+ ],
+ ),
+ )
diff --git a/products/review_hog/backend/api/__init__.py b/products/review_hog/backend/api/__init__.py
index 1090a8fd9f40..ac1b47c215ae 100644
--- a/products/review_hog/backend/api/__init__.py
+++ b/products/review_hog/backend/api/__init__.py
@@ -1,16 +1,24 @@
from products.review_hog.backend.api.blind_spots import ReviewBlindSpotsConfigViewSet
from products.review_hog.backend.api.perspectives import ReviewPerspectiveConfigViewSet
+from products.review_hog.backend.api.project_settings import ReviewProjectSettingsViewSet
+from products.review_hog.backend.api.repositories import (
+ ReviewInstallationClaimViewSet,
+ ReviewRepositoryChoiceViewSet,
+ ReviewRepositoryViewSet,
+)
from products.review_hog.backend.api.resolution import ReviewResolutionConfigViewSet
from products.review_hog.backend.api.reviews import ReviewRecentReviewsViewSet
from products.review_hog.backend.api.settings import ReviewUserSettingsViewSet
-from products.review_hog.backend.api.trigger import ReviewHogTriggerViewSet
from products.review_hog.backend.api.validators import ReviewValidatorConfigViewSet
__all__ = [
"ReviewBlindSpotsConfigViewSet",
- "ReviewHogTriggerViewSet",
+ "ReviewInstallationClaimViewSet",
"ReviewPerspectiveConfigViewSet",
+ "ReviewProjectSettingsViewSet",
"ReviewRecentReviewsViewSet",
+ "ReviewRepositoryChoiceViewSet",
+ "ReviewRepositoryViewSet",
"ReviewResolutionConfigViewSet",
"ReviewUserSettingsViewSet",
"ReviewValidatorConfigViewSet",
diff --git a/products/review_hog/backend/api/project_settings.py b/products/review_hog/backend/api/project_settings.py
new file mode 100644
index 000000000000..5403d47a8e4c
--- /dev/null
+++ b/products/review_hog/backend/api/project_settings.py
@@ -0,0 +1,364 @@
+import logging
+from typing import Any, cast
+
+from django.db import transaction
+
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.user import User
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.review_hog.backend.api.repositories import (
+ UUID_PATH_PATTERN,
+ AutomaticReviewDecisionSerializer,
+ EffectiveTeamStrictManagementPermission,
+ ReviewHogProjectViewSetMixin,
+ ReviewHogSettingsErrorSerializer,
+ ReviewInstallationSerializer,
+ ReviewProjectRefSerializer,
+ ReviewRepositoryPersonRequestSerializer,
+ ReviewRepositoryPersonSerializer,
+ check_active_member,
+ decision_data,
+ installation_data,
+ project_ref_data,
+)
+from products.review_hog.backend.automatic_review_rules import load_people
+from products.review_hog.backend.models import (
+ AutomaticFlashFor,
+ ReviewInstallationClaim,
+ ReviewProjectSettings,
+ ReviewRepositoryPerson,
+ ReviewUserRepositoryChoice,
+)
+from products.review_hog.backend.preferences import InvalidPreference, UrgencyThreshold
+from products.review_hog.backend.repository_settings import (
+ OverviewEntry,
+ RepositoryOverview,
+ RepositoryOverviewView,
+ RepositoryOwnerKind,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class ReviewProjectSettingsSerializer(serializers.Serializer):
+ flash_for = serializers.ChoiceField(
+ choices=AutomaticFlashFor.choices,
+ required=False,
+ help_text="Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except "
+ "the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the "
+ "default). A repository exception or a person's own choice wins over it.",
+ )
+ bot_prs = serializers.ChoiceField(
+ choices=ReviewProjectSettings.BotPullRequests.choices,
+ required=False,
+ help_text="Pull requests from bots, and from authors who are not project members, in every repository "
+ "this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the "
+ "person who connected GitHub, with default settings and no changes to the pull request).",
+ )
+ urgency_threshold = serializers.ChoiceField(
+ choices=UrgencyThreshold.choices,
+ required=False,
+ help_text="Project default for the minimum priority a Full review publishes: 'consider' (all, the "
+ "built-in default), 'should_fix', or 'must_fix'. A person's own value wins.",
+ )
+ celebrate_clean_reviews = serializers.BooleanField(
+ required=False,
+ help_text="Project default for the image in a Full review that finds nothing to raise. On by default. "
+ "A person's own value wins.",
+ )
+ people = ReviewRepositoryPersonSerializer(
+ many=True,
+ read_only=True,
+ help_text="The people on the project rule's two lists. Only the list that matches flash_for has an effect.",
+ )
+ installations = ReviewInstallationSerializer(
+ many=True,
+ read_only=True,
+ help_text="Every GitHub installation connected to this project, and which of its repositories this "
+ "project reviews.",
+ )
+ can_edit = serializers.BooleanField(
+ read_only=True, help_text="Whether the requesting user is a project admin and can change these settings."
+ )
+
+
+class ReviewRepositoryOverviewQuerySerializer(serializers.Serializer):
+ installation_id = serializers.CharField(max_length=64, help_text="The GitHub App installation to list.")
+ search = serializers.CharField(
+ required=False, default="", allow_blank=True, help_text="Only repositories whose name contains this text."
+ )
+ view = serializers.ChoiceField(
+ choices=RepositoryOverviewView.choices,
+ required=False,
+ default="all",
+ help_text="'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository "
+ "exception), or 'mine' (with the requesting user's own choice).",
+ )
+ offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Entries to skip.")
+ limit = serializers.IntegerField(
+ required=False, default=50, min_value=1, max_value=200, help_text="Entries per page (max 200)."
+ )
+
+
+class ReviewRepositoryExceptionSerializer(serializers.Serializer):
+ flash_for = serializers.ChoiceField(
+ choices=AutomaticFlashFor.choices, help_text="The exception's rule: 'everyone', 'listed', or 'off'."
+ )
+ people = ReviewRepositoryPersonSerializer(many=True, help_text="The people on the exception's two lists.")
+
+
+class ReviewRepositoryOverviewEntrySerializer(serializers.Serializer):
+ full_name = serializers.CharField(help_text="GitHub repository in 'owner/name' form.")
+ github_repo_id = serializers.IntegerField(allow_null=True, help_text="GitHub's repository id.")
+ owner = serializers.ChoiceField(
+ choices=RepositoryOwnerKind.choices,
+ help_text="Which project reviews the repository: 'this_project', 'other_project', or 'none'.",
+ )
+ owner_project = ReviewProjectRefSerializer(
+ allow_null=True, help_text="The other project that reviews the repository, when owner is 'other_project'."
+ )
+ in_project = serializers.BooleanField(help_text="Whether this project reviews the repository.")
+ selected = serializers.BooleanField(help_text="Whether this project selected the repository explicitly.")
+ repository_id = serializers.UUIDField(
+ allow_null=True, help_text="Id of this project's repository entry, for the people list endpoints."
+ )
+ exception = ReviewRepositoryExceptionSerializer(
+ allow_null=True, help_text="This project's repository exception. Null when the repository follows the project."
+ )
+ my_choice = serializers.ChoiceField(
+ choices=ReviewUserRepositoryChoice.Mode.choices,
+ allow_null=True,
+ help_text="The requesting user's own choice for this repository: 'flash', 'off', or null.",
+ )
+ my_choice_id = serializers.UUIDField(allow_null=True, help_text="Id of that choice, to clear it.")
+ my_result = AutomaticReviewDecisionSerializer(
+ help_text="What the requesting user's own pull requests get here, and the rule that decided it."
+ )
+
+
+class ReviewRepositoryOverviewSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(help_text="The listed GitHub App installation.")
+ claim_scope = serializers.ChoiceField(
+ choices=ReviewInstallationClaim.Scope.choices,
+ allow_null=True,
+ help_text="This project's claim on the installation: 'all', 'selected', or null.",
+ )
+ results = ReviewRepositoryOverviewEntrySerializer(many=True, help_text="One page of repositories.")
+ total = serializers.IntegerField(help_text="Repositories that match the search and the view.")
+ has_more = serializers.BooleanField(help_text="Whether more entries follow this page.")
+ next_offset = serializers.IntegerField(allow_null=True, help_text="Offset of the next page, or null.")
+
+
+def _entry_data(entry: OverviewEntry) -> dict[str, Any]:
+ repository = entry.repository
+ exception = None
+ if repository is not None and repository.flash_for is not None:
+ exception = {
+ "flash_for": repository.flash_for,
+ "people": [dict(ReviewRepositoryPersonSerializer(person).data) for person in entry.exception_people],
+ }
+ return {
+ "full_name": entry.full_name,
+ "github_repo_id": entry.github_repo_id,
+ "owner": entry.owner,
+ "owner_project": project_ref_data(entry.owner_project),
+ "in_project": entry.in_project,
+ "selected": entry.selected,
+ "repository_id": repository.id if repository is not None else None,
+ "exception": exception,
+ "my_choice": entry.my_choice.mode if entry.my_choice is not None else None,
+ "my_choice_id": entry.my_choice.id if entry.my_choice is not None else None,
+ "my_result": decision_data(entry.my_result),
+ }
+
+
+class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):
+ """The project-wide ReviewHog rule and the repository overview.
+
+ Project members can read everything here. Only project admins can change the rule and its lists,
+ and every change goes to the activity log.
+ """
+
+ scope_object = "review_hog"
+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
+ posthog_feature_flag = "review-hog"
+ # Unscoped only to satisfy the router/introspection; every real query goes through `for_team`.
+ queryset = ReviewProjectSettings.objects.unscoped()
+ serializer_class = ReviewProjectSettingsSerializer
+
+ def _settings_response(self, response_status: int = status.HTTP_200_OK) -> Response:
+ team_id = self.effective_team_id
+ row = ReviewProjectSettings.load(team_id)
+ defaults = row.defaults
+ data = {
+ "flash_for": row.flash_for,
+ "bot_prs": row.bot_prs,
+ "urgency_threshold": defaults.urgency_threshold,
+ "celebrate_clean_reviews": defaults.celebrate_clean_reviews,
+ "people": load_people(team_id, [])[None],
+ "installations": [installation_data(summary) for summary in self.project_repositories().installations()],
+ "can_edit": self.is_effective_team_admin(),
+ }
+ return Response(ReviewProjectSettingsSerializer(data).data, status=response_status)
+
+ def _settings_row(self) -> ReviewProjectSettings:
+ team_id = self.effective_team_id
+ row, _created = ReviewProjectSettings.objects.for_team(team_id, canonical=True).get_or_create(team_id=team_id)
+ return row
+
+ @extend_schema(
+ methods=["GET"],
+ responses={200: OpenApiResponse(response=ReviewProjectSettingsSerializer)},
+ summary="Get the project's ReviewHog rule",
+ description="The project rule for automatic Flash reviews, bot pull requests, the Full review defaults, "
+ "and the connected GitHub installations.",
+ )
+ @extend_schema(
+ methods=["PATCH"],
+ request=ReviewProjectSettingsSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewProjectSettingsSerializer, description="The updated rule."),
+ 400: OpenApiResponse(description="Invalid field value."),
+ 403: OpenApiResponse(description="Only project admins can change the rule."),
+ },
+ summary="Update the project's ReviewHog rule",
+ description="Partially update the project rule. Only the provided fields change. Project admins only.",
+ )
+ @action(detail=False, methods=["GET", "PATCH"], url_path="project_settings", url_name="project_settings")
+ def project_settings(self, request: Request, **kwargs: Any) -> Response:
+ if request.method == "PATCH":
+ serializer = ReviewProjectSettingsSerializer(data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ with transaction.atomic():
+ row = (
+ ReviewProjectSettings.objects.for_team(self.effective_team_id)
+ .select_for_update()
+ .get(id=self._settings_row().id)
+ )
+ for field in ("flash_for", "bot_prs"):
+ if field in data:
+ setattr(row, field, data[field])
+ changes = {key: data[key] for key in ("urgency_threshold", "celebrate_clean_reviews") if key in data}
+ try:
+ row.preferences = row.defaults.with_changes(changes)
+ except InvalidPreference as error:
+ raise serializers.ValidationError({error.key: str(error)})
+ row.save()
+ return self._settings_response()
+
+ @extend_schema(
+ request=ReviewRepositoryPersonRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewProjectSettingsSerializer, description="Already on that list."),
+ 201: OpenApiResponse(response=ReviewProjectSettingsSerializer, description="The person was added."),
+ 400: OpenApiResponse(description="The user is not an active member of this project's organization."),
+ },
+ summary="Add a person to a project rule list",
+ description="Add a project member to the project rule's 'listed' or 'excepted' list. Project admins only.",
+ )
+ @action(detail=False, methods=["POST"], url_path="project_settings/people", required_scopes=["review_hog:write"])
+ def add_project_person(self, request: Request, **kwargs: Any) -> Response:
+ serializer = ReviewRepositoryPersonRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ user_id: int = serializer.validated_data["user_id"]
+ check_active_member(self.team, user_id)
+ # The row exists first, so the activity log has an item to attach the list change to.
+ self._settings_row()
+ created = self.project_repositories().add_person(None, user_id=user_id, kind=serializer.validated_data["kind"])
+ return self._settings_response(status.HTTP_201_CREATED if created else status.HTTP_200_OK)
+
+ @extend_schema(
+ parameters=[OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry.")],
+ responses={
+ 200: OpenApiResponse(response=ReviewProjectSettingsSerializer, description="The person was removed."),
+ 404: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="No such list entry."),
+ },
+ summary="Remove a person from a project rule list",
+ description="Remove one entry from the project rule's 'listed' or 'excepted' list. Project admins only.",
+ )
+ @action(
+ detail=False,
+ methods=["DELETE"],
+ url_path=rf"project_settings/people/(?P<person_id>{UUID_PATH_PATTERN})",
+ required_scopes=["review_hog:write"],
+ )
+ def remove_project_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:
+ person = (
+ ReviewRepositoryPerson.objects.for_team(self.effective_team_id, canonical=True)
+ .filter(repository__isnull=True, id=person_id)
+ .first()
+ )
+ if person is None:
+ return Response(
+ {"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND
+ )
+ person.delete()
+ return self._settings_response()
+
+ @extend_schema(
+ parameters=[ReviewRepositoryOverviewQuerySerializer],
+ responses={
+ 200: OpenApiResponse(response=ReviewRepositoryOverviewSerializer),
+ 400: OpenApiResponse(
+ response=ReviewHogSettingsErrorSerializer, description="The installation is not connected here."
+ ),
+ },
+ summary="List the repositories of a GitHub installation with their review settings",
+ description="Every repository the GitHub installation can see, with the project that reviews it, this "
+ "project's settings, the requesting user's choice, and the automatic review the requesting user gets.",
+ )
+ @action(detail=False, methods=["GET"], url_path="repository_overview", url_name="repository_overview")
+ def repository_overview(self, request: Request, **kwargs: Any) -> Response:
+ query = ReviewRepositoryOverviewQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ installation_id: str = query.validated_data["installation_id"]
+ integration = Integration.objects.filter(
+ team_id=self.effective_team_id, kind="github", integration_id=installation_id
+ ).first()
+ if integration is None:
+ return Response(
+ {"error": "This project has no GitHub connection for that installation.", "conflicting_project": None},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ try:
+ repositories = GitHubIntegration(integration).list_all_cached_repositories()
+ except Exception:
+ # The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.
+ logger.warning("review_hog_repository_overview_list_failed", exc_info=True)
+ return Response(
+ {"error": "GitHub did not return the repository list. Try again shortly.", "conflicting_project": None},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ search = query.validated_data["search"].strip().casefold()
+ if search:
+ repositories = [
+ repository for repository in repositories if search in str(repository["full_name"]).casefold()
+ ]
+ overview = RepositoryOverview(self.effective_team, cast(User, request.user), installation_id, repositories)
+ offset: int = query.validated_data["offset"]
+ entries, total = overview.page(
+ repositories, view=query.validated_data["view"], offset=offset, limit=query.validated_data["limit"]
+ )
+ has_more = offset + len(entries) < total
+ claim = (
+ ReviewInstallationClaim.objects.for_team(self.effective_team_id)
+ .filter(installation_id=installation_id)
+ .first()
+ )
+ data = {
+ "installation_id": installation_id,
+ "claim_scope": claim.scope if claim is not None else None,
+ "results": [_entry_data(entry) for entry in entries],
+ "total": total,
+ "has_more": has_more,
+ "next_offset": offset + len(entries) if has_more else None,
+ }
+ return Response(ReviewRepositoryOverviewSerializer(data).data)
diff --git a/products/review_hog/backend/api/repositories.py b/products/review_hog/backend/api/repositories.py
new file mode 100644
index 000000000000..e76d1cd9082c
--- /dev/null
+++ b/products/review_hog/backend/api/repositories.py
@@ -0,0 +1,667 @@
+import re
+from typing import Any, cast
+
+from django.db.models import QuerySet
+
+from drf_spectacular.utils import (
+ OpenApiParameter,
+ OpenApiResponse,
+ extend_schema,
+ extend_schema_field,
+ extend_schema_view,
+)
+from rest_framework import mixins, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
+from rest_framework.permissions import SAFE_METHODS, BasePermission
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.models.organization import OrganizationMembership
+from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.review_hog.backend.activity_logging import installation_account_name
+from products.review_hog.backend.automatic_review_rules import (
+ AutomaticReviewDecision,
+ AutomaticReviewReason,
+ load_people,
+)
+from products.review_hog.backend.models import (
+ AutomaticFlashFor,
+ ReviewInstallationClaim,
+ ReviewRepository,
+ ReviewRepositoryPerson,
+ ReviewUserRepositoryChoice,
+)
+from products.review_hog.backend.ownership import RepositoryRef
+from products.review_hog.backend.repository_settings import (
+ UNSET,
+ InstallationSummary,
+ OwnershipConflict,
+ ProjectRef,
+ ProjectRepositories,
+ RepositoryChoices,
+ RepositorySettingsError,
+ Unset,
+)
+
+# GitHub owners and repository names use letters, digits, '-', '_' and '.'.
+_FULL_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
+UUID_PATH_PATTERN = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
+
+
+def validate_full_name(value: str) -> str:
+ value = value.strip()
+ if not _FULL_NAME_PATTERN.match(value):
+ raise ValidationError("Use the 'owner/name' form, for example 'PostHog/posthog'.")
+ return value
+
+
+def project_ref_data(project: ProjectRef | None) -> dict[str, Any] | None:
+ if project is None:
+ return None
+ return {"id": project.team_id if project.name else None, "name": project.name}
+
+
+def conflict_response(error: OwnershipConflict) -> Response:
+ return Response(
+ {"error": str(error), "conflicting_project": project_ref_data(error.project)},
+ status=status.HTTP_409_CONFLICT,
+ )
+
+
+def bad_request_response(error: RepositorySettingsError) -> Response:
+ return Response({"error": str(error), "conflicting_project": None}, status=status.HTTP_400_BAD_REQUEST)
+
+
+def check_active_member(team: Team, user_id: int) -> None:
+ is_member = OrganizationMembership.objects.filter(
+ organization_id=team.organization_id, user_id=user_id, user__is_active=True
+ ).exists()
+ if not is_member:
+ raise ValidationError({"user_id": "This user is not an active member of the organization."})
+
+
+def decision_data(decision: AutomaticReviewDecision) -> dict[str, Any]:
+ return {"flash": decision.flash, "reason": decision.reason.value}
+
+
+class ReviewProjectRefSerializer(serializers.Serializer):
+ id = serializers.IntegerField(
+ allow_null=True, help_text="Id of the other project. Null when it belongs to another organization."
+ )
+ name = serializers.CharField(
+ allow_null=True, help_text="Name of the other project. Null when it belongs to another organization."
+ )
+
+
+class ReviewHogSettingsErrorSerializer(serializers.Serializer):
+ error = serializers.CharField(help_text="Why the request was rejected.")
+ conflicting_project = ReviewProjectRefSerializer(
+ allow_null=True, help_text="The project that already holds the repository or the installation, if any."
+ )
+
+
+class ReviewRepositoryPersonSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Id of this list entry. Use it to remove the person.")
+ user = UserBasicSerializer(read_only=True, help_text="The project member on the list.")
+ kind = serializers.ChoiceField(
+ choices=ReviewRepositoryPerson.Kind.choices,
+ read_only=True,
+ help_text="Which list: 'listed' (gets Flash when the rule reviews only listed people) or "
+ "'excepted' (skipped when the rule reviews everyone).",
+ )
+
+ class Meta:
+ model = ReviewRepositoryPerson
+ fields = ["id", "user", "kind"]
+
+
+class ReviewRepositoryPersonRequestSerializer(serializers.Serializer):
+ user_id = serializers.IntegerField(help_text="Id of the project member to add. Must be an active member.")
+ kind = serializers.ChoiceField(
+ choices=ReviewRepositoryPerson.Kind.choices,
+ help_text="Which list to add the person to: 'listed' or 'excepted'.",
+ )
+
+
+class AutomaticReviewDecisionSerializer(serializers.Serializer):
+ flash = serializers.BooleanField(
+ help_text="Whether the requesting user's own pull requests get automatic Flash reviews in this repository."
+ )
+ reason = serializers.ChoiceField(
+ choices=AutomaticReviewReason.choices,
+ help_text="Which rule decided: the user's own choice ('own_repository_choice', 'own_default'), the "
+ "repository exception ('repository_*'), the project rule ('project_*'), or 'not_in_project' when this "
+ "project does not review the repository.",
+ )
+
+
+class ReviewRepositorySerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Id of the repository entry.")
+ installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation that sees it.")
+ github_repo_id = serializers.IntegerField(
+ read_only=True, allow_null=True, help_text="GitHub's id of the repository. Null until it is first seen."
+ )
+ full_name = serializers.CharField(read_only=True, help_text="GitHub repository in 'owner/name' form.")
+ selected = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether this project selected the repository. A selected repository belongs to this project "
+ "even when another project takes all repositories of the installation.",
+ )
+ flash_for = serializers.ChoiceField(
+ choices=AutomaticFlashFor.choices,
+ read_only=True,
+ allow_null=True,
+ help_text="The repository exception: 'everyone', 'listed', or 'off' (opt-in only). Null when the "
+ "repository follows the project rule.",
+ )
+ people = serializers.SerializerMethodField(
+ help_text="The people on the exception's two lists. Only the list that matches flash_for has an effect."
+ )
+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who added the repository.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the repository was added.")
+
+ class Meta:
+ model = ReviewRepository
+ fields = [
+ "id",
+ "installation_id",
+ "github_repo_id",
+ "full_name",
+ "selected",
+ "flash_for",
+ "people",
+ "created_by",
+ "created_at",
+ ]
+
+ @extend_schema_field(ReviewRepositoryPersonSerializer(many=True))
+ def get_people(self, instance: ReviewRepository) -> list[dict]:
+ people = self.context.get("people")
+ if people is None:
+ people = load_people(instance.team_id, [instance.id])
+ return [dict(ReviewRepositoryPersonSerializer(person).data) for person in people.get(instance.id, [])]
+
+
+class ReviewRepositoryWriteSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(
+ max_length=64, help_text="The GitHub App installation that sees the repository, from the overview."
+ )
+ full_name = serializers.CharField(
+ max_length=200, help_text="GitHub repository in 'owner/name' form, spelled as GitHub returns it."
+ )
+ github_repo_id = serializers.IntegerField(
+ required=False, min_value=1, help_text="GitHub's id of the repository, from the overview. Keeps renames."
+ )
+ selected = serializers.BooleanField(
+ required=False,
+ help_text="True includes the repository into this project, also when another project takes all "
+ "repositories of the installation. False removes it; with an 'only selected' claim its exception goes too.",
+ )
+ flash_for = serializers.ChoiceField(
+ choices=AutomaticFlashFor.choices,
+ required=False,
+ allow_null=True,
+ help_text="The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository "
+ "follows the project rule again. Omit it to keep the current value.",
+ )
+
+ def validate_full_name(self, value: str) -> str:
+ return validate_full_name(value)
+
+
+class ReviewRepositoryWriteResponseSerializer(serializers.Serializer):
+ repository = ReviewRepositorySerializer(
+ allow_null=True,
+ help_text="The repository entry after the write. Null when nothing is left to store, so the entry was "
+ "deleted and the repository follows the project rule or left the project.",
+ )
+ taken_from_project = ReviewProjectRefSerializer(
+ allow_null=True,
+ help_text="The project that took all repositories of the installation, when this write took the "
+ "repository from it.",
+ )
+
+
+class ReviewInstallationSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(help_text="The GitHub App installation id.")
+ account_name = serializers.CharField(help_text="The GitHub account (organization or user) of the installation.")
+ connected_by = UserBasicSerializer(
+ allow_null=True,
+ help_text="Who connected the installation to this project. Automatic Flash reviews of bot pull requests "
+ "run as this user.",
+ )
+ claim_id = serializers.UUIDField(
+ allow_null=True, help_text="Id of this project's claim. Null when the project reviews nothing there."
+ )
+ scope = serializers.ChoiceField(
+ choices=ReviewInstallationClaim.Scope.choices,
+ allow_null=True,
+ help_text="Which repositories this project reviews: 'all' (every repository no other project selected, "
+ "including future ones), 'selected' (only the selected ones), or null (none).",
+ )
+ all_taken_by_project = ReviewProjectRefSerializer(
+ allow_null=True,
+ help_text="Another project that takes all repositories of the installation, if any.",
+ )
+
+
+def installation_data(summary: InstallationSummary) -> dict[str, Any]:
+ return {
+ "installation_id": summary.installation_id,
+ "account_name": summary.account_name,
+ "connected_by": summary.connected_by,
+ "claim_id": summary.claim.id if summary.claim is not None else None,
+ "scope": summary.claim.scope if summary.claim is not None else None,
+ "all_taken_by_project": project_ref_data(summary.all_taken_by),
+ }
+
+
+class ReviewInstallationClaimSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Id of the claim.")
+ installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation id.")
+ scope = serializers.ChoiceField(
+ choices=ReviewInstallationClaim.Scope.choices,
+ read_only=True,
+ help_text="'all' (every repository no other project selected, including future ones) or 'selected'.",
+ )
+ account_name = serializers.SerializerMethodField(
+ help_text="The GitHub account (organization or user) of the installation."
+ )
+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="Who made the claim.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the claim was made.")
+
+ class Meta:
+ model = ReviewInstallationClaim
+ fields = ["id", "installation_id", "scope", "account_name", "created_by", "created_at"]
+
+ @extend_schema_field(serializers.CharField())
+ def get_account_name(self, instance: ReviewInstallationClaim) -> str:
+ return installation_account_name(instance.installation_id)
+
+
+class ReviewInstallationClaimCreateSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(max_length=64, help_text="The GitHub App installation id.")
+ scope = serializers.ChoiceField(
+ choices=ReviewInstallationClaim.Scope.choices,
+ help_text="'all' reviews every repository of the installation that no other project selected. "
+ "At most one project per installation can choose it. 'selected' reviews only selected repositories.",
+ )
+
+
+class ReviewInstallationClaimUpdateSerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(
+ choices=ReviewInstallationClaim.Scope.choices,
+ help_text="'all' or 'selected'. Switching to 'selected' removes the exceptions of the repositories that "
+ "leave the project.",
+ )
+
+
+class ReviewRepositoryChoiceSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Id of the choice. Use it to clear the choice.")
+ installation_id = serializers.CharField(read_only=True, help_text="The GitHub App installation.")
+ github_repo_id = serializers.IntegerField(read_only=True, allow_null=True, help_text="GitHub's repository id.")
+ full_name = serializers.CharField(read_only=True, help_text="GitHub repository in 'owner/name' form.")
+ mode = serializers.ChoiceField(
+ choices=ReviewUserRepositoryChoice.Mode.choices,
+ read_only=True,
+ help_text="'flash' or 'off' for the user's own pull requests in this repository.",
+ )
+
+ class Meta:
+ model = ReviewUserRepositoryChoice
+ fields = ["id", "installation_id", "github_repo_id", "full_name", "mode"]
+
+
+class ReviewRepositoryChoiceWriteSerializer(serializers.Serializer):
+ installation_id = serializers.CharField(max_length=64, help_text="The GitHub App installation.")
+ full_name = serializers.CharField(max_length=200, help_text="GitHub repository in 'owner/name' form.")
+ github_repo_id = serializers.IntegerField(required=False, min_value=1, help_text="GitHub's repository id.")
+ mode = serializers.ChoiceField(
+ choices=ReviewUserRepositoryChoice.Mode.choices,
+ help_text="The requesting user's own automatic review for their pull requests in this repository: "
+ "'flash' or 'off'. A value equal to what the user inherits clears the choice instead.",
+ )
+
+ def validate_full_name(self, value: str) -> str:
+ return validate_full_name(value)
+
+
+class ReviewRepositoryChoiceWriteResponseSerializer(serializers.Serializer):
+ choice = ReviewRepositoryChoiceSerializer(
+ allow_null=True, help_text="The stored choice. Null when the value equals the inherited one."
+ )
+ my_result = AutomaticReviewDecisionSerializer(
+ help_text="What the requesting user's own pull requests get in this repository after the write."
+ )
+
+
+class ReviewHogProjectViewSetMixin(TeamAndOrgViewSetMixin):
+ """Shared plumbing for the project-wide settings viewsets: the root project and the acting user."""
+
+ @property
+ def effective_team_id(self) -> int:
+ return resolve_effective_team_id(self.team_id)
+
+ @property
+ def effective_team(self) -> Team:
+ team_id = self.effective_team_id
+ return self.team if self.team.id == team_id else Team.objects.get(id=team_id)
+
+ def is_effective_team_admin(self) -> bool:
+ level = self.user_permissions.team(self.effective_team).effective_membership_level
+ return level is not None and level >= OrganizationMembership.Level.ADMIN
+
+ def project_repositories(self) -> ProjectRepositories:
+ return ProjectRepositories(self.effective_team, cast(User, self.request.user))
+
+
+class EffectiveTeamStrictManagementPermission(BasePermission):
+ """Members read, admins write, both checked on the root project that the writes change.
+
+ An environment URL resolves to its parent project, and a user can be admin of the environment
+ but only a member of the parent.
+ """
+
+ message = "You don't have sufficient permissions in the project."
+
+ def has_permission(self, request: Request, view: Any) -> bool:
+ if not isinstance(view, ReviewHogProjectViewSetMixin):
+ return False
+ if request.method in SAFE_METHODS:
+ return view.user_permissions.team(view.effective_team).effective_membership_level is not None
+ return view.is_effective_team_admin()
+
+
+# `list` keeps the inherited method, because overriding it marks the viewset as a custom list for
+# the pagination contract check. Its schema comes from the serializer and the class docstring.
+@extend_schema_view(
+ destroy=extend_schema(
+ summary="Remove a repository's settings",
+ description="Remove the repository from this project and clear its exception and lists. With an 'all "
+ "repositories' claim the repository stays in the project and follows the project rule.",
+ ),
+)
+class ReviewRepositoryViewSet(
+ ReviewHogProjectViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ """The repositories this project has settings for: selected repositories and repository exceptions.
+
+ Project members can read them. Only project admins can change them, and every change goes to the
+ activity log. A repository has settings in one project at most.
+ """
+
+ scope_object = "review_hog"
+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
+ posthog_feature_flag = "review-hog"
+ # Unscoped only to satisfy the router/introspection; `safely_get_queryset` scopes every read.
+ queryset = ReviewRepository.objects.unscoped()
+ serializer_class = ReviewRepositorySerializer
+ pagination_class = None
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return (
+ ReviewRepository.objects.for_team(self.effective_team_id, canonical=True)
+ .select_related("created_by")
+ .order_by("created_at")
+ )
+
+ def get_serializer_context(self) -> dict:
+ context = super().get_serializer_context()
+ team_id = self.effective_team_id
+ repository_ids = ReviewRepository.objects.for_team(team_id, canonical=True).values_list("id", flat=True)
+ context["people"] = load_people(team_id, repository_ids)
+ return context
+
+ def _repository_response(self, repository: ReviewRepository, response_status: int = status.HTTP_200_OK) -> Response:
+ return Response(self.get_serializer(repository).data, status=response_status)
+
+ @extend_schema(
+ request=ReviewRepositoryWriteSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewRepositoryWriteResponseSerializer, description="The saved settings."),
+ 400: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="The rules forbid the write."),
+ 409: OpenApiResponse(
+ response=ReviewHogSettingsErrorSerializer,
+ description="Another project already has settings for the repository.",
+ ),
+ },
+ summary="Save a repository's settings",
+ description="Include a repository into this project, remove it, or set or clear its exception. Only the "
+ "provided fields change. Including a repository that another project's 'all repositories' claim covers "
+ "takes it from that project; the response names it.",
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = ReviewRepositoryWriteSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ ref = RepositoryRef(
+ installation_id=data["installation_id"],
+ github_repo_id=data.get("github_repo_id"),
+ full_name=data["full_name"],
+ )
+ flash_for: str | None | Unset = data["flash_for"] if "flash_for" in data else UNSET
+ try:
+ result = self.project_repositories().save_repository(
+ ref, selected=data.get("selected"), flash_for=flash_for
+ )
+ except OwnershipConflict as error:
+ return conflict_response(error)
+ except RepositorySettingsError as error:
+ return bad_request_response(error)
+ response = ReviewRepositoryWriteResponseSerializer(
+ {"repository": result.repository, "taken_from_project": project_ref_data(result.taken_from)},
+ context=self.get_serializer_context(),
+ )
+ return Response(response.data)
+
+ @extend_schema(
+ request=ReviewRepositoryPersonRequestSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was already on it."),
+ 201: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was added."),
+ 400: OpenApiResponse(description="The user is not an active member of this project's organization."),
+ },
+ summary="Add a person to a repository exception list",
+ description="Add a project member to the 'listed' or 'excepted' list of the repository exception.",
+ )
+ @action(detail=True, methods=["POST"], url_path="people", required_scopes=["review_hog:write"])
+ def add_person(self, request: Request, **kwargs: Any) -> Response:
+ repository = self.get_object()
+ serializer = ReviewRepositoryPersonRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ user_id: int = serializer.validated_data["user_id"]
+ check_active_member(self.team, user_id)
+ created = self.project_repositories().add_person(
+ repository, user_id=user_id, kind=serializer.validated_data["kind"]
+ )
+ return self._repository_response(repository, status.HTTP_201_CREATED if created else status.HTTP_200_OK)
+
+ @extend_schema(
+ parameters=[OpenApiParameter("person_id", str, OpenApiParameter.PATH, description="Id of the list entry.")],
+ responses={
+ 200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was removed."),
+ 404: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="No such list entry."),
+ },
+ summary="Remove a person from a repository exception list",
+ description="Remove one entry from the 'listed' or 'excepted' list of the repository exception.",
+ )
+ @action(
+ detail=True,
+ methods=["DELETE"],
+ url_path=rf"people/(?P<person_id>{UUID_PATH_PATTERN})",
+ required_scopes=["review_hog:write"],
+ )
+ def remove_person(self, request: Request, person_id: str, **kwargs: Any) -> Response:
+ repository = self.get_object()
+ person = (
+ ReviewRepositoryPerson.objects.for_team(repository.team_id, canonical=True)
+ .filter(repository=repository, id=person_id)
+ .first()
+ )
+ if person is None:
+ return Response(
+ {"error": "No such list entry.", "conflicting_project": None}, status=status.HTTP_404_NOT_FOUND
+ )
+ person.delete()
+ return self._repository_response(repository)
+
+
+class ReviewInstallationClaimViewSet(
+ ReviewHogProjectViewSetMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ """Which repositories of each connected GitHub installation this project reviews.
+
+ Project members can read the claims. Only project admins can change them, and every change goes
+ to the activity log. The project settings response lists every connected installation, also the
+ ones without a claim.
+ """
+
+ scope_object = "review_hog"
+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
+ posthog_feature_flag = "review-hog"
+ queryset = ReviewInstallationClaim.objects.unscoped()
+ serializer_class = ReviewInstallationClaimSerializer
+ pagination_class = None
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return (
+ ReviewInstallationClaim.objects.for_team(self.effective_team_id, canonical=True)
+ .select_related("created_by")
+ .order_by("created_at")
+ )
+
+ @extend_schema(
+ request=ReviewInstallationClaimCreateSerializer,
+ responses={
+ 201: OpenApiResponse(response=ReviewInstallationClaimSerializer, description="The claim was saved."),
+ 400: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="The rules forbid it."),
+ 409: OpenApiResponse(
+ response=ReviewHogSettingsErrorSerializer,
+ description="Another project already takes all repositories of the installation.",
+ ),
+ },
+ summary="Claim a GitHub installation",
+ description="Choose which repositories of a connected GitHub installation this project reviews.",
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = ReviewInstallationClaimCreateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ claim = self.project_repositories().create_claim(
+ serializer.validated_data["installation_id"], serializer.validated_data["scope"]
+ )
+ except OwnershipConflict as error:
+ return conflict_response(error)
+ except RepositorySettingsError as error:
+ return bad_request_response(error)
+ return Response(self.get_serializer(claim).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(
+ request=ReviewInstallationClaimUpdateSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewInstallationClaimSerializer, description="The claim was changed."),
+ 409: OpenApiResponse(
+ response=ReviewHogSettingsErrorSerializer,
+ description="Another project already takes all repositories of the installation.",
+ ),
+ },
+ summary="Change a GitHub installation claim",
+ description="Switch between all repositories and only selected repositories. Switching to selected "
+ "removes the exceptions of the repositories that leave this project. Personal choices stay.",
+ )
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ claim = self.get_object()
+ serializer = ReviewInstallationClaimUpdateSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ claim = self.project_repositories().update_claim(claim, serializer.validated_data["scope"])
+ except OwnershipConflict as error:
+ return conflict_response(error)
+ return Response(self.get_serializer(claim).data)
+
+ @extend_schema(
+ responses={
+ 204: OpenApiResponse(description="The claim and this project's repository settings there are gone.")
+ },
+ summary="Stop reviewing a GitHub installation",
+ description="Remove the claim, so this project reviews no repository of the installation. Its selected "
+ "repositories and exceptions there are removed too. Personal choices stay.",
+ )
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ self.project_repositories().delete_claim(self.get_object())
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+@extend_schema_view(
+ destroy=extend_schema(
+ summary="Clear my choice for a repository",
+ description="Clear the requesting user's own choice for one repository, so their default applies again.",
+ ),
+)
+class ReviewRepositoryChoiceViewSet(
+ ReviewHogProjectViewSetMixin,
+ mixins.ListModelMixin,
+ mixins.DestroyModelMixin,
+ viewsets.GenericViewSet,
+):
+ """The requesting user's own automatic review choices for repositories of this project.
+
+ Any project member can manage their own choices. A choice stores only what differs from what the
+ user inherits, so picking the inherited value clears it.
+ """
+
+ scope_object = "review_hog"
+ permission_classes = [PostHogFeatureFlagPermission]
+ posthog_feature_flag = "review-hog"
+ queryset = ReviewUserRepositoryChoice.objects.unscoped()
+ serializer_class = ReviewRepositoryChoiceSerializer
+ pagination_class = None
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return (
+ ReviewUserRepositoryChoice.objects.for_team(self.effective_team_id, canonical=True)
+ .filter(user_id=cast(User, self.request.user).id)
+ .order_by("full_name")
+ )
+
+ @extend_schema(
+ request=ReviewRepositoryChoiceWriteSerializer,
+ responses={
+ 200: OpenApiResponse(response=ReviewRepositoryChoiceWriteResponseSerializer, description="Saved."),
+ 400: OpenApiResponse(
+ response=ReviewHogSettingsErrorSerializer, description="This project does not review the repository."
+ ),
+ },
+ summary="Set my choice for a repository",
+ description="Set the requesting user's own automatic review for their pull requests in one repository. "
+ "It wins over their default and over the repository and project rules.",
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = ReviewRepositoryChoiceWriteSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ ref = RepositoryRef(
+ installation_id=data["installation_id"],
+ github_repo_id=data.get("github_repo_id"),
+ full_name=data["full_name"],
+ )
+ try:
+ choice, decision = RepositoryChoices(self.effective_team, cast(User, request.user)).save(ref, data["mode"])
+ except RepositorySettingsError as error:
+ return bad_request_response(error)
+ response = ReviewRepositoryChoiceWriteResponseSerializer(
+ {"choice": choice, "my_result": decision_data(decision)}
+ )
+ return Response(response.data)
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index f77045c8ed6e..4a7ec7eed404 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -2,6 +2,7 @@ import uuid
import logging
from typing import Any, cast, get_args
+from django.db import models
from django.db.models import Max, Q, QuerySet
from django.utils import timezone
@@ -29,6 +30,7 @@ from products.review_hog.backend.requested_reviews import (
PRReviewRequestStatus,
request_pr_review,
)
+from products.review_hog.backend.review_request_rules import ReviewRequestRefusal
from products.review_hog.backend.reviewer.artefact_content import (
ReviewIssueCategory,
ReviewIssueFinding,
@@ -246,9 +248,19 @@ _TRIGGER_REFUSAL_STATUS = {
PRReviewRequestStatus.INVALID: status.HTTP_400_BAD_REQUEST,
PRReviewRequestStatus.NOT_ALLOWED: status.HTTP_403_FORBIDDEN,
PRReviewRequestStatus.BUSY: status.HTTP_409_CONFLICT,
+ PRReviewRequestStatus.REFUSED: status.HTTP_409_CONFLICT,
}
+# Values come from `requested_reviews`, so the API and the comment trigger name the same modes. A
+# class (not an inline list) pins the generated enum name.
+class ReviewTriggerRequestRunMode(models.TextChoices):
+ REVIEW = RUN_MODE_REVIEW, "Review"
+ REVIEW_ONLY = RUN_MODE_REVIEW_ONLY, "Review only"
+ RESOLVE_ONLY = RUN_MODE_RESOLVE_ONLY, "Resolve only"
+ FLASH = RUN_MODE_FLASH, "Flash"
+
+
class ReviewTriggerRequestSerializer(serializers.Serializer):
pr_url = serializers.CharField(
help_text="GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. "
@@ -256,14 +268,15 @@ class ReviewTriggerRequestSerializer(serializers.Serializer):
)
run_mode = serializers.ChoiceField(
required=False,
- default=RUN_MODE_REVIEW,
- choices=[RUN_MODE_REVIEW, RUN_MODE_REVIEW_ONLY, RUN_MODE_RESOLVE_ONLY, RUN_MODE_FLASH],
- help_text="What to run on the pull request. 'review' (default) reviews it and, when the "
- "requesting user's resolve_comments setting is on, chains the resolution stage; "
- "'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips "
- "the review and only runs the resolution stage on the PR's existing unresolved review "
- "threads; 'flash' uses a lower-cost model for the review passes and validation, and never "
- "resolves comments.",
+ default=ReviewTriggerRequestRunMode.REVIEW,
+ choices=ReviewTriggerRequestRunMode.choices,
+ help_text="What to run on the pull request. 'review' (default) reviews it and, when the pull "
+ "request owner's resolve_comments setting is on, chains the resolution stage; 'review_only' "
+ "reviews without resolving regardless of that setting; 'resolve_only' skips the review and only "
+ "runs the resolution stage on the PR's existing unresolved review threads, which needs the owner's "
+ "opt-in; 'flash' uses a lower-cost model for the review passes and validation, never resolves "
+ "comments, and is refused once the PR has a published Full review. The owner is the PR's author, "
+ "or the Inbox reviewer of a pull request the PostHog app opened.",
)
@@ -281,6 +294,14 @@ class ReviewTriggerResponseSerializer(serializers.Serializer):
class ReviewTriggerErrorSerializer(serializers.Serializer):
error = serializers.CharField(help_text="Human-readable explanation of why the trigger was rejected.")
+ code = serializers.ChoiceField(
+ required=False,
+ choices=ReviewRequestRefusal.choices,
+ help_text="Why the request was refused, for a client that shows its own reason: 'flash_after_full' "
+ "(the PR already has a published Full review), 'resolution_not_opted_in' (the PR owner has not "
+ "turned on resolving comments), 'internal_feature' (the run mode is not available in this project). "
+ "Absent for other errors.",
+ )
class ReviewFindingLineRangeSerializer(serializers.Serializer):
@@ -686,23 +707,26 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
),
403: OpenApiResponse(
response=ReviewTriggerErrorSerializer,
- description="The review-hog feature flag is off for this project, or Flash was requested in a "
- "project without internal features (see show_internal_features in the settings response).",
+ description="The review-hog feature flag is off for this project, or Flash or resolve-only was "
+ "requested in a project without the review-hog-internal flag (code 'internal_feature').",
),
409: OpenApiResponse(
response=ReviewTriggerErrorSerializer,
description="The pull request's cycle is busy (busy-guard): reviews are blocked while its "
- "comments are being resolved, and resolve-only runs are blocked while a review is running.",
+ "comments are being resolved, and resolve-only runs are blocked while a review is running. "
+ "Also returned with a code when Flash follows a published Full review ('flash_after_full') "
+ "or the PR owner has not opted in to resolution ('resolution_not_opted_in').",
),
429: OpenApiResponse(description="GitHub rate-limited the App's token; retry after the Retry-After delay."),
},
summary="Start a review of a pull request",
description="Start a ReviewHog review of any pull request the project's GitHub App installation can "
"access, and publish it back to the PR. The requesting user is the review's acting user: their "
- "enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria "
- "drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review "
- "(which chains the resolution stage per the user's resolve_comments setting), a review without "
- "resolving, resolution only, or a lower-cost Flash review that never resolves comments. "
+ "enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it "
+ "appears under their recent reviews. Resolution writes to the branch only when the pull request "
+ "owner opted in, whoever asks. `run_mode` picks the variant: a review (which chains the resolution "
+ "stage per the owner's resolve_comments setting), a review without resolving, resolution only, or a "
+ "lower-cost Flash review that never resolves comments and is refused after a published Full review. "
"Nonexistent, closed, and fork PRs are rejected synchronously; "
"a PR whose current commit already has a published review returns 'already_reviewed' without "
"starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole "
@@ -737,7 +761,12 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
except GitHubRateLimitError as e:
return github_rate_limited_response(e)
if outcome.error:
- return Response({"error": outcome.error}, status=_TRIGGER_REFUSAL_STATUS[outcome.status])
+ return Response(
+ ReviewTriggerErrorSerializer({"error": outcome.error, "code": outcome.refusal}).data
+ if outcome.refusal
+ else {"error": outcome.error},
+ status=_TRIGGER_REFUSAL_STATUS[outcome.status],
+ )
return Response(
ReviewTriggerResponseSerializer({"workflow_id": outcome.workflow_id, "status": outcome.status.value}).data,
status=status.HTTP_200_OK
diff --git a/products/review_hog/backend/api/settings.py b/products/review_hog/backend/api/settings.py
index 50fb0b041f08..259390a86487 100644
--- a/products/review_hog/backend/api/settings.py
+++ b/products/review_hog/backend/api/settings.py
@@ -1,4 +1,7 @@
import logging
+from typing import cast
+
+from django.db import transaction
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import serializers, viewsets
@@ -8,71 +11,98 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
from products.review_hog.backend.internal_features import has_internal_features
-from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.models import ReviewProjectSettings, ReviewUserSettings
+from products.review_hog.backend.preferences import (
+ PREFERENCE_KEYS,
+ DefaultReviewMode,
+ PreferenceSource,
+ ReviewPreferences,
+ UrgencyThreshold,
+)
from products.review_hog.backend.reviewer.lazy_seed import seed_canonicals_tolerantly, sync_canonical_authoring
from products.stamphog.backend.facade.api import has_reviewable_repo_config
logger = logging.getLogger(__name__)
-class ReviewUserSettingsSerializer(serializers.ModelSerializer):
- review_inbox_prs = serializers.BooleanField(
- required=False,
- help_text="Automatically review pull requests opened by self-driving implementations from the "
- "user's Inbox: ReviewHog reviews each one and posts its findings to the pull request.",
+def _source_field(key: str) -> serializers.ChoiceField:
+ return serializers.ChoiceField(
+ choices=PreferenceSource.choices,
+ help_text=f"Where the effective {key} comes from: 'user' (the user set it), 'project' (the project "
+ "default), or 'default' (the built-in default).",
)
- stamphog_review_inbox_prs = serializers.BooleanField(
- required=False,
- help_text="Also have hosted Stamphog review those same Inbox pull requests: an approve-first "
- "review that posts a real GitHub approval when the change passes, and a comment when it "
- "doesn't. Only takes effect when the project has a synced, enabled Stamphog repository "
- "(see stamphog_connected).",
+
+
+class ReviewPreferenceSourcesSerializer(serializers.Serializer):
+ default_review_mode = _source_field("default_review_mode")
+ resolve_comments = _source_field("resolve_comments")
+ urgency_threshold = _source_field("urgency_threshold")
+ celebrate_clean_reviews = _source_field("celebrate_clean_reviews")
+ review_inbox_prs = _source_field("review_inbox_prs")
+ stamphog_review_inbox_prs = _source_field("stamphog_review_inbox_prs")
+
+
+class ReviewProjectDefaultsSerializer(serializers.Serializer):
+ urgency_threshold = serializers.ChoiceField(
+ choices=UrgencyThreshold.choices,
+ help_text="The project's default for the minimum priority a Full review publishes.",
)
- review_labeled_prs = serializers.BooleanField(
+ celebrate_clean_reviews = serializers.BooleanField(
+ help_text="The project's default for the image in a Full review that finds nothing to raise.",
+ )
+
+
+class ReviewUserSettingsSerializer(serializers.Serializer):
+ default_review_mode = serializers.ChoiceField(
required=False,
- help_text="Review the user's pull requests when the trigger label is added on GitHub. "
- "On by default; turning it off makes the label trigger skip PRs this user authored.",
+ choices=DefaultReviewMode.choices,
+ help_text="Automatic reviews of the user's own pull requests in every repository this project reviews: "
+ "'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' "
+ "turns automatic Flash off everywhere. A choice for one repository wins over this default.",
)
resolve_comments = serializers.BooleanField(
required=False,
- help_text="After a review of the user's pull requests is published, run the resolution stage: "
- "triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR "
- "branch, and reply on every thread. On by default; turning it off makes reviews stop at "
- "publishing.",
+ help_text="After a Full review of the user's pull requests is published, run the resolution stage: "
+ "triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and "
+ "reply on every thread. Off by default. Personal only: no project default applies.",
)
- celebrate_clean_reviews = serializers.BooleanField(
+ urgency_threshold = serializers.ChoiceField(
required=False,
- help_text="Show a fun image in the review comment when a review of this user's pull requests "
- "finds nothing to raise. On by default; turning it off makes clean reviews end with the "
- "text summary only.",
+ choices=UrgencyThreshold.choices,
+ help_text="Minimum priority a validated Full review finding needs to be published: 'consider' "
+ "publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only "
+ "blocking issues. Without the user's own value the project default applies.",
)
- review_authored_prs = serializers.BooleanField(
+ celebrate_clean_reviews = serializers.BooleanField(
required=False,
- help_text="Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. "
- "Off by default. Flash reviews post findings without resolving comments.",
+ help_text="Show a fun image in the review comment when a Full review of the user's pull requests "
+ "finds nothing to raise. Without the user's own value the project default applies.",
)
- flash_reasoning_effort = serializers.ChoiceField(
+ review_inbox_prs = serializers.BooleanField(
required=False,
- choices=ReviewUserSettings.FlashReasoningEffort.choices,
- help_text="Reasoning effort for this user's automatic and manually requested Flash reviews: "
- "'medium' (default) or 'xhigh'. Applies to both review and validation. "
- "Saved independently of the automatic-review toggle.",
+ help_text="Review the pull requests the agent opens for Inbox reports assigned to the user: "
+ "ReviewHog reviews each one and posts its findings to the pull request. Off by default.",
)
- urgency_threshold = serializers.ChoiceField(
+ stamphog_review_inbox_prs = serializers.BooleanField(
required=False,
- choices=ReviewUserSettings.UrgencyThreshold.choices,
- help_text="Minimum priority a validated finding needs to be published: 'consider' (default) "
- "publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only "
- "blocking issues.",
+ help_text="Also have hosted Stamphog review those same Inbox pull requests: an approve-first "
+ "review that posts a real GitHub approval when the change passes, and a comment when it "
+ "doesn't. Only takes effect when the project has a synced, enabled Stamphog repository "
+ "(see stamphog_connected).",
)
- can_trigger_reviews = serializers.SerializerMethodField(
- help_text="Whether reviews can be started from this project's Code review page.",
+ sources = ReviewPreferenceSourcesSerializer(
+ read_only=True,
+ help_text="Where each effective value comes from. A value equal to the inherited one is never "
+ "stored, so writing the project default or the built-in default makes the source follow it again.",
)
- show_internal_features = serializers.SerializerMethodField(
- help_text="Whether to show Flash mode and settings for automatic, label-triggered, and Inbox reviews.",
+ project_defaults = ReviewProjectDefaultsSerializer(
+ read_only=True,
+ source="project",
+ help_text="The project defaults the Full review preferences fall back to.",
)
stamphog_connected = serializers.SerializerMethodField(
help_text="Whether this project has at least one synced, enabled Stamphog repository. When "
@@ -80,49 +110,28 @@ class ReviewUserSettingsSerializer(serializers.ModelSerializer):
"disabled with a pointer to connect the Stamphog GitHub App.",
)
- class Meta:
- model = ReviewUserSettings
- fields = [
- "review_inbox_prs",
- "stamphog_review_inbox_prs",
- "review_labeled_prs",
- "resolve_comments",
- "celebrate_clean_reviews",
- "review_authored_prs",
- "flash_reasoning_effort",
- "urgency_threshold",
- "can_trigger_reviews",
- "show_internal_features",
- "stamphog_connected",
- ]
+ def _team_id(self) -> int:
+ return self.context["team_id"]
@extend_schema_field(serializers.BooleanField())
- def get_can_trigger_reviews(self, instance: ReviewUserSettings) -> bool:
- return True
-
- @extend_schema_field(serializers.BooleanField())
- def get_show_internal_features(self, instance: ReviewUserSettings) -> bool:
- return has_internal_features(instance.team_id)
-
- @extend_schema_field(serializers.BooleanField())
- def get_stamphog_connected(self, instance: ReviewUserSettings) -> bool:
- if not self.get_show_internal_features(instance):
+ def get_stamphog_connected(self, instance: ReviewPreferences) -> bool:
+ if not has_internal_features(self._team_id()):
return False
# This reads the stamphog product DB, which can fail fast on its own circuit breaker. An
# informational UI flag must not fail the settings endpoint, so fall back to False.
try:
- return has_reviewable_repo_config(instance.team_id)
+ return has_reviewable_repo_config(self._team_id())
except Exception:
logger.exception("review_hog_stamphog_connected_check_failed")
return False
class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- """The requesting user's ReviewHog settings for a project (one row, created on first read).
+ """The requesting user's ReviewHog preferences for a project.
Sibling of the perspective/validator/blind-spots config viewsets: skills control *how* a review
- runs, this controls *what gets reviewed* (trigger opt-outs) and *how strict publishing is*
- (urgency threshold). Per-user like the skill configs — the workflow reads the PR author's row.
+ runs, these preferences control *what gets reviewed* and *how strict publishing is*. Only the
+ values the user changed are stored; the response gives the effective values and their source.
Every row is self-scoped, and the review-hog feature flag controls project access.
"""
@@ -133,25 +142,35 @@ class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
queryset = ReviewUserSettings.objects.unscoped()
serializer_class = ReviewUserSettingsSerializer
- def _get_or_create(self, request: Request) -> ReviewUserSettings:
+ def _user_id(self) -> int:
+ return cast(User, self.request.user).id
+
+ def _save_changes(self, team_id: int, changes: dict) -> ReviewPreferences:
# Resolve a raw environment URL id to its root team once: `for_team` canonicalizes its filter
# but not the create kwargs, and mismatched ids mean a never-matching get plus 500s on re-read.
- team_id = resolve_effective_team_id(self.team_id)
- instance, _created = ReviewUserSettings.objects.for_team(team_id, canonical=True).get_or_create(
- team_id=team_id, user_id=request.user.id
- )
- return instance
+ rows = ReviewUserSettings.objects.for_team(team_id, canonical=True)
+ with transaction.atomic():
+ row, _created = rows.get_or_create(team_id=team_id, user_id=self._user_id())
+ # The lock keeps two concurrent edits of different keys from losing one of them.
+ row = rows.select_for_update().get(id=row.id)
+ current = ReviewPreferences.resolve(row.preferences, ReviewProjectSettings.load(team_id).defaults)
+ row.preferences = current.with_changes(changes)
+ row.save(update_fields=["preferences", "updated_at"])
+ return ReviewUserSettings.load_preferences(team_id, self._user_id())
+
+ def _response(self, team_id: int, preferences: ReviewPreferences) -> Response:
+ return Response(ReviewUserSettingsSerializer(preferences, context={"team_id": team_id}).data)
@extend_schema(
methods=["GET"],
responses={
200: OpenApiResponse(
- response=ReviewUserSettingsSerializer, description="The requesting user's ReviewHog settings."
+ response=ReviewUserSettingsSerializer, description="The requesting user's ReviewHog preferences."
),
},
summary="Get the user's ReviewHog settings",
- description="Fetch the requesting user's ReviewHog settings for this project, creating the row "
- "with defaults on first read.",
+ description="Fetch the requesting user's effective ReviewHog preferences for this project, and where "
+ "each value comes from.",
)
@extend_schema(
methods=["PATCH"],
@@ -161,21 +180,23 @@ class ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
400: OpenApiResponse(description="Invalid field value (e.g. unknown urgency threshold)."),
},
summary="Update the user's ReviewHog settings",
- description="Partially update the requesting user's ReviewHog settings for this project. Only the "
- "provided fields change.",
+ description="Partially update the requesting user's ReviewHog preferences for this project. Only the "
+ "provided fields change. A value equal to the inherited one clears the user's own value.",
)
# Not named `settings` — that would shadow DRF's `APIView.settings` (its APISettings object).
@action(detail=False, methods=["GET", "PATCH"], url_path="settings", url_name="settings")
def user_settings(self, request: Request, **kwargs) -> Response:
- instance = self._get_or_create(request)
+ team_id = resolve_effective_team_id(self.team_id)
if request.method == "PATCH":
- serializer = ReviewUserSettingsSerializer(instance, data=request.data, partial=True)
+ serializer = ReviewUserSettingsSerializer(data=request.data, partial=True, context={"team_id": team_id})
serializer.is_valid(raise_exception=True)
- serializer.save()
- return Response(serializer.data)
+ changes = {
+ key: serializer.validated_data[key] for key in PREFERENCE_KEYS if key in serializer.validated_data
+ }
+ return self._response(team_id, self._save_changes(team_id, changes))
# Seed the authoring companion before any review has run: the "Create your own …" tasks
# `skill-get` it over MCP, and this settings GET is the Code review tab's always-called
- # endpoint. `instance.team_id` is already the effective (root) team — the same team the
- # review runs under, so the skill lands where the sandbox agent's `skill-get` will look.
- seed_canonicals_tolerantly(instance.team_id, sync_canonical_authoring)
- return Response(ReviewUserSettingsSerializer(instance).data)
+ # endpoint. `team_id` is already the effective (root) team, the same team the review runs
+ # under, so the skill lands where the sandbox agent's `skill-get` will look.
+ seed_canonicals_tolerantly(team_id, sync_canonical_authoring)
+ return self._response(team_id, ReviewUserSettings.load_preferences(team_id, self._user_id()))
diff --git a/products/review_hog/backend/api/trigger.py b/products/review_hog/backend/api/trigger.py
deleted file mode 100644
index 8a4df893a4c8..000000000000
--- a/products/review_hog/backend/api/trigger.py
+++ /dev/null
@@ -1,310 +0,0 @@
-import hmac
-import logging
-
-from django.conf import settings
-
-from drf_spectacular.utils import OpenApiResponse, extend_schema
-from rest_framework import serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.models.integration import Integration
-from posthog.models.organization import OrganizationMembership
-from posthog.models.team import Team
-
-from products.review_hog.backend.reviewer.persistence import lift_review_tier_for_joined_trigger
-from products.review_hog.backend.temporal.client import (
- start_resolution_workflow,
- start_review_pr_workflow,
- workflow_running,
-)
-from products.review_hog.backend.temporal.types import TRIGGER_LABEL, resolve_pr_workflow_id, review_pr_workflow_id
-
-logger = logging.getLogger(__name__)
-
-ALLOWED_REPOS = {"posthog/posthog", "posthog/ai-gateway"}
-
-
-class ReviewHogTriggerRequestSerializer(serializers.Serializer):
- repo = serializers.CharField(
- help_text="GitHub repository to review, in 'owner/name' form; must be on the allowlist (e.g. 'PostHog/posthog').",
- )
- pr_number = serializers.IntegerField(
- min_value=1,
- help_text="Pull request number to review.",
- )
- publish = serializers.BooleanField(
- required=False,
- default=True,
- help_text="Whether to post the review back to the PR. Defaults true (the label trigger publishes).",
- )
-
-
-class ReviewHogResolveRequestSerializer(serializers.Serializer):
- repo = serializers.CharField(
- help_text="GitHub repository, in 'owner/name' form; must be on the allowlist (e.g. 'PostHog/posthog').",
- )
- pr_number = serializers.IntegerField(
- min_value=1,
- help_text="Pull request whose unresolved review threads to settle.",
- )
-
-
-class ReviewHogTriggerResponseSerializer(serializers.Serializer):
- workflow_id = serializers.CharField(help_text="Temporal workflow id for the started review run.")
- status = serializers.CharField(
- help_text="Run lifecycle marker: 'started' when the review was queued, 'joined_running_review' when a "
- "review of this pull request was already in flight. A requested Full review waits for an active Flash review."
- )
-
-
-class ReviewHogTriggerErrorSerializer(serializers.Serializer):
- error = serializers.CharField(help_text="Human-readable explanation of why the trigger was rejected.")
-
-
-def _bearer_token(request: Request) -> str:
- """Extract the bearer token from the Authorization header (accepts a bare token too)."""
- auth = request.headers.get("Authorization", "")
- if auth.startswith("Bearer "):
- return auth[len("Bearer ") :].strip()
- return auth.strip()
-
-
-def _resolve_run_user_id(team_id: int) -> int | None:
- """The user the sandbox tasks run as: the GitHub integration creator if still an active org
- member, else the oldest active org member (same semantics as signals' resolve_user_id_for_team).
-
- A disabled run user is worse than none: every user-scoped sandbox credential 403s and the agent
- hangs silently until the poll budget expires, so never return an inactive user here.
- """
- team = Team.objects.select_related("organization").get(id=team_id)
- integration = Integration.objects.filter(team_id=team_id, kind="github").order_by("id").first()
- if integration is not None and integration.created_by_id:
- creator_is_active = OrganizationMembership.objects.filter(
- organization=team.organization,
- user_id=integration.created_by_id,
- user__is_active=True,
- ).exists()
- if creator_is_active:
- return integration.created_by_id
- logger.warning(
- "ReviewHog run-user fallback: integration creator %s is not an active org member",
- integration.created_by_id,
- )
- membership = (
- OrganizationMembership.objects.select_related("user")
- .filter(organization=team.organization, user__is_active=True)
- .order_by("id")
- .first()
- )
- return membership.user_id if membership else None
-
-
-class ReviewHogTriggerViewSet(viewsets.ViewSet):
- """Shared-secret-gated triggers that start ReviewHog runs for a PR: `trigger` (a review, which
- can chain the resolution stage) and `resolve` (a standalone resolution run).
-
- Unscoped (no team in the URL): the team and run user are resolved server-side from settings, and CI
- authenticates with the `REVIEWHOG_TRIGGER_TOKEN` shared secret — no session or API key. The first
- client is the `reviewhog` label GitHub Action, but the endpoint is the durable reusable interface.
- """
-
- authentication_classes = ()
- permission_classes = ()
-
- def _authenticate(self, request: Request) -> Response | None:
- """Return an error Response if the shared-secret check fails, else None."""
- expected = settings.REVIEWHOG_TRIGGER_TOKEN
- if not expected:
- # Fail closed in real deployments; allow locally so the endpoint is testable without a secret.
- if settings.DEBUG or settings.TEST:
- return None
- return Response(
- {"error": "ReviewHog trigger token is not configured"},
- status=status.HTTP_403_FORBIDDEN,
- )
- if not hmac.compare_digest(_bearer_token(request), expected):
- return Response({"error": "Invalid trigger token"}, status=status.HTTP_403_FORBIDDEN)
- return None
-
- def _run_gates(self, repo: str) -> tuple[int, int] | Response:
- """The shared trigger gates: repo allowlist → configured team → authorized run user.
-
- Returns `(team_id, user_id)` when every gate passes, else the error `Response` to return.
- (Shared-secret auth runs before body validation in each action, so it is not part of this.)
- """
- if repo.lower() not in ALLOWED_REPOS:
- return Response({"error": f"Repository {repo} is not allowed"}, status=status.HTTP_403_FORBIDDEN)
-
- # First configured team = the one label-triggered runs execute and publish under.
- team_id = settings.REVIEWHOG_TEAM_IDS[0] if settings.REVIEWHOG_TEAM_IDS else None
- if not team_id:
- return Response({"error": "ReviewHog team is not configured"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
-
- user_id = settings.REVIEWHOG_RUN_USER_ID or _resolve_run_user_id(team_id)
- if not user_id:
- return Response(
- {"error": "No active run user found for the team (no GitHub integration creator or org member)"},
- status=status.HTTP_400_BAD_REQUEST,
- )
- # Fail loud here rather than silently downstream: sandbox credentials are authorized against
- # active org membership, so an unauthorized run user hangs the review until its poll budget expires.
- run_user_is_authorized = OrganizationMembership.objects.filter(
- organization__team__id=team_id,
- user_id=user_id,
- user__is_active=True,
- ).exists()
- if not run_user_is_authorized:
- # The Action echoes error bodies into public CI logs, so the id stays server-side.
- logger.warning("ReviewHog trigger: run user %s is not an active member of the team's organization", user_id)
- return Response(
- {"error": "Configured run user is not an active member of the team's organization"},
- status=status.HTTP_400_BAD_REQUEST,
- )
- return team_id, user_id
-
- @extend_schema(
- request=ReviewHogTriggerRequestSerializer,
- responses={
- 202: OpenApiResponse(response=ReviewHogTriggerResponseSerializer, description="Review run started"),
- 400: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer, description="Invalid body or unresolved run user"
- ),
- 403: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer, description="Missing/invalid token or disallowed repo"
- ),
- 409: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer,
- description="The PR's resolution run is still going (busy-guard); retry once it finishes",
- ),
- 503: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Trigger team not configured"),
- },
- summary="Trigger a ReviewHog PR review",
- description=(
- "Start a single-turn ReviewHog review for a pull request and (by default) publish it back to "
- "the PR. A published review chains into the resolution stage when the PR author's "
- "resolve_comments setting is on (the default). Authenticated with the REVIEWHOG_TRIGGER_TOKEN "
- "shared secret in the Authorization header. Non-blocking: returns the Temporal workflow id "
- "immediately while the review runs in the worker."
- ),
- )
- @action(detail=False, methods=["POST"], url_path="trigger")
- def trigger(self, request: Request) -> Response:
- auth_error = self._authenticate(request)
- if auth_error is not None:
- return auth_error
-
- serializer = ReviewHogTriggerRequestSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- repo: str = serializer.validated_data["repo"]
- pr_number: int = serializer.validated_data["pr_number"]
- publish: bool = serializer.validated_data["publish"]
-
- gates = self._run_gates(repo)
- if isinstance(gates, Response):
- return gates
- team_id, user_id = gates
-
- # The busy-guard (CONTEXT.md): a review is refused while this PR's resolution run is still
- # going — Temporal joins same-id review starts on its own, but resolve-pr is a different id.
- owner, _, repo_name = repo.partition("/")
- if workflow_running(resolve_pr_workflow_id(team_id=team_id, owner=owner, repo=repo_name, pr_number=pr_number)):
- return Response(
- {"error": "Still resolving comments from the last review. Try again when it finishes."},
- status=status.HTTP_409_CONFLICT,
- )
-
- # Forks are rejected server-side in the workflow's fetch activity (and by the Action gate); the
- # endpoint stays free of GitHub I/O and returns immediately. Reviewing includes resolving:
- # whether the run chains the resolution stage is the PR author's `resolve_comments` setting
- # (default on), not a caller flag.
- pr_url = f"https://github.com/{repo}/pull/{pr_number}"
- # Probed before the start: a same-id start joins the running turn, whose inputs keep the
- # original trigger, so the label's tier lift has to be written here (see the helper).
- joins_running_review = workflow_running(
- review_pr_workflow_id(team_id=team_id, owner=owner, repo=repo_name, pr_number=pr_number)
- )
- workflow_id = start_review_pr_workflow(
- pr_url=pr_url,
- team_id=team_id,
- user_id=user_id,
- publish=publish,
- trigger_source=TRIGGER_LABEL,
- )
- if joins_running_review:
- lifted = lift_review_tier_for_joined_trigger(team_id=team_id, repository=repo, pr_number=pr_number)
- logger.info(
- f"ReviewHog trigger joined running workflow {workflow_id} for {repo}#{pr_number} (tier lifted={lifted})"
- )
- return Response(
- ReviewHogTriggerResponseSerializer(
- {"workflow_id": workflow_id, "status": "joined_running_review"}
- ).data,
- status=status.HTTP_202_ACCEPTED,
- )
- logger.info(f"ReviewHog trigger started workflow {workflow_id} for {repo}#{pr_number} (publish={publish})")
- return Response(
- ReviewHogTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,
- status=status.HTTP_202_ACCEPTED,
- )
-
- @extend_schema(
- request=ReviewHogResolveRequestSerializer,
- responses={
- 202: OpenApiResponse(response=ReviewHogTriggerResponseSerializer, description="Resolution run started"),
- 400: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer, description="Invalid body or unresolved run user"
- ),
- 403: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer, description="Missing/invalid token or disallowed repo"
- ),
- 409: OpenApiResponse(
- response=ReviewHogTriggerErrorSerializer,
- description="The PR's review workflow is still going (busy-guard); it chains resolution itself",
- ),
- 503: OpenApiResponse(response=ReviewHogTriggerErrorSerializer, description="Trigger team not configured"),
- },
- summary="Trigger the ReviewHog resolution stage on a PR",
- description=(
- "Start a standalone resolution run for a pull request: triage every unresolved review thread "
- "(human- or bot-authored), implement the worth-and-safe asks directly on the PR branch, reply "
- "on each thread, and resolve settled bot threads. Works on PRs that never had a ReviewHog "
- "review. Same shared-secret auth as the review trigger; non-blocking."
- ),
- )
- @action(detail=False, methods=["POST"], url_path="resolve")
- def resolve(self, request: Request) -> Response:
- auth_error = self._authenticate(request)
- if auth_error is not None:
- return auth_error
-
- serializer = ReviewHogResolveRequestSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- repo: str = serializer.validated_data["repo"]
- pr_number: int = serializer.validated_data["pr_number"]
-
- gates = self._run_gates(repo)
- if isinstance(gates, Response):
- return gates
- team_id, user_id = gates
-
- # The busy-guard's other direction: a standalone resolution is refused while the PR's
- # review workflow is still going (a finishing review chains its own resolution anyway).
- owner, _, repo_name = repo.partition("/")
- if workflow_running(review_pr_workflow_id(team_id=team_id, owner=owner, repo=repo_name, pr_number=pr_number)):
- return Response(
- {"error": "A review is already running on this pull request. It resolves comments when it finishes."},
- status=status.HTTP_409_CONFLICT,
- )
-
- # Fork/closed gates run server-side in the workflow's prepare step (they need GitHub I/O).
- pr_url = f"https://github.com/{repo}/pull/{pr_number}"
- workflow_id = start_resolution_workflow(
- pr_url=pr_url, team_id=team_id, user_id=user_id, trigger_source=TRIGGER_LABEL
- )
- logger.info(f"ReviewHog resolve trigger started workflow {workflow_id} for {repo}#{pr_number}")
- return Response(
- ReviewHogTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,
- status=status.HTTP_202_ACCEPTED,
- )
diff --git a/products/review_hog/backend/apps.py b/products/review_hog/backend/apps.py
index 3cce0d8712e0..8f7b238a30d1 100644
--- a/products/review_hog/backend/apps.py
+++ b/products/review_hog/backend/apps.py
@@ -11,3 +11,7 @@ class ReviewHogConfig(AppConfig):
from products.review_hog.backend import receivers # noqa: PLC0415
receivers.connect()
+ # The settings receivers must connect in every process, so that a write from a shell or a
+ # management command is logged too, not only a write from the API. The same applies to the
+ # receivers that clear the cached ownership summary the webhook handler reads.
+ from products.review_hog.backend import activity_logging, ownership # noqa: F401, PLC0415
diff --git a/products/review_hog/backend/automatic_review_rules.py b/products/review_hog/backend/automatic_review_rules.py
new file mode 100644
index 000000000000..b3e4795b4c53
--- /dev/null
+++ b/products/review_hog/backend/automatic_review_rules.py
@@ -0,0 +1,240 @@
+"""Which automatic review a pull request author gets in a repository that a project reviews.
+
+The highest level that has an opinion wins:
+
+1. The author's choice for this repository.
+2. The author's default, unless it is "follow".
+3. The repository exception of the owning project.
+4. The project rule: Flash for everyone except the excepted people, Flash only for the listed
+ people, or Flash only for people who opt in.
+
+Bot authors, and authors who map to no project member, have no choices. They get automatic Flash
+only when the project reviews bot pull requests.
+
+`AutomaticReviewRule.resolve` is pure, so the dispatch, the workflow re-check, and the settings API
+all give the same answer. The loaders below read the rows it needs.
+"""
+
+from collections.abc import Iterable, Mapping, Sequence
+from uuid import UUID
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+from products.review_hog.backend.models import (
+ AutomaticFlashFor,
+ ReviewProjectSettings,
+ ReviewRepository,
+ ReviewRepositoryPerson,
+ ReviewUserRepositoryChoice,
+ ReviewUserSettings,
+)
+from products.review_hog.backend.ownership import RepositoryRef
+from products.review_hog.backend.preferences import DefaultReviewMode
+
+
+class AutomaticReviewReason(models.TextChoices):
+ OWN_REPOSITORY_CHOICE = "own_repository_choice", "Own choice for this repository"
+ OWN_DEFAULT = "own_default", "Own default"
+ REPOSITORY_EVERYONE = "repository_everyone", "The repository exception reviews everyone"
+ REPOSITORY_EXCEPTED = "repository_excepted", "Excepted by the repository exception"
+ REPOSITORY_LISTED = "repository_listed", "Listed by the repository exception"
+ REPOSITORY_NOT_LISTED = "repository_not_listed", "Not listed by the repository exception"
+ REPOSITORY_OPT_IN = "repository_opt_in", "The repository exception reviews only people who opt in"
+ PROJECT_EVERYONE = "project_everyone", "The project reviews everyone"
+ PROJECT_EXCEPTED = "project_excepted", "Excepted by the project"
+ PROJECT_LISTED = "project_listed", "Listed by the project"
+ PROJECT_NOT_LISTED = "project_not_listed", "Not listed by the project"
+ PROJECT_OPT_IN = "project_opt_in", "The project reviews only people who opt in"
+ BOT_REVIEWED = "bot_reviewed", "The project reviews bot pull requests"
+ BOT_SKIPPED = "bot_skipped", "The project does not review bot pull requests"
+ NOT_IN_PROJECT = "not_in_project", "This project does not review the repository"
+
+
+_RULE_REASONS: dict[tuple[bool, str], AutomaticReviewReason] = {
+ (True, "everyone"): AutomaticReviewReason.REPOSITORY_EVERYONE,
+ (True, "excepted"): AutomaticReviewReason.REPOSITORY_EXCEPTED,
+ (True, "listed"): AutomaticReviewReason.REPOSITORY_LISTED,
+ (True, "not_listed"): AutomaticReviewReason.REPOSITORY_NOT_LISTED,
+ (True, "opt_in"): AutomaticReviewReason.REPOSITORY_OPT_IN,
+ (False, "everyone"): AutomaticReviewReason.PROJECT_EVERYONE,
+ (False, "excepted"): AutomaticReviewReason.PROJECT_EXCEPTED,
+ (False, "listed"): AutomaticReviewReason.PROJECT_LISTED,
+ (False, "not_listed"): AutomaticReviewReason.PROJECT_NOT_LISTED,
+ (False, "opt_in"): AutomaticReviewReason.PROJECT_OPT_IN,
+}
+
+
+def is_bot_login(github_login: str) -> bool:
+ # GitHub App accounts, the only accounts GitHub types as "Bot", end their login in "[bot]".
+ return github_login.lower().endswith("[bot]")
+
+
+@frozen
+class AutomaticReviewDecision:
+ flash: bool
+ reason: AutomaticReviewReason
+
+
+@frozen
+class AuthorChoice:
+ # None when the GitHub author maps to no PostHog user.
+ user_id: int | None
+ is_bot: bool
+ default_mode: DefaultReviewMode
+ repository_choice: ReviewUserRepositoryChoice.Mode | None
+
+
+@frozen
+class FlashRule:
+ """One level's rule, the project rule or a repository exception, with its people lists."""
+
+ flash_for: AutomaticFlashFor
+ listed_user_ids: frozenset[int]
+ excepted_user_ids: frozenset[int]
+
+ @classmethod
+ def from_people(cls, flash_for: str, people: Sequence[ReviewRepositoryPerson]) -> "FlashRule":
+ return cls(
+ flash_for=AutomaticFlashFor(flash_for),
+ listed_user_ids=frozenset(
+ person.user_id for person in people if person.kind == ReviewRepositoryPerson.Kind.LISTED
+ ),
+ excepted_user_ids=frozenset(
+ person.user_id for person in people if person.kind == ReviewRepositoryPerson.Kind.EXCEPTED
+ ),
+ )
+
+ def decide(self, user_id: int, *, is_repository: bool) -> AutomaticReviewDecision:
+ if self.flash_for == AutomaticFlashFor.EVERYONE:
+ flash, outcome = (False, "excepted") if user_id in self.excepted_user_ids else (True, "everyone")
+ elif self.flash_for == AutomaticFlashFor.LISTED:
+ flash, outcome = (True, "listed") if user_id in self.listed_user_ids else (False, "not_listed")
+ else:
+ flash, outcome = False, "opt_in"
+ return AutomaticReviewDecision(flash=flash, reason=_RULE_REASONS[(is_repository, outcome)])
+
+
+@frozen
+class AutomaticReviewRule:
+ project: FlashRule
+ # None when the repository follows the project rule.
+ repository: FlashRule | None
+ review_bots: bool
+
+ def resolve(self, author: AuthorChoice) -> AutomaticReviewDecision:
+ if author.is_bot or author.user_id is None:
+ if self.review_bots:
+ return AutomaticReviewDecision(flash=True, reason=AutomaticReviewReason.BOT_REVIEWED)
+ return AutomaticReviewDecision(flash=False, reason=AutomaticReviewReason.BOT_SKIPPED)
+ if author.repository_choice is not None:
+ return AutomaticReviewDecision(
+ flash=author.repository_choice == ReviewUserRepositoryChoice.Mode.FLASH,
+ reason=AutomaticReviewReason.OWN_REPOSITORY_CHOICE,
+ )
+ if author.default_mode != DefaultReviewMode.FOLLOW:
+ return AutomaticReviewDecision(
+ flash=author.default_mode == DefaultReviewMode.FLASH, reason=AutomaticReviewReason.OWN_DEFAULT
+ )
+ if self.repository is not None:
+ return self.repository.decide(author.user_id, is_repository=True)
+ return self.project.decide(author.user_id, is_repository=False)
+
+
+def load_people(team_id: int, repository_ids: Iterable[UUID]) -> dict[UUID | None, list[ReviewRepositoryPerson]]:
+ """People lists keyed by repository id. The key None holds the lists of the project rule."""
+ people: dict[UUID | None, list[ReviewRepositoryPerson]] = {None: []}
+ people.update({repository_id: [] for repository_id in repository_ids})
+ repository_filter = models.Q(repository_id__in=[key for key in people if key is not None])
+ rows = (
+ ReviewRepositoryPerson.objects.for_team(team_id)
+ .filter(repository_filter | models.Q(repository__isnull=True))
+ .select_related("user")
+ .order_by("created_at")
+ )
+ for person in rows:
+ people[person.repository_id].append(person)
+ return people
+
+
+@frozen
+class ProjectRuleContext:
+ """What a project needs to resolve its rule in many repositories without another query."""
+
+ settings: ReviewProjectSettings
+ people: Mapping[UUID | None, Sequence[ReviewRepositoryPerson]]
+
+ @classmethod
+ def load(cls, team_id: int, repositories: Iterable[ReviewRepository]) -> "ProjectRuleContext":
+ return cls(
+ settings=ReviewProjectSettings.load(team_id),
+ people=load_people(team_id, [repository.id for repository in repositories]),
+ )
+
+ def rule_for(self, repository: ReviewRepository | None) -> AutomaticReviewRule:
+ exception = None
+ if repository is not None and repository.flash_for is not None:
+ exception = FlashRule.from_people(repository.flash_for, self.people.get(repository.id, []))
+ return AutomaticReviewRule(
+ project=FlashRule.from_people(self.settings.flash_for, self.people.get(None, [])),
+ repository=exception,
+ review_bots=self.settings.bot_prs == ReviewProjectSettings.BotPullRequests.RUN,
+ )
+
+
+@frozen
+class AuthorPreferences:
+ """An author's own choices across all repositories of a project."""
+
+ user_id: int | None
+ is_bot: bool
+ default_mode: DefaultReviewMode
+ choices: Sequence[ReviewUserRepositoryChoice]
+
+ def choice_for(self, repository: RepositoryRef) -> ReviewUserRepositoryChoice | None:
+ if repository.github_repo_id is not None:
+ for choice in self.choices:
+ if choice.github_repo_id == repository.github_repo_id:
+ return choice
+ name = repository.full_name.lower()
+ for choice in self.choices:
+ # A name match with another id is an older repository that had this name.
+ same_repository = choice.github_repo_id is None or repository.github_repo_id is None
+ if choice.full_name.lower() == name and same_repository:
+ return choice
+ return None
+
+ def for_repository(self, repository: RepositoryRef) -> AuthorChoice:
+ choice = self.choice_for(repository)
+ return AuthorChoice(
+ user_id=self.user_id,
+ is_bot=self.is_bot,
+ default_mode=self.default_mode,
+ repository_choice=ReviewUserRepositoryChoice.Mode(choice.mode) if choice is not None else None,
+ )
+
+
+def load_author_preferences(team_id: int, *, user_id: int | None, is_bot: bool) -> AuthorPreferences:
+ if user_id is None or is_bot:
+ return AuthorPreferences(user_id=user_id, is_bot=is_bot, default_mode=DefaultReviewMode.FOLLOW, choices=())
+ return AuthorPreferences(
+ user_id=user_id,
+ is_bot=is_bot,
+ default_mode=ReviewUserSettings.load_preferences(team_id, user_id).default_review_mode,
+ choices=tuple(ReviewUserRepositoryChoice.objects.for_team(team_id).filter(user_id=user_id)),
+ )
+
+
+def decide_automatic_review(
+ team_id: int,
+ repository: RepositoryRef,
+ row: ReviewRepository | None,
+ *,
+ author_user_id: int | None,
+ author_login: str,
+) -> AutomaticReviewDecision:
+ """The decision for one author in a repository that `team_id` owns. `row` is that project's row."""
+ rule = ProjectRuleContext.load(team_id, [row] if row is not None else []).rule_for(row)
+ author = load_author_preferences(team_id, user_id=author_user_id, is_bot=is_bot_login(author_login))
+ return rule.resolve(author.for_repository(repository))
diff --git a/products/review_hog/backend/automatic_reviews.py b/products/review_hog/backend/automatic_reviews.py
index d910ae686c86..adfdb350f3e8 100644
--- a/products/review_hog/backend/automatic_reviews.py
+++ b/products/review_hog/backend/automatic_reviews.py
@@ -1,23 +1,32 @@
import logging
-from collections.abc import Mapping
from typing import Literal
-from django.conf import settings
-
from prometheus_client import Counter
from posthog.dataclasses import frozen
from posthog.models.integration import Integration
from posthog.otel_metrics import OtelInstrumentFactory
-from products.review_hog.backend.models import ReviewUserSettings
-
-AUTOMATIC_REVIEW_REPOSITORY = "PostHog/posthog"
+from products.review_hog.backend.automatic_review_rules import AutomaticReviewReason, decide_automatic_review
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.ownership import RepositoryOwner, RepositoryOwnership, RepositoryRef
+from products.review_hog.backend.pr_owner import is_active_member
+from products.review_hog.backend.review_request_rules import full_review_published
logger = logging.getLogger(__name__)
_otel = OtelInstrumentFactory("review_hog")
-AuthoredPRReviewOutcome = Literal["no_team", "installation_mismatch", "author_unmapped", "not_opted_in", "started"]
+AuthoredPRReviewOutcome = Literal[
+ "repository_not_added",
+ "internal_features_off",
+ "installation_mismatch",
+ "bot_skipped",
+ "bot_no_connector",
+ "not_opted_in",
+ "full_review_published",
+ "started",
+]
# A rejected dispatch returns normally, so Celery records the task as successful and no workflow
# starts to report the skip. Without this counter a misconfigured deploy or a drifted installation
@@ -35,71 +44,111 @@ def _observe_dispatch(outcome: AuthoredPRReviewOutcome) -> None:
_otel.record_counter_twin(AUTHORED_PR_REVIEW_TOTAL, 1, {"outcome": outcome})
-def _mapping(value: object) -> Mapping[str, object]:
- return value if isinstance(value, Mapping) else {}
-
+def connector_user_id(*, team_id: int, installation_id: str) -> int | None:
+ """The active member who connected the installation to the project. Bot pull requests run as them."""
+ creator_ids = Integration.objects.filter(
+ team_id=team_id, kind="github", integration_id=installation_id, created_by__isnull=False
+ ).values_list("created_by_id", flat=True)
+ for creator_id in creator_ids:
+ if is_active_member(team_id=team_id, user_id=creator_id):
+ return creator_id
+ return None
-def _allowed_repository(value: object) -> bool:
- full_name = _mapping(value).get("full_name")
- return isinstance(full_name, str) and full_name.lower() == AUTOMATIC_REVIEW_REPOSITORY.lower()
+@frozen
+class AutomaticDispatch:
+ outcome: AuthoredPRReviewOutcome
+ team_id: int | None = None
+ # The user the review runs as: the author, or the connector for a bot pull request.
+ run_as_user_id: int | None = None
+
+
+def plan_automatic_review(
+ repository: RepositoryRef, owner: RepositoryOwner | None, *, author_login: str
+) -> AutomaticDispatch:
+ """Whether a push gets an automatic Flash review, in which project, and as which user."""
+ # These clients pull in the signals product; planning a webhook must not load it at import.
+ from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
+ resolve_org_github_login_to_users,
+ )
-def authored_reviews_enabled(*, team_id: int, user_id: int) -> bool:
- return (
- ReviewUserSettings.objects.for_team(team_id)
- .filter(
- user_id=user_id,
- review_authored_prs=True,
- user__is_active=True,
- user__organization_membership__organization__team__id=team_id,
+ if owner is None:
+ return AutomaticDispatch(outcome="repository_not_added")
+ team_id = owner.team_id
+ if not has_internal_features(team_id):
+ return AutomaticDispatch(outcome="internal_features_off", team_id=team_id)
+ has_integration = Integration.objects.filter(
+ team_id=team_id, kind="github", integration_id=owner.installation_id
+ ).exists()
+ if not has_integration:
+ logger.warning(
+ "Team %s has no GitHub integration for installation %s; skipping automatic review of %s",
+ team_id,
+ owner.installation_id,
+ repository.full_name,
)
- .exists()
+ return AutomaticDispatch(outcome="installation_mismatch", team_id=team_id)
+ author = resolve_org_github_login_to_users(team_id, [author_login]).get(author_login.strip().lower())
+ # An inactive user cannot act: every user-scoped sandbox credential of the run would fail. So an
+ # inactive author counts as unmapped, and unmapped authors follow the project's bot rule.
+ author_user_id = author.id if author is not None and is_active_member(team_id=team_id, user_id=author.id) else None
+ decision = decide_automatic_review(
+ team_id, repository, owner.row, author_user_id=author_user_id, author_login=author_login
)
+ if not decision.flash:
+ outcome: AuthoredPRReviewOutcome = (
+ "bot_skipped" if decision.reason == AutomaticReviewReason.BOT_SKIPPED else "not_opted_in"
+ )
+ return AutomaticDispatch(outcome=outcome, team_id=team_id)
+ if decision.reason == AutomaticReviewReason.BOT_REVIEWED:
+ run_as_user_id = connector_user_id(team_id=team_id, installation_id=owner.installation_id)
+ if run_as_user_id is None:
+ return AutomaticDispatch(outcome="bot_no_connector", team_id=team_id)
+ return AutomaticDispatch(outcome="started", team_id=team_id, run_as_user_id=run_as_user_id)
+ return AutomaticDispatch(outcome="started", team_id=team_id, run_as_user_id=author_user_id)
+
+
+def automatic_flash_allowed(
+ *,
+ team_id: int,
+ repository: str,
+ user_id: int,
+ author_login: str,
+ installation_id: str | None = None,
+ github_repo_id: int | None = None,
+) -> bool:
+ """Whether the rules still give this pull request an automatic Flash review run as `user_id`.
+
+ The workflow calls this again when the run starts, because ownership, settings and lists can
+ change while the task waits in the queue.
+ """
+ if installation_id:
+ # The installation id comes from the signed webhook. The cached account name of the
+ # integration can be a placeholder, so a lookup by name can miss an owner the dispatch found.
+ owner = RepositoryOwnership.find(
+ RepositoryRef(installation_id=installation_id, github_repo_id=github_repo_id, full_name=repository)
+ )
+ else:
+ owner = RepositoryOwnership.find_by_name(repository)
+ if owner is None or owner.team_id != team_id:
+ return False
+ ref = RepositoryRef(installation_id=owner.installation_id, github_repo_id=github_repo_id, full_name=repository)
+ return plan_automatic_review(ref, owner, author_login=author_login).run_as_user_id == user_id
@frozen
class AuthoredPRReview:
installation_id: str
+ repository: str
author_login: str
pr_number: int
head_sha: str
+ github_repo_id: int | None = None
- @classmethod
- def from_payload(cls, payload: Mapping[str, object]) -> "AuthoredPRReview | None":
- if payload.get("action") not in ("opened", "synchronize"):
- return None
- pull_request = _mapping(payload.get("pull_request"))
- if pull_request.get("state") != "open" or pull_request.get("merged"):
- return None
- head = _mapping(pull_request.get("head"))
- base = _mapping(pull_request.get("base"))
- if not all(
- _allowed_repository(repo) for repo in (payload.get("repository"), head.get("repo"), base.get("repo"))
- ):
- return None
-
- installation_id = _mapping(payload.get("installation")).get("id")
- author_login = _mapping(pull_request.get("user")).get("login")
- pr_number = pull_request.get("number")
- head_sha = head.get("sha")
- if (
- not isinstance(installation_id, int)
- or isinstance(installation_id, bool)
- or installation_id < 1
- or not isinstance(pr_number, int)
- or isinstance(pr_number, bool)
- or pr_number < 1
- or not isinstance(author_login, str)
- or not author_login.strip()
- or not isinstance(head_sha, str)
- or not head_sha.strip()
- ):
- return None
- return cls(
- installation_id=str(installation_id),
- author_login=author_login.strip().lower(),
- pr_number=pr_number,
- head_sha=head_sha,
+ @property
+ def ref(self) -> RepositoryRef:
+ return RepositoryRef(
+ installation_id=self.installation_id, github_repo_id=self.github_repo_id, full_name=self.repository
)
def start(self) -> None:
@@ -107,65 +156,35 @@ class AuthoredPRReview:
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH # noqa: PLC0415
from products.review_hog.backend.temporal.client import start_review_pr_workflow # noqa: PLC0415
from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC # noqa: PLC0415
- from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
- resolve_org_github_login_to_users,
- )
- if not settings.REVIEWHOG_TEAM_IDS:
- logger.warning("No ReviewHog team is configured; skipping automatic review of PR #%s", self.pr_number)
- _observe_dispatch("no_team")
- return
- team_id = settings.REVIEWHOG_TEAM_IDS[0]
- if not Integration.objects.filter(team_id=team_id, kind="github", integration_id=self.installation_id).exists():
- logger.warning(
- "Team %s has no GitHub integration for installation %s; skipping automatic review of PR #%s",
- team_id,
- self.installation_id,
- self.pr_number,
- )
- _observe_dispatch("installation_mismatch")
- return
- author = resolve_org_github_login_to_users(team_id, [self.author_login]).get(self.author_login)
- if author is None:
- logger.info(
- "PR author '%s' is not a PostHog org user on team %s; skipping automatic review of PR #%s",
- self.author_login,
- team_id,
- self.pr_number,
- )
- _observe_dispatch("author_unmapped")
+ dispatch = plan_automatic_review(
+ self.ref, RepositoryOwnership.find(self.ref, backfill=True), author_login=self.author_login
+ )
+ if dispatch.team_id is None or dispatch.run_as_user_id is None:
+ # Most pushes get no automatic review, so the counter carries the signal and the logs
+ # stay quiet.
+ _observe_dispatch(dispatch.outcome)
return
- # The high-volume branch: most authors on the repository have not opted in. The counter
- # carries the signal, so this one stays out of the logs.
- if not authored_reviews_enabled(team_id=team_id, user_id=author.id):
- _observe_dispatch("not_opted_in")
+ report = (
+ ReviewReport.objects.for_team(dispatch.team_id)
+ .filter(repository__iexact=self.repository, pr_number=self.pr_number)
+ .first()
+ )
+ if full_review_published(report):
+ _observe_dispatch("full_review_published")
return
start_review_pr_workflow(
- pr_url=f"https://github.com/{AUTOMATIC_REVIEW_REPOSITORY}/pull/{self.pr_number}",
- team_id=team_id,
- user_id=author.id,
- acting_user_id=author.id,
+ pr_url=f"https://github.com/{self.repository}/pull/{self.pr_number}",
+ team_id=dispatch.team_id,
+ user_id=dispatch.run_as_user_id,
+ acting_user_id=dispatch.run_as_user_id,
publish=True,
resolve_comments=False,
review_mode=REVIEW_MODE_FLASH,
trigger_source=TRIGGER_AUTOMATIC,
requested_head_sha=self.head_sha,
+ installation_id=self.installation_id,
+ github_repo_id=self.github_repo_id,
)
# After the start, so a retried task cannot count a dispatch it never made.
_observe_dispatch("started")
-
-
-def enqueue_authored_pr_review(payload: Mapping[str, object]) -> None:
- review = AuthoredPRReview.from_payload(payload)
- if review is None:
- return
- from products.review_hog.backend.tasks import ( # noqa: PLC0415 - keeps Celery off the registry import path
- process_authored_pr_event,
- )
-
- process_authored_pr_event.delay(
- installation_id=review.installation_id,
- author_login=review.author_login,
- pr_number=review.pr_number,
- head_sha=review.head_sha,
- )
diff --git a/products/review_hog/backend/facade/github.py b/products/review_hog/backend/facade/github.py
index 926adf686db8..a55df8ff9592 100644
--- a/products/review_hog/backend/facade/github.py
+++ b/products/review_hog/backend/facade/github.py
@@ -1,3 +1,13 @@
-from products.review_hog.backend.automatic_reviews import enqueue_authored_pr_review
+from products.review_hog.backend.ownership import RepositoryOwnership, RepositoryRef
+from products.review_hog.backend.pull_request_events import accept_pull_request_event
-__all__ = ["enqueue_authored_pr_review"]
+
+def owning_team_id(installation_id: str, repository: str, github_repo_id: int | None = None) -> int | None:
+ """The project that reviews `repository` (`owner/name`) for this installation, or None when none does."""
+ owner = RepositoryOwnership.find(
+ RepositoryRef(installation_id=installation_id, github_repo_id=github_repo_id, full_name=repository)
+ )
+ return owner.team_id if owner is not None else None
+
+
+__all__ = ["accept_pull_request_event", "owning_team_id"]
diff --git a/products/review_hog/backend/facade/reviews.py b/products/review_hog/backend/facade/reviews.py
index de2ad2cfb2ec..8d76d92b10ee 100644
--- a/products/review_hog/backend/facade/reviews.py
+++ b/products/review_hog/backend/facade/reviews.py
@@ -32,7 +32,7 @@ _FEATURE_FLAG = "review-hog"
def flash_available(team_id: int) -> bool:
- """Flash is limited to the internal ReviewHog project until that gate becomes a flag."""
+ """Flash is limited to projects with the `review-hog-internal` flag."""
return has_internal_features(resolve_effective_team_id(team_id))
@@ -41,9 +41,8 @@ def request_pr_review(
) -> PRReviewRequestOutcome:
"""Start the run, with the requester as both the run user and the acting user.
- This is the pull request comment path. The run uses the commenter's settings, but the resolution
- stage writes commits to the pull request's branch. Until the pull request owner's own opt-in
- decides that, a comment must not write to anyone's branch, so resolution stays off.
+ This is the pull request comment path. The run uses the commenter's settings. The resolution
+ stage writes commits only when the pull request owner opted in, the same rule as every trigger.
Applies the `review-hog` flag, which the review API applies through its permission class.
The caller has already checked that the requester is a member of the project.
Raises `GitHubRateLimitError` when GitHub rate-limits the App's token.
@@ -67,5 +66,4 @@ def request_pr_review(
pr_number=pr_number,
run_mode=run_mode,
trigger_source=TRIGGER_COMMENT,
- resolve_comments=False,
)
diff --git a/products/review_hog/backend/internal_features.py b/products/review_hog/backend/internal_features.py
index e554cdc58b29..4d2cab8944b6 100644
--- a/products/review_hog/backend/internal_features.py
+++ b/products/review_hog/backend/internal_features.py
@@ -1,6 +1,30 @@
-from django.conf import settings
+import logging
+
+from posthog.models.team.team import Team
+from posthog.permissions import posthog_feature_flag_enabled
+
+logger = logging.getLogger(__name__)
+
+# Gates the parts of ReviewHog that stay internal: automatic reviews, the label trigger, resolution,
+# manual Flash, Inbox reviews (ReviewHog and the Stamphog handoff), and the tiered review arms.
+# The `review-hog` flag stays the product switch.
+REVIEW_HOG_INTERNAL_FLAG = "review-hog-internal"
def has_internal_features(team_id: int) -> bool:
- """Whether a project gets Flash and the automation settings: only the first configured ReviewHog team."""
- return bool(settings.REVIEWHOG_TEAM_IDS and team_id == settings.REVIEWHOG_TEAM_IDS[0])
+ """Whether the `review-hog-internal` flag is on for this project.
+
+ Evaluated with the project group, the same way the `review-hog` permission evaluates the product flag.
+ A flag service failure reads as off, so an outage cannot turn on writes for a project.
+ """
+ try:
+ team = Team.objects.filter(id=team_id).values_list("organization_id", "uuid").first()
+ if team is None:
+ return False
+ organization_id, team_uuid = team
+ return posthog_feature_flag_enabled(
+ REVIEW_HOG_INTERNAL_FLAG, str(team_uuid), organization_id=organization_id, team_id=team_id
+ )
+ except Exception:
+ logger.exception("Could not evaluate %s for team %s; treating it as off", REVIEW_HOG_INTERNAL_FLAG, team_id)
+ return False
diff --git a/products/review_hog/backend/label_reviews.py b/products/review_hog/backend/label_reviews.py
new file mode 100644
index 000000000000..30788796598b
--- /dev/null
+++ b/products/review_hog/backend/label_reviews.py
@@ -0,0 +1,176 @@
+"""The label trigger: the `reviewhog` label on a pull request starts a Full review.
+
+The PostHog GitHub App's own `labeled` delivery starts it, so the trigger works in every repository the
+app is installed on and a project owns (`ownership.py`). One label add is one review: pushes do not
+review again, and the workflow removes the label when the run ends.
+
+- A person can add the label, and so can Stamphog, which hands a refused or escalated pull request to
+ ReviewHog this way. Another bot's label gets an explaining comment and is removed.
+- The review runs in the owning project, which needs the `review-hog-internal` flag.
+- It runs as the pull request owner (`pr_owner.py`). Without an owner it runs as the person who
+ connected the installation, with default settings and no resolution.
+"""
+
+import logging
+from typing import Literal
+
+from prometheus_client import Counter
+
+from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.otel_metrics import OtelInstrumentFactory
+
+from products.review_hog.backend.automatic_reviews import connector_user_id
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.ownership import RepositoryOwnership, RepositoryRef
+from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
+from products.review_hog.backend.pull_request_events import REVIEWHOG_LABEL
+from products.review_hog.backend.reviewer.persistence import lift_review_tier_for_joined_trigger
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+
+logger = logging.getLogger(__name__)
+_otel = OtelInstrumentFactory("review_hog")
+
+# Stamphog hands a refused or escalated pull request to ReviewHog with the label.
+STAMPHOG_BOT_LOGIN = "stamphog[bot]"
+
+BOT_LABEL_COMMENT = (
+ f"ReviewHog reviews start only when a person adds the `{REVIEWHOG_LABEL}` label, so this label from a bot "
+ "was removed. Add it again yourself to start a review."
+)
+
+LabelReviewOutcome = Literal[
+ "repository_not_added",
+ "internal_features_off",
+ "installation_mismatch",
+ "bot_labeler",
+ "no_run_user",
+ "resolution_running",
+ "started",
+]
+
+# The label trigger answers nobody, so a skipped label leaves no trace on the pull request. This
+# counter names why labels stopped starting reviews.
+LABEL_REVIEW_TOTAL = Counter(
+ "posthog_review_hog_label_review_total",
+ "Label trigger decisions, keyed by outcome",
+ labelnames=["outcome"],
+)
+
+
+def _observe(outcome: LabelReviewOutcome) -> None:
+ LABEL_REVIEW_TOTAL.labels(outcome=outcome).inc()
+ _otel.record_counter_twin(LABEL_REVIEW_TOTAL, 1, {"outcome": outcome})
+
+
+@frozen
+class LabelReview:
+ installation_id: str
+ repository: str
+ github_repo_id: int | None
+ pr_number: int
+ author_login: str
+ # The payload refuses forks, so the head branch is in the base repository.
+ head_branch: str
+ labeler_login: str
+ labeled_by_bot: bool
+
+ @property
+ def ref(self) -> RepositoryRef:
+ return RepositoryRef(
+ installation_id=self.installation_id, github_repo_id=self.github_repo_id, full_name=self.repository
+ )
+
+ @property
+ def labeler_allowed(self) -> bool:
+ return not self.labeled_by_bot or self.labeler_login.lower() == STAMPHOG_BOT_LOGIN
+
+ def _github(self, integration: Integration) -> GitHubIntegration:
+ return GitHubIntegration(integration, source="review_hog", priority=Priority.NORMAL)
+
+ def _refuse_bot_label(self, integration: Integration) -> None:
+ # The label goes first: a failed call retries the task, and the comment must post only once.
+ token = self._github(integration).get_access_token()
+ try:
+ github_api_request(
+ "DELETE",
+ f"/repos/{self.repository}/issues/{self.pr_number}/labels/{REVIEWHOG_LABEL}",
+ token=token,
+ installation_id=self.installation_id,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/labels/{name}",
+ )
+ except GitHubAPIError as error:
+ if error.status != 404:
+ raise
+ github_api_request(
+ "POST",
+ f"/repos/{self.repository}/issues/{self.pr_number}/comments",
+ token=token,
+ installation_id=self.installation_id,
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
+ json={"body": BOT_LABEL_COMMENT},
+ )
+
+ def start(self) -> None:
+ # The temporal package registers the activities, which pull in the sandbox runtime.
+ from products.review_hog.backend.temporal.client import ( # noqa: PLC0415
+ start_review_pr_workflow,
+ workflow_running,
+ )
+ from products.review_hog.backend.temporal.types import ( # noqa: PLC0415
+ TRIGGER_LABEL,
+ resolve_pr_workflow_id,
+ review_pr_workflow_id,
+ )
+
+ owner = RepositoryOwnership.find(self.ref)
+ if owner is None:
+ _observe("repository_not_added")
+ return
+ team_id = owner.team_id
+ if not has_internal_features(team_id):
+ _observe("internal_features_off")
+ return
+ integration = (
+ Integration.objects.filter(team_id=team_id, kind="github", integration_id=self.installation_id)
+ .order_by("id")
+ .first()
+ )
+ if integration is None:
+ _observe("installation_mismatch")
+ return
+ if not self.labeler_allowed:
+ self._refuse_bot_label(integration)
+ _observe("bot_labeler")
+ return
+ pr_owner = PullRequestOwnerResolver.resolve(
+ team_id, repository=self.repository, author_login=self.author_login, head_branch=self.head_branch
+ )
+ run_user_id = pr_owner.user_id or connector_user_id(team_id=team_id, installation_id=self.installation_id)
+ if run_user_id is None:
+ _observe("no_run_user")
+ return
+ github_owner, _, github_repo = self.repository.partition("/")
+ # The busy-guard (CONTEXT.md): a review waits until this PR's resolution run is done. The label
+ # stays, so a person can add it again once the run ends.
+ if workflow_running(
+ resolve_pr_workflow_id(team_id=team_id, owner=github_owner, repo=github_repo, pr_number=self.pr_number)
+ ):
+ _observe("resolution_running")
+ return
+ # Probed before the start: a same-id start joins the running turn, whose inputs keep the
+ # original trigger, so the label's tier lift has to be written here.
+ joins_running_review = workflow_running(
+ review_pr_workflow_id(team_id=team_id, owner=github_owner, repo=github_repo, pr_number=self.pr_number)
+ )
+ start_review_pr_workflow(
+ pr_url=f"https://github.com/{self.repository}/pull/{self.pr_number}",
+ team_id=team_id,
+ user_id=run_user_id,
+ publish=True,
+ trigger_source=TRIGGER_LABEL,
+ )
+ if joins_running_review:
+ lift_review_tier_for_joined_trigger(team_id=team_id, repository=self.repository, pr_number=self.pr_number)
+ _observe("started")
diff --git a/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py b/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py
deleted file mode 100644
index 77267ad9209c..000000000000
--- a/products/review_hog/backend/management/commands/disable_authored_pr_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn off automatic Flash reviews of authored PRs (review_authored_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids. Preserves Flash reasoning effort."
- )
- field = "review_authored_prs"
- enabled = False
diff --git a/products/review_hog/backend/management/commands/disable_comment_resolution.py b/products/review_hog/backend/management/commands/disable_comment_resolution.py
deleted file mode 100644
index e0a3b4de762d..000000000000
--- a/products/review_hog/backend/management/commands/disable_comment_resolution.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn off comment resolution after published reviews (resolve_comments) for every active member "
- "of the organization that owns the given team, or for the given user ids."
- )
- field = "resolve_comments"
- enabled = False
diff --git a/products/review_hog/backend/management/commands/disable_inbox_reviews.py b/products/review_hog/backend/management/commands/disable_inbox_reviews.py
deleted file mode 100644
index 8ffc7497add8..000000000000
--- a/products/review_hog/backend/management/commands/disable_inbox_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn off ReviewHog inbox PR reviews (review_inbox_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids."
- )
- field = "review_inbox_prs"
- enabled = False
diff --git a/products/review_hog/backend/management/commands/disable_stamphog_inbox_reviews.py b/products/review_hog/backend/management/commands/disable_stamphog_inbox_reviews.py
deleted file mode 100644
index e58cc69ec162..000000000000
--- a/products/review_hog/backend/management/commands/disable_stamphog_inbox_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn off Stamphog inbox PR reviews (stamphog_review_inbox_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids."
- )
- field = "stamphog_review_inbox_prs"
- enabled = False
diff --git a/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py b/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py
deleted file mode 100644
index e50bb245b716..000000000000
--- a/products/review_hog/backend/management/commands/enable_authored_pr_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn on automatic Flash reviews of authored PRs (review_authored_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids."
- )
- field = "review_authored_prs"
- enabled = True
diff --git a/products/review_hog/backend/management/commands/enable_comment_resolution.py b/products/review_hog/backend/management/commands/enable_comment_resolution.py
deleted file mode 100644
index 29bb3c4f3053..000000000000
--- a/products/review_hog/backend/management/commands/enable_comment_resolution.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn on comment resolution after published reviews (resolve_comments) for every active member "
- "of the organization that owns the given team, or for the given user ids."
- )
- field = "resolve_comments"
- enabled = True
diff --git a/products/review_hog/backend/management/commands/enable_inbox_reviews.py b/products/review_hog/backend/management/commands/enable_inbox_reviews.py
deleted file mode 100644
index 4cba46a609f6..000000000000
--- a/products/review_hog/backend/management/commands/enable_inbox_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn on ReviewHog inbox PR reviews (review_inbox_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids."
- )
- field = "review_inbox_prs"
- enabled = True
diff --git a/products/review_hog/backend/management/commands/enable_stamphog_inbox_reviews.py b/products/review_hog/backend/management/commands/enable_stamphog_inbox_reviews.py
deleted file mode 100644
index 231b358dccf6..000000000000
--- a/products/review_hog/backend/management/commands/enable_stamphog_inbox_reviews.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from products.review_hog.backend.management.toggle_command import SettingsToggleCommand
-
-
-class Command(SettingsToggleCommand):
- help = (
- "Turn on Stamphog inbox PR reviews (stamphog_review_inbox_prs) for every active member of the "
- "organization that owns the given team, or for the given user ids."
- )
- field = "stamphog_review_inbox_prs"
- enabled = True
diff --git a/products/review_hog/backend/management/toggle_command.py b/products/review_hog/backend/management/toggle_command.py
deleted file mode 100644
index e54b0d450038..000000000000
--- a/products/review_hog/backend/management/toggle_command.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""Base class for the `enable_*` / `disable_*` review settings management commands.
-
-Each command names one toggle and one direction; this class carries the shared arguments, the
-error mapping, and the output. It lives outside `commands/` so Django does not register it as a
-command of its own.
-"""
-
-from typing import Any, ClassVar
-
-from django.core.management.base import BaseCommand, CommandError, CommandParser
-
-from posthog.models.scoping.manager import TeamScopeError
-from posthog.models.team import Team
-
-from products.review_hog.backend.models import ReviewUserSettings
-from products.review_hog.backend.settings_toggles import ToggleField, apply_toggle, plan_toggle
-
-
-class SettingsToggleCommand(BaseCommand):
- field: ClassVar[ToggleField]
- enabled: ClassVar[bool]
-
- def add_arguments(self, parser: CommandParser) -> None:
- parser.add_argument(
- "--team-id",
- type=int,
- required=True,
- help="The team whose settings rows change. Without --user-ids, every active member of its organization.",
- )
- parser.add_argument(
- "--user-ids",
- type=int,
- nargs="+",
- metavar="USER_ID",
- help="Only change these users. Each must be a member of the team's organization.",
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Print what would change without touching the database.",
- )
- if self.field == "review_authored_prs" and self.enabled:
- parser.add_argument(
- "--effort",
- choices=ReviewUserSettings.FlashReasoningEffort.values,
- help="Set these users' Flash reasoning effort. Omit to preserve their saved preference.",
- )
-
- def handle(self, *args: Any, **options: Any) -> None:
- try:
- effort = options.get("effort")
- plan = plan_toggle(
- team_id=options["team_id"],
- field=self.field,
- enabled=self.enabled,
- user_ids=options.get("user_ids"),
- flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort(effort) if effort is not None else None,
- )
- except (TeamScopeError, Team.DoesNotExist, ValueError) as err:
- raise CommandError(str(err)) from err
-
- changed = ", ".join(str(user_id) for user_id in plan.changed_user_ids) or "none"
- if options["dry_run"]:
- self.stdout.write(self.style.NOTICE(f"[dry-run] {plan.summary}. Nothing written."))
- self.stdout.write(f"Would change user id(s): {changed}")
- return
-
- apply_toggle(plan)
- self.stdout.write(self.style.SUCCESS(f"Done. {plan.summary}."))
- self.stdout.write(f"Changed user id(s): {changed}")
diff --git a/products/review_hog/backend/migrations/0034_review_repositories.py b/products/review_hog/backend/migrations/0034_review_repositories.py
new file mode 100644
index 000000000000..3fc4da2ad56f
--- /dev/null
+++ b/products/review_hog/backend/migrations/0034_review_repositories.py
@@ -0,0 +1,298 @@
+# Generated by Django 5.2.18 on 2026-10-08 09:37
+
+import django.db.models.deletion
+import django.db.models.functions.text
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1394_backfill_secret_tokens_to_psak"),
+ ("review_hog", "0033_reviewusersettings_celebrate_clean_reviews"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="reviewusersettings",
+ name="preferences",
+ field=models.JSONField(blank=True, db_default={}, default=dict),
+ ),
+ migrations.AlterField(
+ model_name="reviewusersettings",
+ name="urgency_threshold",
+ field=models.CharField(
+ choices=[("consider", "Consider (all)"), ("should_fix", "Should fix"), ("must_fix", "Must fix")],
+ db_default="consider",
+ default="consider",
+ max_length=20,
+ ),
+ ),
+ migrations.CreateModel(
+ name="ReviewRepository",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("installation_id", models.CharField(max_length=64)),
+ ("github_repo_id", models.BigIntegerField(blank=True, null=True)),
+ ("full_name", models.CharField(max_length=200)),
+ ("selected", models.BooleanField(db_default=False, default=False)),
+ (
+ "flash_for",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("everyone", "Automatic Flash for everyone"),
+ ("listed", "Automatic Flash for these people"),
+ ("off", "Automatic Flash opt-in only"),
+ ],
+ max_length=20,
+ null=True,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="ReviewRepositoryPerson",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("kind", models.CharField(choices=[("listed", "Listed"), ("excepted", "Excepted")], max_length=20)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "repository",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="review_hog.reviewrepository",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="ReviewUserRepositoryChoice",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("installation_id", models.CharField(max_length=64)),
+ ("github_repo_id", models.BigIntegerField(blank=True, null=True)),
+ ("full_name", models.CharField(max_length=200)),
+ ("mode", models.CharField(choices=[("flash", "Flash"), ("off", "Off")], max_length=10)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="ReviewInstallationClaim",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ ("installation_id", models.CharField(max_length=64)),
+ (
+ "scope",
+ models.CharField(
+ choices=[("all", "All repositories"), ("selected", "Only selected repositories")], max_length=10
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(fields=("team", "installation_id"), name="uniq_review_installation_claim"),
+ models.UniqueConstraint(
+ condition=models.Q(("scope", "all")),
+ fields=("installation_id",),
+ name="uniq_review_installation_claim_all",
+ ),
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="ReviewProjectSettings",
+ fields=[
+ (
+ "id",
+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),
+ ),
+ (
+ "flash_for",
+ models.CharField(
+ choices=[
+ ("everyone", "Automatic Flash for everyone"),
+ ("listed", "Automatic Flash for these people"),
+ ("off", "Automatic Flash opt-in only"),
+ ],
+ db_default="off",
+ default="off",
+ max_length=20,
+ ),
+ ),
+ (
+ "bot_prs",
+ models.CharField(
+ choices=[("skip", "Not reviewed"), ("run", "Automatic Flash")],
+ db_default="skip",
+ default="skip",
+ max_length=10,
+ ),
+ ),
+ ("preferences", models.JSONField(blank=True, db_default={}, default=dict)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(fields=("team",), name="uniq_review_project_settings_per_team")
+ ],
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="reviewrepository",
+ constraint=models.UniqueConstraint(
+ django.db.models.functions.text.Lower("full_name"),
+ name="uniq_review_repository_name",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="reviewrepository",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("github_repo_id__isnull", False)),
+ fields=("github_repo_id",),
+ name="uniq_review_repository_github_id",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="reviewrepositoryperson",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("repository__isnull", False)),
+ fields=("repository", "user", "kind"),
+ name="uniq_review_repository_person",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="reviewrepositoryperson",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("repository__isnull", True)),
+ fields=("team", "user", "kind"),
+ name="uniq_review_project_person",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="reviewuserrepositorychoice",
+ constraint=models.UniqueConstraint(
+ models.F("team"),
+ models.F("user"),
+ django.db.models.functions.text.Lower("full_name"),
+ name="uniq_review_user_repository_choice",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="reviewuserrepositorychoice",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("github_repo_id__isnull", False)),
+ fields=("team", "user", "github_repo_id"),
+ name="uniq_review_user_repository_choice_id",
+ ),
+ ),
+ ]
diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txt
index 0dc678646cff..401f454ad7b2 100644
--- a/products/review_hog/backend/migrations/max_migration.txt
+++ b/products/review_hog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0033_reviewusersettings_celebrate_clean_reviews
+0034_review_repositories
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 43d94cece9c7..625a2f691e05 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -1,9 +1,12 @@
from django.db import models
+from django.db.models.functions import Lower
from django.utils.functional import Promise
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDModel
+from products.review_hog.backend.preferences import ReviewPreferences, ReviewProjectDefaults, UrgencyThreshold
from products.review_hog.backend.reviewer.artefact_content import (
ArtefactContentValidationError,
DroppedFindingArtefact,
@@ -386,31 +389,71 @@ class ReviewSkillConfig(UUIDModel, TeamScopedRootMixin):
]
+class AutomaticFlashFor(models.TextChoices):
+ """Who gets automatic Flash reviews under a project rule or a repository exception."""
+
+ EVERYONE = "everyone", "Automatic Flash for everyone"
+ LISTED = "listed", "Automatic Flash for these people"
+ OFF = "off", "Automatic Flash opt-in only"
+
+
+class ReviewProjectSettings(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
+ """A project's ReviewHog rule: who gets automatic Flash, bot pull requests, and Full defaults.
+
+ One row per root project, created on the first save. Without a row the defaults apply: automatic
+ Flash only for people who opt in, no reviews of bot pull requests, and the code defaults for the
+ Full review preferences. The rule's people lists are `ReviewRepositoryPerson` rows without a
+ repository.
+ """
+
+ class BotPullRequests(models.TextChoices):
+ SKIP = "skip", "Not reviewed"
+ RUN = "run", "Automatic Flash"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ flash_for = models.CharField(
+ max_length=20,
+ choices=AutomaticFlashFor.choices,
+ default=AutomaticFlashFor.OFF,
+ db_default=AutomaticFlashFor.OFF.value,
+ )
+ bot_prs = models.CharField(
+ max_length=10,
+ choices=BotPullRequests.choices,
+ default=BotPullRequests.SKIP,
+ db_default=BotPullRequests.SKIP.value,
+ )
+ # Project defaults for the Full review preferences (see `preferences.PROJECT_DEFAULT_FIELDS`).
+ preferences = models.JSONField(default=dict, db_default={}, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["team"], name="uniq_review_project_settings_per_team"),
+ ]
+
+ @classmethod
+ def load(cls, team_id: int) -> "ReviewProjectSettings":
+ """The project's row, or an unsaved instance carrying the defaults when none exists."""
+ row = cls.objects.for_team(team_id).first()
+ return row if row is not None else cls(team_id=team_id)
+
+ @property
+ def defaults(self) -> ReviewProjectDefaults:
+ return ReviewProjectDefaults.resolve(self.preferences)
+
+
class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
- """Per-(team, user) ReviewHog settings: what gets reviewed and how strict publishing is.
-
- One row per user per project, created with defaults on first read. `review_labeled_prs` is the
- label trigger's opt-out — the workflow gates on the PR author's row (no row = the defaults).
- `urgency_threshold` is the minimum priority a validated finding needs to be published; it snaps
- to a run at acting-user resolution, so mid-run edits don't flip gates between body and publish.
- `review_inbox_prs` is the inbox trigger's opt-in (default off — the budget gate for 100%-coverage
- cost): checked cheaply at the TaskRun-completion receiver and re-checked off the resolve snapshot.
- `stamphog_review_inbox_prs` is the same opt-in for hosted Stamphog (approve-first review with a
- real GitHub approval) on those same inbox PRs. It is a cross-product preference kept here so both
- toggles live on one row, and it only takes effect for teams with a synced, enabled
- StamphogRepoConfig covering the PR's repository.
- `resolve_comments` is the resolution stage's opt-out (default on — reviewing includes resolving):
- when on, every published review of the user's PRs chains into the resolution stage.
- `review_authored_prs` opts into automatic Flash reviews of the user's own PRs independently of
- the inbox and label triggers. `flash_reasoning_effort` also applies to manually requested Flash
- reviews, so disabling the automatic trigger preserves that preference.
+ """Per-(team, user) ReviewHog preferences.
+
+ One row per user per project, created on the first save. `preferences` holds only the keys the
+ user changed; `preferences.ReviewPreferences` fills in the project and code defaults. Use
+ `load_preferences` to read them. The boolean and choice columns are unused: their values moved
+ into `preferences`, and the columns stay only so that no migration has to drop them.
"""
- class UrgencyThreshold(models.TextChoices):
- # Values mirror `IssuePriority` so the threshold compares directly against finding priorities.
- CONSIDER = "consider" # "All issues"
- SHOULD_FIX = "should_fix"
- MUST_FIX = "must_fix"
+ UrgencyThreshold = UrgencyThreshold
class FlashReasoningEffort(models.TextChoices):
MEDIUM = "medium", "Medium"
@@ -420,19 +463,27 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
# table takes no lock on the parents (app-level enforcement only).
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ preferences = models.JSONField(default=dict, db_default={}, blank=True)
+ # Unused: values live in preferences.
review_inbox_prs = models.BooleanField(default=False, db_default=False)
+ # Unused: values live in preferences.
stamphog_review_inbox_prs = models.BooleanField(default=False, db_default=False)
+ # Unused: a label always runs.
review_labeled_prs = models.BooleanField(default=True, db_default=True)
+ # Unused: values live in preferences.
resolve_comments = models.BooleanField(default=True, db_default=True)
- # Opt-out of the clean-review media in the PR status comment ("Nothing worth raising this time").
+ # Unused: values live in preferences.
celebrate_clean_reviews = models.BooleanField(default=True, db_default=True)
+ # Unused: values live in preferences (`default_review_mode`).
review_authored_prs = models.BooleanField(default=False, db_default=False)
+ # Unused: Flash reviews use the default reasoning effort.
flash_reasoning_effort = models.CharField(
max_length=10,
choices=FlashReasoningEffort.choices,
default=FlashReasoningEffort.MEDIUM,
db_default=FlashReasoningEffort.MEDIUM.value,
)
+ # Unused: values live in preferences.
urgency_threshold = models.CharField(
max_length=20,
choices=UrgencyThreshold.choices,
@@ -458,3 +509,159 @@ class ReviewUserSettings(UUIDModel, TeamScopedRootMixin):
"""`load` for several users in one query; users with no row get the same defaults."""
rows = {row.user_id: row for row in cls.objects.for_team(team_id).filter(user_id__in=user_ids)}
return {user_id: rows.get(user_id) or cls(team_id=team_id, user_id=user_id) for user_id in user_ids}
+
+ @classmethod
+ def load_preferences(cls, team_id: int, user_id: int) -> ReviewPreferences:
+ """The user's effective preferences: their own values over the project and code defaults."""
+ return cls.load_preferences_many(team_id, [user_id])[user_id]
+
+ @classmethod
+ def load_preferences_many(cls, team_id: int, user_ids: list[int]) -> dict[int, ReviewPreferences]:
+ project = ReviewProjectSettings.load(team_id).defaults
+ rows = cls.load_many(team_id, user_ids)
+ return {user_id: ReviewPreferences.resolve(row.preferences, project) for user_id, row in rows.items()}
+
+
+class ReviewInstallationClaim(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
+ """Which repositories of a GitHub installation this project reviews, like GitHub's install picker.
+
+ `all` takes every repository of the installation that no other project selected. At most one
+ project can take all repositories of an installation. `selected` takes only the repositories
+ this project selected (`ReviewRepository.selected`). Read `ownership.py` for the resolution.
+ """
+
+ activity_logging_on_delete = True
+
+ class Scope(models.TextChoices):
+ ALL = "all", "All repositories"
+ SELECTED = "selected", "Only selected repositories"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ # The GitHub App installation id, as `Integration.integration_id` stores it.
+ installation_id = models.CharField(max_length=64)
+ scope = models.CharField(max_length=10, choices=Scope.choices)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["team", "installation_id"], name="uniq_review_installation_claim"),
+ models.UniqueConstraint(
+ fields=["installation_id"],
+ condition=models.Q(scope="all"),
+ name="uniq_review_installation_claim_all",
+ ),
+ ]
+
+
+class ReviewRepository(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
+ """A GitHub repository that one project has settings for.
+
+ `selected` includes the repository into this project, also when another project takes all
+ repositories of the installation. `flash_for` is the repository exception: null follows the
+ project rule (`ReviewProjectSettings.flash_for`). A row that is neither selected nor an exception
+ has no meaning and is deleted. A repository has at most one row across all projects, so it
+ belongs to one project only.
+ """
+
+ activity_logging_on_delete = True
+
+ # db_constraint=False keeps the migration lock-free on hot posthog_team / posthog_user.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ # The installation that last reported the repository. Not part of the identity: a reinstall of
+ # the GitHub App gets a new installation id for the same repositories.
+ installation_id = models.CharField(max_length=64)
+ # Null until a webhook or the repository list shows the id. Renames keep the id, so lookups
+ # match the id first and then the name.
+ github_repo_id = models.BigIntegerField(null=True, blank=True)
+ # `owner/name` as GitHub spells it. GitHub treats the name case-insensitively, so every lookup
+ # and the unique constraint compare it lowercased.
+ full_name = models.CharField(max_length=200)
+ selected = models.BooleanField(default=False, db_default=False)
+ flash_for = models.CharField(max_length=20, choices=AutomaticFlashFor.choices, null=True, blank=True)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(Lower("full_name"), name="uniq_review_repository_name"),
+ models.UniqueConstraint(
+ fields=["github_repo_id"],
+ condition=models.Q(github_repo_id__isnull=False),
+ name="uniq_review_repository_github_id",
+ ),
+ ]
+
+
+class ReviewRepositoryPerson(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):
+ """A person on one of the two lists of the project rule, or of a repository exception.
+
+ `repository` is null for the lists of the project rule. The lists are separate, so a change of
+ `flash_for` does not turn listed people into excepted people. Only the list that matches
+ `flash_for` has an effect.
+ """
+
+ activity_logging_on_delete = True
+
+ class Kind(models.TextChoices):
+ LISTED = "listed", "Listed"
+ EXCEPTED = "excepted", "Excepted"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ repository = models.ForeignKey(ReviewRepository, on_delete=models.CASCADE, related_name="+", null=True, blank=True)
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ kind = models.CharField(max_length=20, choices=Kind.choices)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["repository", "user", "kind"],
+ condition=models.Q(repository__isnull=False),
+ name="uniq_review_repository_person",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "user", "kind"],
+ condition=models.Q(repository__isnull=True),
+ name="uniq_review_project_person",
+ ),
+ ]
+
+
+class ReviewUserRepositoryChoice(UUIDModel, TeamScopedRootMixin):
+ """A user's own automatic review choice for their PRs in one repository.
+
+ Keyed by the repository itself, not by a `ReviewRepository` row, so a choice works in every
+ repository the project reviews. A choice in a repository that another project reviews stays
+ stored but has no effect. No row means the user's default applies, so there is no "follow" value.
+ """
+
+ class Mode(models.TextChoices):
+ FLASH = "flash", "Flash"
+ OFF = "off", "Off"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="+", db_constraint=False)
+ # The installation that last reported the repository. Not part of the identity, as on `ReviewRepository`.
+ installation_id = models.CharField(max_length=64)
+ github_repo_id = models.BigIntegerField(null=True, blank=True)
+ full_name = models.CharField(max_length=200)
+ mode = models.CharField(max_length=10, choices=Mode.choices)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint("team", "user", Lower("full_name"), name="uniq_review_user_repository_choice"),
+ models.UniqueConstraint(
+ fields=["team", "user", "github_repo_id"],
+ condition=models.Q(github_repo_id__isnull=False),
+ name="uniq_review_user_repository_choice_id",
+ ),
+ ]
diff --git a/products/review_hog/backend/ownership.py b/products/review_hog/backend/ownership.py
new file mode 100644
index 000000000000..f488c171d5a8
--- /dev/null
+++ b/products/review_hog/backend/ownership.py
@@ -0,0 +1,244 @@
+"""Which project reviews a GitHub repository.
+
+A repository belongs to at most one project, like GitHub's install picker:
+
+1. A project that selected the repository (`ReviewRepository.selected`), or that has a row for it
+ and takes all repositories of the installation, owns it.
+2. Else the project that takes all repositories of the installation owns it.
+3. Else no project owns it: no automatic review, and the label trigger reports "not set up".
+
+`resolve_owner` is pure. `RepositoryOwnership` loads the rows across projects, because ownership is
+a question about every project that shares the installation. `OwnedRepositoryPrefilter` lets the
+webhook handler drop events of repositories nobody reviews before it queues a task.
+"""
+
+import logging
+from collections.abc import Iterable, Sequence
+from typing import Any
+
+from django.core.cache import cache
+from django.db import transaction
+from django.db.models import Q
+from django.db.models.functions import Lower
+from django.db.models.signals import post_delete, post_save
+from django.dispatch import receiver
+
+from posthog.dataclasses import frozen
+from posthog.ingress.dispatch.database import bounded_statement_timeout
+from posthog.models.integration import Integration
+from posthog.utils import safe_cache_delete
+
+from products.review_hog.backend.models import ReviewInstallationClaim, ReviewRepository
+
+logger = logging.getLogger(__name__)
+
+
+@frozen
+class RepositoryRef:
+ installation_id: str
+ # None when the caller only knows the name, for example the label trigger.
+ github_repo_id: int | None
+ full_name: str
+
+ def matches(self, row: ReviewRepository) -> bool:
+ if self.github_repo_id is not None and row.github_repo_id == self.github_repo_id:
+ return True
+ # A name match with another id is an older repository that had this name.
+ same_repository = row.github_repo_id is None or self.github_repo_id is None
+ return same_repository and row.full_name.lower() == self.full_name.lower()
+
+
+@frozen
+class RepositoryOwner:
+ team_id: int
+ installation_id: str
+ row: ReviewRepository | None
+
+
+def find_matching_row(ref: RepositoryRef, rows: Sequence[ReviewRepository]) -> ReviewRepository | None:
+ """The row for this repository: an id match first, then a name match."""
+ if ref.github_repo_id is not None:
+ for row in rows:
+ if row.github_repo_id == ref.github_repo_id:
+ return row
+ for row in rows:
+ if ref.matches(row):
+ return row
+ return None
+
+
+def resolve_owner(
+ ref: RepositoryRef, rows: Sequence[ReviewRepository], all_claim: ReviewInstallationClaim | None
+) -> RepositoryOwner | None:
+ """The owning project of one repository, from the installation's rows and its "all" claim."""
+ row = find_matching_row(ref, rows)
+ if row is not None and (row.selected or (all_claim is not None and all_claim.team_id == row.team_id)):
+ return RepositoryOwner(team_id=row.team_id, installation_id=ref.installation_id, row=row)
+ if all_claim is not None:
+ return RepositoryOwner(team_id=all_claim.team_id, installation_id=ref.installation_id, row=None)
+ return None
+
+
+class RepositoryOwnership:
+ @staticmethod
+ def rows_for(ref: RepositoryRef) -> list[ReviewRepository]:
+ # Unscoped on purpose: a repository can belong to any project. The name and the id identify
+ # it, not the installation, so a reinstall of the GitHub App keeps the rows.
+ name_or_id = Q(full_name__iexact=ref.full_name)
+ if ref.github_repo_id is not None:
+ name_or_id |= Q(github_repo_id=ref.github_repo_id)
+ return list(ReviewRepository.objects.unscoped().filter(name_or_id))
+
+ @staticmethod
+ def rows_for_listing(full_names: Iterable[str], github_repo_ids: Iterable[int]) -> list[ReviewRepository]:
+ """The rows of every repository in one listing, matched by name or id like `rows_for`."""
+ return list(
+ ReviewRepository.objects.unscoped()
+ .annotate(name_lower=Lower("full_name"))
+ .filter(
+ Q(name_lower__in={name.lower() for name in full_names}) | Q(github_repo_id__in=set(github_repo_ids))
+ )
+ )
+
+ @staticmethod
+ def all_claim(installation_id: str) -> ReviewInstallationClaim | None:
+ return (
+ ReviewInstallationClaim.objects.unscoped()
+ .filter(installation_id=installation_id, scope=ReviewInstallationClaim.Scope.ALL)
+ .first()
+ )
+
+ @classmethod
+ def find(cls, ref: RepositoryRef, *, backfill: bool = False) -> RepositoryOwner | None:
+ """The owning project. Only a signed GitHub webhook may pass `backfill=True`.
+
+ The backfill writes the id and the name of `ref` onto a row of any project, so a ref built
+ from client input must never reach it.
+ """
+ owner = resolve_owner(ref, cls.rows_for(ref), cls.all_claim(ref.installation_id))
+ if backfill and owner is not None and owner.row is not None:
+ cls._backfill(owner.row, ref)
+ return owner
+
+ @staticmethod
+ def _backfill(row: ReviewRepository, ref: RepositoryRef) -> None:
+ """Store the repository id the first time it shows, and the current name after a rename."""
+ updates: dict[str, Any] = {}
+ if row.github_repo_id is None and ref.github_repo_id is not None:
+ updates["github_repo_id"] = ref.github_repo_id
+ if ref.github_repo_id is not None and row.full_name != ref.full_name:
+ updates["full_name"] = ref.full_name
+ if not updates:
+ return
+ try:
+ # A plain update, because bookkeeping must not add an activity log entry. The savepoint
+ # keeps a unique violation from breaking a surrounding transaction.
+ with transaction.atomic():
+ ReviewRepository.objects.unscoped().filter(id=row.id).update(**updates)
+ except Exception:
+ # Another row can hold the new name or id after an unusual rename. The match still holds.
+ logger.warning("Could not backfill ReviewHog repository %s", row.id, exc_info=True)
+ return
+ OwnedRepositoryPrefilter.invalidate(row.installation_id)
+
+ @staticmethod
+ def installation_ids_for_account(account_login: str) -> list[str]:
+ """The installations of the PostHog GitHub App on one GitHub account, from any project."""
+ installation_ids = (
+ Integration.objects.filter(kind="github", config__account__name__iexact=account_login)
+ .values_list("integration_id", flat=True)
+ .distinct()
+ )
+ return sorted({installation_id for installation_id in installation_ids if installation_id})
+
+ @classmethod
+ def find_by_name(cls, full_name: str) -> RepositoryOwner | None:
+ """Ownership when only the name is known. The account login in the name finds the installation."""
+ account_login, _, _ = full_name.partition("/")
+ for installation_id in cls.installation_ids_for_account(account_login):
+ owner = cls.find(RepositoryRef(installation_id=installation_id, github_repo_id=None, full_name=full_name))
+ if owner is not None:
+ return owner
+ return None
+
+
+class OwnedRepositoryPrefilter:
+ """A cached summary of which repositories of an installation any project reviews.
+
+ The webhook handler uses it to drop pull request events of repositories nobody reviews, so it
+ queues no task for them. `RepositoryOwnership.find` stays the source of truth: the cache is only
+ a prefilter. The receivers below delete the key on every change, and the TTL caps staleness for
+ writes that bypass the ORM signals.
+ """
+
+ TTL_SECONDS = 5 * 60
+ STATEMENT_TIMEOUT_MS = 500
+
+ @staticmethod
+ def cache_key(installation_id: str) -> str:
+ return f"review_hog:owned_repositories:{installation_id}"
+
+ @staticmethod
+ def load(installation_id: str) -> dict[str, Any]:
+ # JSON-shaped values only, because the cache serializes them.
+ takes_all = ReviewInstallationClaim.objects.unscoped().filter(
+ installation_id=installation_id, scope=ReviewInstallationClaim.Scope.ALL
+ )
+ selected = ReviewRepository.objects.unscoped().filter(installation_id=installation_id, selected=True)
+ rows = list(selected.values_list("full_name", "github_repo_id"))
+ return {
+ "all": takes_all.exists(),
+ "names": sorted({full_name.lower() for full_name, _ in rows}),
+ "ids": sorted({github_repo_id for _, github_repo_id in rows if github_repo_id is not None}),
+ }
+
+ @classmethod
+ def load_bounded(cls, installation_id: str) -> dict[str, Any]:
+ # The webhook handler reads inside the request, so a slow read must not hold the delivery.
+ with bounded_statement_timeout(cls.STATEMENT_TIMEOUT_MS, models=[ReviewInstallationClaim, ReviewRepository]):
+ return cls.load(installation_id)
+
+ @classmethod
+ def may_be_owned(cls, ref: RepositoryRef) -> bool:
+ try:
+ summary = cache.get_or_set(
+ cls.cache_key(ref.installation_id), lambda: cls.load_bounded(ref.installation_id), cls.TTL_SECONDS
+ )
+ if not isinstance(summary, dict):
+ summary = cls.load_bounded(ref.installation_id)
+ except Exception:
+ # Fail open: the task checks ownership again, and a Redis blip must not stop reviews.
+ logger.warning("Could not read the owned ReviewHog repositories; queueing the event", exc_info=True)
+ return True
+ return (
+ bool(summary.get("all"))
+ or ref.full_name.lower() in summary.get("names", [])
+ or ref.github_repo_id in summary.get("ids", [])
+ )
+
+ @classmethod
+ def invalidate(cls, installation_id: str) -> None:
+ key = cls.cache_key(installation_id)
+ safe_cache_delete(key)
+ # A reader between this delete and the commit can cache the old rows again.
+ transaction.on_commit(lambda: safe_cache_delete(key))
+
+
+@receiver(post_save, sender=ReviewRepository)
+@receiver(post_save, sender=ReviewInstallationClaim)
+def _invalidate_owned_repositories_on_save(
+ sender: type[ReviewRepository | ReviewInstallationClaim],
+ instance: ReviewRepository | ReviewInstallationClaim,
+ **kwargs: Any,
+) -> None:
+ OwnedRepositoryPrefilter.invalidate(instance.installation_id)
+
+
+@receiver(post_delete, sender=ReviewRepository)
+@receiver(post_delete, sender=ReviewInstallationClaim)
+def _invalidate_owned_repositories_on_delete(
+ sender: type[ReviewRepository | ReviewInstallationClaim],
+ instance: ReviewRepository | ReviewInstallationClaim,
+ **kwargs: Any,
+) -> None:
+ OwnedRepositoryPrefilter.invalidate(instance.installation_id)
diff --git a/products/review_hog/backend/pr_owner.py b/products/review_hog/backend/pr_owner.py
new file mode 100644
index 000000000000..3f361848973b
--- /dev/null
+++ b/products/review_hog/backend/pr_owner.py
@@ -0,0 +1,97 @@
+"""Who owns a pull request: the person whose opt-ins decide what ReviewHog may do to it.
+
+1. The author, when the GitHub login maps to an active member of the project's organization.
+2. A self-driving pull request, which the PostHog GitHub App authors for an Inbox report: the report's
+ canonical reviewer among the active members (`receivers.pick_reviewer`).
+3. Else nobody. A pull request without an owner never gets writes, because nobody opted in to them.
+
+`pick_pr_owner` is pure. `PullRequestOwnerResolver.resolve` loads what it needs. Callers pass the head
+branch only for a head in the base repository: a fork's branch name is chosen by the fork's owner, and
+the Inbox link matches on it.
+"""
+
+from typing import Literal
+
+from posthog.dataclasses import frozen
+from posthog.models.instance_setting import get_instance_setting
+from posthog.models.organization import OrganizationMembership
+
+from products.review_hog.backend.receivers import pick_reviewer, resolve_assigned_reviewers
+
+PullRequestOwnerSource = Literal["author", "inbox_reviewer", "none"]
+
+
+@frozen
+class PullRequestOwner:
+ user_id: int | None
+ source: PullRequestOwnerSource
+
+
+def pick_pr_owner(
+ *, author_user_id: int | None, authored_by_posthog_app: bool, inbox_reviewer_id: int | None
+) -> PullRequestOwner:
+ if author_user_id is not None:
+ return PullRequestOwner(user_id=author_user_id, source="author")
+ if authored_by_posthog_app and inbox_reviewer_id is not None:
+ return PullRequestOwner(user_id=inbox_reviewer_id, source="inbox_reviewer")
+ return PullRequestOwner(user_id=None, source="none")
+
+
+def is_active_member(*, team_id: int, user_id: int) -> bool:
+ return OrganizationMembership.objects.filter(
+ organization__team__id=team_id, user_id=user_id, user__is_active=True
+ ).exists()
+
+
+def posthog_app_login() -> str | None:
+ """The login GitHub gives the PostHog GitHub App, which opens self-driving pull requests."""
+ slug = get_instance_setting("GITHUB_APP_SLUG")
+ return f"{slug}[bot]".lower() if slug else None
+
+
+class PullRequestOwnerResolver:
+ @staticmethod
+ def active_author_id(team_id: int, author_login: str) -> int | None:
+ # Pulls in the signals product, which a webhook must not load at import.
+ from products.signals.backend.report_generation.resolve_reviewers import ( # noqa: PLC0415
+ resolve_org_github_login_to_users,
+ )
+
+ login = author_login.strip().lower()
+ if not login:
+ return None
+ user = resolve_org_github_login_to_users(team_id, [login]).get(login)
+ # An inactive user cannot act and cannot opt in, so they own nothing.
+ if user is None or not is_active_member(team_id=team_id, user_id=user.id):
+ return None
+ return user.id
+
+ @staticmethod
+ def inbox_reviewer_id(team_id: int, *, repository: str, head_branch: str | None) -> int | None:
+ # The tasks facade loads the tasks product, which a webhook must not load at import.
+ from products.tasks.backend.facade.api import find_signal_implementation_run # noqa: PLC0415
+
+ run = find_signal_implementation_run(team_id=team_id, repository=repository, head_branch=head_branch)
+ if run is None or run.team_id != team_id:
+ return None
+ # An inactive reviewer cannot act or opt in, so ownership falls to the next active one.
+ reviewers = [
+ user
+ for user in resolve_assigned_reviewers(team_id, run.signal_report_id)
+ if is_active_member(team_id=team_id, user_id=user.id)
+ ]
+ return pick_reviewer(reviewers, run.task_created_by_id) if reviewers else None
+
+ @classmethod
+ def resolve(cls, team_id: int, *, repository: str, author_login: str, head_branch: str | None) -> PullRequestOwner:
+ author_user_id = cls.active_author_id(team_id, author_login)
+ app_login = posthog_app_login()
+ authored_by_posthog_app = app_login is not None and author_login.strip().lower() == app_login
+ inbox_reviewer_id = None
+ if author_user_id is None and authored_by_posthog_app:
+ inbox_reviewer_id = cls.inbox_reviewer_id(team_id, repository=repository, head_branch=head_branch)
+ return pick_pr_owner(
+ author_user_id=author_user_id,
+ authored_by_posthog_app=authored_by_posthog_app,
+ inbox_reviewer_id=inbox_reviewer_id,
+ )
diff --git a/products/review_hog/backend/preferences.py b/products/review_hog/backend/preferences.py
new file mode 100644
index 000000000000..09cd91fa6b48
--- /dev/null
+++ b/products/review_hog/backend/preferences.py
@@ -0,0 +1,194 @@
+"""Personal ReviewHog preferences: one typed schema over sparse JSON.
+
+A person's stored preferences hold only the keys they changed. An absent key means the inherited
+value: the project default for the keys a project can set, else the code default. Reads drop
+unknown keys and invalid values, so a removed or renamed key never breaks a load. Writes validate
+every key and drop a value that equals the inherited one, so a later change of the project default
+reaches everyone who did not choose their own value.
+
+This module is pure. `ReviewUserSettings` and `ReviewProjectSettings` store the dicts.
+"""
+
+from collections.abc import Mapping
+from typing import cast
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+PreferenceValue = str | bool
+
+
+class DefaultReviewMode(models.TextChoices):
+ FOLLOW = "follow", "Follow each repository"
+ FLASH = "flash", "Flash everywhere"
+ OFF = "off", "Off everywhere"
+
+
+class UrgencyThreshold(models.TextChoices):
+ # Values mirror `IssuePriority`, so the threshold compares directly against finding priorities.
+ CONSIDER = "consider", "Consider (all)"
+ SHOULD_FIX = "should_fix", "Should fix"
+ MUST_FIX = "must_fix", "Must fix"
+
+
+class PreferenceSource(models.TextChoices):
+ USER = "user", "Set by the user"
+ PROJECT = "project", "Project default"
+ DEFAULT = "default", "Built-in default"
+
+
+class InvalidPreference(ValueError):
+ def __init__(self, key: str, message: str) -> None:
+ super().__init__(message)
+ self.key = key
+
+
+@frozen
+class PreferenceField:
+ key: str
+ default: PreferenceValue
+ # None for a boolean preference.
+ choices: tuple[str, ...] | None = None
+ project_default: bool = False
+
+ def is_valid(self, value: object) -> bool:
+ if self.choices is None:
+ return isinstance(value, bool)
+ return isinstance(value, str) and value in self.choices
+
+
+PREFERENCE_FIELDS: tuple[PreferenceField, ...] = (
+ PreferenceField(
+ key="default_review_mode", default=DefaultReviewMode.FOLLOW.value, choices=tuple(DefaultReviewMode.values)
+ ),
+ PreferenceField(key="resolve_comments", default=False),
+ PreferenceField(
+ key="urgency_threshold",
+ default=UrgencyThreshold.CONSIDER.value,
+ choices=tuple(UrgencyThreshold.values),
+ project_default=True,
+ ),
+ PreferenceField(key="celebrate_clean_reviews", default=True, project_default=True),
+ PreferenceField(key="review_inbox_prs", default=False),
+ PreferenceField(key="stamphog_review_inbox_prs", default=False),
+)
+PREFERENCE_KEYS: tuple[str, ...] = tuple(field.key for field in PREFERENCE_FIELDS)
+PROJECT_DEFAULT_FIELDS: tuple[PreferenceField, ...] = tuple(
+ field for field in PREFERENCE_FIELDS if field.project_default
+)
+PROJECT_DEFAULT_KEYS: tuple[str, ...] = tuple(field.key for field in PROJECT_DEFAULT_FIELDS)
+
+
+def clean_values(raw: object, fields: tuple[PreferenceField, ...]) -> dict[str, PreferenceValue]:
+ """The valid known keys of a stored dict. Anything else is ignored."""
+ if not isinstance(raw, Mapping):
+ return {}
+ return {field.key: raw[field.key] for field in fields if field.key in raw and field.is_valid(raw[field.key])}
+
+
+def _validated_changes(
+ changes: Mapping[str, object], fields: tuple[PreferenceField, ...]
+) -> dict[str, PreferenceValue]:
+ by_key = {field.key: field for field in fields}
+ validated: dict[str, PreferenceValue] = {}
+ for key, value in changes.items():
+ field = by_key.get(key)
+ if field is None:
+ raise InvalidPreference(key, f"Unknown preference '{key}'.")
+ if not field.is_valid(value):
+ expected = "true or false" if field.choices is None else ", ".join(field.choices)
+ raise InvalidPreference(key, f"Invalid value for '{key}'. Expected one of: {expected}.")
+ validated[key] = cast(PreferenceValue, value)
+ return validated
+
+
+@frozen
+class ReviewProjectDefaults:
+ """A project's defaults for the Full review preferences, with the code default filled in."""
+
+ urgency_threshold: UrgencyThreshold
+ celebrate_clean_reviews: bool
+ stored: Mapping[str, PreferenceValue]
+
+ @classmethod
+ def resolve(cls, stored: object) -> "ReviewProjectDefaults":
+ values = clean_values(stored, PROJECT_DEFAULT_FIELDS)
+ effective = {field.key: values.get(field.key, field.default) for field in PROJECT_DEFAULT_FIELDS}
+ return cls(
+ urgency_threshold=UrgencyThreshold(str(effective["urgency_threshold"])),
+ celebrate_clean_reviews=bool(effective["celebrate_clean_reviews"]),
+ stored=values,
+ )
+
+ def with_changes(self, changes: Mapping[str, object]) -> dict[str, PreferenceValue]:
+ """The stored dict after `changes`. A value equal to the code default is removed.
+
+ Raises `InvalidPreference` for an unknown key or an invalid value.
+ """
+ merged = {**self.stored, **_validated_changes(changes, PROJECT_DEFAULT_FIELDS)}
+ return {
+ field.key: merged[field.key]
+ for field in PROJECT_DEFAULT_FIELDS
+ if merged.get(field.key, field.default) != field.default
+ }
+
+
+@frozen
+class ReviewPreferences:
+ """A person's effective preferences, and where each value comes from."""
+
+ default_review_mode: DefaultReviewMode
+ resolve_comments: bool
+ urgency_threshold: UrgencyThreshold
+ celebrate_clean_reviews: bool
+ review_inbox_prs: bool
+ stamphog_review_inbox_prs: bool
+ sources: Mapping[str, PreferenceSource]
+ stored: Mapping[str, PreferenceValue]
+ project: ReviewProjectDefaults
+
+ @staticmethod
+ def _inherited(field: PreferenceField, project: ReviewProjectDefaults) -> tuple[PreferenceValue, PreferenceSource]:
+ if field.project_default and field.key in project.stored:
+ return project.stored[field.key], PreferenceSource.PROJECT
+ return field.default, PreferenceSource.DEFAULT
+
+ @classmethod
+ def resolve(cls, stored: object, project: ReviewProjectDefaults) -> "ReviewPreferences":
+ values = clean_values(stored, PREFERENCE_FIELDS)
+ effective: dict[str, PreferenceValue] = {}
+ sources: dict[str, PreferenceSource] = {}
+ for field in PREFERENCE_FIELDS:
+ if field.key in values:
+ effective[field.key], sources[field.key] = values[field.key], PreferenceSource.USER
+ else:
+ effective[field.key], sources[field.key] = cls._inherited(field, project)
+ return cls(
+ default_review_mode=DefaultReviewMode(str(effective["default_review_mode"])),
+ resolve_comments=bool(effective["resolve_comments"]),
+ urgency_threshold=UrgencyThreshold(str(effective["urgency_threshold"])),
+ celebrate_clean_reviews=bool(effective["celebrate_clean_reviews"]),
+ review_inbox_prs=bool(effective["review_inbox_prs"]),
+ stamphog_review_inbox_prs=bool(effective["stamphog_review_inbox_prs"]),
+ sources=sources,
+ stored=values,
+ project=project,
+ )
+
+ @classmethod
+ def defaults(cls) -> "ReviewPreferences":
+ return cls.resolve({}, ReviewProjectDefaults.resolve({}))
+
+ def with_changes(self, changes: Mapping[str, object]) -> dict[str, PreferenceValue]:
+ """The stored dict after `changes`. A value equal to the inherited value is removed.
+
+ Raises `InvalidPreference` for an unknown key or an invalid value.
+ """
+ merged = {**self.stored, **_validated_changes(changes, PREFERENCE_FIELDS)}
+ stored: dict[str, PreferenceValue] = {}
+ for field in PREFERENCE_FIELDS:
+ inherited, _source = self._inherited(field, self.project)
+ if field.key in merged and merged[field.key] != inherited:
+ stored[field.key] = merged[field.key]
+ return stored
diff --git a/products/review_hog/backend/pull_request_events.py b/products/review_hog/backend/pull_request_events.py
new file mode 100644
index 000000000000..919c38e22369
--- /dev/null
+++ b/products/review_hog/backend/pull_request_events.py
@@ -0,0 +1,136 @@
+"""GitHub `pull_request` deliveries of the PostHog GitHub App, routed by action.
+
+- `opened` / `synchronize`: an automatic review (`automatic_reviews.py`).
+- `labeled` with the `reviewhog` label: a label review (`label_reviews.py`).
+
+The webhook handler runs inside the request, so this module only parses the payload, reads the
+cached ownership summary, and queues a Celery task. The task checks ownership and the rules again.
+"""
+
+from collections.abc import Mapping
+
+from posthog.dataclasses import frozen
+
+from products.review_hog.backend.ownership import OwnedRepositoryPrefilter, RepositoryRef
+
+REVIEWHOG_LABEL = "reviewhog"
+AUTOMATIC_REVIEW_ACTIONS = frozenset({"opened", "synchronize"})
+
+
+def _mapping(value: object) -> Mapping[str, object]:
+ return value if isinstance(value, Mapping) else {}
+
+
+def _repository_name(value: object) -> str | None:
+ full_name = _mapping(value).get("full_name")
+ return full_name if isinstance(full_name, str) and full_name.strip() else None
+
+
+def _positive_int(value: object) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
+ return None
+ return value
+
+
+def _text(value: object) -> str | None:
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+@frozen
+class PullRequestEvent:
+ """The parts of an open, same-repository pull request delivery that ReviewHog acts on."""
+
+ action: str
+ installation_id: str
+ repository: str
+ github_repo_id: int | None
+ pr_number: int
+ author_login: str
+ head_sha: str
+ head_branch: str
+ # Set on `labeled` deliveries only.
+ label_name: str | None = None
+ sender_login: str | None = None
+ sender_is_bot: bool = False
+
+ @classmethod
+ def from_payload(cls, payload: Mapping[str, object]) -> "PullRequestEvent | None":
+ action = payload.get("action")
+ if not isinstance(action, str):
+ return None
+ pull_request = _mapping(payload.get("pull_request"))
+ if pull_request.get("state") != "open" or pull_request.get("merged"):
+ return None
+ head = _mapping(pull_request.get("head"))
+ base = _mapping(pull_request.get("base"))
+ # The PR must come from a branch of the same repository, because a fork's head cannot be
+ # trusted.
+ names = [_repository_name(repo) for repo in (payload.get("repository"), head.get("repo"), base.get("repo"))]
+ repository = names[0]
+ if repository is None or any(name is None or name.lower() != repository.lower() for name in names):
+ return None
+
+ installation_id = _positive_int(_mapping(payload.get("installation")).get("id"))
+ author_login = _text(_mapping(pull_request.get("user")).get("login"))
+ pr_number = _positive_int(pull_request.get("number"))
+ head_sha = _text(head.get("sha"))
+ if installation_id is None or pr_number is None or author_login is None or head_sha is None:
+ return None
+ sender = _mapping(payload.get("sender"))
+ return cls(
+ action=action,
+ installation_id=str(installation_id),
+ repository=repository,
+ github_repo_id=_positive_int(_mapping(payload.get("repository")).get("id")),
+ pr_number=pr_number,
+ author_login=author_login.lower(),
+ head_sha=head_sha,
+ head_branch=_text(head.get("ref")) or "",
+ label_name=_text(_mapping(payload.get("label")).get("name")),
+ sender_login=_text(sender.get("login")),
+ sender_is_bot=sender.get("type") == "Bot",
+ )
+
+ @property
+ def ref(self) -> RepositoryRef:
+ return RepositoryRef(
+ installation_id=self.installation_id, github_repo_id=self.github_repo_id, full_name=self.repository
+ )
+
+ @property
+ def is_label_request(self) -> bool:
+ return self.action == "labeled" and (self.label_name or "").lower() == REVIEWHOG_LABEL
+
+
+def accept_pull_request_event(payload: Mapping[str, object]) -> None:
+ event = PullRequestEvent.from_payload(payload)
+ if event is None:
+ return
+ wants_automatic_review = event.action in AUTOMATIC_REVIEW_ACTIONS
+ if not (wants_automatic_review or event.is_label_request):
+ return
+ if not OwnedRepositoryPrefilter.may_be_owned(event.ref):
+ return
+ # Keeps Celery off the registry import path.
+ from products.review_hog.backend.tasks import process_authored_pr_event, process_label_event # noqa: PLC0415
+
+ if wants_automatic_review:
+ process_authored_pr_event.delay(
+ installation_id=event.installation_id,
+ repository=event.repository,
+ author_login=event.author_login,
+ pr_number=event.pr_number,
+ head_sha=event.head_sha,
+ github_repo_id=event.github_repo_id,
+ )
+ return
+ process_label_event.delay(
+ installation_id=event.installation_id,
+ repository=event.repository,
+ github_repo_id=event.github_repo_id,
+ pr_number=event.pr_number,
+ author_login=event.author_login,
+ head_branch=event.head_branch,
+ labeler_login=event.sender_login or "",
+ labeled_by_bot=event.sender_is_bot,
+ )
diff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.py
index f24752e4a458..95eff2a60e0e 100644
--- a/products/review_hog/backend/receivers.py
+++ b/products/review_hog/backend/receivers.py
@@ -30,6 +30,9 @@ whose PR never opens is spend with no reader, and the PR save re-fires this rece
for the PR costs only the head start. The workflow and client keep their branch-target support for
callers that know what they are doing; this receiver just never uses it.
+Both reviews start only in projects with the `review-hog-internal` flag, the same flag that shows
+the Inbox switches in settings. A saved opt-in in any other project starts nothing.
+
The `TaskRun.branch` FIELD is never used as a target: auto-start seeds it with the BASE branch and
the agent server later overwrites it with the work branch, so its meaning depends on the path taken.
@@ -44,6 +47,7 @@ from django.db import transaction
from django.db.models.signals import post_save
from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.preferences import ReviewPreferences
from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.report_generation.priority import persisted_report_priority
@@ -53,6 +57,8 @@ from products.stamphog.backend.facade.inbox_hooks import register_inbox_acting_r
# posthog/test/repo_invariants/test_startup_import_budget.py forbids temporalio/modal/openai/anthropic at setup —
# the temporal client and the stamphog task module reach all four, so those two imports stay
# function-local in _start_review / _start_stamphog_review per the budget test's own prescription.
+# The internal flag check reaches posthog.permissions, which loads webauthn and zxcvbn, so it is
+# function-local too.
logger = logging.getLogger(__name__)
@@ -105,12 +111,16 @@ def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs:
# both signal_report_id and internal=True with it, so only ai_stage tells them apart.
if (instance.state or {}).get("ai_stage") != "implementation":
return
+ from products.review_hog.backend.internal_features import has_internal_features # noqa: PLC0415
+
+ if not has_internal_features(instance.team_id):
+ return
repository = (task.repository or "").strip() or None
- resolved = _resolve_assigned_reviewers(instance.team_id, task.signal_report_id)
+ resolved = resolve_assigned_reviewers(instance.team_id, task.signal_report_id)
if not resolved:
return
- settings_by_user = ReviewUserSettings.load_many(instance.team_id, [user.id for user in resolved])
- acting_user_id = _pick_reviewer(resolved, task.created_by_id)
+ settings_by_user = ReviewUserSettings.load_preferences_many(instance.team_id, [user.id for user in resolved])
+ acting_user_id = pick_reviewer(resolved, task.created_by_id)
stamphog_user_id = _pick_stamphog_reviewer(resolved, settings_by_user, task.created_by_id)
# robust=True on both: the two dispatches are independent but share one commit-hook queue, so
# a failure in one must not cancel the other. Django logs the failing hook and runs the rest.
@@ -160,15 +170,19 @@ def resolve_stamphog_acting_reviewer(team_id: int, signal_report_id: str, prefer
approval while somebody is still opted in. ``preferred_user_id`` (the task's creator, or the
reviewer a queued job was attributed to) wins while still opted in, keeping attribution stable.
"""
- resolved = _resolve_assigned_reviewers(team_id, signal_report_id)
+ from products.review_hog.backend.internal_features import has_internal_features # noqa: PLC0415
+
+ if not has_internal_features(team_id):
+ return None
+ resolved = resolve_assigned_reviewers(team_id, signal_report_id)
if not resolved:
return None
- settings_by_user = ReviewUserSettings.load_many(team_id, [user.id for user in resolved])
+ settings_by_user = ReviewUserSettings.load_preferences_many(team_id, [user.id for user in resolved])
return _pick_stamphog_reviewer(resolved, settings_by_user, preferred_user_id)
def _pick_stamphog_reviewer(
- resolved: list[Any], settings_by_user: dict[int, ReviewUserSettings], preferred_user_id: int | None
+ resolved: list[Any], settings_by_user: dict[int, ReviewPreferences], preferred_user_id: int | None
) -> int | None:
"""The user id to attribute a stamphog inbox review to, or None when nobody is opted in.
@@ -180,10 +194,10 @@ def _pick_stamphog_reviewer(
returns a single id however many are opted in, and stamphog dedupes on (pull request, head sha).
"""
opted_in = [user for user in resolved if settings_by_user[user.id].stamphog_review_inbox_prs]
- return _pick_reviewer(opted_in, preferred_user_id) if opted_in else None
+ return pick_reviewer(opted_in, preferred_user_id) if opted_in else None
-def _pick_reviewer(resolved: list[Any], task_created_by_id: int | None) -> int:
+def pick_reviewer(resolved: list[Any], task_created_by_id: int | None) -> int:
"""The canonical reviewer out of a non-empty resolved list: the task's own user, else the first.
The task's user (`created_by`: the auto-start assignee, or whoever clicked "Create PR") wins when
@@ -195,13 +209,13 @@ def _pick_reviewer(resolved: list[Any], task_created_by_id: int | None) -> int:
return next((user.id for user in resolved if user.id == task_created_by_id), resolved[0].id)
-def _resolve_assigned_reviewers(team_id: int, signal_report_id: Any) -> list[Any]:
+def resolve_assigned_reviewers(team_id: int, signal_report_id: Any) -> list[Any]:
"""The report's assigned reviewers, in assignment order (no opt-in toggles checked here).
Assignment means the report's latest `suggested_reviewers` artefact, the same set the Inbox "For
you" filter matches and Slack notifications fan out to, with logins resolved to org members the
same way those surfaces resolve them. Callers decide which of them gates what: ReviewHog runs
- under the canonical reviewer (`_pick_reviewer`, whose perspectives, blind spots, validator, and
+ under the canonical reviewer (`pick_reviewer`, whose perspectives, blind spots, validator, and
urgency threshold drive the review), stamphog under any who opted in (`_pick_stamphog_reviewer`).
Empty when the report has no reviewers or none resolve to an org member.
"""
diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.py
new file mode 100644
index 000000000000..16ca2cb36f54
--- /dev/null
+++ b/products/review_hog/backend/repository_settings.py
@@ -0,0 +1,443 @@
+"""Writes and reads behind the repository settings API: claims, repository rows, personal choices.
+
+The viewsets stay thin and call these classes. Every write keeps the ownership rules of
+`ownership.py`: a repository has at most one row across projects, at most one project takes all
+repositories of an installation, and a project only stores what differs from what it inherits.
+"""
+
+import logging
+from collections.abc import Mapping, Sequence
+from dataclasses import replace
+from typing import Any
+
+from django.db import IntegrityError, models, transaction
+
+from posthog.dataclasses import frozen
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.review_hog.backend.activity_logging import log_repository_taken
+from products.review_hog.backend.automatic_review_rules import (
+ AuthorPreferences,
+ AutomaticReviewDecision,
+ AutomaticReviewReason,
+ ProjectRuleContext,
+ load_author_preferences,
+)
+from products.review_hog.backend.models import (
+ ReviewInstallationClaim,
+ ReviewRepository,
+ ReviewRepositoryPerson,
+ ReviewUserRepositoryChoice,
+)
+from products.review_hog.backend.ownership import RepositoryOwnership, RepositoryRef, find_matching_row, resolve_owner
+
+logger = logging.getLogger(__name__)
+
+
+class Unset:
+ """Marks a field the request did not mention, because None is a valid value."""
+
+
+UNSET = Unset()
+
+
+class RepositorySettingsError(Exception):
+ """A write the rules do not allow. The API answers 400 with the message."""
+
+
+@frozen
+class ProjectRef:
+ """Another project, named only inside its own organization."""
+
+ team_id: int
+ name: str | None
+
+ @classmethod
+ def load(cls, team_id: int, *, viewer_organization_id: Any) -> "ProjectRef":
+ team = Team.objects.filter(id=team_id).values("name", "organization_id").first() or {}
+ same_organization = team.get("organization_id") == viewer_organization_id
+ return cls(team_id=team_id, name=team.get("name") if same_organization else None)
+
+ @property
+ def label(self) -> str:
+ return f"the {self.name} project" if self.name else "a project in another organization"
+
+
+class OwnershipConflict(Exception):
+ """Another project already holds what this write asks for. The API answers 409."""
+
+ def __init__(self, message: str, project: ProjectRef | None) -> None:
+ super().__init__(message)
+ self.project = project
+
+
+@frozen
+class RepositoryWriteResult:
+ # None when the write left nothing to store, so the row was deleted.
+ repository: ReviewRepository | None
+ # The project that took all repositories of the installation, when this write took one from it.
+ taken_from: ProjectRef | None
+
+
+@frozen
+class InstallationSummary:
+ installation_id: str
+ account_name: str
+ connected_by: User | None
+ claim: ReviewInstallationClaim | None
+ all_taken_by: ProjectRef | None
+
+
+class ProjectRepositories:
+ """The repository settings of one project, as one acting user changes them."""
+
+ def __init__(self, team: Team, user: User) -> None:
+ self.team = team
+ self.team_id = team.id
+ self.user = user
+
+ def _project(self, team_id: int) -> ProjectRef:
+ return ProjectRef.load(team_id, viewer_organization_id=self.team.organization_id)
+
+ def integrations(self) -> list[Integration]:
+ return list(
+ Integration.objects.filter(team_id=self.team_id, kind="github").select_related("created_by").order_by("id")
+ )
+
+ def integration_for(self, installation_id: str) -> Integration:
+ integration = next((row for row in self.integrations() if row.integration_id == installation_id), None)
+ if integration is None:
+ raise RepositorySettingsError("This project has no GitHub connection for that installation.")
+ return integration
+
+ def verified_ref(self, ref: RepositoryRef) -> RepositoryRef:
+ """The repository as the installation reports it. A client cannot store a pair GitHub does not know."""
+ integration = self.integration_for(ref.installation_id)
+ try:
+ repositories = GitHubIntegration(integration).list_all_cached_repositories()
+ except Exception:
+ # The list refreshes from GitHub when the cache is cold, and GitHub can fail or rate limit.
+ logger.warning("review_hog_repository_write_list_failed", exc_info=True)
+ raise RepositorySettingsError("GitHub did not return the repository list. Try again shortly.")
+ for repository in repositories:
+ github_repo_id = repository.get("id") if isinstance(repository.get("id"), int) else None
+ full_name = str(repository.get("full_name") or "")
+ if full_name.lower() != ref.full_name.lower():
+ continue
+ if ref.github_repo_id is not None and ref.github_repo_id != github_repo_id:
+ continue
+ return RepositoryRef(
+ installation_id=ref.installation_id, github_repo_id=github_repo_id, full_name=full_name
+ )
+ raise RepositorySettingsError(f"The GitHub installation has no repository {ref.full_name} with that id.")
+
+ def claim_for(self, installation_id: str) -> ReviewInstallationClaim | None:
+ return ReviewInstallationClaim.objects.for_team(self.team_id).filter(installation_id=installation_id).first()
+
+ def installations(self) -> list[InstallationSummary]:
+ claims = {claim.installation_id: claim for claim in ReviewInstallationClaim.objects.for_team(self.team_id)}
+ summaries: list[InstallationSummary] = []
+ for integration in self.integrations():
+ installation_id = integration.integration_id or ""
+ all_claim = RepositoryOwnership.all_claim(installation_id)
+ account = (integration.config or {}).get("account") or {}
+ summaries.append(
+ InstallationSummary(
+ installation_id=installation_id,
+ account_name=account.get("name") or installation_id,
+ connected_by=integration.created_by,
+ claim=claims.get(installation_id),
+ all_taken_by=(
+ self._project(all_claim.team_id)
+ if all_claim is not None and all_claim.team_id != self.team_id
+ else None
+ ),
+ )
+ )
+ return summaries
+
+ def _check_all_is_free(self, installation_id: str) -> None:
+ all_claim = RepositoryOwnership.all_claim(installation_id)
+ if all_claim is not None and all_claim.team_id != self.team_id:
+ project = self._project(all_claim.team_id)
+ raise OwnershipConflict(
+ f"All repositories of this installation are already reviewed in {project.label}.", project
+ )
+
+ def _delete_rows(self, installation_id: str, *, only_unselected: bool) -> None:
+ rows = ReviewRepository.objects.for_team(self.team_id).filter(installation_id=installation_id)
+ if only_unselected:
+ rows = rows.filter(selected=False)
+ # One delete per row, so the activity log records each one.
+ for row in rows:
+ row.delete()
+
+ def create_claim(self, installation_id: str, scope: str) -> ReviewInstallationClaim:
+ self.integration_for(installation_id)
+ if self.claim_for(installation_id) is not None:
+ raise RepositorySettingsError("This project already has a choice for that installation. Change it instead.")
+ if scope == ReviewInstallationClaim.Scope.ALL:
+ self._check_all_is_free(installation_id)
+ try:
+ with transaction.atomic():
+ return ReviewInstallationClaim.objects.for_team(self.team_id).create(
+ team_id=self.team_id, installation_id=installation_id, scope=scope, created_by=self.user
+ )
+ except IntegrityError:
+ # A concurrent write took all repositories, or added the same claim.
+ self._check_all_is_free(installation_id)
+ raise RepositorySettingsError("This project already has a choice for that installation. Change it instead.")
+
+ def update_claim(self, claim: ReviewInstallationClaim, scope: str) -> ReviewInstallationClaim:
+ if scope == claim.scope:
+ return claim
+ if scope == ReviewInstallationClaim.Scope.ALL:
+ self._check_all_is_free(claim.installation_id)
+ with transaction.atomic():
+ if scope == ReviewInstallationClaim.Scope.SELECTED:
+ # The repositories this project did not select leave it, and their exceptions go too.
+ self._delete_rows(claim.installation_id, only_unselected=True)
+ claim.scope = scope
+ try:
+ with transaction.atomic():
+ claim.save()
+ except IntegrityError:
+ self._check_all_is_free(claim.installation_id)
+ raise
+ return claim
+
+ def delete_claim(self, claim: ReviewInstallationClaim) -> None:
+ with transaction.atomic():
+ self._delete_rows(claim.installation_id, only_unselected=False)
+ claim.delete()
+
+ def save_repository(
+ self,
+ ref: RepositoryRef,
+ *,
+ selected: bool | None = None,
+ flash_for: str | None | Unset = UNSET,
+ ) -> RepositoryWriteResult:
+ """Include or remove a repository, or set or clear its exception. Omitted fields keep their value."""
+ ref = self.verified_ref(ref)
+ with transaction.atomic():
+ row = find_matching_row(ref, RepositoryOwnership.rows_for(ref))
+ if row is not None and row.team_id != self.team_id:
+ project = self._project(row.team_id)
+ raise OwnershipConflict(f"{ref.full_name} is already reviewed in {project.label}.", project)
+ claim = self.claim_for(ref.installation_id)
+ takes_all = claim is not None and claim.scope == ReviewInstallationClaim.Scope.ALL
+ was_selected = row is not None and row.selected
+ new_selected = selected if selected is not None else was_selected
+ if isinstance(flash_for, Unset):
+ new_flash_for = row.flash_for if row is not None else None
+ else:
+ new_flash_for = flash_for
+
+ if not new_selected and not takes_all:
+ if isinstance(flash_for, str):
+ raise RepositorySettingsError("Include the repository in this project before you add an exception.")
+ # The repository leaves the project, so its exception goes too.
+ new_flash_for = None
+ if not new_selected and new_flash_for is None:
+ if row is not None:
+ row.delete()
+ return RepositoryWriteResult(repository=None, taken_from=None)
+
+ all_claim = RepositoryOwnership.all_claim(ref.installation_id)
+ taken_from_claim = (
+ all_claim
+ if new_selected and not was_selected and all_claim is not None and all_claim.team_id != self.team_id
+ else None
+ )
+ if claim is None:
+ ReviewInstallationClaim.objects.for_team(self.team_id).create(
+ team_id=self.team_id,
+ installation_id=ref.installation_id,
+ scope=ReviewInstallationClaim.Scope.SELECTED,
+ created_by=self.user,
+ )
+ if row is None:
+ row = ReviewRepository(
+ team_id=self.team_id,
+ installation_id=ref.installation_id,
+ full_name=ref.full_name,
+ created_by=self.user,
+ )
+ if row.github_repo_id is None and ref.github_repo_id is not None:
+ row.github_repo_id = ref.github_repo_id
+ row.installation_id = ref.installation_id
+ row.selected = new_selected
+ row.flash_for = new_flash_for
+ try:
+ with transaction.atomic():
+ row.save()
+ except IntegrityError:
+ raise OwnershipConflict(f"{ref.full_name} is already reviewed in another project.", None)
+ if taken_from_claim is not None:
+ log_repository_taken(
+ claim=taken_from_claim, full_name=ref.full_name, taken_by_team_id=self.team_id, user=self.user
+ )
+ return RepositoryWriteResult(
+ repository=row,
+ taken_from=self._project(taken_from_claim.team_id) if taken_from_claim is not None else None,
+ )
+
+ def add_person(self, repository: ReviewRepository | None, *, user_id: int, kind: str) -> bool:
+ """Add a person to a list of the project rule (no repository) or of an exception. True when added."""
+ _person, created = ReviewRepositoryPerson.objects.for_team(self.team_id).get_or_create(
+ team_id=self.team_id, repository=repository, user_id=user_id, kind=kind
+ )
+ return created
+
+
+class RepositoryOwnerKind(models.TextChoices):
+ THIS_PROJECT = "this_project", "This project"
+ OTHER_PROJECT = "other_project", "Another project"
+ NONE = "none", "No project"
+
+
+class RepositoryOverviewView(models.TextChoices):
+ ALL = "all", "All repositories"
+ IN_PROJECT = "in_project", "In this project"
+ EXCEPTIONS = "exceptions", "With exceptions"
+ MINE = "mine", "My choices"
+
+
+@frozen
+class OverviewEntry:
+ full_name: str
+ github_repo_id: int | None
+ owner: RepositoryOwnerKind
+ owner_project: ProjectRef | None
+ in_project: bool
+ selected: bool
+ repository: ReviewRepository | None
+ exception_people: Sequence[ReviewRepositoryPerson]
+ my_choice: ReviewUserRepositoryChoice | None
+ my_result: AutomaticReviewDecision
+
+
+class RepositoryOverview:
+ """Every repository an installation can see, joined with this project's settings and the viewer's.
+
+ The decision comes from the same resolver as the automatic dispatch, so the UI never re-implements it.
+ """
+
+ def __init__(self, team: Team, user: User, installation_id: str, repositories: Sequence[Mapping[str, Any]]) -> None:
+ self.team = team
+ self.user = user
+ self.installation_id = installation_id
+ self.rows = RepositoryOwnership.rows_for_listing(
+ (str(repository["full_name"]) for repository in repositories),
+ (repository["id"] for repository in repositories if isinstance(repository.get("id"), int)),
+ )
+ self.all_claim = RepositoryOwnership.all_claim(installation_id)
+ own_rows = [row for row in self.rows if row.team_id == team.id]
+ self.rules = ProjectRuleContext.load(team.id, own_rows)
+ self.viewer: AuthorPreferences = load_author_preferences(team.id, user_id=user.id, is_bot=False)
+ self._projects: dict[int, ProjectRef] = {}
+
+ def _project(self, team_id: int) -> ProjectRef:
+ if team_id not in self._projects:
+ self._projects[team_id] = ProjectRef.load(team_id, viewer_organization_id=self.team.organization_id)
+ return self._projects[team_id]
+
+ def entry(self, repository: Mapping[str, Any]) -> OverviewEntry:
+ github_repo_id = repository.get("id") if isinstance(repository.get("id"), int) else None
+ ref = RepositoryRef(
+ installation_id=self.installation_id, github_repo_id=github_repo_id, full_name=str(repository["full_name"])
+ )
+ owner = resolve_owner(ref, self.rows, self.all_claim)
+ own_row = find_matching_row(ref, [row for row in self.rows if row.team_id == self.team.id])
+ in_project = owner is not None and owner.team_id == self.team.id
+ choice = self.viewer.choice_for(ref)
+ if in_project:
+ result = self.rules.rule_for(own_row).resolve(self.viewer.for_repository(ref))
+ else:
+ result = AutomaticReviewDecision(flash=False, reason=AutomaticReviewReason.NOT_IN_PROJECT)
+ if owner is None:
+ owner_kind, owner_project = RepositoryOwnerKind.NONE, None
+ elif in_project:
+ owner_kind, owner_project = RepositoryOwnerKind.THIS_PROJECT, None
+ else:
+ owner_kind, owner_project = RepositoryOwnerKind.OTHER_PROJECT, self._project(owner.team_id)
+ has_exception = own_row is not None and own_row.flash_for is not None
+ return OverviewEntry(
+ full_name=ref.full_name,
+ github_repo_id=github_repo_id,
+ owner=owner_kind,
+ owner_project=owner_project,
+ in_project=in_project,
+ selected=own_row is not None and own_row.selected,
+ repository=own_row,
+ exception_people=self.rules.people.get(own_row.id, []) if has_exception and own_row is not None else [],
+ my_choice=choice,
+ my_result=result,
+ )
+
+ def _in_view(self, entry: OverviewEntry, view: str) -> bool:
+ if view == RepositoryOverviewView.IN_PROJECT:
+ return entry.in_project
+ if view == RepositoryOverviewView.EXCEPTIONS:
+ return entry.repository is not None and entry.repository.flash_for is not None
+ if view == RepositoryOverviewView.MINE:
+ return entry.my_choice is not None
+ return True
+
+ def page(
+ self, repositories: Sequence[Mapping[str, Any]], *, view: str, offset: int, limit: int
+ ) -> tuple[list[OverviewEntry], int]:
+ """One page of entries and the total that match the view."""
+ if view == RepositoryOverviewView.ALL:
+ return [self.entry(repository) for repository in repositories[offset : offset + limit]], len(repositories)
+ matching = [
+ entry for entry in (self.entry(repository) for repository in repositories) if self._in_view(entry, view)
+ ]
+ return matching[offset : offset + limit], len(matching)
+
+
+class RepositoryChoices:
+ """A person's own choices for repositories of one project. A choice stores only what differs."""
+
+ def __init__(self, team: Team, user: User) -> None:
+ self.team = team
+ self.user = user
+
+ def save(self, ref: RepositoryRef, mode: str) -> tuple[ReviewUserRepositoryChoice | None, AutomaticReviewDecision]:
+ ProjectRepositories(self.team, self.user).integration_for(ref.installation_id)
+ owner = RepositoryOwnership.find(ref)
+ if owner is None or owner.team_id != self.team.id:
+ raise RepositorySettingsError(f"This project does not review {ref.full_name}.")
+ viewer = load_author_preferences(self.team.id, user_id=self.user.id, is_bot=False)
+ rule = ProjectRuleContext.load(self.team.id, [owner.row] if owner.row is not None else []).rule_for(owner.row)
+ existing = viewer.choice_for(ref)
+ author = viewer.for_repository(ref)
+ inherited = rule.resolve(replace(author, repository_choice=None))
+ wants_flash = mode == ReviewUserRepositoryChoice.Mode.FLASH
+ with transaction.atomic():
+ if inherited.flash == wants_flash:
+ # Equal to what the user inherits, so storing it would pin a value that only looks set.
+ if existing is not None:
+ existing.delete()
+ return None, inherited
+ choices = ReviewUserRepositoryChoice.objects.for_team(self.team.id)
+ if existing is None:
+ existing = choices.create(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ installation_id=ref.installation_id,
+ github_repo_id=ref.github_repo_id,
+ full_name=ref.full_name,
+ mode=mode,
+ )
+ else:
+ existing.mode = mode
+ existing.installation_id = ref.installation_id
+ existing.full_name = ref.full_name
+ existing.github_repo_id = existing.github_repo_id or ref.github_repo_id
+ existing.save()
+ decision = rule.resolve(replace(author, repository_choice=ReviewUserRepositoryChoice.Mode(mode)))
+ return existing, decision
diff --git a/products/review_hog/backend/requested_reviews.py b/products/review_hog/backend/requested_reviews.py
index 715112d95c0a..7e7a90b86e6f 100644
--- a/products/review_hog/backend/requested_reviews.py
+++ b/products/review_hog/backend/requested_reviews.py
@@ -7,13 +7,14 @@ requester and checked their access to the project.
import logging
from enum import StrEnum
-from typing import Literal
from posthog.dataclasses import frozen
from posthog.models.integration import GitHubIntegration
from products.review_hog.backend.internal_features import has_internal_features
from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
+from products.review_hog.backend.review_request_rules import ResolutionGate, ReviewRequestRefusal, flash_refusal
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
from products.review_hog.backend.reviewer.persistence import lift_review_tier_for_joined_trigger
from products.review_hog.backend.reviewer.review_state import review_already_published
@@ -28,8 +29,8 @@ from products.review_hog.backend.temporal.types import TRIGGER_UI, resolve_pr_wo
logger = logging.getLogger(__name__)
-# What the trigger runs. The default 'review' includes the resolution stage when the requesting
-# user's `resolve_comments` setting is on; the others are the split button's explicit variants.
+# What the trigger runs. The default 'review' includes the resolution stage when the pull request
+# owner's `resolve_comments` setting is on; the others are the split button's explicit variants.
# Flash never resolves comments because it must not write code.
RUN_MODE_REVIEW = "review"
RUN_MODE_REVIEW_ONLY = "review_only"
@@ -48,6 +49,8 @@ class PRReviewRequestStatus(StrEnum):
NOT_ALLOWED = "not_allowed"
# The pull request's review cycle is busy, so the request is refused rather than queued.
BUSY = "busy"
+ # A review rule refuses the request for this pull request; `refusal` says which.
+ REFUSED = "refused"
@frozen
@@ -56,6 +59,7 @@ class PRReviewRequestOutcome:
workflow_id: str = ""
# Written for the requester. Built from the repository name, the PR number and fixed text only.
error: str = ""
+ refusal: ReviewRequestRefusal | None = None
@property
def started(self) -> bool:
@@ -91,27 +95,21 @@ def request_pr_review(
pr_number: int,
run_mode: str,
trigger_source: str = TRIGGER_UI,
- resolve_comments: Literal[False] | None = None,
) -> PRReviewRequestOutcome:
"""Start the requested run, or say why not.
The requester is both the run user (sandbox identity) and the acting user, whose perspectives,
- validator, threshold and resolution criteria apply. Raises `GitHubRateLimitError` when GitHub
- rate-limits the App's token, so the caller can answer with the wait.
-
- `resolve_comments=False` turns the resolution stage off in every mode. A caller cannot turn it
- on: `None` lets the run mode and the requester's setting decide.
+ validator, threshold and resolution criteria apply. Every trigger follows the same rules:
+ resolution writes only when the pull request owner opted in, and no Flash follows a published
+ Full review. Raises `GitHubRateLimitError` when GitHub rate-limits the App's token, so the
+ caller can answer with the wait.
"""
- # The scene hides Flash outside the internal project; this also stops API and MCP callers there.
- if run_mode == RUN_MODE_FLASH and not has_internal_features(team_id):
+ # The scene hides these outside internal projects; this also stops API and MCP callers there.
+ if run_mode in (RUN_MODE_FLASH, RUN_MODE_RESOLVE_ONLY) and not has_internal_features(team_id):
return PRReviewRequestOutcome(
status=PRReviewRequestStatus.NOT_ALLOWED,
- error="Flash reviews aren't available in this project. Start a regular review instead.",
- )
- if run_mode == RUN_MODE_RESOLVE_ONLY and resolve_comments is False:
- return PRReviewRequestOutcome(
- status=PRReviewRequestStatus.NOT_ALLOWED,
- error="This trigger can't resolve review comments. Start a review instead.",
+ error="This run mode isn't available in this project. Start a regular review instead.",
+ refusal=ReviewRequestRefusal.INTERNAL_FEATURE,
)
repository = f"{owner}/{repo}"
# Checked synchronously (one GitHub API call) so an inaccessible repo errors here, in the UI —
@@ -162,6 +160,17 @@ def request_pr_review(
pr_url = f"https://github.com/{owner}/{repo}/pull/{pr_number}"
if run_mode == RUN_MODE_RESOLVE_ONLY:
+ # Checked here so the requester sees the answer. The resolution run checks again before it writes.
+ pull_request_owner = PullRequestOwnerResolver.resolve(
+ team_id, repository=repository, author_login=pr_meta.author, head_branch=pr_meta.head_branch
+ )
+ if not ResolutionGate.load(team_id, pull_request_owner.user_id).allows(REVIEW_MODE_FULL):
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.REFUSED,
+ error="Comments are resolved only on pull requests whose owner turned on resolving comments "
+ "in their PostHog Review settings.",
+ refusal=ReviewRequestRefusal.RESOLUTION_NOT_OPTED_IN,
+ )
# No already-reviewed early-return here: an already-reviewed head is exactly when a
# standalone resolution run is useful (the threads exist, the review won't re-run).
workflow_id = start_resolution_workflow(
@@ -179,6 +188,13 @@ def request_pr_review(
# Repository casing can differ per trigger (the report stores whatever its trigger carried).
report = ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()
review_mode = REVIEW_MODE_FLASH if run_mode == RUN_MODE_FLASH else REVIEW_MODE_FULL
+ if flash_refusal(report, review_mode) is not None:
+ return PRReviewRequestOutcome(
+ status=PRReviewRequestStatus.REFUSED,
+ error="This pull request already has a Full review, so it gets no more Flash reviews. "
+ "Start a Full review instead.",
+ refusal=ReviewRequestRefusal.FLASH_AFTER_FULL,
+ )
if report is not None and review_already_published(report, pr_meta.head_sha or "", review_mode):
# The workflow would early-exit before resolving the acting user anyway — say so instead
# of answering "started" for a run that will do nothing.
@@ -195,8 +211,8 @@ def request_pr_review(
publish=True,
acting_user_id=requester_id,
trigger_source=trigger_source,
- # None = the requester's setting decides; review_only, flash and a caller's False pin it off.
- resolve_comments=False if run_mode in (RUN_MODE_REVIEW_ONLY, RUN_MODE_FLASH) else resolve_comments,
+ # None = the PR owner's setting decides; review_only and flash pin it off.
+ resolve_comments=False if run_mode in (RUN_MODE_REVIEW_ONLY, RUN_MODE_FLASH) else None,
review_mode=review_mode,
requested_head_sha=pr_meta.head_sha,
)
diff --git a/products/review_hog/backend/review_request_rules.py b/products/review_hog/backend/review_request_rules.py
new file mode 100644
index 000000000000..42f1d07a754d
--- /dev/null
+++ b/products/review_hog/backend/review_request_rules.py
@@ -0,0 +1,60 @@
+"""The rules every review request follows, whichever trigger asks.
+
+- Resolution writes to the branch only after a Full review, only when the pull request's owner opted
+ in (`resolve_comments`), and only where the `review-hog-internal` flag is on. Who triggered does not
+ matter: one person's opt-in never writes to a teammate's branch.
+- No Flash after Full: once a Full review of a pull request is published, Flash reviews of it stop.
+
+The checks are small functions so every trigger can call the same ones.
+"""
+
+from django.db import models
+
+from posthog.dataclasses import frozen
+
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FLASH, REVIEW_MODE_FULL
+from products.review_hog.backend.reviewer.review_state import published_heads_by_mode
+
+
+class ReviewRequestRefusal(models.TextChoices):
+ """Why a request is refused. Clients show a reason per code."""
+
+ FLASH_AFTER_FULL = "flash_after_full", "Flash after a published Full review"
+ RESOLUTION_NOT_OPTED_IN = "resolution_not_opted_in", "The pull request owner has not opted in to resolution"
+ INTERNAL_FEATURE = "internal_feature", "Not available in this project"
+
+
+@frozen
+class ResolutionGate:
+ owner_user_id: int | None
+ owner_opted_in: bool
+ internal_features: bool
+
+ def allows(self, review_mode: str) -> bool:
+ return (
+ review_mode == REVIEW_MODE_FULL
+ and self.internal_features
+ and self.owner_user_id is not None
+ and self.owner_opted_in
+ )
+
+ @classmethod
+ def load(cls, team_id: int, owner_user_id: int | None) -> "ResolutionGate":
+ opted_in = (
+ owner_user_id is not None and ReviewUserSettings.load_preferences(team_id, owner_user_id).resolve_comments
+ )
+ return cls(
+ owner_user_id=owner_user_id, owner_opted_in=opted_in, internal_features=has_internal_features(team_id)
+ )
+
+
+def full_review_published(report: ReviewReport | None) -> bool:
+ return report is not None and REVIEW_MODE_FULL in published_heads_by_mode(report)
+
+
+def flash_refusal(report: ReviewReport | None, review_mode: str) -> ReviewRequestRefusal | None:
+ if review_mode == REVIEW_MODE_FLASH and full_review_published(report):
+ return ReviewRequestRefusal.FLASH_AFTER_FULL
+ return None
diff --git a/products/review_hog/backend/reviewer/models/thread_resolution.py b/products/review_hog/backend/reviewer/models/thread_resolution.py
index 332aa5f0854a..c87ef55e05be 100644
--- a/products/review_hog/backend/reviewer/models/thread_resolution.py
+++ b/products/review_hog/backend/reviewer/models/thread_resolution.py
@@ -22,6 +22,9 @@ class CommitHold(StrEnum):
# The stage commits to the head branch only, so a fix here leaves every PR stacked on top
# behind its base until someone restacks.
STACKED = "pr_has_stacked_pull_requests"
+ # Branch protection on the head branch would refuse the push, or let only some people push. A
+ # person decides what lands on a protected branch.
+ BRANCH_PROTECTED = "pr_branch_protected"
class ThreadResolution(BaseModel):
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index 92fc0c0344e2..8f87e76469c8 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -190,7 +190,7 @@ def _gather_report_inputs(*, team_id: int, report: ReviewReport, final_head: str
# mirror IssuePriority, coerced through the value like the publish path).
snapshotted = report.published_urgency_thresholds or {}
fallback_threshold = (
- str(ReviewUserSettings.load(team_id, report.acting_user_id).urgency_threshold)
+ ReviewUserSettings.load_preferences(team_id, report.acting_user_id).urgency_threshold.value
if report.acting_user_id
else DEFAULT_URGENCY_THRESHOLD.value
)
diff --git a/products/review_hog/backend/reviewer/outcomes/comment_signal.py b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
index 995894913a05..bd66c3d2e4a5 100644
--- a/products/review_hog/backend/reviewer/outcomes/comment_signal.py
+++ b/products/review_hog/backend/reviewer/outcomes/comment_signal.py
@@ -63,8 +63,8 @@ def engagement_method(
treating its own follow-up as engagement would let the feature grade its own homework. A fix it
lands itself still shows up, as a commit in the post-review compare that the judge rules on —
engagement is not where that belongs. Note `is_app_bot_author` can only single out our bot when
- `REVIEWHOG_GITHUB_BOT_LOGIN` is set; unset it fails open to "any bot", which degrades this to the
- old behavior of ignoring every bot reply.
+ `REVIEWHOG_GITHUB_BOT_LOGIN` is set. Unset, local runs fall back to "any bot", which ignores
+ every bot reply, and production trusts no bot, which counts our own replies as agent replies.
A human reply beats an agent one when both are present, and a reaction beats both: it is the
cheaper, unambiguous signal. ``reactions`` are the comment's reactions with their actors, and the
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index d811b2191adf..d8cf19dbf953 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -31,13 +31,13 @@ import logging
from collections.abc import Sequence
from dataclasses import asdict, dataclass, field
-from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
from django.utils import timezone
from pydantic import ValidationError
+from products.review_hog.backend.internal_features import has_internal_features
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.reviewer.artefact_content import (
ArtefactContentValidationError,
@@ -223,11 +223,11 @@ def lift_review_tier_for_joined_trigger(*, team_id: int, repository: str, pr_num
def _review_tier_fields(team_id: int, tier: ReviewTier) -> dict[str, object]:
"""The tier column plus the arm bundle a report placed in `tier` reviews on.
- Tiered arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood gate. Other teams
+ Tiered arms are rolled out per project through the `review-hog-internal` flag. Other projects
keep the single default arm but still record their tier, so the label stays truthful and the
tiers can be compared on their traffic before the rollout widens.
"""
- arm = REVIEW_ARMS_BY_TIER[tier] if team_id in settings.REVIEWHOG_TEAM_IDS else DEFAULT_REVIEW_ARM
+ arm = REVIEW_ARMS_BY_TIER[tier] if has_internal_features(team_id) else DEFAULT_REVIEW_ARM
return {
"review_tier": tier.value,
"review_runtime_adapter": arm.runtime_adapter.value,
diff --git a/products/review_hog/backend/reviewer/push_gate.py b/products/review_hog/backend/reviewer/push_gate.py
index b1d9db02ef62..acb45d13e837 100644
--- a/products/review_hog/backend/reviewer/push_gate.py
+++ b/products/review_hog/backend/reviewer/push_gate.py
@@ -7,10 +7,12 @@ sees a first review or a human trigger: the workflow calls it only for automatic
The rules, in order. The first rule that matches gives the reason:
1. `no_new_commits`: the PR has no commit it did not have at the last reviewed head (a force-push back).
-2. `merge_only`: the PR's full diff against its base is the same at both heads (a base merge or a
+2. `reviewhog_commits_only`: the ReviewHog app authored every new commit, for example the fixes the
+ resolution stage pushed. Reviewing them again would review ReviewHog's own answer to its review.
+3. `merge_only`: the PR's full diff against its base is the same at both heads (a base merge or a
rebase). A merge that changes the PR's own lines runs the review.
-3. `docs_only`: the new own commits touch only docs, lockfiles, snapshots, images, and generated files.
-4. `system_one_below_threshold`: System One rates the new own commits below a threshold.
+4. `docs_only`: the new own commits touch only docs, lockfiles, snapshots, images, and generated files.
+5. `system_one_below_threshold`: System One rates the new own commits below a threshold.
Each rule has its own switch. A rule that is switched off still reports the turn it would skip
(`would_skip`), so production data can calibrate it before it skips anything. Every failure fails
@@ -31,13 +33,18 @@ from posthog.egress.github.transport import GitHubRateLimitError
from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfigured, SystemOneRequestFailed
from posthog.llm.system_one_client import build_system_one_client
-from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
+from products.review_hog.backend.reviewer.tools.github_client import (
+ GitHubAPIError,
+ github_api_request,
+ is_app_bot_author,
+)
from products.review_hog.backend.reviewer.tools.github_meta import GITHUB_COMPARE_FILES_CAP, PRParser
logger = logging.getLogger(__name__)
# A rule that is off only records the skip it would make, so production data can calibrate it first.
SKIP_NO_NEW_COMMITS = True
+SKIP_REVIEWHOG_COMMITS_ONLY = True
SKIP_MERGE_ONLY = True
SKIP_DOCS_ONLY = False
SKIP_SYSTEM_ONE = False
@@ -85,7 +92,9 @@ _NON_CODE_FILE = re.compile(
)
)
-SkipReason = Literal["no_new_commits", "merge_only", "docs_only", "system_one_below_threshold"]
+SkipReason = Literal[
+ "no_new_commits", "reviewhog_commits_only", "merge_only", "docs_only", "system_one_below_threshold"
+]
RunReason = Literal[
"commits_removed",
"system_one_above_threshold",
@@ -127,11 +136,14 @@ class _PRDiff:
commit_shas: list[str]
merge_shas: set[str]
files: list[_ChangedFile]
+ reviewhog_shas: set[str]
def _rule_enabled(reason: SkipReason) -> bool:
if reason == "no_new_commits":
return SKIP_NO_NEW_COMMITS
+ if reason == "reviewhog_commits_only":
+ return SKIP_REVIEWHOG_COMMITS_ONLY
if reason == "merge_only":
return SKIP_MERGE_ONLY
if reason == "docs_only":
@@ -229,6 +241,7 @@ class PushGate:
commit_shas=[commit["sha"] for commit in commits],
merge_shas={commit["sha"] for commit in commits if len(commit.get("parents") or []) > 1},
files=files,
+ reviewhog_shas={commit["sha"] for commit in commits if is_app_bot_author(commit.get("author"))},
)
def _commit_files(self, shas: list[str]) -> list[_ChangedFile] | None:
@@ -287,6 +300,8 @@ class PushGate:
# A force-push back to an earlier commit adds no commit but removes changes the last review saw.
return _runs("commits_removed")
own_shas = [sha for sha in new_shas if sha not in current.merge_shas]
+ if all(sha in current.reviewhog_shas for sha in new_shas):
+ return _matched("reviewhog_commits_only", own_commits=len(own_shas))
if _same_full_diff(previous, current):
return _matched("merge_only", own_commits=len(own_shas))
if not own_shas:
diff --git a/products/review_hog/backend/reviewer/status_comment.py b/products/review_hog/backend/reviewer/status_comment.py
index 369148294fee..3ff9213117f2 100644
--- a/products/review_hog/backend/reviewer/status_comment.py
+++ b/products/review_hog/backend/reviewer/status_comment.py
@@ -367,6 +367,13 @@ def render_resolution_held_section(hold: CommitHold, *, done: int = 0, total: in
else "Not resolving comments: other pull requests are stacked on this branch"
)
why = "A fix commit here would leave the stacked pull requests out of date"
+ elif hold == CommitHold.BRANCH_PROTECTED:
+ line = (
+ f"Stopped resolving comments at {done}/{total}: this branch is now protected"
+ if total
+ else "Not resolving comments: this branch is protected"
+ )
+ why = "A person decides what lands on a protected branch"
else:
line = (
f"Stopped resolving comments at {done}/{total}: this pull request was submitted to the merge queue"
diff --git a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
index cbfbe6cb2d47..3e0e5bf987dd 100644
--- a/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
+++ b/products/review_hog/backend/reviewer/tests/test_outcome_comment_signal.py
@@ -108,8 +108,8 @@ class TestEngagementMethod:
)
def test_agent_replies_are_ignored_when_our_bot_login_is_unconfigured(self):
- # `is_app_bot_author` fails open to "any bot" without REVIEWHOG_GITHUB_BOT_LOGIN, so a
- # stranger's bot is never credited as engagement on a deployment that cannot tell it from
+ # Outside production `is_app_bot_author` falls back to "any bot" without REVIEWHOG_GITHUB_BOT_LOGIN,
+ # so a stranger's bot is never credited as engagement on a deployment that cannot tell it from
# ours — the signal degrades to the old ignore-every-bot behaviour rather than misattributing.
comment: dict[str, Any] = {"id": 1}
reply: dict[str, Any] = {"id": 2, "in_reply_to_id": 1, "user": _OTHER_BOT}
diff --git a/products/review_hog/backend/reviewer/tools/github_client.py b/products/review_hog/backend/reviewer/tools/github_client.py
index d36c998f7f90..73a4ca2e0642 100644
--- a/products/review_hog/backend/reviewer/tools/github_client.py
+++ b/products/review_hog/backend/reviewer/tools/github_client.py
@@ -26,14 +26,20 @@ def is_app_bot_author(user: dict[str, Any] | None) -> bool:
Guards the marker-based idempotency scans: on a public repo anyone can paste a marker, and a
spoofed match suppresses a publish or gets a stranger's comment PATCHed. `type == "Bot"` blocks
human spoofers; when `REVIEWHOG_GITHUB_BOT_LOGIN` is configured (the app's `<slug>[bot]` login),
- markers pasted by OTHER installed bots are rejected too. Unset fails open to the type check —
+ markers pasted by OTHER installed bots are rejected too. Unset, it fails closed in production,
+ because any installed bot would pass. Local development and tests fall back to the type check:
the app's own login isn't derivable from an installation token without extra API calls.
"""
author = user or {}
if author.get("type") != "Bot":
return False
expected = settings.REVIEWHOG_GITHUB_BOT_LOGIN
- return author.get("login") == expected if expected else True
+ if expected:
+ return author.get("login") == expected
+ if settings.DEBUG or settings.TEST:
+ return True
+ logger.warning("REVIEWHOG_GITHUB_BOT_LOGIN is not set; no GitHub author counts as the ReviewHog app")
+ return False
GITHUB_API_BASE = "https://api.github.com"
diff --git a/products/review_hog/backend/reviewer/tools/github_threads.py b/products/review_hog/backend/reviewer/tools/github_threads.py
index bddec09ee2f7..715055243af1 100644
--- a/products/review_hog/backend/reviewer/tools/github_threads.py
+++ b/products/review_hog/backend/reviewer/tools/github_threads.py
@@ -433,8 +433,8 @@ def inspect_fix_commit(
Fails closed on GitHub's 300-file cap: a files list that may be truncated reports the commit as
unverifiable rather than clean — a comment-driven fix that big deserves human eyes anyway.
- Provenance: signed-commit fixes are authored as the app's bot (`is_app_bot_author`, fail-open on
- login when `REVIEWHOG_GITHUB_BOT_LOGIN` is unset) and carry a verified web-flow signature; a
+ Provenance: signed-commit fixes are authored as the app's bot (`is_app_bot_author`, which fails
+ closed in production when `REVIEWHOG_GITHUB_BOT_LOGIN` is unset) and carry a verified web-flow signature; a
reachable SHA failing either is not provably this run's fix. The residual — echoing one of the
bot's own earlier commits — stays with the recorded session-provenance follow-up.
"""
diff --git a/products/review_hog/backend/routes.py b/products/review_hog/backend/routes.py
index b556a272d89f..a6b09cbda3dc 100644
--- a/products/review_hog/backend/routes.py
+++ b/products/review_hog/backend/routes.py
@@ -2,9 +2,12 @@ from posthog.api.routing import RouterRegistry
from products.review_hog.backend.api import (
ReviewBlindSpotsConfigViewSet,
- ReviewHogTriggerViewSet,
+ ReviewInstallationClaimViewSet,
ReviewPerspectiveConfigViewSet,
+ ReviewProjectSettingsViewSet,
ReviewRecentReviewsViewSet,
+ ReviewRepositoryChoiceViewSet,
+ ReviewRepositoryViewSet,
ReviewResolutionConfigViewSet,
ReviewUserSettingsViewSet,
ReviewValidatorConfigViewSet,
@@ -12,9 +15,6 @@ from products.review_hog.backend.api import (
def register_routes(routers: RouterRegistry) -> None:
- # Unscoped: the trigger resolves team + run user server-side and is gated by a shared secret, so it
- # mounts at /api/review_hog/trigger (no team in the URL) rather than under the project router.
- routers.root.register(r"review_hog", ReviewHogTriggerViewSet, "review_hog")
# Team-scoped: per-user perspective enablement for the project's reviews (the config UI).
routers.projects.register(
r"review_hog/perspectives",
@@ -50,6 +50,35 @@ def register_routes(routers: RouterRegistry) -> None:
"project_review_hog_reviews",
["team_id"],
)
+ # Team-scoped: the repositories this project has settings for (admins write, members read).
+ routers.projects.register(
+ r"review_hog/repositories",
+ ReviewRepositoryViewSet,
+ "project_review_hog_repositories",
+ ["team_id"],
+ )
+ # Team-scoped: which repositories of each GitHub installation this project reviews.
+ routers.projects.register(
+ r"review_hog/installation_claims",
+ ReviewInstallationClaimViewSet,
+ "project_review_hog_installation_claims",
+ ["team_id"],
+ )
+ # Team-scoped: the requesting user's own choices for single repositories.
+ routers.projects.register(
+ r"review_hog/repository_choices",
+ ReviewRepositoryChoiceViewSet,
+ "project_review_hog_repository_choices",
+ ["team_id"],
+ )
+ # Team-scoped: the project rule and the repository overview, at review_hog/project_settings and
+ # review_hog/repository_overview (the viewset has only those actions).
+ routers.projects.register(
+ r"review_hog",
+ ReviewProjectSettingsViewSet,
+ "project_review_hog_project_settings",
+ ["team_id"],
+ )
# Team-scoped: per-user trigger opt-outs + urgency threshold, at review_hog/settings (the viewset
# has no list/detail routes — only the GET+PATCH "settings" action).
routers.projects.register(
diff --git a/products/review_hog/backend/settings_toggles.py b/products/review_hog/backend/settings_toggles.py
deleted file mode 100644
index ec2fd996de19..000000000000
--- a/products/review_hog/backend/settings_toggles.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""Bulk on/off for the per-user boolean toggles on `ReviewUserSettings`.
-
-The inbox and authored PR toggles default to off per user because they are the budget gate for
-100%-coverage review cost, and `resolve_comments` defaults to on
-because reviewing includes resolving. Flipping any of them for a whole team is a deliberate operator
-action rather than a default change. The `enable_*` / `disable_*` management commands are thin
-wrappers over `plan_toggle` + `apply_toggle`: one toggle, one direction, for every active member of
-the team's organization or for an explicit list of user ids. Authored PR opt-in can also set the
-Flash effort; all other fields stay untouched. Users can change the settings afterwards, and members
-who join later keep the default until a command is re-run.
-"""
-
-from collections.abc import Sequence
-from typing import Literal
-
-from django.db import transaction
-
-from posthog.dataclasses import frozen
-from posthog.models.organization import OrganizationMembership
-from posthog.models.scoping.manager import resolve_effective_team_id
-from posthog.models.team import Team
-
-from products.review_hog.backend.models import ReviewUserSettings
-
-ToggleField = Literal["review_inbox_prs", "stamphog_review_inbox_prs", "resolve_comments", "review_authored_prs"]
-
-
-def toggle_default(field: ToggleField) -> bool:
- # An unsaved instance carries the model defaults, the same way `ReviewUserSettings.load` does.
- return bool(getattr(ReviewUserSettings(), field))
-
-
-class UsersNotInOrganization(ValueError):
- def __init__(self, team_id: int, user_ids: Sequence[int]) -> None:
- self.user_ids = tuple(user_ids)
- ids = ", ".join(str(user_id) for user_id in self.user_ids)
- super().__init__(f"user id(s) {ids} are not members of the organization that owns team {team_id}")
-
-
-@frozen
-class TogglePlan:
- team_id: int
- field: ToggleField
- enabled: bool
- target_count: int
- # Users with no row yet. Empty when the requested value is the field's default, because a
- # missing row already reads as the default.
- to_create: tuple[int, ...]
- to_update: tuple[int, ...]
- flash_reasoning_effort: ReviewUserSettings.FlashReasoningEffort | None = None
-
- @property
- def changed_user_ids(self) -> tuple[int, ...]:
- return self.to_create + self.to_update
-
- @property
- def already_set(self) -> int:
- return self.target_count - len(self.changed_user_ids)
-
- @property
- def summary(self) -> str:
- verb = "enable" if self.enabled else "disable"
- effort = f", flash_reasoning_effort: {self.flash_reasoning_effort.value}" if self.flash_reasoning_effort else ""
- return (
- f"team {self.team_id}, {self.field} {verb}d{effort}: {self.target_count} target user(s), "
- f"{len(self.to_create)} row(s) to create, {len(self.to_update)} existing row(s) to update, "
- f"{self.already_set} already set"
- )
-
-
-def plan_toggle(
- *,
- team_id: int,
- field: ToggleField,
- enabled: bool,
- user_ids: Sequence[int] | None = None,
- flash_reasoning_effort: ReviewUserSettings.FlashReasoningEffort | None = None,
-) -> TogglePlan:
- """Work out which `ReviewUserSettings` rows a bulk toggle change touches, without writing.
-
- Raises `TeamScopeError` / `Team.DoesNotExist` for a bad team id and `UsersNotInOrganization`
- when an explicit id is not a member of the team's organization, so a typo fails loudly instead
- of silently changing nothing.
- """
- if flash_reasoning_effort is not None and (field != "review_authored_prs" or not enabled):
- raise ValueError("Flash effort can only be set when enabling authored PR reviews")
-
- # Environment ids resolve to the root team, mirroring the settings API: the rows must land
- # on the same team the workflow's `ReviewUserSettings.load` reads them from.
- team_id = resolve_effective_team_id(team_id)
- team = Team.objects.get(id=team_id)
- memberships = OrganizationMembership.objects.filter(organization_id=team.organization_id)
- if user_ids is None:
- target_ids = list(memberships.filter(user__is_active=True).values_list("user_id", flat=True))
- else:
- target_ids = list(dict.fromkeys(user_ids))
- member_ids = set(memberships.filter(user_id__in=target_ids).values_list("user_id", flat=True))
- unknown = [user_id for user_id in target_ids if user_id not in member_ids]
- if unknown:
- raise UsersNotInOrganization(team_id, unknown)
-
- existing = {
- row.user_id: row
- for row in ReviewUserSettings.objects.for_team(team_id, canonical=True).filter(user_id__in=target_ids)
- }
- to_update = tuple(
- user_id
- for user_id in target_ids
- if user_id in existing
- and (
- getattr(existing[user_id], field) is not enabled
- or (
- flash_reasoning_effort is not None
- and existing[user_id].flash_reasoning_effort != flash_reasoning_effort
- )
- )
- )
- missing = tuple(user_id for user_id in target_ids if user_id not in existing)
- to_create = missing if enabled is not toggle_default(field) else ()
- return TogglePlan(
- team_id=team_id,
- field=field,
- enabled=enabled,
- target_count=len(target_ids),
- to_create=to_create,
- to_update=to_update,
- flash_reasoning_effort=flash_reasoning_effort,
- )
-
-
-def apply_toggle(plan: TogglePlan) -> None:
- rows = ReviewUserSettings.objects.for_team(plan.team_id, canonical=True)
- updates: dict[str, bool | str] = {plan.field: plan.enabled}
- if plan.flash_reasoning_effort is not None:
- updates["flash_reasoning_effort"] = plan.flash_reasoning_effort.value
- with transaction.atomic():
- to_update = list(rows.filter(user_id__in=plan.to_update))
- for user_id in plan.to_create:
- # get_or_create because a settings GET auto-creates rows with the model defaults: a
- # user opening the Code review tab between the plan and this write must end at the
- # requested value, not crash the run on the unique (team, user) constraint.
- row, created = rows.get_or_create(team_id=plan.team_id, user_id=user_id, defaults=updates)
- if not created:
- to_update.append(row)
- for row in to_update:
- for field, value in updates.items():
- setattr(row, field, value)
- row.save(update_fields=[*updates, "updated_at"])
diff --git a/products/review_hog/backend/tasks.py b/products/review_hog/backend/tasks.py
index 3a5846bc1c2f..69970c3b9a30 100644
--- a/products/review_hog/backend/tasks.py
+++ b/products/review_hog/backend/tasks.py
@@ -1,6 +1,7 @@
from celery import shared_task
from products.review_hog.backend.automatic_reviews import AuthoredPRReview
+from products.review_hog.backend.label_reviews import LabelReview
@shared_task(
@@ -13,10 +14,56 @@ from products.review_hog.backend.automatic_reviews import AuthoredPRReview
retry_backoff_max=300,
retry_jitter=True,
)
-def process_authored_pr_event(*, installation_id: str, author_login: str, pr_number: int, head_sha: str) -> None:
+def process_authored_pr_event(
+ *,
+ installation_id: str,
+ author_login: str,
+ pr_number: int,
+ head_sha: str,
+ # Messages queued before this argument existed came only from the one repository the handler
+ # accepted then.
+ repository: str = "PostHog/posthog",
+ # Messages queued before this argument existed match the repository by name.
+ github_repo_id: int | None = None,
+) -> None:
AuthoredPRReview(
installation_id=installation_id,
+ repository=repository,
author_login=author_login,
pr_number=pr_number,
head_sha=head_sha,
+ github_repo_id=github_repo_id,
+ ).start()
+
+
+@shared_task(
+ ignore_result=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ autoretry_for=(Exception,),
+ max_retries=5,
+ retry_backoff=True,
+ retry_backoff_max=300,
+ retry_jitter=True,
+)
+def process_label_event(
+ *,
+ installation_id: str,
+ repository: str,
+ github_repo_id: int | None,
+ pr_number: int,
+ author_login: str,
+ head_branch: str,
+ labeler_login: str,
+ labeled_by_bot: bool,
+) -> None:
+ LabelReview(
+ installation_id=installation_id,
+ repository=repository,
+ github_repo_id=github_repo_id,
+ pr_number=pr_number,
+ author_login=author_login,
+ head_branch=head_branch,
+ labeler_login=labeler_login,
+ labeled_by_bot=labeled_by_bot,
).start()
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index ac3b1f9f36f1..ce8700937c40 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -33,15 +33,18 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
-from products.review_hog.backend.automatic_reviews import authored_reviews_enabled
-from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
+from products.review_hog.backend.automatic_reviews import automatic_flash_allowed
+from products.review_hog.backend.internal_features import has_internal_features
+from products.review_hog.backend.models import ReviewProjectSettings, ReviewReport, ReviewUserSettings
+from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
+from products.review_hog.backend.preferences import ReviewPreferences
+from products.review_hog.backend.review_request_rules import ResolutionGate, full_review_published
from products.review_hog.backend.reviewer.constants import (
ALREADY_RAISED_SHOWN,
CHUNKING_MODEL,
CHUNKING_ONESHOT_MAX_ADDITIONS,
CHUNKING_REASONING_EFFORT,
CHUNKING_RUNTIME_ADAPTER,
- DEFAULT_URGENCY_THRESHOLD,
FLASH_LENSES,
NON_RETRYABLE_UNIT_FAILURE_CATEGORIES,
REVIEW_MODE_FLASH,
@@ -258,7 +261,7 @@ class ReviewMeta:
automatic_reviewed_head_sha: str | None = None
-@dataclass
+@dataclass(frozen=False)
class ResolveActingUserInput:
team_id: int
author_login: str
@@ -273,6 +276,14 @@ class ResolveActingUserInput:
# drift from the identity the sandboxes execute under. Defaulted for old in-flight payloads.
trigger_source: str = TRIGGER_MANUAL
default_user_id: int | None = None
+ # `owner/name` of the PR, for the automatic trigger's re-check of the repository rules. None in
+ # payloads serialized before the field existed, which fails that re-check closed.
+ repository: str | None = None
+ installation_id: str | None = None
+ github_repo_id: int | None = None
+ # The PR's head branch, which links a self-driving PR to its Inbox report. The fetch refuses forks,
+ # so the branch is in the base repository. None in older payloads: such a PR then has no owner.
+ head_branch: str | None = None
@dataclass(frozen=False)
@@ -280,24 +291,29 @@ class ResolveActingUserResult:
# The user whose enabled perspectives drive this review; None when nothing in the resolution
# chain maps to a PostHog org user — the parent then skips the review.
acting_user_id: int | None
- # The acting user's `ReviewUserSettings`, snapshotted here so mid-run edits don't flip gates
- # between stages. Defaults match the model's (and cover payloads serialized before these existed).
- # `review_labeled_prs` is the AUTHOR's opt-out: when the acting user is the default-user
- # fallback, it is forced True — a borrowed user's personal switch never governs someone else's PR.
+ # The acting user's preferences, snapshotted here so mid-run edits don't flip gates between
+ # stages. Defaults match the code defaults (and cover payloads serialized before these existed).
+ # `review_labeled_prs` is always True: no setting turns the label trigger off. The field stays,
+ # because recorded workflow histories carry it and their replay still reads it.
review_labeled_prs: bool = True
urgency_threshold: str = IssuePriority.CONSIDER.value
review_inbox_prs: bool = False
# Which chain link resolved: "author" | "default" | "override" (observability + tests).
resolved_from: str = "author"
- # Whether a published review of this user's PRs chains into the resolution stage. Defaults False
- # — the SKIP value — so pre-field histories replay deterministically (the chained dispatch is a
- # new workflow command; old runs must never reach it on replay). The model default is True.
+ # Whether a published Full review chains into the resolution stage: the PR owner opted in and the
+ # project has the internal features (`ResolutionGate`). Defaults False, the SKIP value, so
+ # pre-field histories replay deterministically (the chained dispatch is a workflow command).
resolve_comments: bool = False
# Cosmetic only: whether the clean-review media appears in the status comment. Defaults True,
# the model default, so pre-field histories keep the media and a resolve failure falls back to it.
celebrate_clean_reviews: bool = True
+ # Whether the repository rules allow this automatic review. False for every other trigger. The
+ # name predates the rules and stays, because recorded workflow histories carry it.
review_authored_prs: bool = False
+ # Always the default effort. The field stays, because recorded workflow histories carry it.
flash_reasoning_effort: str = ReasoningEffort.MEDIUM.value
+ # The PR owner (`pr_owner.py`): the resolution stage runs under their criteria. None when the PR has no owner.
+ owner_user_id: int | None = None
@dataclass
@@ -821,22 +837,44 @@ def _login_to_user_id(team_id: int, login: str | None) -> int | None:
return user.id if user is not None else None
+def _automatic_review_allowed(input: ResolveActingUserInput, acting_user_id: int | None) -> bool:
+ """Whether the rules still give this PR its automatic Flash review when the turn starts."""
+ if acting_user_id is None or input.repository is None:
+ return False
+ if input.report_id is not None:
+ report = ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first()
+ if full_review_published(report):
+ return False
+ return automatic_flash_allowed(
+ team_id=input.team_id,
+ repository=input.repository,
+ user_id=acting_user_id,
+ author_login=input.author_login,
+ installation_id=input.installation_id,
+ github_repo_id=input.github_repo_id,
+ )
+
+
def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResult:
- # Resolved even on override runs: the clean-review media switch keys off the mapped author's own
- # preference, not the requester's, so an override run still needs this identity to load it.
- author_user_id = _login_to_user_id(input.team_id, input.author_login)
+ # Resolved even on override runs: the owner decides resolution and the clean-review media,
+ # whoever asked for the review.
+ owner = PullRequestOwnerResolver.resolve(
+ input.team_id,
+ repository=input.repository or "",
+ author_login=input.author_login,
+ head_branch=input.head_branch if input.repository else None,
+ )
acting_user_id: int | None
if input.override_user_id is not None:
acting_user_id, resolved_from = input.override_user_id, "override"
else:
- acting_user_id, resolved_from = author_user_id, "author"
- # Label-trigger fallback — someone explicitly asked for this review, so borrow the run user
- # the trigger already resolved. Other triggers keep the author-only contract and skip.
+ acting_user_id, resolved_from = owner.user_id, "author"
+ # Label-trigger fallback: someone explicitly asked for this review, so borrow the run user
+ # the trigger already resolved. Other triggers keep the owner-only contract and skip.
if acting_user_id is None and input.trigger_source == TRIGGER_LABEL:
acting_user_id, resolved_from = input.default_user_id, "default"
- if input.trigger_source == TRIGGER_AUTOMATIC and (
- acting_user_id is None or not authored_reviews_enabled(team_id=input.team_id, user_id=acting_user_id)
- ):
+ automatic_allowed = input.trigger_source == TRIGGER_AUTOMATIC and _automatic_review_allowed(input, acting_user_id)
+ if input.trigger_source == TRIGGER_AUTOMATIC and not automatic_allowed:
if input.report_id is not None:
ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(
status=ReviewReport.Status.IDLE
@@ -845,53 +883,42 @@ def _resolve_acting_user(input: ResolveActingUserInput) -> ResolveActingUserResu
if acting_user_id is None:
return ResolveActingUserResult(acting_user_id=None)
if resolved_from == "default":
- logger.info(
- "PR author %r has no PostHog user; acting as the default user %s", input.author_login, acting_user_id
- )
+ logger.info("PR %r has no owner; acting as the default user %s", input.author_login, acting_user_id)
if input.report_id is not None:
ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).update(acting_user_id=acting_user_id)
- # celebrate_clean_reviews follows the author, who can differ from the acting user on an
- # override run, so load both rows in one query instead of a second round trip below.
- extra_settings_ids = [author_user_id] if author_user_id is not None and author_user_id != acting_user_id else []
- settings_by_user = ReviewUserSettings.load_many(input.team_id, [acting_user_id, *extra_settings_ids])
- settings = settings_by_user[acting_user_id]
+ # A review that runs as a borrowed user (the run user on a label without an owner, or the user
+ # who connected GitHub on an automatic bot review) gets the default settings: that user's own
+ # preferences must not shape someone else's pull request.
+ borrowed = resolved_from == "default" or (
+ input.trigger_source == TRIGGER_AUTOMATIC and acting_user_id != owner.user_id
+ )
+ # celebrate_clean_reviews follows the owner, who can differ from the acting user on an override
+ # run, so load both users in one query instead of a second round trip below.
+ extra_settings_ids = [owner.user_id] if owner.user_id is not None and owner.user_id != acting_user_id else []
+ preferences_by_user = ReviewUserSettings.load_preferences_many(input.team_id, [acting_user_id, *extra_settings_ids])
+ defaults = ReviewPreferences.resolve({}, ReviewProjectSettings.load(input.team_id).defaults)
+ preferences = defaults if borrowed else preferences_by_user[acting_user_id]
+ owner_preferences = preferences_by_user[owner.user_id] if owner.user_id is not None else defaults
+ resolution = ResolutionGate(
+ owner_user_id=owner.user_id,
+ owner_opted_in=owner_preferences.resolve_comments,
+ internal_features=owner.user_id is not None and has_internal_features(input.team_id),
+ )
return ResolveActingUserResult(
acting_user_id=acting_user_id,
- # The labeled-PR opt-out protects authors ("don't review my PRs") — the borrowed default
- # user never imports their personal switch into someone else's PR.
- review_labeled_prs=settings.review_labeled_prs if resolved_from in ("author", "override") else True,
- # str() unwraps the TextChoices member an unsaved defaults instance carries — the payload
- # must hold the plain value. A default-resolved run gates at the built-in default, never the
- # borrowed run user's saved threshold — the same "borrowed settings must not leak into
- # someone else's PR" rule that forces review_labeled_prs above.
- urgency_threshold=(
- str(settings.urgency_threshold)
- if resolved_from in ("author", "override")
- else DEFAULT_URGENCY_THRESHOLD.value
- ),
- review_inbox_prs=settings.review_inbox_prs,
+ review_labeled_prs=True,
+ # .value unwraps the TextChoices member, because the payload must hold the plain value.
+ urgency_threshold=preferences.urgency_threshold.value,
+ review_inbox_prs=preferences.review_inbox_prs,
resolved_from=resolved_from,
- # Same author-protection shape as `review_labeled_prs`: the borrowed default user's personal
- # switch never governs someone else's PR — an unmapped author gets the default posture (on).
- resolve_comments=settings.resolve_comments if resolved_from in ("author", "override") else True,
- # Unlike the switches above, this one follows the AUTHOR, not the requester: its copy scopes
- # it to "your pull requests". A teammate-triggered override still honors the mapped author's
- # own preference. Only an unmapped author falls back to the default.
- celebrate_clean_reviews=(
- settings.celebrate_clean_reviews
- if resolved_from == "author" or (resolved_from == "override" and acting_user_id == author_user_id)
- else (
- settings_by_user[author_user_id].celebrate_clean_reviews
- if resolved_from == "override" and author_user_id is not None
- else True
- )
- ),
- review_authored_prs=settings.review_authored_prs if resolved_from in ("author", "override") else False,
- flash_reasoning_effort=(
- str(settings.flash_reasoning_effort)
- if resolved_from in ("author", "override")
- else ReasoningEffort.MEDIUM.value
- ),
+ # The workflow also requires a publishing Full turn, because only it knows the turn's mode.
+ resolve_comments=resolution.allows(REVIEW_MODE_FULL),
+ # Unlike the values above, this one follows the OWNER, not the requester: its copy scopes
+ # it to "your pull requests". Only a PR without an owner falls back to the default.
+ celebrate_clean_reviews=owner_preferences.celebrate_clean_reviews,
+ review_authored_prs=automatic_allowed,
+ flash_reasoning_effort=ReasoningEffort.MEDIUM.value,
+ owner_user_id=owner.user_id,
)
diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.py
index 95af5574aa7c..01eb2f81b4fb 100644
--- a/products/review_hog/backend/temporal/client.py
+++ b/products/review_hog/backend/temporal/client.py
@@ -96,6 +96,8 @@ def _build_inputs(
signal_priority: ReportPriority | None = None,
review_mode: str = REVIEW_MODE_FULL,
requested_head_sha: str | None = None,
+ installation_id: str | None = None,
+ github_repo_id: int | None = None,
) -> tuple[ReviewPRWorkflowInputs, str]:
"""Validate the review target, the team, and build the workflow inputs + deterministic id.
@@ -134,6 +136,8 @@ def _build_inputs(
resolve_comments=resolve_comments,
review_mode=review_mode,
requested_head_sha=requested_head_sha,
+ installation_id=installation_id,
+ github_repo_id=github_repo_id,
)
return inputs, workflow_id
@@ -208,6 +212,8 @@ def start_review_pr_workflow(
resolve_comments: bool | None = None,
review_mode: str = REVIEW_MODE_FULL,
requested_head_sha: str | None = None,
+ installation_id: str | None = None,
+ github_repo_id: int | None = None,
) -> str:
"""Start or signal the review queue without blocking and return the workflow id.
@@ -234,6 +240,8 @@ def start_review_pr_workflow(
resolve_comments=resolve_comments,
review_mode=review_mode,
requested_head_sha=requested_head_sha,
+ installation_id=installation_id,
+ github_repo_id=github_repo_id,
)
client = sync_connect()
diff --git a/products/review_hog/backend/temporal/resolution.py b/products/review_hog/backend/temporal/resolution.py
index 921b1d18ffbb..5f6cbc483c0a 100644
--- a/products/review_hog/backend/temporal/resolution.py
+++ b/products/review_hog/backend/temporal/resolution.py
@@ -22,6 +22,7 @@ import re
import logging
from dataclasses import field
from datetime import timedelta
+from urllib.parse import quote
import temporalio
from temporalio import activity, workflow
@@ -38,6 +39,8 @@ from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
+from products.review_hog.backend.pr_owner import PullRequestOwnerResolver
+from products.review_hog.backend.review_request_rules import ResolutionGate, ReviewRequestRefusal
from products.review_hog.backend.reviewer.artefact_content import ResolutionRunArtefact, ThreadVerdictArtefact
from products.review_hog.backend.reviewer.constants import (
MAX_THREADS_PER_RUN,
@@ -46,6 +49,7 @@ from products.review_hog.backend.reviewer.constants import (
RESOLUTION_MODEL,
RESOLUTION_REASONING_EFFORT,
RESOLUTION_RUNTIME_ADAPTER,
+ REVIEW_MODE_FULL,
)
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
from products.review_hog.backend.reviewer.models.thread_resolution import CommitHold, ThreadOutcome, ThreadResolution
@@ -95,7 +99,6 @@ from products.review_hog.backend.temporal.activities import (
SyncReviewSkillsInput,
ValidateIntegrationInput,
_installation_for,
- _login_to_user_id,
_sandbox_workflow_id_prefix,
generate_schemas_activity,
sync_review_skills_activity,
@@ -116,16 +119,21 @@ _RESOLUTION_HEARTBEAT = timedelta(minutes=5)
_RETRY = RetryPolicy(maximum_attempts=2)
# The activity's final-attempt turn fallback keys off the same constant — don't let them drift.
_RESOLUTION_RETRY = RetryPolicy(maximum_attempts=RESOLUTION_MAX_ATTEMPTS)
+# Ruleset rule types that never refuse a fix push. Fix commits are signed by GitHub, sit on top of
+# the head, and never force-push, create or delete the branch. Any other rule type, including types
+# GitHub adds later, holds the run.
+_RULES_FIX_PUSH_SATISFIES = frozenset(
+ {"required_signatures", "required_linear_history", "non_fast_forward", "creation", "deletion"}
+)
@frozen
class ResolveThreadsInput:
team_id: int
user_id: int
- # Whose selected resolution-criteria skill applies to this run. None (the shared-secret
- # /resolve path) means "the PR author": prepare maps the fetched author login to a PostHog
- # user; an unmapped author pins the canonical bar — a borrowed account's personal selection
- # never governs someone else's PR.
+ # Whose selected resolution-criteria skill applies to this run. None means the PR owner
+ # (`pr_owner.py`), which prepare resolves from the fetched PR. A borrowed account's personal
+ # selection never governs someone else's PR.
acting_user_id: int | None
owner: str
repo: str
@@ -204,6 +212,42 @@ def _merge_queue_state(input: ResolveThreadsInput, github: GitHubIntegration) ->
return github.get_pull_request_merge_queue_state(f"{input.owner}/{input.repo}", input.pr_number)
+def _branch_protected(input: ResolveThreadsInput, github: GitHubIntegration, head_branch: str) -> bool:
+ """Whether protection on the PR's head branch could refuse or restrict the fix push.
+
+ GitHub sets `protected` for classic protection and also for any ruleset that matches the branch,
+ so a branch whose only rule asks for signed commits reads as protected. Classic protection holds
+ the run; a ruleset match holds it only for a rule type outside `_RULES_FIX_PUSH_SATISFIES`.
+ A failed read raises, so the run never pushes blind.
+ """
+ token, installation_id = github.get_access_token(), github.github_installation_id
+ branch_path = quote(head_branch, safe="/")
+ branch = github_api_request(
+ "GET",
+ f"/repos/{input.owner}/{input.repo}/branches/{branch_path}",
+ token=token,
+ installation_id=installation_id,
+ endpoint="/repos/{owner}/{repo}/branches/{branch}",
+ ).json()
+ if not isinstance(branch, dict) or branch.get("protected") is not True:
+ return False
+ protection = branch.get("protection")
+ # Without `protection.enabled` a classic protection cannot be told apart from a ruleset match.
+ if not isinstance(protection, dict) or protection.get("enabled") is not False:
+ return True
+ rules = github_api_request(
+ "GET",
+ f"/repos/{input.owner}/{input.repo}/rules/branches/{branch_path}",
+ token=token,
+ installation_id=installation_id,
+ endpoint="/repos/{owner}/{repo}/rules/branches/{branch}",
+ params={"per_page": 100},
+ ).json()
+ if not isinstance(rules, list):
+ return True
+ return any(not isinstance(rule, dict) or rule.get("type") not in _RULES_FIX_PUSH_SATISFIES for rule in rules)
+
+
def _commit_hold(
input: ResolveThreadsInput,
github: GitHubIntegration,
@@ -219,6 +263,8 @@ def _commit_hold(
# or one old push would block the stage on this PR for good.
if queue_state == MergeQueueState.EJECTED and queue_state_at_start != MergeQueueState.EJECTED:
return CommitHold.MERGE_QUEUE
+ if _branch_protected(input, github, head_branch):
+ return CommitHold.BRANCH_PROTECTED
if github.has_open_pull_request_with_base(f"{input.owner}/{input.repo}", head_branch):
return CommitHold.STACKED
return None
@@ -252,6 +298,22 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu
)
if pr_metadata.state != "open":
return ResolutionRunResult(skipped_reason="pr_not_open")
+ # Every trigger reaches this gate, so no path writes to a branch whose owner did not opt in. The
+ # fork check above makes the head branch the base repository's, which the Inbox link needs.
+ owner = PullRequestOwnerResolver.resolve(
+ input.team_id,
+ repository=f"{input.owner}/{input.repo}",
+ author_login=pr_metadata.author,
+ head_branch=pr_metadata.head_branch,
+ )
+ if not ResolutionGate.load(input.team_id, owner.user_id).allows(REVIEW_MODE_FULL):
+ logger.info(
+ "Resolution skipped for %s/%s#%s: the pull request owner did not opt in",
+ input.owner,
+ input.repo,
+ input.pr_number,
+ )
+ return ResolutionRunResult(skipped_reason=ReviewRequestRefusal.RESOLUTION_NOT_OPTED_IN.value)
pr_url = input.pr_url or f"https://github.com/{input.owner}/{input.repo}/pull/{input.pr_number}"
report_id = upsert_review_report(
@@ -310,17 +372,7 @@ def _prepare_run(input: ResolveThreadsInput) -> _PreparedRun | ResolutionRunResu
)
_mark_queued_threads(input, triage, token=token, installation_id=installation_id)
- acting_user_id = input.acting_user_id
- if acting_user_id is None:
- acting_user_id = _login_to_user_id(input.team_id, pr_metadata.author)
- logger.info(
- "Resolution acting user for %s/%s#%s: author %r -> %s",
- input.owner,
- input.repo,
- input.pr_number,
- pr_metadata.author,
- acting_user_id if acting_user_id is not None else "unmapped (canonical criteria)",
- )
+ acting_user_id = input.acting_user_id if input.acting_user_id is not None else owner.user_id
skill = load_resolution_skill_for_run(input.team_id, acting_user_id)
return _PreparedRun(
report_id=report_id,
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index 1706485065dd..2237f3f80a09 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -8,8 +8,8 @@ from posthog.dataclasses import frozen
from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FULL
-# How a review run was triggered. Gates are trigger-aware: label → `review_labeled_prs`,
-# inbox → `review_inbox_prs`, manual (CLI/eval), ui (an explicit human ask from the Code review
+# How a review run was triggered. Gates are trigger-aware: inbox → `review_inbox_prs`, automatic →
+# the repository rules; label, manual (CLI/eval), ui (an explicit human ask from the Code review
# scene) and comment (an `@posthog review` pull request comment) → ungated. Plain strings (not an
# Enum) so Temporal payloads stay forward/backward-compatible across deploys.
TRIGGER_LABEL = "label"
@@ -35,9 +35,8 @@ class ReviewPRWorkflowInputs:
no resolvable PR stores the review instead — the target's shape decides, not a mode flag.
`acting_user_id` overrides whose perspectives run: the label trigger leaves it None (the workflow
- resolves the PR author after fetch, falling back to the default run user when the author isn't a
- PostHog user); the eval CLI and the inbox trigger set it explicitly (the inbox PR author is a
- bot, so it can't be resolved from GitHub).
+ resolves the PR owner after fetch, falling back to the default run user when the PR has no
+ owner); the UI, the eval CLI and the inbox trigger set it explicitly.
`trigger_source` / `signal_report_id` default so in-flight payloads serialized before these
fields existed still deserialize.
@@ -61,20 +60,19 @@ class ReviewPRWorkflowInputs:
signal_priority: str | None = None
# Branch target (PR-less review): the pushed head branch to review when no PR URL is known.
head_branch: str | None = None
- # Per-run override for chaining the resolution stage after this turn (fire-and-forget
- # `resolve-pr` dispatch once the turn finishes, when the target has a PR). None — the default,
- # and what every trigger passes except the UI's explicit "review without resolving" — means the
- # acting user's `resolve_comments` setting decides (snapshotted by `resolve_acting_user`, and
- # only on publishing runs — an unpublished eval/CLI review must not write to the PR). Replay-safe
- # both ways: pre-field payloads decode to None and their recorded snapshot lacks the setting
- # (False), while payloads serialized under the old `bool = False` default decode to an explicit
- # False — in both cases the dispatch never fires for old histories, exactly as they ran.
+ # Per-run switch-off for chaining the resolution stage after this turn (fire-and-forget
+ # `resolve-pr` dispatch once the turn finishes, when the target has a PR). None, the default,
+ # means the PR owner's `resolve_comments` opt-in decides (snapshotted by `resolve_acting_user`,
+ # and only on publishing runs: an unpublished eval/CLI review must not write to the PR). False
+ # turns resolution off for this run; True cannot turn it on without the owner's opt-in.
resolve_comments: bool | None = None
# What this turn runs on (`REVIEW_MODE_FULL` / `REVIEW_MODE_FLASH`). Per turn, never persisted:
# a flash turn must not change what the PR's next normal review runs on. Defaulted so in-flight
# payloads from before the field still deserialize as full reviews.
review_mode: str = REVIEW_MODE_FULL
requested_head_sha: str | None = None
+ installation_id: str | None = None
+ github_repo_id: int | None = None
@property
def repository(self) -> str:
@@ -103,8 +101,8 @@ class ResolvePRWorkflowInputs:
PR-only — review threads live on PRs, so there is no branch-target shape. `(team_id, user_id)`
are the explicit identity the sandbox session runs under; `acting_user_id` pins whose selected
- resolution-criteria skill applies (None means the PR author: prepare maps the author login to a
- PostHog user, and an unmapped author pins the canonical criteria — never `user_id`'s).
+ resolution-criteria skill applies (None means the PR owner, which prepare resolves; a PR without
+ an owner never resolves, because nobody opted in).
"""
team_id: int
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index dc7e3e13f01b..4a42f91e588a 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -40,6 +40,7 @@ from products.review_hog.backend.reviewer.constants import (
VALIDATION_MAX_ATTEMPTS,
)
from products.review_hog.backend.reviewer.fingerprint import ReviewHogMarker
+from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.review_design import REVIEW_DESIGN_PIPELINE, REVIEW_DESIGN_SINGLE_AGENT
from products.review_hog.backend.reviewer.status_comment import FinalizeStatusCommentInput
from products.review_hog.backend.reviewer.tools.select_perspectives import PerspectiveSelectionDTO, apply_selection
@@ -526,6 +527,10 @@ class ReviewPRWorkflow:
report_id=report_id,
trigger_source=inputs.trigger_source,
default_user_id=inputs.user_id,
+ repository=repository,
+ installation_id=inputs.installation_id,
+ github_repo_id=inputs.github_repo_id,
+ head_branch=branch,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
@@ -537,10 +542,15 @@ class ReviewPRWorkflow:
)
return report_id
# Trigger-aware opt-outs, read off the resolve-time settings snapshot (mid-run edits can't
- # flip gates). Label gates only the cloud path (no explicit acting-user override) — an
- # explicit CLI/eval invocation always runs. Inbox re-checks the receiver-side gate here for
- # snapshot-at-resolve consistency. Manual stays ungated.
- if inputs.trigger_source == TRIGGER_LABEL and inputs.acting_user_id is None and not acting.review_labeled_prs:
+ # flip gates). Inbox re-checks the receiver-side gate here for snapshot-at-resolve
+ # consistency. A label always runs, and manual stays ungated.
+ # Histories from before the patch recorded the label opt-out, so they replay its early return.
+ if (
+ inputs.trigger_source == TRIGGER_LABEL
+ and not workflow.patched("reviewhog-label-always-runs-2026-10")
+ and inputs.acting_user_id is None
+ and not acting.review_labeled_prs
+ ):
workflow.logger.info(
f"PR author '{meta.author_login}' (user {acting.acting_user_id}) has labeled-PR reviews "
"turned off; skipping review"
@@ -553,6 +563,11 @@ class ReviewPRWorkflow:
workflow.logger.info("Automatic reviews are disabled for the author; skipping review")
return report_id
acting_user_id = acting.acting_user_id
+ # Flash publishes every kept finding: the threshold is a Full review setting. Recording
+ # "consider" keeps the outcome classification of a Flash turn truthful.
+ urgency_threshold = (
+ IssuePriority.CONSIDER.value if inputs.review_mode == REVIEW_MODE_FLASH else acting.urgency_threshold
+ )
# Only an automatic follow-up is gated. The first automatic review of a PR and every human
# trigger always run. The gate fails open: an activity failure reviews the push.
@@ -735,7 +750,7 @@ class ReviewPRWorkflow:
head_sha=head_sha,
run_index=stage.run_index,
issue_ids=dedup.issue_ids,
- urgency_threshold=acting.urgency_threshold,
+ urgency_threshold=urgency_threshold,
# Publishing runs stay ACTIVE through stage 7; publish/failure return them to rest.
will_publish=publishes_to_pr,
),
@@ -758,7 +773,7 @@ class ReviewPRWorkflow:
# The resolved destination: the input PR, or the open PR fetch discovered
# for a branch target.
pr_number=meta.pr_number,
- urgency_threshold=acting.urgency_threshold,
+ urgency_threshold=urgency_threshold,
review_mode=inputs.review_mode,
trigger_source=inputs.trigger_source,
),
@@ -853,7 +868,7 @@ class ReviewPRWorkflow:
team_id=inputs.team_id,
report_id=report_id,
run_index=meta.run_index,
- urgency_threshold=acting.urgency_threshold,
+ urgency_threshold=urgency_threshold,
review_url=publish_result.review_url if publish_result is not None else None,
resolved_from=acting.resolved_from,
review_mode=inputs.review_mode,
@@ -881,18 +896,23 @@ class ReviewPRWorkflow:
)
# Reviewing includes resolving: hand the PR to the resolution stage once this turn's comments
- # are on it. The acting user's `resolve_comments` setting decides (via the resolve-time
- # snapshot, publishing runs only — an unpublished eval/CLI review must not write to the PR);
- # `inputs.resolve_comments` is the per-run override (the UI's "review without resolving").
- # Fire-and-forget (ABANDON) — the resolution run outlives this workflow — and best-effort: a
- # dispatch failure must never fail a finished review. Deterministic under replay: both
- # operands come from recorded history (workflow input + activity result), and pre-field
- # histories decode input None + snapshot False, so the command never fires where it didn't.
- resolve_after = (
- inputs.resolve_comments
- if inputs.resolve_comments is not None
- else (inputs.publish and acting.resolve_comments)
- )
+ # are on it. The PR owner's opt-in decides, whoever triggered (the resolve-time snapshot,
+ # publishing runs only: an unpublished eval/CLI review must not write to the PR).
+ # `inputs.resolve_comments=False` turns it off for one run (the UI's "review without
+ # resolving"); no input turns it on. Fire-and-forget (ABANDON), because the resolution run
+ # outlives this workflow, and best-effort: a dispatch failure must never fail a finished
+ # review. Deterministic under replay: both operands come from recorded history, and the
+ # patch keeps older histories on the rule they ran with.
+ if workflow.patched("reviewhog-owner-resolution-2026-10"):
+ resolve_after = inputs.publish and acting.resolve_comments and inputs.resolve_comments is not False
+ resolution_acting_user_id = acting.owner_user_id
+ else:
+ resolve_after = (
+ inputs.resolve_comments
+ if inputs.resolve_comments is not None
+ else (inputs.publish and acting.resolve_comments)
+ )
+ resolution_acting_user_id = acting_user_id
# A flash turn never writes code, whatever the override or the setting says: the trigger pins
# the override off, and this is the guarantee for any other producer of a flash input.
if resolve_after and inputs.review_mode == REVIEW_MODE_FLASH:
@@ -910,7 +930,7 @@ class ReviewPRWorkflow:
repo=inputs.repo,
pr_number=meta.pr_number,
pr_url=meta.pr_url or "",
- acting_user_id=acting_user_id,
+ acting_user_id=resolution_acting_user_id,
trigger_source=inputs.trigger_source,
),
id=resolve_pr_workflow_id(
diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.py
index 7f02bf4e6dff..7027dc7ed83c 100644
--- a/products/review_hog/backend/tests/test_acting_user.py
+++ b/products/review_hog/backend/tests/test_acting_user.py
@@ -1,19 +1,30 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
from parameterized import parameterized
from social_django.models import UserSocialAuth
-from products.review_hog.backend.models import ReviewReport, ReviewUserSettings
+from posthog.models.integration import Integration
+
+from products.review_hog.backend.models import (
+ ReviewInstallationClaim,
+ ReviewProjectSettings,
+ ReviewReport,
+ ReviewRepository,
+ ReviewUserSettings,
+)
from products.review_hog.backend.temporal.activities import ResolveActingUserInput, _resolve_acting_user
from products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_LABEL, TRIGGER_MANUAL
_SELF = "SELF"
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
class TestResolveActingUser(BaseTest):
def setUp(self) -> None:
super().setUp()
UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "OctoCat"})
+ self.internal_flag = self.enterContext(patch(_INTERNAL_FLAG, return_value=True))
@parameterized.expand(
[
@@ -34,32 +45,70 @@ class TestResolveActingUser(BaseTest):
assert result.acting_user_id == (self.user.id if expected == _SELF else expected)
def test_settings_default_when_user_has_no_row(self) -> None:
- # No settings row → the resolve result carries the MODEL defaults (labeled reviews on, inbox
- # reviews off, consider, resolution on), so every validated finding publishes — and reviews
- # chain resolution — for users who never opened the UI. resolve_comments is the opposite of
- # its DATACLASS default (False, the replay-safe skip value), so dropping its passthrough
- # line would silently disable the resolution stage for everyone with the suite still green.
+ # No settings row → the code defaults (inbox reviews off, consider, resolution off), so every
+ # validated finding publishes and nothing writes to the PR for users who never opened the UI.
result = _resolve_acting_user(
ResolveActingUserInput(team_id=self.team.id, author_login="octocat", override_user_id=None)
)
assert result.review_labeled_prs is True
assert result.review_inbox_prs is False
assert result.urgency_threshold == "consider"
- assert result.resolve_comments is True
+ assert result.resolve_comments is False
assert result.review_authored_prs is False
assert result.flash_reasoning_effort == "medium"
+ def test_project_defaults_reach_authors_and_borrowed_runs(self) -> None:
+ ReviewProjectSettings.objects.for_team(self.team.id).create(
+ team=self.team, preferences={"urgency_threshold": "must_fix", "celebrate_clean_reviews": False}
+ )
+ as_author = _resolve_acting_user(
+ ResolveActingUserInput(team_id=self.team.id, author_login="octocat", override_user_id=None)
+ )
+ as_default = _resolve_acting_user(
+ ResolveActingUserInput(
+ team_id=self.team.id,
+ author_login="ghost",
+ override_user_id=None,
+ trigger_source=TRIGGER_LABEL,
+ default_user_id=self.user.id,
+ )
+ )
+ for result in (as_author, as_default):
+ assert (result.urgency_threshold, result.celebrate_clean_reviews) == ("must_fix", False)
+
@parameterized.expand(
[
- ("enabled", True, True, True),
- ("opted_out", False, True, True),
- ("inactive", True, False, True),
- ("left_organization", True, True, False),
+ ("enabled", True, True, True, True, False, "PostHog", None),
+ ("opted_out", False, True, True, True, False, "PostHog", None),
+ ("inactive", True, False, True, True, False, "PostHog", None),
+ ("left_organization", True, True, False, True, False, "PostHog", None),
+ ("repository_removed", True, True, True, False, False, "PostHog", None),
+ # No Flash after Full: a Full review published while the push waited stops it.
+ ("full_review_published", True, True, True, True, True, "PostHog", None),
+ ("placeholder_account_name", True, True, True, True, False, "installation-1234", "1234"),
]
)
def test_automatic_trigger_rechecks_eligible_author(
- self, _name: str, opted_in: bool, active: bool, member: bool
+ self,
+ _name: str,
+ opted_in: bool,
+ active: bool,
+ member: bool,
+ repository_added: bool,
+ full_published: bool,
+ account_name: str,
+ installation_id: str | None,
) -> None:
+ Integration.objects.create(
+ team=self.team, kind="github", integration_id="1234", config={"account": {"name": account_name}}
+ )
+ if repository_added:
+ ReviewInstallationClaim.objects.for_team(self.team.id).create(
+ team=self.team, installation_id="1234", scope=ReviewInstallationClaim.Scope.SELECTED
+ )
+ ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id="1234", full_name="PostHog/posthog", selected=True
+ )
report = ReviewReport.objects.for_team(self.team.id).create(
team_id=self.team.id,
repository="PostHog/posthog",
@@ -67,9 +116,12 @@ class TestResolveActingUser(BaseTest):
pr_url="https://github.com/PostHog/posthog/pull/7",
head_branch="feat",
base_branch="main",
+ published_heads_by_mode={"full": "a" * 40} if full_published else None,
)
ReviewUserSettings.objects.for_team(self.team.id).create(
- team_id=self.team.id, user_id=self.user.id, review_authored_prs=opted_in
+ team_id=self.team.id,
+ user_id=self.user.id,
+ preferences={"default_review_mode": "flash" if opted_in else "off"},
)
self.user.is_active = active
self.user.save(update_fields=["is_active"])
@@ -82,40 +134,37 @@ class TestResolveActingUser(BaseTest):
override_user_id=self.user.id,
trigger_source=TRIGGER_AUTOMATIC,
report_id=str(report.id),
+ repository="posthog/PostHog",
+ installation_id=installation_id,
)
)
- eligible = opted_in and active and member
+ eligible = opted_in and active and member and repository_added and not full_published
assert result.acting_user_id == (self.user.id if eligible else None)
+ # The workflow gates the automatic run on this flag after the resolve.
+ assert result.review_authored_prs is eligible
report.refresh_from_db()
assert report.status == (ReviewReport.Status.ACTIVE if eligible else ReviewReport.Status.IDLE)
def test_settings_row_flows_into_the_result(self) -> None:
- # The user's saved settings must reach the workflow — if resolve stops loading any of them,
- # the gates and publish silently revert to defaults. review_inbox_prs is set to the OPPOSITE
- # of its dataclass default: dropping its one passthrough line would silently disable the
- # entire inbox trigger for every opted-in user with the whole suite still green.
+ # The user's saved preferences must reach the workflow — if resolve stops loading any of them,
+ # the gates and publish silently revert to defaults. Each value is the OPPOSITE of its
+ # default, so dropping one passthrough line fails here.
ReviewUserSettings.objects.for_team(self.team.id).create(
team_id=self.team.id,
user_id=self.user.id,
- review_labeled_prs=False,
- review_inbox_prs=True,
- urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
- resolve_comments=False,
- review_authored_prs=True,
- flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
- celebrate_clean_reviews=False,
+ preferences={
+ "review_inbox_prs": True,
+ "urgency_threshold": "must_fix",
+ "resolve_comments": True,
+ "celebrate_clean_reviews": False,
+ },
)
result = _resolve_acting_user(
ResolveActingUserInput(team_id=self.team.id, author_login="octocat", override_user_id=None)
)
- assert result.review_labeled_prs is False
assert result.review_inbox_prs is True
assert result.urgency_threshold == "must_fix"
- # The opt-out must reach the workflow — hardwiring the snapshot on would strip users of the
- # only lever that stops reviews from writing to their PRs.
- assert result.resolve_comments is False
- assert result.review_authored_prs is True
- assert result.flash_reasoning_effort == "xhigh"
+ assert result.resolve_comments is True
assert result.celebrate_clean_reviews is False
def test_label_trigger_falls_back_to_the_run_user(self) -> None:
@@ -144,25 +193,22 @@ class TestResolveActingUser(BaseTest):
)
assert result.acting_user_id is None
- def test_labeled_opt_out_protects_authors_but_never_travels_with_a_borrowed_user(self) -> None:
+ def test_personal_preferences_never_travel_with_a_borrowed_user(self) -> None:
# self.user is both the mapped author (octocat) and the run-user fallback.
ReviewUserSettings.objects.for_team(self.team.id).create(
team_id=self.team.id,
user_id=self.user.id,
- review_labeled_prs=False,
- resolve_comments=False,
- celebrate_clean_reviews=False,
+ preferences={"resolve_comments": True, "celebrate_clean_reviews": False},
)
- # Acting as the author: their own opt-outs apply (the workflow will skip / stop at publish).
as_author = _resolve_acting_user(
ResolveActingUserInput(
team_id=self.team.id, author_login="octocat", override_user_id=None, trigger_source=TRIGGER_LABEL
)
)
- assert (as_author.resolved_from, as_author.review_labeled_prs) == ("author", False)
- assert as_author.resolve_comments is False
- # Acting as the borrowed run user on someone else's PR: the same row must NOT kill the
- # review, nor switch off resolution for a PR that isn't theirs (the default posture applies).
+ assert as_author.resolved_from == "author"
+ assert as_author.resolve_comments is True
+ # Acting as the borrowed run user on someone else's PR: the same row must NOT switch on
+ # resolution for a PR that isn't theirs (the default posture applies).
as_default = _resolve_acting_user(
ResolveActingUserInput(
team_id=self.team.id,
@@ -174,7 +220,7 @@ class TestResolveActingUser(BaseTest):
)
assert (as_default.acting_user_id, as_default.resolved_from) == (self.user.id, "default")
assert as_default.review_labeled_prs is True
- assert as_default.resolve_comments is True
+ assert as_default.resolve_comments is False
# Same borrowed-user protection: the run user's own media preference never shapes
# someone else's PR.
assert as_author.celebrate_clean_reviews is False
@@ -187,9 +233,7 @@ class TestResolveActingUser(BaseTest):
ReviewUserSettings.objects.for_team(self.team.id).create(
team_id=self.team.id,
user_id=self.user.id,
- urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
- flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
- celebrate_clean_reviews=False,
+ preferences={"urgency_threshold": "must_fix", "celebrate_clean_reviews": False},
)
as_author = _resolve_acting_user(
ResolveActingUserInput(
@@ -197,7 +241,6 @@ class TestResolveActingUser(BaseTest):
)
)
assert (as_author.resolved_from, as_author.urgency_threshold) == ("author", "must_fix")
- assert as_author.flash_reasoning_effort == "xhigh"
# The media switch follows the author: an override that IS the mapped author (a UI
# self-review) keeps the saved value...
as_author_override = _resolve_acting_user(
@@ -216,7 +259,6 @@ class TestResolveActingUser(BaseTest):
)
)
assert (as_override.resolved_from, as_override.urgency_threshold) == ("override", "must_fix")
- assert as_override.flash_reasoning_effort == "xhigh"
assert as_override.celebrate_clean_reviews is True
as_default = _resolve_acting_user(
ResolveActingUserInput(
@@ -228,7 +270,6 @@ class TestResolveActingUser(BaseTest):
)
)
assert (as_default.resolved_from, as_default.urgency_threshold) == ("default", "consider")
- assert as_default.flash_reasoning_effort == "medium"
def test_override_by_a_different_mapped_user_still_follows_the_authors_media_preference(self) -> None:
# A teammate triggering a review from the UI supplies themselves as override_user_id while the
@@ -237,7 +278,7 @@ class TestResolveActingUser(BaseTest):
teammate = self._create_user("[email protected]")
UserSocialAuth.objects.create(user=teammate, provider="github", uid="gh-2", extra_data={"login": "teammate"})
ReviewUserSettings.objects.for_team(self.team.id).create(
- team_id=self.team.id, user_id=teammate.id, celebrate_clean_reviews=False
+ team_id=self.team.id, user_id=teammate.id, preferences={"celebrate_clean_reviews": False}
)
result = _resolve_acting_user(
ResolveActingUserInput(team_id=self.team.id, author_login="teammate", override_user_id=self.user.id)
@@ -245,6 +286,69 @@ class TestResolveActingUser(BaseTest):
assert (result.acting_user_id, result.resolved_from) == (self.user.id, "override")
assert result.celebrate_clean_reviews is False
+ @parameterized.expand(
+ [
+ ("owner_opted_in_and_a_teammate_asks", "teammate", True, False, True, True),
+ ("requester_opted_in_but_the_owner_did_not", "teammate", False, True, True, False),
+ ("internal_flag_off", "teammate", True, False, False, False),
+ ("no_owner", "ghost", False, True, True, False),
+ ]
+ )
+ def test_resolution_follows_the_pr_owners_opt_in(
+ self,
+ _name: str,
+ author_login: str,
+ owner_opted_in: bool,
+ requester_opted_in: bool,
+ internal: bool,
+ expected: bool,
+ ) -> None:
+ teammate = self._create_user("[email protected]")
+ UserSocialAuth.objects.create(user=teammate, provider="github", uid="gh-2", extra_data={"login": "teammate"})
+ for user, opted_in in ((teammate, owner_opted_in), (self.user, requester_opted_in)):
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=user.id, preferences={"resolve_comments": opted_in}
+ )
+ self.internal_flag.return_value = internal
+
+ result = _resolve_acting_user(
+ ResolveActingUserInput(team_id=self.team.id, author_login=author_login, override_user_id=self.user.id)
+ )
+
+ assert result.acting_user_id == self.user.id
+ assert result.owner_user_id == (teammate.id if author_login == "teammate" else None)
+ assert result.resolve_comments is expected
+
+ def test_automatic_bot_review_runs_as_the_connector_with_default_settings(self) -> None:
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="1234",
+ config={"account": {"name": "PostHog"}},
+ created_by=self.user,
+ )
+ ReviewInstallationClaim.objects.for_team(self.team.id).create(
+ team=self.team, installation_id="1234", scope=ReviewInstallationClaim.Scope.ALL
+ )
+ ReviewProjectSettings.objects.for_team(self.team.id).create(
+ team=self.team, bot_prs=ReviewProjectSettings.BotPullRequests.RUN
+ )
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, preferences={"urgency_threshold": "must_fix"}
+ )
+ result = _resolve_acting_user(
+ ResolveActingUserInput(
+ team_id=self.team.id,
+ author_login="dependabot[bot]",
+ override_user_id=self.user.id,
+ trigger_source=TRIGGER_AUTOMATIC,
+ repository="PostHog/posthog",
+ )
+ )
+ assert (result.acting_user_id, result.review_authored_prs) == (self.user.id, True)
+ # The connector only lends the credentials: their own threshold must not shape a bot's PR.
+ assert result.urgency_threshold == "consider"
+
def test_resolve_stamps_the_acting_user_onto_the_report(self) -> None:
# "Your recent reviews" filters on this stamp — if resolve stops writing it, the list goes empty.
report = ReviewReport.objects.for_team(self.team.id).create(
diff --git a/products/review_hog/backend/tests/test_automatic_review_rules.py b/products/review_hog/backend/tests/test_automatic_review_rules.py
new file mode 100644
index 000000000000..7c92e16fdbca
--- /dev/null
+++ b/products/review_hog/backend/tests/test_automatic_review_rules.py
@@ -0,0 +1,163 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.review_hog.backend.automatic_review_rules import (
+ AuthorChoice,
+ AutomaticReviewDecision,
+ AutomaticReviewReason,
+ AutomaticReviewRule,
+ FlashRule,
+)
+from products.review_hog.backend.models import AutomaticFlashFor, ReviewUserRepositoryChoice
+from products.review_hog.backend.preferences import DefaultReviewMode
+
+YOU, TEAMMATE_A, TEAMMATE_B, TEAMMATE_C = 1, 2, 3, 4
+
+EVERYONE_EXCEPT_A = FlashRule(
+ flash_for=AutomaticFlashFor.EVERYONE,
+ listed_user_ids=frozenset({TEAMMATE_C}),
+ excepted_user_ids=frozenset({TEAMMATE_A}),
+)
+ONLY_A_B = FlashRule(
+ flash_for=AutomaticFlashFor.LISTED,
+ listed_user_ids=frozenset({TEAMMATE_A, TEAMMATE_B}),
+ excepted_user_ids=frozenset({TEAMMATE_C}),
+)
+EVERYONE_NO_LISTS = FlashRule(
+ flash_for=AutomaticFlashFor.EVERYONE, listed_user_ids=frozenset(), excepted_user_ids=frozenset()
+)
+OPT_IN_ONLY = FlashRule(flash_for=AutomaticFlashFor.OFF, listed_user_ids=frozenset(), excepted_user_ids=frozenset())
+
+Default = DefaultReviewMode
+Choice = ReviewUserRepositoryChoice.Mode
+Reason = AutomaticReviewReason
+
+
+def rule(project: FlashRule, repository: FlashRule | None = None, *, review_bots: bool = False) -> AutomaticReviewRule:
+ return AutomaticReviewRule(project=project, repository=repository, review_bots=review_bots)
+
+
+class TestAutomaticReviewRule(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("project_everyone", rule(EVERYONE_EXCEPT_A), YOU, Default.FOLLOW, None, True, Reason.PROJECT_EVERYONE),
+ (
+ "project_excepted",
+ rule(EVERYONE_EXCEPT_A),
+ TEAMMATE_A,
+ Default.FOLLOW,
+ None,
+ False,
+ Reason.PROJECT_EXCEPTED,
+ ),
+ ("project_listed", rule(ONLY_A_B), TEAMMATE_A, Default.FOLLOW, None, True, Reason.PROJECT_LISTED),
+ ("project_not_listed", rule(ONLY_A_B), YOU, Default.FOLLOW, None, False, Reason.PROJECT_NOT_LISTED),
+ ("project_opt_in", rule(OPT_IN_ONLY), YOU, Default.FOLLOW, None, False, Reason.PROJECT_OPT_IN),
+ # A repository exception replaces the project rule, lists included.
+ (
+ "exception_beats_project",
+ rule(EVERYONE_EXCEPT_A, OPT_IN_ONLY),
+ YOU,
+ Default.FOLLOW,
+ None,
+ False,
+ Reason.REPOSITORY_OPT_IN,
+ ),
+ (
+ "exception_lists_not_project_lists",
+ rule(EVERYONE_EXCEPT_A, EVERYONE_NO_LISTS),
+ TEAMMATE_A,
+ Default.FOLLOW,
+ None,
+ True,
+ Reason.REPOSITORY_EVERYONE,
+ ),
+ (
+ "exception_listed",
+ rule(OPT_IN_ONLY, ONLY_A_B),
+ TEAMMATE_B,
+ Default.FOLLOW,
+ None,
+ True,
+ Reason.REPOSITORY_LISTED,
+ ),
+ # The author's default beats the repository exception and the project rule.
+ ("default_flash", rule(OPT_IN_ONLY, OPT_IN_ONLY), YOU, Default.FLASH, None, True, Reason.OWN_DEFAULT),
+ (
+ "default_off",
+ rule(EVERYONE_EXCEPT_A, EVERYONE_EXCEPT_A),
+ YOU,
+ Default.OFF,
+ None,
+ False,
+ Reason.OWN_DEFAULT,
+ ),
+ # The author's repository choice beats everything else.
+ (
+ "choice_beats_default",
+ rule(EVERYONE_EXCEPT_A),
+ YOU,
+ Default.OFF,
+ Choice.FLASH,
+ True,
+ Reason.OWN_REPOSITORY_CHOICE,
+ ),
+ (
+ "choice_beats_except_list",
+ rule(EVERYONE_EXCEPT_A),
+ TEAMMATE_A,
+ Default.FOLLOW,
+ Choice.FLASH,
+ True,
+ Reason.OWN_REPOSITORY_CHOICE,
+ ),
+ (
+ "choice_off",
+ rule(EVERYONE_EXCEPT_A),
+ YOU,
+ Default.FLASH,
+ Choice.OFF,
+ False,
+ Reason.OWN_REPOSITORY_CHOICE,
+ ),
+ ]
+ )
+ def test_resolve_for_members(
+ self,
+ _name: str,
+ automatic_rule: AutomaticReviewRule,
+ user_id: int,
+ default_mode: DefaultReviewMode,
+ repository_choice: ReviewUserRepositoryChoice.Mode | None,
+ flash: bool,
+ reason: AutomaticReviewReason,
+ ) -> None:
+ author = AuthorChoice(
+ user_id=user_id, is_bot=False, default_mode=default_mode, repository_choice=repository_choice
+ )
+
+ assert automatic_rule.resolve(author) == AutomaticReviewDecision(flash=flash, reason=reason)
+
+ @parameterized.expand(
+ [
+ ("bot_skipped", True, TEAMMATE_C, False, False, Reason.BOT_SKIPPED),
+ ("bot_reviewed_even_when_excepted", True, TEAMMATE_A, True, True, Reason.BOT_REVIEWED),
+ ("unmapped_skipped", False, None, False, False, Reason.BOT_SKIPPED),
+ ("unmapped_reviewed", False, None, True, True, Reason.BOT_REVIEWED),
+ ]
+ )
+ def test_bots_and_unmapped_authors_follow_the_bot_rule(
+ self,
+ _name: str,
+ is_bot: bool,
+ user_id: int | None,
+ review_bots: bool,
+ flash: bool,
+ reason: AutomaticReviewReason,
+ ) -> None:
+ author = AuthorChoice(user_id=user_id, is_bot=is_bot, default_mode=Default.FOLLOW, repository_choice=None)
+
+ decision = rule(EVERYONE_EXCEPT_A, review_bots=review_bots).resolve(author)
+
+ assert decision == AutomaticReviewDecision(flash=flash, reason=reason)
diff --git a/products/review_hog/backend/tests/test_automatic_reviews.py b/products/review_hog/backend/tests/test_automatic_reviews.py
index 0cbd64efeaf0..7734e7e9fbd5 100644
--- a/products/review_hog/backend/tests/test_automatic_reviews.py
+++ b/products/review_hog/backend/tests/test_automatic_reviews.py
@@ -7,7 +7,7 @@ from unittest.mock import MagicMock, patch
from django.core.cache import caches
from django.http import HttpResponse
-from django.test import RequestFactory, SimpleTestCase, override_settings
+from django.test import RequestFactory, SimpleTestCase
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -18,52 +18,81 @@ from posthog.ingress.dispatch.dispatcher import WebhookDispatcher
from posthog.ingress.dispatch.loading import reset_consumer_registry
from posthog.ingress.dispatch.registry import ConsumerRegistry
from posthog.ingress.github.provider import SPECS, build_github_provider
-from posthog.ingress.test import LOCMEM_CACHES
from posthog.ingress.views import build_webhook_view
from posthog.models.integration import Integration
from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
-
-from products.review_hog.backend.automatic_reviews import enqueue_authored_pr_review
-from products.review_hog.backend.models import ReviewUserSettings
-from products.review_hog.backend.tasks import process_authored_pr_event
+from posthog.models.user import User
+
+from products.review_hog.backend.models import (
+ ReviewInstallationClaim,
+ ReviewProjectSettings,
+ ReviewReport,
+ ReviewRepository,
+ ReviewRepositoryPerson,
+ ReviewUserSettings,
+)
+from products.review_hog.backend.ownership import OwnedRepositoryPrefilter
+from products.review_hog.backend.pull_request_events import accept_pull_request_event
+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
+from products.review_hog.backend.tasks import process_authored_pr_event, process_label_event
from products.review_hog.backend.webhook_consumers import WEBHOOK_CONSUMERS
_QUEUE = "products.review_hog.backend.tasks.process_authored_pr_event.delay"
+_LABEL_QUEUE = "products.review_hog.backend.tasks.process_label_event.delay"
_START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"
+_BUSY = "products.review_hog.backend.temporal.client.workflow_running"
+_GITHUB = "products.review_hog.backend.label_reviews.github_api_request"
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
_SECRET = "test-review-hog-webhook-secret"
_HEAD_SHA = "a" * 40
_DISPATCH_METRIC = "posthog_review_hog_authored_pr_review_total"
+_INSTALLATION_ID = "1234"
+_REPO_ID = 5001
def _dispatch_count(outcome: str) -> float:
return REGISTRY.get_sample_value(_DISPATCH_METRIC, {"outcome": outcome}) or 0.0
-def _payload(*, action: str = "opened", draft: bool = False) -> dict[str, object]:
+def _payload(
+ *, action: str = "opened", draft: bool = False, repository: str = "PostHog/posthog", login: str = "OctoCat"
+) -> dict[str, object]:
return {
"action": action,
- "installation": {"id": 1234},
- "repository": {"full_name": "PostHog/posthog"},
+ "installation": {"id": int(_INSTALLATION_ID)},
+ "repository": {"id": _REPO_ID, "full_name": repository},
"pull_request": {
"number": 42,
"state": "open",
"draft": draft,
"merged": False,
- "user": {"login": "OctoCat"},
- "head": {"sha": _HEAD_SHA, "repo": {"full_name": "posthog/PostHog"}},
- "base": {"repo": {"full_name": "PostHog/posthog"}},
+ "user": {"login": login},
+ "head": {"sha": _HEAD_SHA, "ref": "feature", "repo": {"full_name": repository.lower()}},
+ "base": {"repo": {"full_name": repository}},
},
}
-@override_settings(CACHES=LOCMEM_CACHES)
+def _label_payload(
+ *, label: str = "reviewhog", sender: str = "OctoCat", sender_type: str = "User", login: str = "OctoCat"
+) -> dict[str, object]:
+ return {
+ **_payload(action="labeled", login=login),
+ "label": {"name": label},
+ "sender": {"login": sender, "type": sender_type},
+ }
+
+
class TestAuthoredPRWebhook(SimpleTestCase):
def setUp(self) -> None:
reset_consumer_registry()
caches[INGRESS_DEDUP_CACHE_ALIAS].clear()
+ caches["default"].clear()
self.addCleanup(reset_consumer_registry)
self.addCleanup(caches[INGRESS_DEDUP_CACHE_ALIAS].clear)
+ self.addCleanup(caches["default"].clear)
+ self._cache_summary(names=["posthog/posthog"])
self.factory = RequestFactory()
self.view = build_webhook_view(build_github_provider("posthog"))
dispatcher = WebhookDispatcher(ConsumerRegistry(providers=SPECS, consumers=WEBHOOK_CONSUMERS))
@@ -72,6 +101,14 @@ class TestAuthoredPRWebhook(SimpleTestCase):
patch("posthog.ingress.github.provider.get_instance_setting", return_value=_SECRET)
)
+ def _cache_summary(
+ self, *, takes_all: bool = False, names: list[str] | None = None, ids: list[int] | None = None
+ ) -> None:
+ caches["default"].set(
+ OwnedRepositoryPrefilter.cache_key(_INSTALLATION_ID),
+ {"all": takes_all, "names": names or [], "ids": ids or []},
+ )
+
def _post(self, body: bytes, *, event: str = "pull_request", signature: str | None = None) -> HttpResponse:
request = self.factory.post(
"/webhooks/github/",
@@ -85,16 +122,30 @@ class TestAuthoredPRWebhook(SimpleTestCase):
)
return self.view(request)
- @parameterized.expand([("opened", False), ("opened", True), ("synchronize", False), ("synchronize", True)])
+ @parameterized.expand(
+ [
+ ("opened", False, "PostHog/posthog"),
+ ("opened", True, "PostHog/posthog"),
+ ("synchronize", False, "PostHog/posthog"),
+ ("synchronize", True, "PostHog/posthog"),
+ ]
+ )
@patch(_QUEUE)
- def test_signed_eligible_events_enqueue_once(self, action: str, draft: bool, enqueue: MagicMock) -> None:
- body = json.dumps(_payload(action=action, draft=draft)).encode()
+ def test_signed_eligible_events_enqueue_once(
+ self, action: str, draft: bool, repository: str, enqueue: MagicMock
+ ) -> None:
+ body = json.dumps(_payload(action=action, draft=draft, repository=repository)).encode()
assert self._post(body).status_code == 202
assert self._post(body).status_code == 202
enqueue.assert_called_once_with(
- installation_id="1234", author_login="octocat", pr_number=42, head_sha=_HEAD_SHA
+ installation_id=_INSTALLATION_ID,
+ repository=repository,
+ author_login="octocat",
+ pr_number=42,
+ head_sha=_HEAD_SHA,
+ github_repo_id=_REPO_ID,
)
@parameterized.expand(
@@ -125,6 +176,78 @@ class TestAuthoredPRWebhook(SimpleTestCase):
assert response.status_code == expected_status
enqueue.assert_not_called()
+ @parameterized.expand(
+ [
+ ("selected_by_name", "PostHog/posthog", {"names": ["posthog/posthog"]}, False, True),
+ ("selected_by_id_after_rename", "PostHog/posthog-renamed", {"ids": [_REPO_ID]}, False, True),
+ ("all_repositories_claimed", "PostHog/posthog-js", {"takes_all": True}, False, True),
+ ("nobody_reviews_it", "PostHog/posthog-js", {"names": ["posthog/posthog"]}, False, False),
+ ("cache_error_fails_open", "PostHog/posthog-js", {}, True, True),
+ ]
+ )
+ @patch(_QUEUE)
+ def test_only_owned_repositories_enqueue(
+ self,
+ _name: str,
+ repository: str,
+ summary: dict,
+ cache_error: bool,
+ expected_enqueue: bool,
+ enqueue: MagicMock,
+ ) -> None:
+ self._cache_summary(**summary)
+ if cache_error:
+ self.enterContext(
+ patch(
+ "products.review_hog.backend.ownership.cache.get_or_set",
+ side_effect=ConnectionError("redis down"),
+ )
+ )
+
+ assert self._post(json.dumps(_payload(repository=repository)).encode()).status_code == 202
+
+ assert enqueue.called == expected_enqueue
+
+ @parameterized.expand(
+ [
+ ("person_adds_the_label", "reviewhog", "OctoCat", "User", True),
+ ("label_name_ignores_case", "ReviewHog", "OctoCat", "User", True),
+ # The task explains the refusal on the pull request and removes the label.
+ ("bot_adds_the_label", "reviewhog", "renovate[bot]", "Bot", True),
+ ("another_label", "bug", "OctoCat", "User", False),
+ ]
+ )
+ @patch(_QUEUE)
+ @patch(_LABEL_QUEUE)
+ def test_the_reviewhog_label_queues_a_label_review(
+ self,
+ _name: str,
+ label: str,
+ sender: str,
+ sender_type: str,
+ expected_enqueue: bool,
+ label_enqueue: MagicMock,
+ enqueue: MagicMock,
+ ) -> None:
+ body = json.dumps(_label_payload(label=label, sender=sender, sender_type=sender_type)).encode()
+
+ assert self._post(body).status_code == 202
+
+ enqueue.assert_not_called()
+ if expected_enqueue:
+ label_enqueue.assert_called_once_with(
+ installation_id=_INSTALLATION_ID,
+ repository="PostHog/posthog",
+ github_repo_id=_REPO_ID,
+ pr_number=42,
+ author_login="octocat",
+ head_branch="feature",
+ labeler_login=sender,
+ labeled_by_bot=sender_type == "Bot",
+ )
+ else:
+ label_enqueue.assert_not_called()
+
@patch(_QUEUE)
def test_non_post_does_not_enqueue(self, enqueue: MagicMock) -> None:
assert self.view(self.factory.get("/webhooks/github/")).status_code == 405
@@ -132,7 +255,6 @@ class TestAuthoredPRWebhook(SimpleTestCase):
@parameterized.expand(
[
- ("label", ("action",), "labeled"),
("ready_for_review", ("action",), "ready_for_review"),
("closed", ("pull_request", "state"), "closed"),
("merged", ("pull_request", "merged"), True),
@@ -165,66 +287,112 @@ class TestAuthoredPRWebhook(SimpleTestCase):
class TestAuthoredPRReviewTask(BaseTest):
def setUp(self) -> None:
super().setUp()
- self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]))
self.integration = Integration.objects.create(
- team=self.team, kind="github", integration_id="1234", config={"installation_id": "1234"}
+ team=self.team,
+ kind="github",
+ integration_id=_INSTALLATION_ID,
+ config={"installation_id": _INSTALLATION_ID, "account": {"name": "PostHog"}},
+ created_by=self.user,
)
self.github_identity = UserSocialAuth.objects.create(
user=self.user, provider="github", uid="review-author", extra_data={"login": "OctoCat"}
)
+ ReviewInstallationClaim.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=_INSTALLATION_ID, scope=ReviewInstallationClaim.Scope.SELECTED
+ )
+ self.repository = ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=_INSTALLATION_ID, full_name="PostHog/posthog", selected=True
+ )
self.preferences = ReviewUserSettings.objects.for_team(self.team.id).create(
- team_id=self.team.id, user_id=self.user.id, review_authored_prs=True
+ team_id=self.team.id, user_id=self.user.id, preferences={"default_review_mode": "flash"}
)
+ self.internal_flag = self.enterContext(patch(_INTERNAL_FLAG, return_value=True))
- def _queued_event(self) -> Mapping[str, object]:
+ def _queued_event(self, login: str = "OctoCat") -> Mapping[str, object]:
with patch(_QUEUE) as enqueue:
- enqueue_authored_pr_review(_payload())
+ accept_pull_request_event(_payload(login=login))
enqueue.assert_called_once()
return enqueue.call_args.kwargs
+ def _expected_start(self, *, team_id: int, user_id: int) -> dict[str, object]:
+ return {
+ "pr_url": "https://github.com/PostHog/posthog/pull/42",
+ "team_id": team_id,
+ "user_id": user_id,
+ "acting_user_id": user_id,
+ "publish": True,
+ "resolve_comments": False,
+ "review_mode": "flash",
+ "trigger_source": "automatic",
+ "requested_head_sha": _HEAD_SHA,
+ "installation_id": _INSTALLATION_ID,
+ "github_repo_id": _REPO_ID,
+ }
+
+ @parameterized.expand([("own_flash_default",), ("listed_by_the_project",), ("repository_exception",)])
@patch(_START)
- def test_opted_in_author_schedules_flash_on_the_configured_team(self, start: MagicMock) -> None:
+ def test_eligible_author_schedules_flash_in_the_owning_project(self, setup: str, start: MagicMock) -> None:
+ if setup != "own_flash_default":
+ self.preferences.preferences = {}
+ self.preferences.save(update_fields=["preferences"])
+ if setup == "listed_by_the_project":
+ ReviewProjectSettings.objects.for_team(self.team.id).create(team=self.team, flash_for="listed")
+ ReviewRepositoryPerson.objects.for_team(self.team.id).create(
+ team=self.team, repository=None, user=self.user, kind=ReviewRepositoryPerson.Kind.LISTED
+ )
+ if setup == "repository_exception":
+ self.repository.flash_for = "everyone"
+ self.repository.save()
started_before = _dispatch_count("started")
process_authored_pr_event.run(**self._queued_event())
- start.assert_called_once_with(
- pr_url="https://github.com/PostHog/posthog/pull/42",
- team_id=self.team.id,
- user_id=self.user.id,
- acting_user_id=self.user.id,
- publish=True,
- resolve_comments=False,
- review_mode="flash",
- trigger_source="automatic",
- requested_head_sha=_HEAD_SHA,
- )
+ start.assert_called_once_with(**self._expected_start(team_id=self.team.id, user_id=self.user.id))
assert _dispatch_count("started") - started_before == 1.0
+ # The first sighting stores GitHub's id, so a later rename keeps the row.
+ self.repository.refresh_from_db()
+ assert self.repository.github_repo_id == _REPO_ID
@parameterized.expand(
[
- ("disabled", "not_opted_in"),
- ("unset", "not_opted_in"),
- ("inactive", "not_opted_in"),
- ("left_org", "author_unmapped"),
- ("unmapped", "author_unmapped"),
+ ("opted_out", "not_opted_in"),
+ ("repository_removed", "repository_not_added"),
+ ("inactive", "bot_skipped"),
+ ("left_org", "bot_skipped"),
+ ("unmapped", "bot_skipped"),
+ ("missing_installation", "installation_mismatch"),
+ ("internal_flag_off", "internal_features_off"),
+ ("full_review_published", "full_review_published"),
]
)
@patch(_START)
- def test_queued_events_recheck_author_consent_and_membership(
+ def test_queued_events_recheck_ownership_consent_and_membership(
self, change: str, expected_outcome: str, start: MagicMock
) -> None:
queued = self._queued_event()
- if change == "disabled":
- self.preferences.review_authored_prs = False
- self.preferences.save(update_fields=["review_authored_prs"])
- elif change == "unset":
- self.preferences.delete()
+ if change == "opted_out":
+ self.preferences.preferences = {"default_review_mode": "off"}
+ self.preferences.save(update_fields=["preferences"])
+ elif change == "repository_removed":
+ self.repository.delete()
elif change == "inactive":
self.user.is_active = False
self.user.save(update_fields=["is_active"])
elif change == "left_org":
OrganizationMembership.objects.filter(organization=self.organization, user=self.user).delete()
+ elif change == "missing_installation":
+ self.integration.delete()
+ elif change == "internal_flag_off":
+ self.internal_flag.return_value = False
+ elif change == "full_review_published":
+ ReviewReport.objects.for_team(self.team.id).create(
+ team=self.team,
+ repository="PostHog/posthog",
+ pr_number=42,
+ head_branch="feature",
+ base_branch="master",
+ published_heads_by_mode={"full": _HEAD_SHA},
+ )
else:
self.github_identity.delete()
outcome_before = _dispatch_count(expected_outcome)
@@ -234,33 +402,141 @@ class TestAuthoredPRReviewTask(BaseTest):
start.assert_not_called()
assert _dispatch_count(expected_outcome) - outcome_before == 1.0
+ @parameterized.expand([("connector_runs_it", True, "started"), ("no_connector", False, "bot_no_connector")])
+ @patch(_START)
+ def test_bot_pull_requests_run_as_the_connector_when_the_project_reviews_bots(
+ self, _name: str, has_connector: bool, expected_outcome: str, start: MagicMock
+ ) -> None:
+ ReviewProjectSettings.objects.for_team(self.team.id).create(
+ team=self.team, bot_prs=ReviewProjectSettings.BotPullRequests.RUN
+ )
+ if not has_connector:
+ self.integration.created_by = None
+ self.integration.save(update_fields=["created_by"])
+ outcome_before = _dispatch_count(expected_outcome)
+
+ process_authored_pr_event.run(**self._queued_event(login="dependabot[bot]"))
+
+ if has_connector:
+ start.assert_called_once_with(**self._expected_start(team_id=self.team.id, user_id=self.user.id))
+ else:
+ start.assert_not_called()
+ assert _dispatch_count(expected_outcome) - outcome_before == 1.0
+
+ @patch(_START)
+ def test_a_project_that_takes_all_repositories_owns_the_unselected_ones(self, start: MagicMock) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ Integration.objects.create(
+ team=other_team, kind="github", integration_id=_INSTALLATION_ID, config={}, created_by=self.user
+ )
+ ReviewInstallationClaim.objects.for_team(other_team.id).create(
+ team=other_team, installation_id=_INSTALLATION_ID, scope=ReviewInstallationClaim.Scope.ALL
+ )
+ ReviewUserSettings.objects.for_team(other_team.id).create(
+ team_id=other_team.id, user_id=self.user.id, preferences={"default_review_mode": "flash"}
+ )
+ self.repository.delete()
+
+ process_authored_pr_event.run(**self._queued_event())
+
+ start.assert_called_once_with(**self._expected_start(team_id=other_team.id, user_id=self.user.id))
+
+
+class TestLabelReviewTask(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.connector = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id=_INSTALLATION_ID,
+ config={"installation_id": _INSTALLATION_ID, "account": {"name": "PostHog"}},
+ created_by=self.connector,
+ )
+ UserSocialAuth.objects.create(
+ user=self.user, provider="github", uid="review-author", extra_data={"login": "OctoCat"}
+ )
+ ReviewInstallationClaim.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=_INSTALLATION_ID, scope=ReviewInstallationClaim.Scope.SELECTED
+ )
+ self.repository = ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=_INSTALLATION_ID, full_name="PostHog/posthog", selected=True
+ )
+ self.internal_flag = self.enterContext(patch(_INTERNAL_FLAG, return_value=True))
+ self.enterContext(patch(_BUSY, return_value=False))
+ self.start = self.enterContext(patch(_START))
+ self.github = self.enterContext(patch(_GITHUB))
+ self.enterContext(patch("products.review_hog.backend.label_reviews.GitHubIntegration.get_access_token"))
+
+ def _queued_event(self, payload: dict[str, object]) -> Mapping[str, object]:
+ with patch(_LABEL_QUEUE) as enqueue:
+ accept_pull_request_event(payload)
+ enqueue.assert_called_once()
+ return enqueue.call_args.kwargs
+
+ def _run(self, payload: dict[str, object]) -> None:
+ process_label_event.run(**self._queued_event(payload))
+
+ @parameterized.expand([("the_author_owns_it", "OctoCat", "author"), ("no_owner", "stranger", "connector")])
+ def test_a_label_review_runs_as_the_owner_else_as_the_connector(
+ self, _name: str, author_login: str, run_as: str
+ ) -> None:
+ self._run(_label_payload(login=author_login))
+
+ self.start.assert_called_once_with(
+ pr_url="https://github.com/PostHog/posthog/pull/42",
+ team_id=self.team.id,
+ user_id=self.user.id if run_as == "author" else self.connector.id,
+ publish=True,
+ trigger_source="label",
+ )
+
+ @parameterized.expand([("another_bot", "renovate[bot]", False), ("stamphog_hands_off", "stamphog[bot]", True)])
+ def test_only_stamphog_may_label_as_a_bot(self, _name: str, sender: str, starts: bool) -> None:
+ self._run(_label_payload(sender=sender, sender_type="Bot"))
+
+ assert self.start.called == starts
+ calls = [(call.args[0], call.args[1]) for call in self.github.call_args_list]
+ if starts:
+ assert calls == []
+ else:
+ assert calls == [
+ ("DELETE", "/repos/PostHog/posthog/issues/42/labels/reviewhog"),
+ ("POST", "/repos/PostHog/posthog/issues/42/comments"),
+ ]
+
+ def test_a_retried_bot_label_refusal_comments_once(self) -> None:
+ queued = self._queued_event(_label_payload(sender="renovate[bot]", sender_type="Bot"))
+ self.github.side_effect = [GitHubAPIError("boom", status=502), GitHubAPIError("gone", status=404), None]
+
+ with self.assertRaises(GitHubAPIError):
+ process_label_event.run(**queued)
+ process_label_event.run(**queued)
+
+ calls = [call.args[0] for call in self.github.call_args_list]
+ assert calls == ["DELETE", "DELETE", "POST"]
+ self.start.assert_not_called()
+
@parameterized.expand(
[
- ("missing_installation", "installation_mismatch"),
- ("other_team", "installation_mismatch"),
- ("other_configured_team", "installation_mismatch"),
- ("no_team", "no_team"),
+ ("repository_not_added", "repository_not_added"),
+ ("internal_flag_off", "internal_features_off"),
+ ("no_run_user", "no_run_user"),
]
)
- @patch(_START)
- def test_delivery_must_match_the_configured_teams_installation(
- self, change: str, expected_outcome: str, start: MagicMock
- ) -> None:
- queued = self._queued_event()
- if change == "missing_installation":
- self.integration.delete()
- elif change == "no_team":
- self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[]))
+ def test_a_label_without_an_owning_internal_project_starts_nothing(self, change: str, outcome: str) -> None:
+ queued = self._queued_event(_label_payload(login="stranger"))
+ if change == "repository_not_added":
+ self.repository.delete()
+ elif change == "internal_flag_off":
+ self.internal_flag.return_value = False
else:
- other_team = Team.objects.create(organization=self.organization)
- if change == "other_team":
- self.integration.team = other_team
- self.integration.save(update_fields=["team"])
- else:
- self.enterContext(override_settings(REVIEWHOG_TEAM_IDS=[other_team.id, self.team.id]))
- outcome_before = _dispatch_count(expected_outcome)
+ self.integration.created_by = None
+ self.integration.save(update_fields=["created_by"])
+ before = REGISTRY.get_sample_value("posthog_review_hog_label_review_total", {"outcome": outcome}) or 0.0
- process_authored_pr_event.run(**queued)
+ process_label_event.run(**queued)
- start.assert_not_called()
- assert _dispatch_count(expected_outcome) - outcome_before == 1.0
+ self.start.assert_not_called()
+ after = REGISTRY.get_sample_value("posthog_review_hog_label_review_total", {"outcome": outcome}) or 0.0
+ assert after - before == 1.0
diff --git a/products/review_hog/backend/tests/test_feature_flags.py b/products/review_hog/backend/tests/test_feature_flags.py
index 285da23ec2f6..8fc392bc9f54 100644
--- a/products/review_hog/backend/tests/test_feature_flags.py
+++ b/products/review_hog/backend/tests/test_feature_flags.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from products.review_hog.backend.internal_features import has_internal_features
from products.review_hog.backend.reviewer.feature_flags import flash_pipeline_kill_switch_on
_FEATURE_ENABLED = "products.review_hog.backend.reviewer.feature_flags.posthoganalytics.feature_enabled"
@@ -22,3 +23,19 @@ class TestFlashPipelineKillSwitch(BaseTest):
) -> None:
with patch(_FEATURE_ENABLED, feature_enabled):
assert flash_pipeline_kill_switch_on(self.team.id) is expected
+
+
+class TestInternalFeaturesFlag(BaseTest):
+ @parameterized.expand(
+ [
+ ("flag_on", MagicMock(return_value=True), True),
+ # A flag service failure must not switch on writes or automation for a project.
+ ("flag_error", MagicMock(side_effect=RuntimeError("flag service down")), False),
+ ]
+ )
+ def test_internal_features_follow_the_project_flag(
+ self, _name: str, feature_enabled: MagicMock, expected: bool
+ ) -> None:
+ with patch("posthog.permissions.posthoganalytics.feature_enabled", feature_enabled):
+ assert has_internal_features(self.team.id) is expected
+ assert feature_enabled.call_args.kwargs["groups"]["project"] == str(self.team.id)
diff --git a/products/review_hog/backend/tests/test_fetch_review_tier.py b/products/review_hog/backend/tests/test_fetch_review_tier.py
index 3398626690a0..28ac1691a9f5 100644
--- a/products/review_hog/backend/tests/test_fetch_review_tier.py
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -3,8 +3,6 @@ from dataclasses import replace
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from django.test import override_settings
-
from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
@@ -16,6 +14,8 @@ from products.review_hog.backend.temporal.activities import FetchPRDataInput, _f
from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_UI
from products.signals.backend.models import SignalReport
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
+
_MODULE = "products.review_hog.backend.temporal.activities"
@@ -131,7 +131,7 @@ class TestFetchDecidesTheTier(BaseTest):
pr_metadata=_pr_metadata(), pr_comments=[], pr_files=[], diff=""
)
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
fetch_input = FetchPRDataInput(
team_id=self.team.id,
user_id=1,
diff --git a/products/review_hog/backend/tests/test_inbox_trigger.py b/products/review_hog/backend/tests/test_inbox_trigger.py
index 911612f9fe31..dbfbbf164a7d 100644
--- a/products/review_hog/backend/tests/test_inbox_trigger.py
+++ b/products/review_hog/backend/tests/test_inbox_trigger.py
@@ -25,6 +25,7 @@ from products.tasks.backend.models import Task, TaskRun
_START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"
_WORKFLOW_RUNNING = "products.review_hog.backend.temporal.client.workflow_running"
_STAMPHOG_QUEUE = "products.stamphog.backend.facade.tasks.queue_inbox_pr_review"
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
# GitHub's own casing, as a real `output.pr_url` carries it. The task row lowercases its slug, so
# this is what lets an assertion tell the task's repository apart from the PR URL's own claim.
_PR_URL = "https://github.com/PostHog/posthog/pull/9"
@@ -39,6 +40,7 @@ class TestInboxTrigger(BaseTest):
busy_patcher = patch(_WORKFLOW_RUNNING, return_value=False)
self.addCleanup(busy_patcher.stop)
busy_patcher.start()
+ self.internal_flag = self.enterContext(patch(_INTERNAL_FLAG, return_value=True))
self.signal_report = SignalReport.objects.create(
team=self.team, status=SignalReport.Status.IN_PROGRESS, signal_count=1, total_weight=1.0
)
@@ -65,7 +67,7 @@ class TestInboxTrigger(BaseTest):
def _opt_in(self, user: User, **flags: bool) -> None:
# No explicit flags means the classic ReviewHog inbox opt-in.
ReviewUserSettings.objects.for_team(self.team.id).create(
- team=self.team, user=user, **(flags or {"review_inbox_prs": True})
+ team=self.team, user=user, preferences=flags or {"review_inbox_prs": True}
)
def _task(
@@ -236,18 +238,28 @@ class TestInboxTrigger(BaseTest):
mock_start.assert_not_called()
+ @parameterized.expand(
+ [
+ # A soft-deleted task's run can still save output and re-fire the receiver; its PR is
+ # disowned work, and the webhook leg already excludes deleted tasks, so the first review
+ # (the one that mints the approval) must not fire either.
+ ("soft_deleted_task",),
+ # The settings tab hides the Inbox switches without the flag, so saved opt-ins start nothing.
+ ("internal_flag_off",),
+ ]
+ )
@patch(_STAMPHOG_QUEUE)
@patch(_START, return_value="wf-1")
- def test_soft_deleted_task_does_not_trigger(self, mock_start, mock_queue) -> None:
- # A soft-deleted task's run can still save output and re-fire the receiver; its PR is
- # disowned work, and the webhook leg already excludes deleted tasks, so the first review
- # (the one that mints the approval) must not fire either.
+ def test_neither_review_starts(self, change: str, mock_start, mock_queue) -> None:
self._mock_start = mock_start
self._suggest_reviewers(["alice"])
self._opt_in(self.alice, review_inbox_prs=True, stamphog_review_inbox_prs=True)
task = self._task()
- task.deleted = True
- task.save(update_fields=["deleted"])
+ if change == "soft_deleted_task":
+ task.deleted = True
+ task.save(update_fields=["deleted"])
+ else:
+ self.internal_flag.return_value = False
self._record_output(self._run(task), {"pr_url": _PR_URL})
mock_start.assert_not_called()
@@ -452,17 +464,21 @@ class TestInboxTrigger(BaseTest):
@parameterized.expand(
[
- # (name, flags, expected) — the webhook-leg resolver must key on the STAMPHOG toggle:
+ # (name, flags, internal, expected) — the webhook-leg resolver must key on the STAMPHOG toggle:
# keying on review_inbox_prs would re-review for users who never opted into stamphog.
- ("stamphog_toggle_on", {"stamphog_review_inbox_prs": True}, True),
- ("only_review_hog_toggle_on", {"review_inbox_prs": True}, False),
+ ("stamphog_toggle_on", {"stamphog_review_inbox_prs": True}, True, True),
+ ("only_review_hog_toggle_on", {"review_inbox_prs": True}, True, False),
+ ("internal_flag_off", {"stamphog_review_inbox_prs": True}, False, False),
]
)
- def test_resolve_stamphog_acting_reviewer_keys_on_the_stamphog_toggle(self, _name, flags, expected) -> None:
+ def test_resolve_stamphog_acting_reviewer_keys_on_the_stamphog_toggle(
+ self, _name, flags, internal, expected
+ ) -> None:
# The hook stamphog's webhook path calls before re-reviewing a self-driving PR on a later
# push — switching the toggle off mid-PR must stop new runs.
self._suggest_reviewers(["alice"])
self._opt_in(self.alice, **flags)
+ self.internal_flag.return_value = internal
resolved = resolve_stamphog_acting_reviewer(self.team.id, str(self.signal_report.id), None)
diff --git a/products/review_hog/backend/tests/test_ownership.py b/products/review_hog/backend/tests/test_ownership.py
new file mode 100644
index 000000000000..ea54a3878ed8
--- /dev/null
+++ b/products/review_hog/backend/tests/test_ownership.py
@@ -0,0 +1,59 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.review_hog.backend.models import ReviewInstallationClaim, ReviewRepository
+from products.review_hog.backend.ownership import RepositoryRef, resolve_owner
+
+INSTALLATION = "1001"
+PROJECT_A, PROJECT_B = 11, 22
+WEB = RepositoryRef(installation_id=INSTALLATION, github_repo_id=501, full_name="example-org/web")
+
+
+def row(team_id: int, *, selected: bool, flash_for: str | None = None, **fields: object) -> ReviewRepository:
+ values: dict = {"installation_id": INSTALLATION, "github_repo_id": 501, "full_name": "example-org/web", **fields}
+ return ReviewRepository(team_id=team_id, selected=selected, flash_for=flash_for, **values)
+
+
+def all_claim(team_id: int) -> ReviewInstallationClaim:
+ return ReviewInstallationClaim(team_id=team_id, installation_id=INSTALLATION, scope="all")
+
+
+class TestResolveOwner(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("nobody", [], None, None),
+ ("all_claim", [], all_claim(PROJECT_A), PROJECT_A),
+ ("selected", [row(PROJECT_B, selected=True)], None, PROJECT_B),
+ ("selected_beats_all_claim", [row(PROJECT_B, selected=True)], all_claim(PROJECT_A), PROJECT_B),
+ (
+ "exception_in_all_project",
+ [row(PROJECT_A, selected=False, flash_for="off")],
+ all_claim(PROJECT_A),
+ PROJECT_A,
+ ),
+ # An exception without selection does not take the repository from the "all" project.
+ (
+ "stale_exception_elsewhere",
+ [row(PROJECT_B, selected=False, flash_for="off")],
+ all_claim(PROJECT_A),
+ PROJECT_A,
+ ),
+ ("stale_exception_alone", [row(PROJECT_B, selected=False, flash_for="off")], None, None),
+ # Renames keep the id, so the old name still matches.
+ ("renamed", [row(PROJECT_B, selected=True, full_name="example-org/old-web")], None, PROJECT_B),
+ # A name match with another id is an older repository that had this name.
+ ("reused_name", [row(PROJECT_B, selected=True, github_repo_id=999)], None, None),
+ ("id_unknown_yet", [row(PROJECT_B, selected=True, github_repo_id=None)], None, PROJECT_B),
+ ]
+ )
+ def test_resolve_owner(
+ self,
+ _name: str,
+ rows: list[ReviewRepository],
+ claim: ReviewInstallationClaim | None,
+ expected_team_id: int | None,
+ ) -> None:
+ owner = resolve_owner(WEB, rows, claim)
+
+ assert (owner.team_id if owner is not None else None) == expected_team_id
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index 32b300911c56..f9da35163090 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -3,8 +3,7 @@ from dataclasses import replace
from typing import TypeVar
from posthog.test.base import BaseTest
-
-from django.test import override_settings
+from unittest.mock import patch
from parameterized import parameterized
@@ -70,6 +69,8 @@ from products.signals.backend.artefact_schemas import Commit
from products.signals.backend.enums import ReportPriority
from products.tasks.backend.facade.run_config import ReasoningEffort
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
+
_ContentT = TypeVar("_ContentT")
@@ -167,7 +168,7 @@ class TestUpsertReviewReport(BaseTest):
# path would flip a report's reviewer between turns and feed a cheap turn's findings into a
# stronger turn's "already covered" injection; a downgrade would hand a person a cheap review.
signal_report_id = str(uuid.uuid4())
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
report_id = upsert_review_report(
team_id=self.team.id,
repository="o/r",
@@ -261,7 +262,7 @@ class TestUpsertReviewReport(BaseTest):
# The tier is recorded for every team (so the label stays truthful and the tiers can be
# compared on their traffic), but only the dogfood teams run the cheaper arm; a gate that
# leaks the arm would cut review strength for teams nobody enrolled.
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id + 1]):
+ with patch(_INTERNAL_FLAG, return_value=False):
report_id = upsert_review_report(
team_id=self.team.id,
repository="o/r",
diff --git a/products/review_hog/backend/tests/test_pr_owner.py b/products/review_hog/backend/tests/test_pr_owner.py
new file mode 100644
index 000000000000..fd66c5f23c07
--- /dev/null
+++ b/products/review_hog/backend/tests/test_pr_owner.py
@@ -0,0 +1,113 @@
+import json
+
+from posthog.test.base import BaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from social_django.models import UserSocialAuth
+
+from posthog.models.instance_setting import override_instance_config
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+
+from products.review_hog.backend.pr_owner import PullRequestOwner, PullRequestOwnerResolver, pick_pr_owner
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.tasks.backend.models import Task, TaskRun
+
+_HEAD_BRANCH = "posthog-code/fix-the-thing"
+
+
+class TestPickPullRequestOwner(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("mapped_author", 1, False, None, PullRequestOwner(user_id=1, source="author")),
+ ("mapped_author_wins_over_the_inbox", 1, True, 2, PullRequestOwner(user_id=1, source="author")),
+ ("self_driving_pr", None, True, 2, PullRequestOwner(user_id=2, source="inbox_reviewer")),
+ ("self_driving_pr_without_reviewer", None, True, None, PullRequestOwner(user_id=None, source="none")),
+ # Another bot can claim an Inbox branch name; only the PostHog app's pull requests link to a report.
+ ("other_author_on_an_inbox_branch", None, False, 2, PullRequestOwner(user_id=None, source="none")),
+ ]
+ )
+ def test_owner_rule(
+ self,
+ _name: str,
+ author_user_id: int | None,
+ authored_by_posthog_app: bool,
+ inbox_reviewer_id: int | None,
+ expected: PullRequestOwner,
+ ) -> None:
+ owner = pick_pr_owner(
+ author_user_id=author_user_id,
+ authored_by_posthog_app=authored_by_posthog_app,
+ inbox_reviewer_id=inbox_reviewer_id,
+ )
+ assert owner == expected
+
+
+class TestPullRequestOwnerResolver(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "OctoCat"})
+ self.reviewer = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=self.reviewer, organization=self.organization)
+ UserSocialAuth.objects.create(user=self.reviewer, provider="github", uid="gh-2", extra_data={"login": "alice"})
+ report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.IN_PROGRESS, signal_count=1, total_weight=1.0
+ )
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": "alice"}]),
+ )
+ task = Task.objects.create(
+ team=self.team,
+ title="Implement the fix",
+ description="from a signal report",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ repository="PostHog/posthog",
+ signal_report=report,
+ internal=True,
+ )
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ state={"ai_stage": "implementation", "self_driving_head_branch": _HEAD_BRANCH},
+ )
+
+ def _resolve(self, author_login: str, head_branch: str = _HEAD_BRANCH) -> PullRequestOwner:
+ with override_instance_config("GITHUB_APP_SLUG", "posthog-app"):
+ return PullRequestOwnerResolver.resolve(
+ self.team.id, repository="PostHog/posthog", author_login=author_login, head_branch=head_branch
+ )
+
+ def test_an_active_author_owns_the_pull_request(self) -> None:
+ assert self._resolve("octocat") == PullRequestOwner(user_id=self.user.id, source="author")
+
+ @parameterized.expand(
+ [
+ ("author", "user", "octocat"),
+ ("inbox_reviewer", "reviewer", "posthog-app[bot]"),
+ ]
+ )
+ def test_an_inactive_user_owns_nothing(self, _name: str, user_attribute: str, author_login: str) -> None:
+ user: User = getattr(self, user_attribute)
+ user.is_active = False
+ user.save(update_fields=["is_active"])
+ assert self._resolve(author_login) == PullRequestOwner(user_id=None, source="none")
+
+ @parameterized.expand(
+ [
+ ("posthog_app_on_the_inbox_branch", "posthog-app[bot]", _HEAD_BRANCH, "inbox_reviewer"),
+ ("posthog_app_on_another_branch", "posthog-app[bot]", "some-other-branch", "none"),
+ ("another_bot_on_the_inbox_branch", "renovate[bot]", _HEAD_BRANCH, "none"),
+ ]
+ )
+ def test_a_self_driving_pull_request_belongs_to_the_inbox_reviewer(
+ self, _name: str, author_login: str, head_branch: str, source: str
+ ) -> None:
+ owner = self._resolve(author_login, head_branch)
+ assert owner.source == source
+ assert owner.user_id == (self.reviewer.id if source == "inbox_reviewer" else None)
diff --git a/products/review_hog/backend/tests/test_preferences.py b/products/review_hog/backend/tests/test_preferences.py
new file mode 100644
index 000000000000..d657c51db0df
--- /dev/null
+++ b/products/review_hog/backend/tests/test_preferences.py
@@ -0,0 +1,94 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.review_hog.backend.preferences import (
+ DefaultReviewMode,
+ InvalidPreference,
+ PreferenceSource,
+ ReviewPreferences,
+ ReviewProjectDefaults,
+ UrgencyThreshold,
+)
+
+NO_PROJECT_DEFAULTS = ReviewProjectDefaults.resolve({})
+STRICT_PROJECT = ReviewProjectDefaults.resolve({"urgency_threshold": "must_fix", "celebrate_clean_reviews": False})
+
+
+class TestReviewPreferences(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("code_default", {}, NO_PROJECT_DEFAULTS, UrgencyThreshold.CONSIDER, PreferenceSource.DEFAULT),
+ ("project_default", {}, STRICT_PROJECT, UrgencyThreshold.MUST_FIX, PreferenceSource.PROJECT),
+ (
+ "user_beats_project",
+ {"urgency_threshold": "should_fix"},
+ STRICT_PROJECT,
+ UrgencyThreshold.SHOULD_FIX,
+ PreferenceSource.USER,
+ ),
+ # Reads ignore what the schema does not know, so a renamed or broken key never fails a load.
+ (
+ "invalid_value_ignored",
+ {"urgency_threshold": "everything", "removed_key": True},
+ STRICT_PROJECT,
+ UrgencyThreshold.MUST_FIX,
+ PreferenceSource.PROJECT,
+ ),
+ ]
+ )
+ def test_urgency_threshold_layers(
+ self,
+ _name: str,
+ stored: dict,
+ project: ReviewProjectDefaults,
+ expected: UrgencyThreshold,
+ source: PreferenceSource,
+ ) -> None:
+ preferences = ReviewPreferences.resolve(stored, project)
+
+ assert preferences.urgency_threshold == expected
+ assert preferences.sources["urgency_threshold"] == source
+
+ def test_personal_only_keys_ignore_project_defaults(self) -> None:
+ project = ReviewProjectDefaults.resolve({"resolve_comments": True, "default_review_mode": "flash"})
+
+ preferences = ReviewPreferences.resolve({}, project)
+
+ assert preferences.resolve_comments is False
+ assert preferences.default_review_mode == DefaultReviewMode.FOLLOW
+ assert project.stored == {}
+
+ @parameterized.expand(
+ [
+ ("equal_to_project_default_is_dropped", {}, {"urgency_threshold": "must_fix"}, {}),
+ ("equal_to_code_default_is_dropped", {"resolve_comments": True}, {"resolve_comments": False}, {}),
+ ("different_value_is_stored", {}, {"urgency_threshold": "consider"}, {"urgency_threshold": "consider"}),
+ (
+ "other_keys_survive",
+ {"review_inbox_prs": True},
+ {"celebrate_clean_reviews": True},
+ {"review_inbox_prs": True, "celebrate_clean_reviews": True},
+ ),
+ ]
+ )
+ def test_writes_store_only_what_differs(self, _name: str, stored: dict, changes: dict, expected: dict) -> None:
+ current = ReviewPreferences.resolve(stored, STRICT_PROJECT)
+
+ assert current.with_changes(changes) == expected
+
+ @parameterized.expand(
+ [
+ ("unknown_key", {"review_labeled_prs": False}),
+ ("full_mode", {"default_review_mode": "full"}),
+ ("wrong_type", {"resolve_comments": "yes"}),
+ ]
+ )
+ def test_writes_reject_what_the_schema_does_not_allow(self, _name: str, changes: dict) -> None:
+ with self.assertRaises(InvalidPreference):
+ ReviewPreferences.defaults().with_changes(changes)
+
+ def test_project_defaults_store_only_what_differs_from_code(self) -> None:
+ assert STRICT_PROJECT.with_changes({"urgency_threshold": "consider"}) == {"celebrate_clean_reviews": False}
+ with self.assertRaises(InvalidPreference):
+ STRICT_PROJECT.with_changes({"resolve_comments": True})
diff --git a/products/review_hog/backend/tests/test_publish_idempotency.py b/products/review_hog/backend/tests/test_publish_idempotency.py
index 07f1108259e3..295deedd31d6 100644
--- a/products/review_hog/backend/tests/test_publish_idempotency.py
+++ b/products/review_hog/backend/tests/test_publish_idempotency.py
@@ -70,6 +70,9 @@ def test_review_already_posted_detects_our_own_markered_review() -> None:
with override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="posthog[bot]"):
assert _review_posted(marker, [{"body": marker, **bot}]) is True
assert _review_posted(marker, [{"body": marker, "user": {"login": "rogue[bot]", "type": "Bot"}}]) is False
+ # Unconfigured in production, no bot is trusted, because any installed bot could paste the marker.
+ with override_settings(REVIEWHOG_GITHUB_BOT_LOGIN="", DEBUG=False, TEST=False):
+ assert _review_posted(marker, [{"body": marker, **bot}]) is False
def test_review_already_posted_proceeds_when_readback_fails() -> None:
diff --git a/products/review_hog/backend/tests/test_push_gate.py b/products/review_hog/backend/tests/test_push_gate.py
index d93ea7cfe17f..f72474924e11 100644
--- a/products/review_hog/backend/tests/test_push_gate.py
+++ b/products/review_hog/backend/tests/test_push_gate.py
@@ -19,8 +19,15 @@ def _file(filename: str, patch: str | None = "@@ -1 +1 @@\n-a\n+b") -> dict[str,
return {"filename": filename, "changes": 2, "patch": patch}
-def _commit(sha: str, *, merge: bool = False) -> dict[str, Any]:
- return {"sha": sha, "parents": [{"sha": "p1"}, {"sha": "p2"}] if merge else [{"sha": "p1"}]}
+_REVIEWHOG_BOT = {"login": "reviewhog[bot]", "type": "Bot"}
+
+
+def _commit(sha: str, *, merge: bool = False, author: dict[str, str] | None = None) -> dict[str, Any]:
+ return {
+ "sha": sha,
+ "parents": [{"sha": "p1"}, {"sha": "p2"}] if merge else [{"sha": "p1"}],
+ "author": author or {"login": "octocat", "type": "User"},
+ }
def _pr(commits: list[dict[str, Any]], files: list[dict[str, Any]]) -> dict[str, Any]:
@@ -99,6 +106,17 @@ _CODE_PUSH = _push(
"merge_only",
True,
),
+ # The resolution stage pushed fixes for the last review's findings.
+ (
+ "reviewhog_fix_commits",
+ _push(
+ new_commits=[_commit("a"), _commit("c", author=_REVIEWHOG_BOT)],
+ pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ own_commit_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ ),
+ "reviewhog_commits_only",
+ True,
+ ),
# ReviewHog never reviews lockfiles, yet a lockfile bump is the author's own change, not a merge.
(
"lockfile_bump",
@@ -157,6 +175,16 @@ def test_push_gate_asks_system_one_about_own_code_commits(
assert "round" not in str(call["questions"]["alters"].instructions)
+def test_push_gate_reviews_a_push_that_mixes_reviewhog_and_author_commits() -> None:
+ push = _push(
+ new_commits=[_commit("a"), _commit("r", author=_REVIEWHOG_BOT), _commit("c")],
+ pr_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ own_commit_files=[_file("posthog/billing.py", _BILLING_FIX)],
+ )
+ decision = _decide({**push, "commits/r": {"files": []}}, _system_one(0.99))
+ assert (decision.skip, decision.reason) == (False, "system_one_above_threshold")
+
+
@parameterized.expand(
[
("not_configured", SystemOneNotConfigured("no gateway")),
diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.py
new file mode 100644
index 000000000000..6fc7d6e0b1e1
--- /dev/null
+++ b/products/review_hog/backend/tests/test_repositories_api.py
@@ -0,0 +1,331 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.review_hog.backend.models import (
+ ReviewInstallationClaim,
+ ReviewProjectSettings,
+ ReviewRepository,
+ ReviewUserRepositoryChoice,
+)
+
+INSTALLATION = "1001"
+WEB = {"installation_id": INSTALLATION, "full_name": "example-org/web", "github_repo_id": 501}
+CACHED_REPOSITORIES = [
+ {"id": 501, "name": "web", "full_name": "example-org/web"},
+ {"id": 502, "name": "api", "full_name": "example-org/api"},
+ {"id": 503, "name": "docs", "full_name": "example-org/docs"},
+]
+
+ADMIN_WRITES = [
+ ("project_settings/", "patch", {"flash_for": "everyone"}),
+ ("installation_claims/", "post", {"installation_id": INSTALLATION, "scope": "all"}),
+ ("repositories/", "post", {**WEB, "selected": True}),
+]
+
+
+class TestReviewRepositorySettingsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))
+ self.enterContext(
+ patch(
+ "posthog.models.integration.GitHubIntegration.list_all_cached_repositories",
+ return_value=CACHED_REPOSITORIES,
+ )
+ )
+ self._set_level(OrganizationMembership.Level.ADMIN)
+ self.other_team = Team.objects.create(organization=self.organization, name="Other project")
+ for team in (self.team, self.other_team):
+ Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id=INSTALLATION,
+ config={"account": {"name": "example-org"}},
+ created_by=self.user,
+ )
+
+ def _set_level(self, level: OrganizationMembership.Level) -> None:
+ OrganizationMembership.objects.filter(organization=self.organization, user=self.user).update(level=level)
+
+ def _url(self, path: str, team: Team | None = None) -> str:
+ return f"/api/projects/{(team or self.team).id}/review_hog/{path}"
+
+ def _claim(self, team: Team, scope: str) -> ReviewInstallationClaim:
+ return ReviewInstallationClaim.objects.for_team(team.id).create(
+ team=team, installation_id=INSTALLATION, scope=scope
+ )
+
+ @parameterized.expand(ADMIN_WRITES)
+ def test_members_read_but_only_admins_change_project_settings(self, path: str, method: str, body: dict) -> None:
+ self._set_level(OrganizationMembership.Level.MEMBER)
+
+ assert self.client.get(self._url(path)).status_code == 200
+ assert getattr(self.client, method)(self._url(path), body, format="json").status_code == 403
+
+ self._set_level(OrganizationMembership.Level.ADMIN)
+
+ assert getattr(self.client, method)(self._url(path), body, format="json").status_code in (200, 201)
+
+ @parameterized.expand(ADMIN_WRITES)
+ def test_admin_of_an_environment_cannot_change_the_parent_project(self, path: str, method: str, body: dict) -> None:
+ self._set_level(OrganizationMembership.Level.MEMBER)
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Staging")
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="member"
+ )
+ AccessControl.objects.create(
+ team=environment,
+ resource="project",
+ resource_id=str(environment.id),
+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=self.user),
+ access_level="admin",
+ )
+
+ res = getattr(self.client, method)(self._url(path, environment), body, format="json")
+
+ assert res.status_code == 403, res.json()
+ assert self.client.get(self._url(path, environment)).status_code == 200
+
+ def test_project_rule_stores_only_what_differs_and_is_logged(self) -> None:
+ res = self.client.patch(
+ self._url("project_settings/"),
+ {"flash_for": "listed", "bot_prs": "run", "urgency_threshold": "must_fix", "celebrate_clean_reviews": True},
+ format="json",
+ )
+
+ assert res.status_code == 200, res.json()
+ assert res.json()["urgency_threshold"] == "must_fix"
+ assert res.json()["can_edit"] is True
+ assert [installation["account_name"] for installation in res.json()["installations"]] == ["example-org"]
+ row = ReviewProjectSettings.objects.for_team(self.team.id).get()
+ assert (row.flash_for, row.bot_prs, row.preferences) == ("listed", "run", {"urgency_threshold": "must_fix"})
+
+ added = self.client.post(
+ self._url("project_settings/people/"), {"user_id": self.user.id, "kind": "listed"}, format="json"
+ )
+ assert added.status_code == 201, added.json()
+ person_id = added.json()["people"][0]["id"]
+ assert self.client.delete(self._url(f"project_settings/people/{person_id}/")).status_code == 200
+
+ logged = ActivityLog.objects.filter(team_id=self.team.id, scope="ReviewProjectSettings", item_id=str(row.id))
+ fields = [change["field"] for entry in logged for change in (entry.detail or {}).get("changes") or []]
+ assert {"flash_for", "bot_prs", "listed_people"} <= set(fields)
+
+ def test_selecting_a_repository_takes_it_from_the_project_that_claims_all(self) -> None:
+ self._claim(self.other_team, ReviewInstallationClaim.Scope.ALL)
+
+ res = self.client.post(self._url("repositories/"), {**WEB, "selected": True}, format="json")
+
+ assert res.status_code == 200, res.json()
+ assert res.json()["taken_from_project"] == {"id": self.other_team.id, "name": "Other project"}
+ assert res.json()["repository"]["selected"] is True
+ # The first selection also claims the installation for "only selected repositories".
+ assert ReviewInstallationClaim.objects.for_team(self.team.id).get().scope == "selected"
+ taken = ActivityLog.objects.filter(
+ team_id=self.other_team.id, scope="ReviewInstallationClaim", activity="updated"
+ ).first()
+ assert taken is not None and taken.detail is not None
+ assert taken.detail["changes"][0]["before"] == "example-org/web"
+
+ # The repository now has a row in this project, so the other project cannot take it back.
+ conflict = self.client.post(
+ self._url("repositories/", self.other_team), {**WEB, "flash_for": "everyone"}, format="json"
+ )
+
+ assert conflict.status_code == 409
+ assert conflict.json()["conflicting_project"]["id"] == self.team.id
+
+ def test_a_repository_row_from_an_earlier_installation_still_owns_the_repository(self) -> None:
+ # A reinstall of the GitHub App gives the same repositories a new installation id. The row of
+ # the earlier installation must still block another project, or the repository gets two owners.
+ ReviewRepository.objects.for_team(self.other_team.id).create(
+ team=self.other_team, installation_id="1000", github_repo_id=501, full_name="example-org/web", selected=True
+ )
+
+ res = self.client.post(self._url("repositories/"), {**WEB, "selected": True}, format="json")
+
+ assert res.status_code == 409, res.json()
+ assert res.json()["conflicting_project"]["id"] == self.other_team.id
+
+ def test_only_one_project_can_claim_all_repositories(self) -> None:
+ self._claim(self.other_team, ReviewInstallationClaim.Scope.ALL)
+
+ res = self.client.post(
+ self._url("installation_claims/"), {"installation_id": INSTALLATION, "scope": "all"}, format="json"
+ )
+
+ assert res.status_code == 409
+ assert res.json()["conflicting_project"] == {"id": self.other_team.id, "name": "Other project"}
+
+ def test_projects_of_other_organizations_stay_unnamed(self) -> None:
+ stranger_team = Team.objects.create(organization=Organization.objects.create(name="other"), name="Secret")
+ self._claim(stranger_team, ReviewInstallationClaim.Scope.ALL)
+
+ res = self.client.post(
+ self._url("installation_claims/"), {"installation_id": INSTALLATION, "scope": "all"}, format="json"
+ )
+
+ assert res.status_code == 409
+ assert res.json()["conflicting_project"] == {"id": None, "name": None}
+ assert "Secret" not in res.json()["error"]
+
+ taken = self.client.post(self._url("repositories/"), {**WEB, "selected": True}, format="json")
+
+ assert taken.status_code == 200, taken.json()
+ logged = ActivityLog.objects.get(team_id=stranger_team.id, scope="ReviewInstallationClaim", activity="updated")
+ assert logged.user is None
+ assert logged.detail is not None
+ assert logged.detail["changes"][0]["after"] == "A project in another organization"
+
+ def test_switching_to_selected_removes_the_exceptions_of_repositories_that_leave(self) -> None:
+ claim = self._claim(self.team, ReviewInstallationClaim.Scope.ALL)
+ for body in (
+ {**WEB, "flash_for": "off"},
+ {**WEB, "full_name": "example-org/api", "github_repo_id": 502, "selected": True},
+ ):
+ assert self.client.post(self._url("repositories/"), body, format="json").status_code == 200
+
+ res = self.client.patch(self._url(f"installation_claims/{claim.id}/"), {"scope": "selected"}, format="json")
+
+ assert res.status_code == 200, res.json()
+ remaining = ReviewRepository.objects.for_team(self.team.id).values_list("full_name", flat=True)
+ assert list(remaining) == ["example-org/api"]
+
+ @parameterized.expand(
+ [
+ ("exception_without_ownership", {**WEB, "flash_for": "everyone"}, 400),
+ ("nothing_to_store", {**WEB, "selected": False}, 200),
+ ("unknown_to_the_installation", {**WEB, "full_name": "example-org/secret", "selected": True}, 400),
+ ("id_of_another_repository", {**WEB, "github_repo_id": 502, "selected": True}, 400),
+ (
+ "reserve_another_repositorys_id",
+ {**WEB, "full_name": "example-org/not-yet-created", "github_repo_id": 503, "flash_for": "off"},
+ 400,
+ ),
+ ]
+ )
+ def test_repository_writes_keep_rows_meaningful(self, _name: str, body: dict, expected_status: int) -> None:
+ self._claim(self.team, ReviewInstallationClaim.Scope.SELECTED)
+
+ res = self.client.post(self._url("repositories/"), body, format="json")
+
+ assert res.status_code == expected_status, res.json()
+ assert not ReviewRepository.objects.for_team(self.team.id).exists()
+
+ def test_a_choice_equal_to_the_inherited_value_is_not_stored(self) -> None:
+ self._claim(self.team, ReviewInstallationClaim.Scope.ALL)
+ url = self._url("repository_choices/")
+
+ flash = self.client.post(url, {**WEB, "mode": "flash"}, format="json")
+
+ assert flash.status_code == 200, flash.json()
+ assert flash.json()["my_result"] == {"flash": True, "reason": "own_repository_choice"}
+ assert flash.json()["choice"]["mode"] == "flash"
+
+ # The project rule is opt-in only, so "off" is what the user inherits: the choice clears.
+ off = self.client.post(url, {**WEB, "mode": "off"}, format="json")
+
+ assert off.json() == {"choice": None, "my_result": {"flash": False, "reason": "project_opt_in"}}
+ assert not ReviewUserRepositoryChoice.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand(
+ [
+ ("no_project_reviews_it", None, {}),
+ ("rename_through_a_known_id", 501, {"full_name": "example-org/zzz"}),
+ ("store_an_unknown_id", None, {"github_repo_id": 777}),
+ ]
+ )
+ def test_choices_need_a_repository_this_project_reviews(
+ self, _name: str, other_row_repo_id: int | None, overrides: dict
+ ) -> None:
+ other_row = None
+ if overrides:
+ self._claim(self.other_team, ReviewInstallationClaim.Scope.SELECTED)
+ other_row = ReviewRepository.objects.for_team(self.other_team.id).create(
+ team=self.other_team,
+ installation_id=INSTALLATION,
+ github_repo_id=other_row_repo_id,
+ full_name="example-org/web",
+ selected=True,
+ )
+
+ res = self.client.post(self._url("repository_choices/"), {**WEB, **overrides, "mode": "flash"}, format="json")
+
+ assert res.status_code == 400
+ if other_row is not None:
+ stored = ReviewRepository.objects.for_team(self.other_team.id).get(id=other_row.id)
+ assert (stored.full_name, stored.github_repo_id) == ("example-org/web", other_row_repo_id)
+
+ @patch(
+ "posthog.models.integration.GitHubIntegration.list_all_cached_repositories", return_value=CACHED_REPOSITORIES
+ )
+ def test_overview_joins_the_cached_list_with_ownership_and_my_result(self, _cached: object) -> None:
+ self._claim(self.team, ReviewInstallationClaim.Scope.ALL)
+ self._claim(self.other_team, ReviewInstallationClaim.Scope.SELECTED)
+ # Stored before a reinstall of the GitHub App, so under an earlier installation id.
+ ReviewRepository.objects.for_team(self.other_team.id).create(
+ team=self.other_team, installation_id="1000", full_name="example-org/api", selected=True
+ )
+ ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=INSTALLATION, full_name="example-org/docs", flash_for="everyone"
+ )
+ url = self._url(f"repository_overview/?installation_id={INSTALLATION}")
+
+ everything = self.client.get(url)
+
+ assert everything.status_code == 200, everything.json()
+ assert everything.json()["claim_scope"] == "all"
+ entries = {entry["full_name"]: entry for entry in everything.json()["results"]}
+ assert entries["example-org/web"]["owner"] == "this_project"
+ assert entries["example-org/web"]["my_result"] == {"flash": False, "reason": "project_opt_in"}
+ assert entries["example-org/api"]["owner"] == "other_project"
+ assert entries["example-org/api"]["owner_project"] == {"id": self.other_team.id, "name": "Other project"}
+ assert entries["example-org/api"]["my_result"] == {"flash": False, "reason": "not_in_project"}
+ assert entries["example-org/docs"]["exception"]["flash_for"] == "everyone"
+ assert entries["example-org/docs"]["my_result"] == {"flash": True, "reason": "repository_everyone"}
+
+ exceptions = self.client.get(f"{url}&view=exceptions").json()
+ assert [entry["full_name"] for entry in exceptions["results"]] == ["example-org/docs"]
+ page = self.client.get(f"{url}&view=in_project&limit=1").json()
+ assert (page["total"], page["has_more"], page["next_offset"]) == (2, True, 1)
+ searched = self.client.get(f"{url}&search=API").json()
+ assert [entry["full_name"] for entry in searched["results"]] == ["example-org/api"]
+
+ def test_overview_needs_a_connected_installation(self) -> None:
+ res = self.client.get(self._url("repository_overview/?installation_id=9999"))
+
+ assert res.status_code == 400
+
+ def test_settings_of_another_project_are_invisible(self) -> None:
+ other = ReviewRepository.objects.for_team(self.other_team.id).create(
+ team=self.other_team, installation_id=INSTALLATION, full_name="example-org/web", selected=True
+ )
+
+ listed = self.client.get(self._url("repositories/"))
+ removed = self.client.delete(self._url(f"repositories/{other.id}/"))
+
+ assert listed.json() == []
+ assert removed.status_code == 404
+ assert ReviewRepository.objects.for_team(self.other_team.id).filter(id=other.id).exists()
+
+ def test_people_must_be_active_members(self) -> None:
+ outsider = User.objects.create_and_join(Organization.objects.create(name="other"), "[email protected]", None)
+
+ res = self.client.post(
+ self._url("project_settings/people/"), {"user_id": outsider.id, "kind": "listed"}, format="json"
+ )
+
+ assert res.status_code == 400
diff --git a/products/review_hog/backend/tests/test_resolution_activity.py b/products/review_hog/backend/tests/test_resolution_activity.py
index 4d86fc02a4b4..85386bf0ab5f 100644
--- a/products/review_hog/backend/tests/test_resolution_activity.py
+++ b/products/review_hog/backend/tests/test_resolution_activity.py
@@ -16,14 +16,14 @@ from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
-from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfig
+from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact, ReviewSkillConfig, ReviewUserSettings
+from products.review_hog.backend.review_request_rules import ResolutionGate
from products.review_hog.backend.reviewer.artefact_content import ResolutionRunArtefact, ThreadVerdictArtefact
from products.review_hog.backend.reviewer.constants import RESOLUTION_MAX_ATTEMPTS
from products.review_hog.backend.reviewer.lazy_seed import sync_canonical_resolution
from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
-from products.review_hog.backend.reviewer.models.thread_resolution import ThreadResolution
+from products.review_hog.backend.reviewer.models.thread_resolution import CommitHold, ThreadResolution
from products.review_hog.backend.reviewer.persistence import load_thread_verdicts, persist_thread_verdict
-from products.review_hog.backend.reviewer.skill_loader import REVIEW_HOG_RESOLUTION_SKILL_NAME
from products.review_hog.backend.reviewer.tools.github_threads import FixCommitInspection, ReviewThread, ThreadComment
from products.review_hog.backend.temporal.resolution import (
FailResolutionInput,
@@ -31,6 +31,7 @@ from products.review_hog.backend.temporal.resolution import (
ResolveThreadsInput,
_append_run_note,
_append_task_run,
+ _commit_hold,
_deliver_side_effects,
_fail_resolution,
_fold_overlong_reply,
@@ -97,6 +98,19 @@ def _inspection(restricted: list[str] | None = None, *, provenance_ok: bool = Tr
return FixCommitInspection(restricted_paths=restricted or [], provenance_ok=provenance_ok)
+def _patch_open_branch_and_opted_in_owner(test: SimpleTestCase) -> Mock:
+ """The owner gate and the branch read, which the delivery tests take as passed."""
+ test.enterContext(
+ patch(
+ f"{_RESOLUTION}.ResolutionGate.load",
+ return_value=ResolutionGate(owner_user_id=1, owner_opted_in=True, internal_features=True),
+ )
+ )
+ return test.enterContext(
+ patch(f"{_RESOLUTION}.github_api_request", return_value=Mock(json=Mock(return_value={"protected": False})))
+ )
+
+
def _mock_installation() -> Mock:
github = Mock()
github.get_access_token.return_value = "token"
@@ -107,6 +121,53 @@ def _mock_installation() -> Mock:
return github
+class TestBranchProtectionHold(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("unprotected", {"protected": False}, None, None),
+ (
+ "classic_protection",
+ {"protected": True, "protection": {"enabled": True}},
+ None,
+ CommitHold.BRANCH_PROTECTED,
+ ),
+ ("protection_details_missing", {"protected": True}, None, CommitHold.BRANCH_PROTECTED),
+ (
+ "ruleset_signed_commits_only",
+ {"protected": True, "protection": {"enabled": False}},
+ [{"type": "required_signatures"}, {"type": "non_fast_forward"}],
+ None,
+ ),
+ (
+ "ruleset_requires_pull_request",
+ {"protected": True, "protection": {"enabled": False}},
+ [{"type": "required_signatures"}, {"type": "pull_request"}],
+ CommitHold.BRANCH_PROTECTED,
+ ),
+ (
+ "ruleset_unknown_rule_type",
+ {"protected": True, "protection": {"enabled": False}},
+ [{"type": "file_path_restriction"}],
+ CommitHold.BRANCH_PROTECTED,
+ ),
+ ]
+ )
+ def test_holds_only_when_protection_can_refuse_the_push(
+ self, _name: str, branch: dict, rules: list | None, expected: CommitHold | None
+ ) -> None:
+ def github_read(method: str, path: str, *, endpoint: str, **kwargs: object) -> Mock:
+ body = rules if endpoint == "/repos/{owner}/{repo}/rules/branches/{branch}" else branch
+ return Mock(json=Mock(return_value=body))
+
+ input = ResolveThreadsInput(
+ team_id=1, user_id=1, acting_user_id=None, owner="posthog", repo="posthog", pr_number=123
+ )
+ with patch(f"{_RESOLUTION}.github_api_request", side_effect=github_read):
+ hold = _commit_hold(input, _mock_installation(), "feature/x", queue_state=None, queue_state_at_start=None)
+
+ assert hold == expected
+
+
class TestReplyBodyRendering(SimpleTestCase):
@parameterized.expand(
[
@@ -150,6 +211,10 @@ class TestReplyBodyRendering(SimpleTestCase):
class TestResolutionPersistenceAndDelivery(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.branch_read = _patch_open_branch_and_opted_in_owner(self)
+
def _report(self) -> ReviewReport:
# ReviewReport is fail-closed (TeamScopedRootMixin), so creation outside request context
# goes through for_team — the same path the funnel uses.
@@ -324,28 +389,6 @@ class TestResolutionPersistenceAndDelivery(BaseTest):
)
)
- def test_unpinned_acting_user_with_unmapped_author_pins_canonical_criteria(self) -> None:
- # The /resolve landmine: with no acting user pinned and an unmapped author, the RUN user's
- # personal selection must not govern someone else's PR — the canonical bar applies.
- sync_canonical_resolution(self.team)
- LLMSkill.objects.create(
- team=self.team,
- name="review-hog-resolution-run-users-own",
- description="d",
- body="x" * 250,
- version=1,
- is_latest=True,
- created_by=self.user,
- )
- ReviewSkillConfig.objects.for_team(self.team.id).create(
- team_id=self.team.id, user_id=self.user.id, skill_name="review-hog-resolution-run-users-own", enabled=True
- )
-
- prepared = self._prepare_unpinned()
-
- assert isinstance(prepared, _PreparedRun)
- assert prepared.skill_name == REVIEW_HOG_RESOLUTION_SKILL_NAME
-
def test_unpinned_acting_user_maps_the_pr_author(self) -> None:
sync_canonical_resolution(self.team)
author = User.objects.create_and_join(self.organization, "[email protected]", None)
@@ -563,12 +606,14 @@ class TestResolutionPersistenceAndDelivery(BaseTest):
"submitted to the merge queue",
),
("stacked_pull_requests", None, True, "pr_has_stacked_pull_requests", "stacked on this branch"),
+ ("protected_branch", None, False, "pr_branch_protected", "this branch is protected"),
]
)
def test_held_pr_gets_no_turns_and_says_why(
self, _name: str, queue_state: MergeQueueState | None, stacked: bool, reason: str, section_text: str
) -> None:
self._report()
+ self.branch_read.return_value.json.return_value = {"protected": reason == "pr_branch_protected"}
installation = _mock_installation()
installation.get_pull_request_merge_queue_state.return_value = queue_state
installation.has_open_pull_request_with_base.return_value = stacked
@@ -621,6 +666,7 @@ class TestFailedRunActivity(NonAtomicBaseTest):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_user(email="[email protected]", first_name="RH", password="password")
+ _patch_open_branch_and_opted_in_owner(self)
def _input(self) -> ResolveThreadsInput:
return ResolveThreadsInput(
@@ -778,3 +824,53 @@ class TestFailedRunActivity(NonAtomicBaseTest):
assert "Stopped resolving comments at 1/2" in status_comment.call_args.args[2]
assert section_text in status_comment.call_args.args[2]
assert self._report_status() == ReviewReport.Status.IDLE
+
+
+class TestResolutionOwnerGate(BaseTest):
+ @parameterized.expand(
+ [
+ ("owner_opted_in", "octocat", True, True, True),
+ ("owner_did_not_opt_in", "octocat", False, True, False),
+ ("internal_flag_off", "octocat", True, False, False),
+ # The run user's opt-in never writes to a pull request nobody owns.
+ ("no_owner", "ghost", True, True, False),
+ ]
+ )
+ def test_resolution_writes_only_where_the_pr_owner_opted_in(
+ self, _name: str, author_login: str, opted_in: bool, internal: bool, prepared: bool
+ ) -> None:
+ sync_canonical_resolution(self.team)
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "octocat"})
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, preferences={"resolve_comments": opted_in}
+ )
+ thread = ReviewThread(
+ thread_id="PRRT_1",
+ path="f.py",
+ comments=[ThreadComment(id=1, author_login="greptile", author_is_bot=True, body="b")],
+ )
+ metadata = _pr_metadata().model_copy(update={"author": author_login})
+ with (
+ patch("products.review_hog.backend.internal_features.posthog_feature_flag_enabled", return_value=internal),
+ patch(f"{_RESOLUTION}._installation_for", return_value=_mock_installation()),
+ patch(f"{_RESOLUTION}._fetch_pr_metadata", return_value=metadata),
+ patch(f"{_RESOLUTION}.fetch_unresolved_threads", return_value=[thread]),
+ patch(f"{_RESOLUTION}.add_eyes_reaction"),
+ patch(f"{_RESOLUTION}.github_api_request", return_value=Mock(json=Mock(return_value={"protected": False}))),
+ ):
+ result = _prepare_run(
+ ResolveThreadsInput(
+ team_id=self.team.id,
+ user_id=self.user.id,
+ acting_user_id=None,
+ owner="posthog",
+ repo="posthog",
+ pr_number=123,
+ )
+ )
+
+ if prepared:
+ assert isinstance(result, _PreparedRun)
+ else:
+ assert isinstance(result, ResolutionRunResult)
+ assert result.skipped_reason == "resolution_not_opted_in"
diff --git a/products/review_hog/backend/tests/test_review_completed_tracking.py b/products/review_hog/backend/tests/test_review_completed_tracking.py
index 56164e33e6f6..59ebcf794fd6 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -4,8 +4,6 @@ from datetime import UTC, datetime, timedelta
from posthog.test.base import BaseTest
from unittest.mock import patch
-from django.test import override_settings
-
from parameterized import parameterized
from products.review_hog.backend.models import ReviewReport
@@ -46,6 +44,8 @@ from products.review_hog.backend.temporal.activities import (
from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_LABEL
from products.signals.backend.enums import ReportPriority
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
+
_PR_URL = "https://github.com/o/r/pull/7"
@@ -411,7 +411,7 @@ class TestTrackReviewCompleted(BaseTest):
# the report's first turn. The started event is the third event of a turn: a dashboard
# compares it against completed to see a lift, so it must carry the same labels.
signal_report_id = str(uuid.uuid4())
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
report_id = self._review_report(
signal_report_id=signal_report_id, trigger_source=TRIGGER_INBOX, signal_priority=ReportPriority.P3
)
diff --git a/products/review_hog/backend/tests/test_settings_api.py b/products/review_hog/backend/tests/test_settings_api.py
index 11c05fc56982..e9f9a6a579d4 100644
--- a/products/review_hog/backend/tests/test_settings_api.py
+++ b/products/review_hog/backend/tests/test_settings_api.py
@@ -1,17 +1,19 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.test import SimpleTestCase, override_settings
+from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.models import Team, User
from products.review_hog.backend.api.settings import ReviewUserSettingsSerializer
-from products.review_hog.backend.models import ReviewUserSettings
+from products.review_hog.backend.models import ReviewProjectSettings, ReviewUserSettings
from products.skills.backend.models.skills import LLMSkill
from products.stamphog.backend.facade.testing import seed_repo_config
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
+
class TestReviewUserSettingsAPI(APIBaseTest):
# The serializer resolves stamphog_connected off the stamphog product DB on every response.
@@ -22,60 +24,65 @@ class TestReviewUserSettingsAPI(APIBaseTest):
self.enterContext(patch("posthoganalytics.feature_enabled", return_value=True))
self.url = f"/api/projects/{self.team.id}/review_hog/settings/"
- def test_get_creates_the_row_with_defaults(self) -> None:
- # First read auto-creates the singleton with the model defaults, so the UI never special-cases
- # a missing row (and the label trigger keeps its opt-out default of on).
+ def test_get_returns_defaults_without_creating_a_row(self) -> None:
res = self.client.get(self.url)
assert res.status_code == 200
assert res.json() == {
+ "default_review_mode": "follow",
+ "resolve_comments": False,
+ "urgency_threshold": "consider",
+ "celebrate_clean_reviews": True,
"review_inbox_prs": False,
"stamphog_review_inbox_prs": False, # opt-in: a real approval must never be a default
- "review_labeled_prs": True,
- "resolve_comments": True,
- "celebrate_clean_reviews": True,
- "review_authored_prs": False,
- "flash_reasoning_effort": "medium",
- "urgency_threshold": "consider",
- "can_trigger_reviews": True,
- "show_internal_features": False,
+ "sources": {
+ "default_review_mode": "default",
+ "resolve_comments": "default",
+ "urgency_threshold": "default",
+ "celebrate_clean_reviews": "default",
+ "review_inbox_prs": "default",
+ "stamphog_review_inbox_prs": "default",
+ },
+ "project_defaults": {"urgency_threshold": "consider", "celebrate_clean_reviews": True},
"stamphog_connected": False, # no synced+enabled repo config in this project
}
- assert ReviewUserSettings.objects.for_team(self.team.id).filter(user_id=self.user.id).count() == 1
+ assert not ReviewUserSettings.objects.for_team(self.team.id).filter(user_id=self.user.id).exists()
+
+ def test_patch_stores_only_values_that_differ_from_the_inherited_ones(self) -> None:
+ ReviewProjectSettings.objects.for_team(self.team.id).create(
+ team=self.team, preferences={"urgency_threshold": "should_fix"}
+ )
- def test_patch_updates_only_the_provided_fields(self) -> None:
- # resolve_comments rides along: it's the UI toggle's only write path, so a serializer that
- # stops accepting it (e.g. marked read-only) would silently no-op the switch.
res = self.client.patch(
self.url,
{
"urgency_threshold": "must_fix",
"stamphog_review_inbox_prs": True,
- "resolve_comments": False,
- "review_authored_prs": True,
- "flash_reasoning_effort": "xhigh",
- "celebrate_clean_reviews": False,
+ "resolve_comments": True,
+ "default_review_mode": "flash",
+ "celebrate_clean_reviews": True,
},
format="json",
)
assert res.status_code == 200
assert res.json()["urgency_threshold"] == "must_fix"
+ assert res.json()["sources"]["urgency_threshold"] == "user"
+ assert res.json()["sources"]["celebrate_clean_reviews"] == "default"
row = ReviewUserSettings.objects.for_team(self.team.id).get(user_id=self.user.id)
- assert row.urgency_threshold == "must_fix"
- assert row.stamphog_review_inbox_prs is True
- assert row.resolve_comments is False
- assert row.review_authored_prs is True
- assert row.flash_reasoning_effort == "xhigh"
- assert row.celebrate_clean_reviews is False
- assert row.review_labeled_prs is True # untouched field keeps its default
+ assert row.preferences == {
+ "urgency_threshold": "must_fix",
+ "stamphog_review_inbox_prs": True,
+ "resolve_comments": True,
+ "default_review_mode": "flash",
+ }
- disabled = self.client.patch(self.url, {"review_authored_prs": False}, format="json")
+ # Picking the project value clears the user's own value, so later project changes reach them.
+ follows_project = self.client.patch(self.url, {"urgency_threshold": "should_fix"}, format="json")
- assert disabled.status_code == 200
- disabled_row = ReviewUserSettings.objects.for_team(self.team.id).get(user_id=self.user.id)
- assert disabled_row.review_authored_prs is False
- assert disabled_row.flash_reasoning_effort == "xhigh"
+ assert follows_project.json()["sources"]["urgency_threshold"] == "project"
+ row.refresh_from_db()
+ assert "urgency_threshold" not in row.preferences
@parameterized.expand(
[
@@ -99,11 +106,10 @@ class TestReviewUserSettingsAPI(APIBaseTest):
connected_by_user_id=connected_by_user_id,
)
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
res = self.client.get(self.url)
assert res.status_code == 200
- assert res.json()["show_internal_features"] is True
assert res.json()["stamphog_connected"] is expected
def test_patch_rejects_an_unknown_threshold(self) -> None:
@@ -111,21 +117,16 @@ class TestReviewUserSettingsAPI(APIBaseTest):
assert res.status_code == 400
def test_settings_are_per_user(self) -> None:
- # One user's opt-out must not leak into a teammate's row — the gate reads the PR author's.
+ # One user's choice must not leak into a teammate's preferences — the gates read the PR author's.
other = User.objects.create_and_join(self.organization, "[email protected]", None)
- self.client.patch(
- self.url,
- {"review_labeled_prs": False, "review_authored_prs": True, "flash_reasoning_effort": "xhigh"},
- format="json",
- )
+ self.client.patch(self.url, {"default_review_mode": "flash", "resolve_comments": True}, format="json")
self.client.force_login(other)
res = self.client.get(self.url)
assert res.status_code == 200
- assert res.json()["review_labeled_prs"] is True
- assert res.json()["review_authored_prs"] is False
- assert res.json()["flash_reasoning_effort"] == "medium"
+ assert res.json()["default_review_mode"] == "follow"
+ assert res.json()["resolve_comments"] is False
def test_get_seeds_the_authoring_skill_idempotently(self) -> None:
# The settings GET is the tab's always-called endpoint, so it must make the authoring guide
@@ -169,13 +170,18 @@ class TestReviewUserSettingsAPI(APIBaseTest):
assert second.status_code == 200
row = ReviewUserSettings.objects.for_team(self.team.id).get(user_id=self.user.id)
assert row.team_id == self.team.id
- assert row.urgency_threshold == "must_fix"
+ assert row.preferences == {"urgency_threshold": "must_fix"}
class TestReviewUserSettingsValidation(SimpleTestCase):
- @parameterized.expand(["low", "high"])
- def test_flash_effort_rejects_values_outside_its_supported_choices(self, effort: str) -> None:
- serializer = ReviewUserSettingsSerializer(data={"flash_reasoning_effort": effort}, partial=True)
+ @parameterized.expand(
+ [
+ ("full_mode_is_not_offered", {"default_review_mode": "full"}, "default_review_mode"),
+ ("unknown_threshold", {"urgency_threshold": "everything"}, "urgency_threshold"),
+ ]
+ )
+ def test_rejects_values_outside_the_schema(self, _name: str, data: dict, field: str) -> None:
+ serializer = ReviewUserSettingsSerializer(data=data, partial=True)
assert not serializer.is_valid()
- assert "flash_reasoning_effort" in serializer.errors
+ assert field in serializer.errors
diff --git a/products/review_hog/backend/tests/test_settings_toggle_commands.py b/products/review_hog/backend/tests/test_settings_toggle_commands.py
deleted file mode 100644
index cc415688b7ba..000000000000
--- a/products/review_hog/backend/tests/test_settings_toggle_commands.py
+++ /dev/null
@@ -1,172 +0,0 @@
-from io import StringIO
-
-from posthog.test.base import BaseTest
-
-from django.core.management import call_command
-from django.core.management.base import CommandError
-
-from parameterized import parameterized
-
-from posthog.models import Organization, User
-
-from products.review_hog.backend.models import ReviewUserSettings
-from products.review_hog.backend.settings_toggles import ToggleField, toggle_default
-
-REVIEWHOG: ToggleField = "review_inbox_prs"
-STAMPHOG: ToggleField = "stamphog_review_inbox_prs"
-RESOLVE: ToggleField = "resolve_comments"
-AUTHORED: ToggleField = "review_authored_prs"
-OTHER_FIELD: dict[ToggleField, ToggleField] = {
- REVIEWHOG: STAMPHOG,
- STAMPHOG: REVIEWHOG,
- RESOLVE: REVIEWHOG,
- AUTHORED: REVIEWHOG,
-}
-COMMANDS = [
- ("enable_inbox_reviews", REVIEWHOG, True),
- ("disable_inbox_reviews", REVIEWHOG, False),
- ("enable_stamphog_inbox_reviews", STAMPHOG, True),
- ("disable_stamphog_inbox_reviews", STAMPHOG, False),
- ("enable_comment_resolution", RESOLVE, True),
- ("disable_comment_resolution", RESOLVE, False),
- ("enable_authored_pr_reviews", AUTHORED, True),
- ("disable_authored_pr_reviews", AUTHORED, False),
-]
-
-
-class TestSettingsToggleCommands(BaseTest):
- def _row(self, user: User) -> ReviewUserSettings | None:
- return ReviewUserSettings.objects.for_team(self.team.id).filter(user_id=user.id).first()
-
- def _member(self, email: str, **fields: object) -> User:
- user = User.objects.create_and_join(self.organization, email, None)
- if fields:
- ReviewUserSettings.objects.for_team(self.team.id).create(team_id=self.team.id, user_id=user.id, **fields)
- return user
-
- @parameterized.expand(COMMANDS)
- def test_whole_team_sets_only_its_toggle_for_active_org_members(
- self, command: str, field: ToggleField, enabled: bool
- ) -> None:
- member_without_row = self._member("[email protected]")
- member_opposite = self._member(
- **{field: not enabled, OTHER_FIELD[field]: not enabled},
- urgency_threshold=ReviewUserSettings.UrgencyThreshold.MUST_FIX,
- flash_reasoning_effort=ReviewUserSettings.FlashReasoningEffort.XHIGH,
- )
- inactive_member = self._member("[email protected]", **{field: not enabled})
- inactive_member.is_active = False
- inactive_member.save()
- other_org = Organization.objects.create(name="other org")
- outsider = User.objects.create_and_join(other_org, "[email protected]", None)
-
- call_command(command, team_id=self.team.id)
-
- opposite_row = self._row(member_opposite)
- assert opposite_row is not None
- assert getattr(opposite_row, field) is enabled
- assert getattr(opposite_row, OTHER_FIELD[field]) is not enabled
- assert opposite_row.urgency_threshold == ReviewUserSettings.UrgencyThreshold.MUST_FIX
- assert opposite_row.flash_reasoning_effort == "xhigh"
- if enabled is not toggle_default(field):
- for member in (self.user, member_without_row):
- row = self._row(member)
- assert row is not None
- assert getattr(row, field) is enabled
- assert getattr(row, OTHER_FIELD[field]) is toggle_default(OTHER_FIELD[field])
- else:
- # A missing row already reads as the default, so no rows get created.
- assert self._row(self.user) is None
- assert self._row(member_without_row) is None
- inactive_row = self._row(inactive_member)
- assert inactive_row is not None
- assert getattr(inactive_row, field) is not enabled
- assert self._row(outsider) is None
-
- @parameterized.expand(
- [
- ("enable_inbox_reviews", REVIEWHOG, True),
- ("disable_inbox_reviews", REVIEWHOG, False),
- ("enable_authored_pr_reviews", AUTHORED, True),
- ("disable_authored_pr_reviews", AUTHORED, False),
- ]
- )
- def test_user_ids_change_only_those_users(self, command: str, field: ToggleField, enabled: bool) -> None:
- target = self._member("[email protected]", **{field: not enabled})
- untouched = self._member("[email protected]", **{field: not enabled})
-
- call_command(command, team_id=self.team.id, user_ids=[target.id])
-
- target_row, untouched_row = self._row(target), self._row(untouched)
- assert target_row is not None and getattr(target_row, field) is enabled
- assert untouched_row is not None and getattr(untouched_row, field) is not enabled
- assert self._row(self.user) is None
-
- def test_user_ids_outside_the_org_fail_before_writing(self) -> None:
- member = self._member("[email protected]", review_inbox_prs=False)
- other_org = Organization.objects.create(name="other org")
- outsider = User.objects.create_and_join(other_org, "[email protected]", None)
-
- with self.assertRaises(CommandError) as ctx:
- call_command("enable_inbox_reviews", team_id=self.team.id, user_ids=[member.id, outsider.id])
-
- assert str(outsider.id) in str(ctx.exception)
- member_row = self._row(member)
- assert member_row is not None and member_row.review_inbox_prs is False
- assert self._row(outsider) is None
-
- @parameterized.expand([("enable_inbox_reviews", True), ("disable_inbox_reviews", False)])
- def test_dry_run_writes_nothing(self, command: str, enabled: bool) -> None:
- member = self._member("[email protected]", review_inbox_prs=not enabled)
-
- call_command(command, team_id=self.team.id, dry_run=True)
-
- row = self._row(member)
- assert row is not None and row.review_inbox_prs is not enabled
- assert self._row(self.user) is None
-
- @parameterized.expand(["medium", "xhigh"])
- def test_authored_opt_in_sets_effort_for_new_and_already_enabled_users(self, effort: str) -> None:
- opposite_effort = "xhigh" if effort == "medium" else "medium"
- opted_in = self._member(
- "[email protected]", review_authored_prs=True, flash_reasoning_effort=opposite_effort
- )
- untouched = self._member(
- "[email protected]", review_authored_prs=True, flash_reasoning_effort=opposite_effort
- )
-
- call_command(
- "enable_authored_pr_reviews", team_id=self.team.id, user_ids=[self.user.id, opted_in.id], effort=effort
- )
-
- for user in (self.user, opted_in):
- row = self._row(user)
- assert row is not None and row.review_authored_prs is True
- assert row.flash_reasoning_effort == effort
- untouched_row = self._row(untouched)
- assert untouched_row is not None and untouched_row.flash_reasoning_effort == opposite_effort
-
- def test_authored_effort_dry_run_includes_already_enabled_users_without_writing(self) -> None:
- opted_in = self._member("[email protected]", review_authored_prs=True)
- output = StringIO()
-
- call_command(
- "enable_authored_pr_reviews",
- team_id=self.team.id,
- user_ids=[opted_in.id],
- effort="xhigh",
- dry_run=True,
- stdout=output,
- )
-
- row = self._row(opted_in)
- assert row is not None and row.flash_reasoning_effort == "medium"
- assert f"Would change user id(s): {opted_in.id}" in output.getvalue()
- assert "flash_reasoning_effort: xhigh" in output.getvalue()
-
- def test_authored_invalid_effort_fails_before_writing(self) -> None:
- with self.assertRaises(CommandError):
- call_command("enable_authored_pr_reviews", team_id=self.team.id, effort="high")
-
- assert self._row(self.user) is None
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index 2f1eff43d673..03b7fdf825fe 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -127,7 +127,7 @@ async def _run_full_review_pr_workflow(
publish: bool,
already_published: bool = False,
acting_user_id: int | None = 3,
- review_labeled_prs: bool = True,
+ owner_user_id: int | None = 3,
review_inbox_prs: bool = False,
input_acting_user_id: int | None = None,
trigger_source: str = "manual",
@@ -159,8 +159,8 @@ async def _run_full_review_pr_workflow(
) -> dict:
# Runs the real ReviewPRWorkflow with activity stand-ins, recording what fanned out + published.
# already_published / empty_diff drive the early-exit gates; acting_user_id None means the author
- # isn't a PostHog user, so the workflow skips the review. review_labeled_prs / review_inbox_prs
- # are the trigger-aware opt-outs read per trigger_source; input_acting_user_id is the explicit
+ # isn't a PostHog user, so the workflow skips the review. review_inbox_prs is the inbox
+ # trigger's opt-in; input_acting_user_id is the explicit
# override on the workflow input (CLI / inbox). meta_pr_number is the publish destination fetch
# resolved (None = branch target with no PR → store-only); fail_dedup forces a mid-run failure so
# the failed-turn receipt path can be observed.
@@ -249,13 +249,13 @@ async def _run_full_review_pr_workflow(
# dataclass defaults.
return ResolveActingUserResult(
acting_user_id=acting_user_id,
- review_labeled_prs=review_labeled_prs,
urgency_threshold="must_fix",
review_inbox_prs=review_inbox_prs,
resolved_from="override",
resolve_comments=resolve_comments_setting,
flash_reasoning_effort=flash_reasoning_effort,
review_authored_prs=review_authored_prs,
+ owner_user_id=owner_user_id,
)
@activity.defn(name="sync_review_skills_activity")
@@ -659,15 +659,15 @@ async def test_review_pr_workflow_does_not_remove_label_for_other_triggers():
@parameterized.expand(
[
# (name, publish, resolve_comments_setting, input_resolve_comments, expect_dispatch)
- # The default posture: a publishing review chains resolution when the acting user's
- # setting is on (reviewing includes resolving)...
+ # The default posture: a publishing review chains resolution when the PR owner opted in
+ # (reviewing includes resolving)...
("setting_on_chains_after_publish", True, True, None, True),
# ...their opt-out is the off switch...
("setting_off_skips", True, False, None, False),
# ...the UI's "review without resolving" pins a single run off despite the setting...
("ui_review_only_override_pins_off", True, True, False, False),
- # ...an explicit True forces the chain (the input override outranks everything)...
- ("explicit_true_forces", False, False, True, True),
+ # ...no input turns resolution on for a PR whose owner did not opt in...
+ ("explicit_true_cannot_override_the_owner", True, False, True, False),
# ...and an unpublished (eval/CLI) review must never write to the PR off the setting alone.
("unpublished_run_never_chains_by_setting", False, True, None, False),
]
@@ -682,11 +682,12 @@ async def test_review_pr_workflow_chains_resolution_per_setting_and_override(
publish=publish,
resolve_comments_setting=resolve_comments_setting,
input_resolve_comments=input_resolve_comments,
+ owner_user_id=9,
)
if expect_dispatch:
- # The dispatch carries the RESOLVED acting user (their criteria skill applies) and the
- # original trigger source, keyed to the PR the fetch resolved.
- assert recorded["resolve_dispatches"] == [(7, 3, "manual")]
+ # The dispatch carries the PR OWNER, not the acting user: it writes to the owner's branch
+ # under their criteria. The original trigger source is kept, keyed to the PR the fetch resolved.
+ assert recorded["resolve_dispatches"] == [(7, 9, "manual")]
else:
assert recorded["resolve_dispatches"] == []
@@ -707,6 +708,8 @@ async def test_review_pr_workflow_flash_turn_threads_its_mode_and_never_chains_r
)
assert recorded["publish"] == [7]
assert recorded["resolve_dispatches"] == []
+ # Flash publishes every kept finding, whatever the acting user's threshold says.
+ assert {threshold for _, threshold in recorded["thresholds"]} == {"consider"}
assert recorded["modes"] == {
stage: {"flash"} for stage in ("fetch", "select", "review", "validate", "publish", "status", "track")
}
@@ -857,24 +860,20 @@ async def test_review_pr_workflow_skips_when_author_maps_to_no_user():
@parameterized.expand(
[
- # (name, trigger_source, review_labeled_prs, review_inbox_prs, input_acting_user_id, expect_ran)
- # The label trigger's per-author opt-out gates only the cloud path (no explicit override)...
- ("label_opt_out_skips", "label", False, True, None, False),
- # ...an explicit override (CLI re-run of a labeled PR) always runs...
- ("label_override_ignores_opt_out", "label", False, True, 3, True),
- # ...and the inbox toggle has no say over the label path.
- ("label_ignores_inbox_toggle", "label", True, False, None, True),
+ # (name, trigger_source, review_inbox_prs, input_acting_user_id, expect_ran)
+ # A label always runs, and the inbox toggle has no say over it.
+ ("label_ignores_inbox_toggle", "label", False, None, True),
# The inbox trigger honors only review_inbox_prs (default off = the budget gate); the
# receiver always sets the acting override, so the override must NOT bypass this gate.
- ("inbox_default_off_skips", "inbox", True, False, 3, False),
- ("inbox_opt_in_runs_despite_label_opt_out", "inbox", False, True, 3, True),
- # Manual (CLI/eval) stays ungated regardless of either toggle.
- ("manual_ungated", "manual", False, False, 3, True),
+ ("inbox_default_off_skips", "inbox", False, 3, False),
+ ("inbox_opt_in_runs", "inbox", True, 3, True),
+ # Manual (CLI/eval) stays ungated.
+ ("manual_ungated", "manual", False, 3, True),
]
)
@pytest.mark.asyncio
async def test_review_pr_workflow_trigger_aware_gates(
- _name, trigger_source, review_labeled_prs, review_inbox_prs, input_acting_user_id, expect_ran
+ _name, trigger_source, review_inbox_prs, input_acting_user_id, expect_ran
):
# The trigger-source gate matrix: a miswired gate either reviews PRs for opted-out users (burning
# sandbox cost) or silently disables a production trigger. Skipped turns must also append no
@@ -882,7 +881,6 @@ async def test_review_pr_workflow_trigger_aware_gates(
recorded = await _run_full_review_pr_workflow(
publish=False,
trigger_source=trigger_source,
- review_labeled_prs=review_labeled_prs,
review_inbox_prs=review_inbox_prs,
input_acting_user_id=input_acting_user_id,
signal_report_id="sr-1",
diff --git a/products/review_hog/backend/tests/test_trigger_api.py b/products/review_hog/backend/tests/test_trigger_api.py
deleted file mode 100644
index c693471b3d97..000000000000
--- a/products/review_hog/backend/tests/test_trigger_api.py
+++ /dev/null
@@ -1,286 +0,0 @@
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from django.test import override_settings
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.models.integration import Integration
-from posthog.models.organization import OrganizationMembership
-from posthog.models.team import Team
-from posthog.models.user import User
-
-from products.review_hog.backend.models import ReviewReport
-
-TRIGGER_URL = "/api/review_hog/trigger/"
-RESOLVE_URL = "/api/review_hog/resolve/"
-_START = "products.review_hog.backend.api.trigger.start_review_pr_workflow"
-_START_RESOLUTION = "products.review_hog.backend.api.trigger.start_resolution_workflow"
-_BUSY = "products.review_hog.backend.api.trigger.workflow_running"
-
-
-@override_settings(REVIEWHOG_TRIGGER_TOKEN="secret-token")
-class TestReviewHogTriggerApi(APIBaseTest):
- def setUp(self):
- super().setUp()
- # Let Postgres auto-assign IDs to avoid collisions with the sequence.
- self.trigger_team = Team.objects.create(organization=self.organization, name="reviewhog trigger")
- self.run_user = User.objects.create(email="[email protected]")
- OrganizationMembership.objects.create(organization=self.organization, user=self.run_user)
- # Apply dynamic IDs via settings overrides
- self._settings_ctx = self.settings(
- REVIEWHOG_TEAM_IDS=[self.trigger_team.id],
- REVIEWHOG_RUN_USER_ID=self.run_user.id,
- )
- self._settings_ctx.enable()
- # The busy-guard probes Temporal on every trigger; tests must never open real connections.
- busy_patcher = patch(_BUSY, return_value=False)
- self.mock_busy = busy_patcher.start()
- self.addCleanup(busy_patcher.stop)
-
- def tearDown(self):
- self._settings_ctx.disable()
- super().tearDown()
-
- @patch(_START, return_value="wf-1")
- def test_valid_trigger_starts_workflow_and_publishes_by_default(self, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 123},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- self.assertEqual(resp.json(), {"workflow_id": "wf-1", "status": "started"})
- mock_start.assert_called_once_with(
- pr_url="https://github.com/PostHog/posthog/pull/123",
- team_id=self.trigger_team.id,
- user_id=self.run_user.id,
- publish=True,
- trigger_source="label",
- )
-
- @patch(_START, return_value="wf-1")
- def test_publish_flag_passes_through(self, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 5, "publish": False},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- self.assertEqual(mock_start.call_args.kwargs["publish"], False)
-
- @parameterized.expand(
- [
- ("wrong_token", "Bearer nope"),
- ("missing_header", ""),
- ("raw_wrong", "nope"),
- ]
- )
- @patch(_START, return_value="wf-1")
- def test_invalid_token_rejected(self, _name, auth_header, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION=auth_header,
- )
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
- mock_start.assert_not_called()
-
- @parameterized.expand(
- [
- ("other_org", "evil/repo"),
- ("allowlisted_name_other_org", "evil/ai-gateway"),
- ("allowlisted_prefix", "PostHog/ai-gateway-fork"),
- ]
- )
- @patch(_START, return_value="wf-1")
- def test_disallowed_repo_rejected(self, _name, repo, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": repo, "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
- mock_start.assert_not_called()
-
- @parameterized.expand(
- [
- ("posthog_lowercase", "posthog/posthog"),
- ("ai_gateway", "PostHog/ai-gateway"),
- ("ai_gateway_lowercase", "posthog/ai-gateway"),
- ]
- )
- @patch(_START, return_value="wf-1")
- def test_allowlisted_repo_accepted(self, _name, repo, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": repo, "pr_number": 7},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- mock_start.assert_called_once()
- self.assertEqual(mock_start.call_args.kwargs["pr_url"], f"https://github.com/{repo}/pull/7")
-
- @override_settings(REVIEWHOG_TEAM_IDS=[])
- @patch(_START, return_value="wf-1")
- def test_unconfigured_team_returns_503(self, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
- mock_start.assert_not_called()
-
- @override_settings(DEBUG=False, TEST=False, REVIEWHOG_TRIGGER_TOKEN=None)
- @patch(_START, return_value="wf-1")
- def test_unconfigured_token_fails_closed_in_production(self, mock_start):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer anything",
- )
- self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)
- mock_start.assert_not_called()
-
- @override_settings(REVIEWHOG_RUN_USER_ID=None)
- @patch(_START, return_value="wf-1")
- def test_run_user_falls_back_to_integration_creator(self, mock_start):
- Integration.objects.create(
- team=self.team,
- kind="github",
- integration_id="inst-1",
- config={},
- sensitive_config={},
- created_by=self.user,
- )
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- self.assertEqual(mock_start.call_args.kwargs["user_id"], self.user.id)
-
- @parameterized.expand(
- [
- ("membership_removed", False),
- ("still_member_but_disabled", True),
- ]
- )
- @override_settings(REVIEWHOG_RUN_USER_ID=None)
- @patch(_START, return_value="wf-1")
- def test_inactive_integration_creator_falls_back_to_active_org_member(self, _name, keep_membership, mock_start):
- departed = User.objects.create(email="[email protected]", is_active=False)
- if keep_membership:
- OrganizationMembership.objects.create(organization=self.organization, user=departed)
- Integration.objects.create(
- team=self.team,
- kind="github",
- integration_id="inst-1",
- config={},
- sensitive_config={},
- created_by=departed,
- )
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- self.assertEqual(mock_start.call_args.kwargs["user_id"], self.user.id)
-
- @patch(_START, return_value="wf-1")
- def test_trigger_refused_while_resolution_is_running(self, mock_start):
- # The busy-guard: a review started while the PR's resolve-pr workflow runs would race the
- # resolution session's pushes and re-review threads it is mid-way through settling. Temporal
- # can't dedupe across the two workflow ids, so a dropped (or wrong-id) probe here means
- # double runs — the check must hit resolve-pr's exact deterministic id and refuse.
- self.mock_busy.return_value = True
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 123},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT)
- self.assertIn("Still resolving comments", resp.json()["error"])
- self.mock_busy.assert_called_once_with(f"resolve-pr:{self.trigger_team.id}:posthog/posthog:123")
- mock_start.assert_not_called()
-
- @patch(_START, return_value="wf-1")
- def test_label_during_a_running_cheaper_review_lifts_the_tier_and_says_so(self, mock_start):
- # A same-id start joins the in-flight turn, so the label's trigger source never reaches the
- # fetch upsert: without this lift the cheap turn publishes, the full review the label asked
- # for never runs, and the Action reports success.
- report = ReviewReport.objects.for_team(self.trigger_team.id).create(
- team=self.trigger_team,
- repository="posthog/posthog",
- pr_number=123,
- pr_url="https://github.com/PostHog/posthog/pull/123",
- head_branch="fix",
- base_branch="master",
- review_tier="agent_p3_p4",
- review_reasoning_effort="low",
- )
- self.mock_busy.side_effect = lambda workflow_id: workflow_id.startswith("review-pr:")
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 123},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
- self.assertEqual(resp.json(), {"workflow_id": "wf-1", "status": "joined_running_review"})
- mock_start.assert_called_once()
- report.refresh_from_db()
- self.assertEqual((report.review_tier, report.review_reasoning_effort), ("human", "xhigh"))
-
- @patch(_START_RESOLUTION, return_value="wf-r-1")
- def test_resolve_refused_while_review_is_running(self, mock_start_resolution):
- # The other direction: a standalone resolution during a live review would settle threads
- # the finishing review is about to chain its own resolution for.
- self.mock_busy.return_value = True
- resp = self.client.post(
- RESOLVE_URL,
- {"repo": "PostHog/posthog", "pr_number": 123},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT)
- self.assertIn("review is already running", resp.json()["error"])
- self.mock_busy.assert_called_once_with(f"review-pr:{self.trigger_team.id}:posthog/posthog:123")
- mock_start_resolution.assert_not_called()
-
- @parameterized.expand(
- [
- ("deactivated", True),
- ("active_but_not_org_member", False),
- ]
- )
- @patch(_START, return_value="wf-1")
- def test_unauthorized_configured_run_user_rejected(self, _name, deactivate, mock_start):
- if deactivate:
- User.objects.filter(id=self.run_user.id).update(is_active=False)
- else:
- OrganizationMembership.objects.filter(user_id=self.run_user.id).delete()
- resp = self.client.post(
- TRIGGER_URL,
- {"repo": "PostHog/posthog", "pr_number": 1},
- format="json",
- HTTP_AUTHORIZATION="Bearer secret-token",
- )
- self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
- mock_start.assert_not_called()
diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.py
index 61e38012661f..a778d400906c 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -3,10 +3,9 @@ from uuid import uuid4
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.test import override_settings
-
from parameterized import parameterized
from rest_framework import status
+from social_django.models import UserSocialAuth
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.models import Team, User
@@ -26,6 +25,7 @@ _START_RESOLUTION = "products.review_hog.backend.requested_reviews.start_resolut
_ACCESS = "products.review_hog.backend.requested_reviews.GitHubIntegration.first_for_team_repository"
_META = "products.review_hog.backend.requested_reviews.fetch_pr_metadata"
_BUSY = "products.review_hog.backend.requested_reviews.workflow_running"
+_INTERNAL_FLAG = "products.review_hog.backend.internal_features.posthog_feature_flag_enabled"
def _pr_meta(**overrides: object) -> MagicMock:
@@ -33,6 +33,8 @@ def _pr_meta(**overrides: object) -> MagicMock:
meta.is_fork = overrides.get("is_fork", False)
meta.state = overrides.get("state", "open")
meta.head_sha = overrides.get("head_sha", "abc123")
+ meta.author = overrides.get("author", "octocat")
+ meta.head_branch = overrides.get("head_branch", "feature")
return meta
@@ -62,8 +64,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# perspectives instead of the person who asked for it.
member = User.objects.create_and_join(self.organization, "[email protected]", None)
self.client.force_login(member)
- with override_settings(REVIEWHOG_TEAM_IDS=[]):
- resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123/files")
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123/files")
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
self.assertEqual(resp.json(), {"workflow_id": "wf-ui-1", "status": "started"})
@@ -75,7 +76,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
publish=True,
acting_user_id=member.id,
trigger_source="ui",
- # None = the requester's resolve_comments setting decides whether resolution chains.
+ # None = the PR owner's resolve_comments setting decides whether resolution chains.
resolve_comments=None,
review_mode="full",
requested_head_sha="abc123",
@@ -99,7 +100,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# the workflow as an explicit False — passing None would fall back to the user's setting, and
# a flash review that resolved would write code. Flash must also carry its mode, or the
# workflow runs the full pipeline under a flash label.
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
@@ -107,23 +108,41 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
self.assertEqual(mock_start.call_args.kwargs["review_mode"], expected_review_mode)
mock_start_resolution.assert_not_called()
- @patch(_META, return_value=_pr_meta())
+ @patch(_META, return_value=_pr_meta(author="teammate"))
@patch(_ACCESS, return_value=object())
+ @patch(_START_RESOLUTION, return_value="wf-resolve-1")
@patch(_START, return_value="wf-comment-1")
- def test_comment_facade_never_resolves_comments(self, mock_start, _mock_access, _mock_meta):
- # A comment run acts with the commenter's settings, so an unpinned None would let the
- # commenter's resolve_comments setting write commits to someone else's branch.
- outcome = request_pr_review_from_comment(
- team_id=self.team.id,
- requester_id=self.user.id,
- repository="PostHog/posthog.com",
- pr_number=123,
- run_mode="review",
+ def test_comment_facade_follows_the_pr_owner_rule(self, mock_start, mock_start_resolution, *_mocks):
+ # The commenter opted in, the PR owner did not: the commenter's opt-in must not write commits
+ # to the owner's branch, and the review leaves resolution to the owner's setting (None).
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, preferences={"resolve_comments": True}
)
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(user=teammate, provider="github", uid="gh-2", extra_data={"login": "teammate"})
+
+ with patch(_INTERNAL_FLAG, return_value=True):
+ review = request_pr_review_from_comment(
+ team_id=self.team.id,
+ requester_id=self.user.id,
+ repository="PostHog/posthog.com",
+ pr_number=123,
+ run_mode="review",
+ )
+ resolve_only = request_pr_review_from_comment(
+ team_id=self.team.id,
+ requester_id=self.user.id,
+ repository="PostHog/posthog.com",
+ pr_number=123,
+ run_mode="resolve_only",
+ )
- self.assertEqual(outcome.workflow_id, "wf-comment-1")
+ self.assertEqual(review.workflow_id, "wf-comment-1")
self.assertEqual(mock_start.call_args.kwargs["trigger_source"], "comment")
- self.assertIs(mock_start.call_args.kwargs["resolve_comments"], False)
+ self.assertIsNone(mock_start.call_args.kwargs["resolve_comments"])
+ self.assertEqual(resolve_only.status, PRReviewRequestStatus.REFUSED)
+ self.assertEqual(resolve_only.refusal, "resolution_not_opted_in")
+ mock_start_resolution.assert_not_called()
@patch(_START, return_value="wf-comment-1")
def test_comment_facade_gates_on_the_commented_environment_not_its_parent(self, mock_start):
@@ -143,18 +162,86 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
self.assertEqual(outcome.status, PRReviewRequestStatus.NOT_ALLOWED)
mock_start.assert_not_called()
+ @parameterized.expand([("flash",), ("resolve_only",)])
@patch(_META, return_value=_pr_meta())
@patch(_ACCESS, return_value=object())
+ @patch(_START_RESOLUTION)
@patch(_START, return_value="wf-ui-1")
- def test_flash_mode_is_refused_outside_the_internal_project(
- self, mock_start: MagicMock, _mock_access: MagicMock, _mock_meta: MagicMock
+ def test_internal_run_modes_are_refused_without_the_internal_flag(
+ self, run_mode: str, mock_start: MagicMock, mock_start_resolution: MagicMock, *_mocks: MagicMock
) -> None:
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id + 1, self.team.id]):
- resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode="flash")
+ with patch(_INTERNAL_FLAG, return_value=False):
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.content)
+ self.assertEqual(resp.json()["code"], "internal_feature")
+ mock_start.assert_not_called()
+ mock_start_resolution.assert_not_called()
+
+ @patch(_META, return_value=_pr_meta())
+ @patch(_ACCESS, return_value=object())
+ @patch(_START, return_value="wf-ui-1")
+ def test_flash_is_refused_once_a_full_review_is_published(
+ self, mock_start: MagicMock, _mock_access: MagicMock, _mock_meta: MagicMock
+ ) -> None:
+ ReviewReport.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ repository="posthog/posthog.com",
+ pr_number=123,
+ head_branch="feature",
+ base_branch="master",
+ published_heads_by_mode={"full": "older-sha"},
+ )
+
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode="flash")
+
+ self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT, resp.content)
+ self.assertEqual(resp.json()["code"], "flash_after_full")
mock_start.assert_not_called()
+ @parameterized.expand(
+ [
+ ("owner_opted_in", "octocat", True, False, True),
+ # One person's opt-in never writes to a teammate's branch.
+ ("only_the_requester_opted_in", "teammate", False, True, False),
+ ("pr_without_owner", "ghost", False, True, False),
+ ]
+ )
+ @patch(_ACCESS, return_value=object())
+ @patch(_START_RESOLUTION, return_value="wf-resolve-1")
+ def test_resolve_only_needs_the_pr_owners_opt_in(
+ self,
+ _name: str,
+ author: str,
+ owner_opted_in: bool,
+ requester_opted_in: bool,
+ starts: bool,
+ mock_start_resolution: MagicMock,
+ _mock_access: MagicMock,
+ ) -> None:
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)
+ UserSocialAuth.objects.create(user=teammate, provider="github", uid="gh-2", extra_data={"login": "teammate"})
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "octocat"})
+ owner = teammate if author == "teammate" else self.user
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=owner.id, preferences={"resolve_comments": owner_opted_in}
+ )
+ if owner != self.user:
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, preferences={"resolve_comments": requester_opted_in}
+ )
+
+ with patch(_META, return_value=_pr_meta(author=author)):
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode="resolve_only")
+
+ if starts:
+ self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
+ mock_start_resolution.assert_called_once()
+ else:
+ self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT, resp.content)
+ self.assertEqual(resp.json()["code"], "resolution_not_opted_in")
+ mock_start_resolution.assert_not_called()
+
@patch(_META, return_value=_pr_meta(head_sha="abc123"))
@patch(_ACCESS, return_value=object())
@patch(_START_RESOLUTION, return_value="wf-resolve-1")
@@ -162,6 +249,10 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
def test_resolve_only_mode_runs_even_on_an_already_reviewed_head(
self, mock_start, mock_start_resolution, _mock_access, _mock_meta
):
+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="gh-1", extra_data={"login": "octocat"})
+ ReviewUserSettings.objects.for_team(self.team.id).create(
+ team_id=self.team.id, user_id=self.user.id, preferences={"resolve_comments": True}
+ )
# Settling threads on a reviewed head is resolve-only's whole point: the already_reviewed
# early-return must not apply, and no review workflow may start. A published-at-head report
# is exactly the state a "Review" click would refuse.
@@ -174,7 +265,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
base_branch="master",
published_head_sha="abc123",
)
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123/files", run_mode="resolve_only")
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
@@ -214,7 +305,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# ids, so a dropped (or wrong-id) probe means a review racing the resolution session's
# pushes — the incident class this refusal exists for. Blocked, not queued.
self.mock_busy.return_value = True
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT, resp.content)
@@ -259,7 +350,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
review_initial_permission_mode=original_arm.initial_permission_mode,
)
self.mock_busy.side_effect = lambda workflow_id: workflow_id.startswith("review-pr:")
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123", run_mode=run_mode)
self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
@@ -278,7 +369,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# Resolve-only shares the sync UX checks: a closed PR must be rejected here, in the UI,
# not die async in the resolution workflow's prepare step where nothing surfaces.
with (
- override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]),
+ patch(_INTERNAL_FLAG, return_value=True),
patch(_META, return_value=_pr_meta(state="closed")),
):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/7", run_mode="resolve_only")
@@ -330,7 +421,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
("get", "resolution/", {}),
("patch", "resolution/review-hog-resolution-criteria/", {"active": True}),
]
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
for method, path, data in endpoints:
with self.subTest(method=method, path=path, data=data):
response = getattr(self.client, method)(
@@ -347,7 +438,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
@patch(_START)
def test_non_pr_github_url_rejected(self, mock_start):
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog/issues/1")
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
@@ -356,7 +447,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
@patch(_ACCESS, return_value=None)
@patch(_START)
def test_inaccessible_repository_rejected_without_starting_a_workflow(self, mock_start, _mock_access):
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/other-org/private-repo/pull/5")
self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
@@ -378,7 +469,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
side_effect = meta_or_error if isinstance(meta_or_error, Exception) else None
return_value = None if side_effect else meta_or_error
with (
- override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]),
+ patch(_INTERNAL_FLAG, return_value=True),
patch(_META, side_effect=side_effect, return_value=return_value),
):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/7")
@@ -422,7 +513,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
published_head_sha=published_head_sha,
published_heads_by_mode=published_modes,
)
- with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ with patch(_INTERNAL_FLAG, return_value=True):
resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123")
self.assertEqual(resp.status_code, expected_status, resp.content)
@@ -440,7 +531,7 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
# Both GitHub calls must map through github_rate_limited_response — an unwrapped call
# surfaces a 500 to the person clicking Review, exactly during retry-prone windows.
with (
- override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]),
+ patch(_INTERNAL_FLAG, return_value=True),
patch(_ACCESS, return_value=object()),
patch(rate_limited_call, side_effect=GitHubRateLimitError("rate limited", retry_after=30)),
):
@@ -451,24 +542,14 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
self.assertEqual(resp["Retry-After"], "30")
mock_start.assert_not_called()
- @parameterized.expand(
- [
- ("automation_project", True),
- ("manual_project", False),
- ]
- )
- @patch("products.review_hog.backend.api.settings.has_reviewable_repo_config", return_value=False)
- def test_settings_enable_manual_reviews_independently_of_automation(
- self, _name: str, is_automation_project: bool, mock_stamphog: MagicMock
+ @parameterized.expand([("internal_project", True), ("other_project", False)])
+ @patch("products.review_hog.backend.api.settings.has_reviewable_repo_config", return_value=True)
+ def test_settings_query_stamphog_only_in_internal_projects(
+ self, _name: str, internal: bool, mock_stamphog: MagicMock
) -> None:
- legacy_teams = [self.team.id] if is_automation_project else [self.team.id + 1, self.team.id]
- with override_settings(REVIEWHOG_TEAM_IDS=legacy_teams):
+ with patch(_INTERNAL_FLAG, return_value=internal):
resp = self.client.get(f"/api/projects/{self.team.id}/review_hog/settings/")
self.assertEqual(resp.status_code, status.HTTP_200_OK)
- self.assertIs(resp.json()["can_trigger_reviews"], True)
- self.assertEqual(resp.json()["show_internal_features"], is_automation_project)
- if is_automation_project:
- mock_stamphog.assert_called_once_with(self.team.id)
- else:
- mock_stamphog.assert_not_called()
+ self.assertEqual(resp.json()["stamphog_connected"], internal)
+ self.assertEqual(mock_stamphog.called, internal)
diff --git a/products/review_hog/backend/webhook_consumers.py b/products/review_hog/backend/webhook_consumers.py
index 7a98b5fe3b16..3277ad97545f 100644
--- a/products/review_hog/backend/webhook_consumers.py
+++ b/products/review_hog/backend/webhook_consumers.py
@@ -1,20 +1,21 @@
from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery
-def _enqueue_authored_review(delivery: WebhookDelivery) -> None:
+def _accept_pull_request_event(delivery: WebhookDelivery) -> None:
from products.review_hog.backend.facade.github import ( # noqa: PLC0415 - keeps product models off the registry import path
- enqueue_authored_pr_review,
+ accept_pull_request_event,
)
- enqueue_authored_pr_review(delivery.payload)
+ accept_pull_request_event(delivery.payload)
WEBHOOK_CONSUMERS = (
WebhookConsumer(
+ # The name is the dedup cache key, so it keeps the name of its first job, automatic reviews.
name="review_hog_authored_prs",
provider="github",
app="posthog",
event_types=frozenset({"pull_request"}),
- handler=_enqueue_authored_review,
+ handler=_accept_pull_request_event,
),
)
diff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsx
index 63ad601f3492..9f6b47386b65 100644
--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx
@@ -18,16 +18,21 @@ import { expect } from 'storybook/test'
import { CodeReviewScene } from './CodeReviewScene'
const defaultSettings: ReviewUserSettingsApi = {
+ default_review_mode: 'follow',
+ resolve_comments: false,
+ urgency_threshold: 'consider',
+ celebrate_clean_reviews: true,
review_inbox_prs: false,
stamphog_review_inbox_prs: false,
- review_labeled_prs: true,
- resolve_comments: true,
- celebrate_clean_reviews: true,
- review_authored_prs: false,
- flash_reasoning_effort: 'medium',
- urgency_threshold: 'consider',
- can_trigger_reviews: true,
- show_internal_features: false,
+ sources: {
+ default_review_mode: 'default',
+ resolve_comments: 'default',
+ urgency_threshold: 'default',
+ celebrate_clean_reviews: 'default',
+ review_inbox_prs: 'default',
+ stamphog_review_inbox_prs: 'default',
+ },
+ project_defaults: { urgency_threshold: 'consider', celebrate_clean_reviews: true },
stamphog_connected: false,
}
@@ -47,8 +52,6 @@ const meta: Meta<typeof CodeReviewScene> = {
(Story, context): JSX.Element => {
let settings: ReviewUserSettingsApi = {
...defaultSettings,
- show_internal_features: context.parameters.showInternalFeatures ?? false,
- stamphog_connected: context.parameters.showInternalFeatures ?? false,
...context.parameters.savedSettings,
}
return mswDecorator({
@@ -91,7 +94,6 @@ export const Default: Story = {
await expect(await canvas.findByText('Review a pull request')).toBeVisible()
await expect(canvas.queryByLabelText('Review all your Inbox PRs')).not.toBeInTheDocument()
await expect(canvas.queryByLabelText('Let Stamphog review your Inbox PRs')).not.toBeInTheDocument()
- await expect(canvas.queryByLabelText('Review all your PRs with the reviewhog label')).not.toBeInTheDocument()
await expect(canvas.queryByLabelText('Review all your PRs in Flash mode')).not.toBeInTheDocument()
await expect(canvas.getByLabelText('Resolve comments on your PRs')).toBeVisible()
await expect(canvas.getByLabelText('Celebrate clean reviews')).toBeVisible()
@@ -99,12 +101,14 @@ export const Default: Story = {
}
export const InternalFeatures: Story = {
- parameters: { showInternalFeatures: true },
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.REVIEW_HOG, FEATURE_FLAGS.REVIEW_HOG_INTERNAL],
+ savedSettings: { stamphog_connected: true },
+ },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
await expect(await canvas.findByLabelText('Review all your Inbox PRs')).toBeVisible()
await expect(canvas.getByLabelText('Let Stamphog review your Inbox PRs')).toBeVisible()
- await expect(canvas.getByLabelText('Review all your PRs with the reviewhog label')).toBeVisible()
await expect(canvas.getByLabelText('Review all your PRs in Flash mode')).toBeVisible()
},
}
@@ -119,7 +123,6 @@ export const SavedInboxOptIns: Story = {
await expect(inboxSwitch).toBeEnabled()
await expect(stamphogSwitch).toBeChecked()
await expect(stamphogSwitch).toBeEnabled()
- await expect(canvas.queryByLabelText('Review all your PRs with the reviewhog label')).not.toBeInTheDocument()
await expect(canvas.queryByLabelText('Review all your PRs in Flash mode')).not.toBeInTheDocument()
},
}
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index 74051813dbc6..c2339a8bac49 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -33,7 +33,6 @@ import {
} from '@posthog/lemon-ui'
import { Logomark } from 'lib/brand'
-import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { NotFound } from 'lib/components/NotFound'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -55,7 +54,7 @@ import type {
ReviewPerspectiveStatItemApi,
ReviewRecentReviewApi,
ReviewResolutionStatusApi,
- ReviewUserSettingsUrgencyThresholdEnumApi,
+ UrgencyThresholdEnumApi,
} from 'products/review_hog/frontend/generated/api.schemas'
import {
ReviewHogReviewsListScope,
@@ -133,7 +132,7 @@ const PIPELINE_PHASES: { name: string; hint: string; steps: { number: string; ti
},
]
-const URGENCY_STOPS: { key: ReviewUserSettingsUrgencyThresholdEnumApi; label: string; description: string }[] = [
+const URGENCY_STOPS: { key: UrgencyThresholdEnumApi; label: string; description: string }[] = [
{
key: 'consider',
label: 'All issues',
@@ -684,16 +683,14 @@ function RecentReviewsSection(): JSX.Element | null {
* "Review a pull request": paste any PR URL the project's GitHub App installation can access and
* start a publishing review, acting as the requesting user. A review resolves the PR's comment
* threads afterwards when the user's resolve_comments setting is on; the split button's side
- * actions are the per-run variants (review without resolving / resolve only / flash). Hidden unless the
- * backend says this project can trigger reviews.
+ * actions are the per-run variants (review without resolving / resolve only / flash).
*/
-function TriggerReviewSection(): JSX.Element | null {
- const { settings, triggerPrUrl, triggeringReview, triggerUrlResolving } = useValues(reviewHogSettingsLogic)
+function TriggerReviewSection(): JSX.Element {
+ const { triggerPrUrl, triggeringReview, triggerUrlResolving } = useValues(reviewHogSettingsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const showInternalFeatures = !!featureFlags[FEATURE_FLAGS.REVIEW_HOG_INTERNAL]
const { setTriggerPrUrl, submitTriggerReview } = useActions(reviewHogSettingsLogic)
- if (!settings?.can_trigger_reviews) {
- return null
- }
const noUrlReason = !triggerPrUrl.trim() ? 'Paste a pull request URL first' : undefined
// Mirrors the server-side busy-guard for PRs visible in the list; pasted URLs outside it still
// get the same refusal from the trigger endpoint.
@@ -748,7 +745,7 @@ function TriggerReviewSection(): JSX.Element | null {
>
Only resolve existing comments
</LemonButton>
- {settings.show_internal_features && (
+ {showInternalFeatures && (
<LemonButton
fullWidth
onClick={() =>
@@ -1150,6 +1147,8 @@ function ReviewDetailDrawer(): JSX.Element {
function TriggersSection(): JSX.Element {
const { settings, settingsLoading } = useValues(reviewHogSettingsLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const showInternalFeatures = !!featureFlags[FEATURE_FLAGS.REVIEW_HOG_INTERNAL]
const { updateSettings } = useActions(reviewHogSettingsLogic)
const switchDisabledReason = settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined
@@ -1157,14 +1156,13 @@ function TriggersSection(): JSX.Element {
return (
<section className="flex flex-col gap-4 border-t border-primary pt-8">
<SectionHeader icon={<IconFilter />} title="What gets reviewed">
- {settings?.show_internal_features
+ {showInternalFeatures
? 'Choose which pull requests PostHog Review picks up automatically, and whether reviews also resolve the comment threads on them.'
: 'Choose whether reviews also resolve comment threads and how clean reviews appear on your pull requests.'}
</SectionHeader>
<LemonCard hoverEffect={false} className="divide-y divide-primary p-0">
- {/* Inbox reviews start in any project with a saved opt-in, so a switch that is on stays visible
- and the user can turn it off. */}
- {(settings?.show_internal_features || settings?.review_inbox_prs) && (
+ {/* A switch that is on stays visible, so the user can clear a saved opt-in. */}
+ {(showInternalFeatures || settings?.review_inbox_prs) && (
<div className="flex items-center gap-4 p-4">
<div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary *:h-auto *:w-5">
<Logomark />
@@ -1184,7 +1182,7 @@ function TriggersSection(): JSX.Element {
/>
</div>
)}
- {(settings?.show_internal_features || settings?.stamphog_review_inbox_prs) && (
+ {(showInternalFeatures || settings?.stamphog_review_inbox_prs) && (
<div className="flex items-center gap-4 p-4">
<div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">
<IconStamphog className="size-5" />
@@ -1210,37 +1208,6 @@ function TriggersSection(): JSX.Element {
/>
</div>
)}
- {settings?.show_internal_features && (
- <div className="flex items-center gap-4 p-4">
- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">
- <IconGithub className="size-5" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="text-sm font-semibold">
- Review all your PRs with the{' '}
- <CopyToClipboardInline
- explicitValue="reviewhog"
- description="label"
- iconSize="xsmall"
- className="rounded border border-warning bg-warning-highlight px-1.5 py-0.5 font-mono text-xs text-warning"
- >
- reviewhog
- </CopyToClipboardInline>{' '}
- label
- </div>
- <div className="text-xs text-secondary">
- Add the reviewhog label to a pull request you author in a connected repository and
- PostHog Review reviews it.
- </div>
- </div>
- <LemonSwitch
- aria-label="Review all your PRs with the reviewhog label"
- checked={settings?.review_labeled_prs ?? true}
- onChange={(checked) => updateSettings({ review_labeled_prs: checked })}
- disabledReason={switchDisabledReason}
- />
- </div>
- )}
<div className="flex items-center gap-4 p-4">
<div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">
<IconChat className="size-5" />
@@ -1254,7 +1221,7 @@ function TriggersSection(): JSX.Element {
</div>
<LemonSwitch
aria-label="Resolve comments on your PRs"
- checked={settings?.resolve_comments ?? true}
+ checked={settings?.resolve_comments ?? false}
onChange={(checked) => updateSettings({ resolve_comments: checked })}
disabledReason={switchDisabledReason}
/>
@@ -1279,7 +1246,7 @@ function TriggersSection(): JSX.Element {
/>
</div>
</LemonCard>
- {settings?.show_internal_features && (
+ {showInternalFeatures && (
<>
<div className="mt-2">
<h4 className="mb-1 text-sm font-semibold">ReviewHog Flash - Experimental</h4>
@@ -1293,14 +1260,16 @@ function TriggersSection(): JSX.Element {
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold">Review all your PRs in Flash mode</div>
<div className="text-xs text-secondary">
- Automatically review PRs you author in PostHog/posthog, including drafts and new
- commits. Starts with future PR activity.
+ Automatically review PRs you author in the repositories this project reviews,
+ including drafts and new commits. Starts with future PR activity.
</div>
</div>
<LemonSwitch
aria-label="Review all your PRs in Flash mode"
- checked={settings?.review_authored_prs ?? false}
- onChange={(checked) => updateSettings({ review_authored_prs: checked })}
+ checked={settings?.default_review_mode === 'flash'}
+ onChange={(checked) =>
+ updateSettings({ default_review_mode: checked ? 'flash' : 'off' })
+ }
disabledReason={switchDisabledReason}
loading={settingsLoading}
/>
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 1e1a0976acd9..e981378c1fdc 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -23,6 +23,134 @@ export interface PatchedReviewBlindSpotsConfigSelectApi {
active?: boolean
}
+/**
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories
+ */
+export type ReviewInstallationClaimScopeEnumApi =
+ (typeof ReviewInstallationClaimScopeEnumApi)[keyof typeof ReviewInstallationClaimScopeEnumApi]
+
+export const ReviewInstallationClaimScopeEnumApi = {
+ All: 'all',
+ Selected: 'selected',
+} as const
+
+/**
+ * * `engineering` - Engineering
+ * * `data` - Data
+ * * `product` - Product Management
+ * * `founder` - Founder
+ * * `leadership` - Leadership
+ * * `marketing` - Marketing
+ * * `sales` - Sales / Success
+ * * `student` - Student
+ * * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Student: 'student',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+export interface ReviewInstallationClaimApi {
+ /** Id of the claim. */
+ readonly id: string
+ /** The GitHub App installation id. */
+ readonly installation_id: string
+ /** 'all' (every repository no other project selected, including future ones) or 'selected'.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ readonly scope: ReviewInstallationClaimScopeEnumApi
+ /** The GitHub account (organization or user) of the installation. */
+ readonly account_name: string
+ /** Who made the claim. */
+ readonly created_by: UserBasicApi | null
+ /** When the claim was made. */
+ readonly created_at: string
+}
+
+export interface ReviewInstallationClaimCreateApi {
+ /**
+ * The GitHub App installation id.
+ * @maxLength 64
+ */
+ installation_id: string
+ /** 'all' reviews every repository of the installation that no other project selected. At most one project per installation can choose it. 'selected' reviews only selected repositories.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope: ReviewInstallationClaimScopeEnumApi
+}
+
+export interface ReviewProjectRefApi {
+ /**
+ * Id of the other project. Null when it belongs to another organization.
+ * @nullable
+ */
+ id: number | null
+ /**
+ * Name of the other project. Null when it belongs to another organization.
+ * @nullable
+ */
+ name: string | null
+}
+
+export interface ReviewHogSettingsErrorApi {
+ /** Why the request was rejected. */
+ error: string
+ /** The project that already holds the repository or the installation, if any. */
+ conflicting_project: ReviewProjectRefApi | null
+}
+
+export interface PatchedReviewInstallationClaimUpdateApi {
+ /** 'all' or 'selected'. Switching to 'selected' removes the exceptions of the repositories that leave the project.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope?: ReviewInstallationClaimScopeEnumApi
+}
+
export interface ReviewPerspectiveConfigApi {
/** Name of the `review-hog-perspective-*` skill this row toggles (the perspective's identity). */
skill_name: string
@@ -39,6 +167,424 @@ export interface PatchedReviewPerspectiveConfigUpdateApi {
enabled?: boolean
}
+/**
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only
+ */
+export type AutomaticFlashForEnumApi = (typeof AutomaticFlashForEnumApi)[keyof typeof AutomaticFlashForEnumApi]
+
+export const AutomaticFlashForEnumApi = {
+ Everyone: 'everyone',
+ Listed: 'listed',
+ Off: 'off',
+} as const
+
+/**
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash
+ */
+export type ReviewProjectSettingsBotPullRequestsEnumApi =
+ (typeof ReviewProjectSettingsBotPullRequestsEnumApi)[keyof typeof ReviewProjectSettingsBotPullRequestsEnumApi]
+
+export const ReviewProjectSettingsBotPullRequestsEnumApi = {
+ Skip: 'skip',
+ Run: 'run',
+} as const
+
+/**
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix
+ */
+export type UrgencyThresholdEnumApi = (typeof UrgencyThresholdEnumApi)[keyof typeof UrgencyThresholdEnumApi]
+
+export const UrgencyThresholdEnumApi = {
+ Consider: 'consider',
+ ShouldFix: 'should_fix',
+ MustFix: 'must_fix',
+} as const
+
+/**
+ * * `listed` - Listed
+ * * `excepted` - Excepted
+ */
+export type ReviewRepositoryPersonKindEnumApi =
+ (typeof ReviewRepositoryPersonKindEnumApi)[keyof typeof ReviewRepositoryPersonKindEnumApi]
+
+export const ReviewRepositoryPersonKindEnumApi = {
+ Listed: 'listed',
+ Excepted: 'excepted',
+} as const
+
+export interface ReviewRepositoryPersonApi {
+ /** Id of this list entry. Use it to remove the person. */
+ readonly id: string
+ /** The project member on the list. */
+ readonly user: UserBasicApi
+ /** Which list: 'listed' (gets Flash when the rule reviews only listed people) or 'excepted' (skipped when the rule reviews everyone).
+ *
+ * * `listed` - Listed
+ * * `excepted` - Excepted */
+ readonly kind: ReviewRepositoryPersonKindEnumApi
+}
+
+export interface ReviewInstallationApi {
+ /** The GitHub App installation id. */
+ installation_id: string
+ /** The GitHub account (organization or user) of the installation. */
+ account_name: string
+ /** Who connected the installation to this project. Automatic Flash reviews of bot pull requests run as this user. */
+ connected_by: UserBasicApi | null
+ /**
+ * Id of this project's claim. Null when the project reviews nothing there.
+ * @nullable
+ */
+ claim_id: string | null
+ /** Which repositories this project reviews: 'all' (every repository no other project selected, including future ones), 'selected' (only the selected ones), or null (none).
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope: ReviewInstallationClaimScopeEnumApi | null
+ /** Another project that takes all repositories of the installation, if any. */
+ all_taken_by_project: ReviewProjectRefApi | null
+}
+
+export interface ReviewProjectSettingsApi {
+ /** Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the default). A repository exception or a person's own choice wins over it.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnumApi
+ /** Pull requests from bots, and from authors who are not project members, in every repository this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the person who connected GitHub, with default settings and no changes to the pull request).
+ *
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash */
+ bot_prs?: ReviewProjectSettingsBotPullRequestsEnumApi
+ /** Project default for the minimum priority a Full review publishes: 'consider' (all, the built-in default), 'should_fix', or 'must_fix'. A person's own value wins.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnumApi
+ /** Project default for the image in a Full review that finds nothing to raise. On by default. A person's own value wins. */
+ celebrate_clean_reviews?: boolean
+ /** The people on the project rule's two lists. Only the list that matches flash_for has an effect. */
+ readonly people: readonly ReviewRepositoryPersonApi[]
+ /** Every GitHub installation connected to this project, and which of its repositories this project reviews. */
+ readonly installations: readonly ReviewInstallationApi[]
+ /** Whether the requesting user is a project admin and can change these settings. */
+ readonly can_edit: boolean
+}
+
+export interface PatchedReviewProjectSettingsApi {
+ /** Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the default). A repository exception or a person's own choice wins over it.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnumApi
+ /** Pull requests from bots, and from authors who are not project members, in every repository this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the person who connected GitHub, with default settings and no changes to the pull request).
+ *
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash */
+ bot_prs?: ReviewProjectSettingsBotPullRequestsEnumApi
+ /** Project default for the minimum priority a Full review publishes: 'consider' (all, the built-in default), 'should_fix', or 'must_fix'. A person's own value wins.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnumApi
+ /** Project default for the image in a Full review that finds nothing to raise. On by default. A person's own value wins. */
+ celebrate_clean_reviews?: boolean
+ /** The people on the project rule's two lists. Only the list that matches flash_for has an effect. */
+ readonly people?: readonly ReviewRepositoryPersonApi[]
+ /** Every GitHub installation connected to this project, and which of its repositories this project reviews. */
+ readonly installations?: readonly ReviewInstallationApi[]
+ /** Whether the requesting user is a project admin and can change these settings. */
+ readonly can_edit?: boolean
+}
+
+export interface ReviewRepositoryPersonRequestApi {
+ /** Id of the project member to add. Must be an active member. */
+ user_id: number
+ /** Which list to add the person to: 'listed' or 'excepted'.
+ *
+ * * `listed` - Listed
+ * * `excepted` - Excepted */
+ kind: ReviewRepositoryPersonKindEnumApi
+}
+
+export interface ReviewRepositoryApi {
+ /** Id of the repository entry. */
+ readonly id: string
+ /** The GitHub App installation that sees it. */
+ readonly installation_id: string
+ /**
+ * GitHub's id of the repository. Null until it is first seen.
+ * @nullable
+ */
+ readonly github_repo_id: number | null
+ /** GitHub repository in 'owner/name' form. */
+ readonly full_name: string
+ /** Whether this project selected the repository. A selected repository belongs to this project even when another project takes all repositories of the installation. */
+ readonly selected: boolean
+ /** The repository exception: 'everyone', 'listed', or 'off' (opt-in only). Null when the repository follows the project rule.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ readonly flash_for: AutomaticFlashForEnumApi | null
+ /** The people on the exception's two lists. Only the list that matches flash_for has an effect. */
+ readonly people: readonly ReviewRepositoryPersonApi[]
+ /** Who added the repository. */
+ readonly created_by: UserBasicApi | null
+ /** When the repository was added. */
+ readonly created_at: string
+}
+
+export interface ReviewRepositoryWriteApi {
+ /**
+ * The GitHub App installation that sees the repository, from the overview.
+ * @maxLength 64
+ */
+ installation_id: string
+ /**
+ * GitHub repository in 'owner/name' form, spelled as GitHub returns it.
+ * @maxLength 200
+ */
+ full_name: string
+ /**
+ * GitHub's id of the repository, from the overview. Keeps renames.
+ * @minimum 1
+ */
+ github_repo_id?: number
+ /** True includes the repository into this project, also when another project takes all repositories of the installation. False removes it; with an 'only selected' claim its exception goes too. */
+ selected?: boolean
+ /** The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository follows the project rule again. Omit it to keep the current value.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnumApi | null
+}
+
+export interface ReviewRepositoryWriteResponseApi {
+ /** The repository entry after the write. Null when nothing is left to store, so the entry was deleted and the repository follows the project rule or left the project. */
+ repository: ReviewRepositoryApi | null
+ /** The project that took all repositories of the installation, when this write took the repository from it. */
+ taken_from_project: ReviewProjectRefApi | null
+}
+
+/**
+ * * `flash` - Flash
+ * * `off` - Off
+ */
+export type ReviewUserRepositoryChoiceModeEnumApi =
+ (typeof ReviewUserRepositoryChoiceModeEnumApi)[keyof typeof ReviewUserRepositoryChoiceModeEnumApi]
+
+export const ReviewUserRepositoryChoiceModeEnumApi = {
+ Flash: 'flash',
+ Off: 'off',
+} as const
+
+export interface ReviewRepositoryChoiceApi {
+ /** Id of the choice. Use it to clear the choice. */
+ readonly id: string
+ /** The GitHub App installation. */
+ readonly installation_id: string
+ /**
+ * GitHub's repository id.
+ * @nullable
+ */
+ readonly github_repo_id: number | null
+ /** GitHub repository in 'owner/name' form. */
+ readonly full_name: string
+ /** 'flash' or 'off' for the user's own pull requests in this repository.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ readonly mode: ReviewUserRepositoryChoiceModeEnumApi
+}
+
+export interface ReviewRepositoryChoiceWriteApi {
+ /**
+ * The GitHub App installation.
+ * @maxLength 64
+ */
+ installation_id: string
+ /**
+ * GitHub repository in 'owner/name' form.
+ * @maxLength 200
+ */
+ full_name: string
+ /**
+ * GitHub's repository id.
+ * @minimum 1
+ */
+ github_repo_id?: number
+ /** The requesting user's own automatic review for their pull requests in this repository: 'flash' or 'off'. A value equal to what the user inherits clears the choice instead.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ mode: ReviewUserRepositoryChoiceModeEnumApi
+}
+
+/**
+ * * `own_repository_choice` - Own choice for this repository
+ * * `own_default` - Own default
+ * * `repository_everyone` - The repository exception reviews everyone
+ * * `repository_excepted` - Excepted by the repository exception
+ * * `repository_listed` - Listed by the repository exception
+ * * `repository_not_listed` - Not listed by the repository exception
+ * * `repository_opt_in` - The repository exception reviews only people who opt in
+ * * `project_everyone` - The project reviews everyone
+ * * `project_excepted` - Excepted by the project
+ * * `project_listed` - Listed by the project
+ * * `project_not_listed` - Not listed by the project
+ * * `project_opt_in` - The project reviews only people who opt in
+ * * `bot_reviewed` - The project reviews bot pull requests
+ * * `bot_skipped` - The project does not review bot pull requests
+ * * `not_in_project` - This project does not review the repository
+ */
+export type AutomaticReviewReasonEnumApi =
+ (typeof AutomaticReviewReasonEnumApi)[keyof typeof AutomaticReviewReasonEnumApi]
+
+export const AutomaticReviewReasonEnumApi = {
+ OwnRepositoryChoice: 'own_repository_choice',
+ OwnDefault: 'own_default',
+ RepositoryEveryone: 'repository_everyone',
+ RepositoryExcepted: 'repository_excepted',
+ RepositoryListed: 'repository_listed',
+ RepositoryNotListed: 'repository_not_listed',
+ RepositoryOptIn: 'repository_opt_in',
+ ProjectEveryone: 'project_everyone',
+ ProjectExcepted: 'project_excepted',
+ ProjectListed: 'project_listed',
+ ProjectNotListed: 'project_not_listed',
+ ProjectOptIn: 'project_opt_in',
+ BotReviewed: 'bot_reviewed',
+ BotSkipped: 'bot_skipped',
+ NotInProject: 'not_in_project',
+} as const
+
+export interface AutomaticReviewDecisionApi {
+ /** Whether the requesting user's own pull requests get automatic Flash reviews in this repository. */
+ flash: boolean
+ /** Which rule decided: the user's own choice ('own_repository_choice', 'own_default'), the repository exception ('repository_*'), the project rule ('project_*'), or 'not_in_project' when this project does not review the repository.
+ *
+ * * `own_repository_choice` - Own choice for this repository
+ * * `own_default` - Own default
+ * * `repository_everyone` - The repository exception reviews everyone
+ * * `repository_excepted` - Excepted by the repository exception
+ * * `repository_listed` - Listed by the repository exception
+ * * `repository_not_listed` - Not listed by the repository exception
+ * * `repository_opt_in` - The repository exception reviews only people who opt in
+ * * `project_everyone` - The project reviews everyone
+ * * `project_excepted` - Excepted by the project
+ * * `project_listed` - Listed by the project
+ * * `project_not_listed` - Not listed by the project
+ * * `project_opt_in` - The project reviews only people who opt in
+ * * `bot_reviewed` - The project reviews bot pull requests
+ * * `bot_skipped` - The project does not review bot pull requests
+ * * `not_in_project` - This project does not review the repository */
+ reason: AutomaticReviewReasonEnumApi
+}
+
+export interface ReviewRepositoryChoiceWriteResponseApi {
+ /** The stored choice. Null when the value equals the inherited one. */
+ choice: ReviewRepositoryChoiceApi | null
+ /** What the requesting user's own pull requests get in this repository after the write. */
+ my_result: AutomaticReviewDecisionApi
+}
+
+/**
+ * * `this_project` - This project
+ * * `other_project` - Another project
+ * * `none` - No project
+ */
+export type RepositoryOwnerKindEnumApi = (typeof RepositoryOwnerKindEnumApi)[keyof typeof RepositoryOwnerKindEnumApi]
+
+export const RepositoryOwnerKindEnumApi = {
+ ThisProject: 'this_project',
+ OtherProject: 'other_project',
+ None: 'none',
+} as const
+
+export interface ReviewRepositoryExceptionApi {
+ /** The exception's rule: 'everyone', 'listed', or 'off'.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for: AutomaticFlashForEnumApi
+ /** The people on the exception's two lists. */
+ people: ReviewRepositoryPersonApi[]
+}
+
+export interface ReviewRepositoryOverviewEntryApi {
+ /** GitHub repository in 'owner/name' form. */
+ full_name: string
+ /**
+ * GitHub's repository id.
+ * @nullable
+ */
+ github_repo_id: number | null
+ /** Which project reviews the repository: 'this_project', 'other_project', or 'none'.
+ *
+ * * `this_project` - This project
+ * * `other_project` - Another project
+ * * `none` - No project */
+ owner: RepositoryOwnerKindEnumApi
+ /** The other project that reviews the repository, when owner is 'other_project'. */
+ owner_project: ReviewProjectRefApi | null
+ /** Whether this project reviews the repository. */
+ in_project: boolean
+ /** Whether this project selected the repository explicitly. */
+ selected: boolean
+ /**
+ * Id of this project's repository entry, for the people list endpoints.
+ * @nullable
+ */
+ repository_id: string | null
+ /** This project's repository exception. Null when the repository follows the project. */
+ exception: ReviewRepositoryExceptionApi | null
+ /** The requesting user's own choice for this repository: 'flash', 'off', or null.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ my_choice: ReviewUserRepositoryChoiceModeEnumApi | null
+ /**
+ * Id of that choice, to clear it.
+ * @nullable
+ */
+ my_choice_id: string | null
+ /** What the requesting user's own pull requests get here, and the rule that decided it. */
+ my_result: AutomaticReviewDecisionApi
+}
+
+export interface ReviewRepositoryOverviewApi {
+ /** The listed GitHub App installation. */
+ installation_id: string
+ /** This project's claim on the installation: 'all', 'selected', or null.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ claim_scope: ReviewInstallationClaimScopeEnumApi | null
+ /** One page of repositories. */
+ results: ReviewRepositoryOverviewEntryApi[]
+ /** Repositories that match the search and the view. */
+ total: number
+ /** Whether more entries follow this page. */
+ has_more: boolean
+ /**
+ * Offset of the next page, or null.
+ * @nullable
+ */
+ next_offset: number | null
+}
+
export interface ReviewResolutionConfigApi {
/** Name of the `review-hog-resolution-*` skill this row represents (the criteria's identity). */
skill_name: string
@@ -479,10 +1025,10 @@ export interface ReviewPerspectiveStatsApi {
}
/**
- * * `review` - review
- * * `review_only` - review_only
- * * `resolve_only` - resolve_only
- * * `flash` - flash
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Flash
*/
export type ReviewTriggerRequestRunModeEnumApi =
(typeof ReviewTriggerRequestRunModeEnumApi)[keyof typeof ReviewTriggerRequestRunModeEnumApi]
@@ -497,12 +1043,12 @@ export const ReviewTriggerRequestRunModeEnumApi = {
export interface ReviewTriggerRequestApi {
/** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */
pr_url: string
- /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.
+ /** What to run on the pull request. 'review' (default) reviews it and, when the pull request owner's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads, which needs the owner's opt-in; 'flash' uses a lower-cost model for the review passes and validation, never resolves comments, and is refused once the PR has a published Full review. The owner is the PR's author, or the Inbox reviewer of a pull request the PostHog app opened.
*
- * * `review` - review
- * * `review_only` - review_only
- * * `resolve_only` - resolve_only
- * * `flash` - flash */
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Flash */
run_mode?: ReviewTriggerRequestRunModeEnumApi
}
@@ -513,97 +1059,160 @@ export interface ReviewTriggerResponseApi {
status: string
}
+/**
+ * * `flash_after_full` - Flash after a published Full review
+ * * `resolution_not_opted_in` - The pull request owner has not opted in to resolution
+ * * `internal_feature` - Not available in this project
+ */
+export type ReviewRequestRefusalEnumApi = (typeof ReviewRequestRefusalEnumApi)[keyof typeof ReviewRequestRefusalEnumApi]
+
+export const ReviewRequestRefusalEnumApi = {
+ FlashAfterFull: 'flash_after_full',
+ ResolutionNotOptedIn: 'resolution_not_opted_in',
+ InternalFeature: 'internal_feature',
+} as const
+
export interface ReviewTriggerErrorApi {
/** Human-readable explanation of why the trigger was rejected. */
error: string
+ /** Why the request was refused, for a client that shows its own reason: 'flash_after_full' (the PR already has a published Full review), 'resolution_not_opted_in' (the PR owner has not turned on resolving comments), 'internal_feature' (the run mode is not available in this project). Absent for other errors.
+ *
+ * * `flash_after_full` - Flash after a published Full review
+ * * `resolution_not_opted_in` - The pull request owner has not opted in to resolution
+ * * `internal_feature` - Not available in this project */
+ code?: ReviewRequestRefusalEnumApi
}
/**
- * * `medium` - Medium
- * * `xhigh` - Extra high
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere
*/
-export type ReviewUserSettingsFlashReasoningEffortEnumApi =
- (typeof ReviewUserSettingsFlashReasoningEffortEnumApi)[keyof typeof ReviewUserSettingsFlashReasoningEffortEnumApi]
+export type DefaultReviewModeEnumApi = (typeof DefaultReviewModeEnumApi)[keyof typeof DefaultReviewModeEnumApi]
-export const ReviewUserSettingsFlashReasoningEffortEnumApi = {
- Medium: 'medium',
- Xhigh: 'xhigh',
+export const DefaultReviewModeEnumApi = {
+ Follow: 'follow',
+ Flash: 'flash',
+ Off: 'off',
} as const
/**
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default
*/
-export type ReviewUserSettingsUrgencyThresholdEnumApi =
- (typeof ReviewUserSettingsUrgencyThresholdEnumApi)[keyof typeof ReviewUserSettingsUrgencyThresholdEnumApi]
+export type PreferenceSourceEnumApi = (typeof PreferenceSourceEnumApi)[keyof typeof PreferenceSourceEnumApi]
-export const ReviewUserSettingsUrgencyThresholdEnumApi = {
- Consider: 'consider',
- ShouldFix: 'should_fix',
- MustFix: 'must_fix',
+export const PreferenceSourceEnumApi = {
+ User: 'user',
+ Project: 'project',
+ Default: 'default',
} as const
+export interface ReviewPreferenceSourcesApi {
+ /** Where the effective default_review_mode comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ default_review_mode: PreferenceSourceEnumApi
+ /** Where the effective resolve_comments comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ resolve_comments: PreferenceSourceEnumApi
+ /** Where the effective urgency_threshold comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ urgency_threshold: PreferenceSourceEnumApi
+ /** Where the effective celebrate_clean_reviews comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ celebrate_clean_reviews: PreferenceSourceEnumApi
+ /** Where the effective review_inbox_prs comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ review_inbox_prs: PreferenceSourceEnumApi
+ /** Where the effective stamphog_review_inbox_prs comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ stamphog_review_inbox_prs: PreferenceSourceEnumApi
+}
+
+export interface ReviewProjectDefaultsApi {
+ /** The project's default for the minimum priority a Full review publishes.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold: UrgencyThresholdEnumApi
+ /** The project's default for the image in a Full review that finds nothing to raise. */
+ celebrate_clean_reviews: boolean
+}
+
export interface ReviewUserSettingsApi {
- /** Automatically review pull requests opened by self-driving implementations from the user's Inbox: ReviewHog reviews each one and posts its findings to the pull request. */
+ /** Automatic reviews of the user's own pull requests in every repository this project reviews: 'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' turns automatic Flash off everywhere. A choice for one repository wins over this default.
+ *
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere */
+ default_review_mode?: DefaultReviewModeEnumApi
+ /** After a Full review of the user's pull requests is published, run the resolution stage: triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. Off by default. Personal only: no project default applies. */
+ resolve_comments?: boolean
+ /** Minimum priority a validated Full review finding needs to be published: 'consider' publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues. Without the user's own value the project default applies.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnumApi
+ /** Show a fun image in the review comment when a Full review of the user's pull requests finds nothing to raise. Without the user's own value the project default applies. */
+ celebrate_clean_reviews?: boolean
+ /** Review the pull requests the agent opens for Inbox reports assigned to the user: ReviewHog reviews each one and posts its findings to the pull request. Off by default. */
review_inbox_prs?: boolean
/** Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected). */
stamphog_review_inbox_prs?: boolean
- /** Review the user's pull requests when the trigger label is added on GitHub. On by default; turning it off makes the label trigger skip PRs this user authored. */
- review_labeled_prs?: boolean
- /** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
- resolve_comments?: boolean
- /** Show a fun image in the review comment when a review of this user's pull requests finds nothing to raise. On by default; turning it off makes clean reviews end with the text summary only. */
- celebrate_clean_reviews?: boolean
- /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
- review_authored_prs?: boolean
- /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
- *
- * * `medium` - Medium
- * * `xhigh` - Extra high */
- flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnumApi
- /** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
- *
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix */
- urgency_threshold?: ReviewUserSettingsUrgencyThresholdEnumApi
- /** Whether reviews can be started from this project's Code review page. */
- readonly can_trigger_reviews: boolean
- /** Whether to show Flash mode and settings for automatic, label-triggered, and Inbox reviews. */
- readonly show_internal_features: boolean
+ /** Where each effective value comes from. A value equal to the inherited one is never stored, so writing the project default or the built-in default makes the source follow it again. */
+ readonly sources: ReviewPreferenceSourcesApi
+ /** The project defaults the Full review preferences fall back to. */
+ readonly project_defaults: ReviewProjectDefaultsApi
/** Whether this project has at least one synced, enabled Stamphog repository. When false, the stamphog_review_inbox_prs toggle has nothing to act on and the UI renders it disabled with a pointer to connect the Stamphog GitHub App. */
readonly stamphog_connected: boolean
}
export interface PatchedReviewUserSettingsApi {
- /** Automatically review pull requests opened by self-driving implementations from the user's Inbox: ReviewHog reviews each one and posts its findings to the pull request. */
+ /** Automatic reviews of the user's own pull requests in every repository this project reviews: 'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' turns automatic Flash off everywhere. A choice for one repository wins over this default.
+ *
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere */
+ default_review_mode?: DefaultReviewModeEnumApi
+ /** After a Full review of the user's pull requests is published, run the resolution stage: triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. Off by default. Personal only: no project default applies. */
+ resolve_comments?: boolean
+ /** Minimum priority a validated Full review finding needs to be published: 'consider' publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues. Without the user's own value the project default applies.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnumApi
+ /** Show a fun image in the review comment when a Full review of the user's pull requests finds nothing to raise. Without the user's own value the project default applies. */
+ celebrate_clean_reviews?: boolean
+ /** Review the pull requests the agent opens for Inbox reports assigned to the user: ReviewHog reviews each one and posts its findings to the pull request. Off by default. */
review_inbox_prs?: boolean
/** Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected). */
stamphog_review_inbox_prs?: boolean
- /** Review the user's pull requests when the trigger label is added on GitHub. On by default; turning it off makes the label trigger skip PRs this user authored. */
- review_labeled_prs?: boolean
- /** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
- resolve_comments?: boolean
- /** Show a fun image in the review comment when a review of this user's pull requests finds nothing to raise. On by default; turning it off makes clean reviews end with the text summary only. */
- celebrate_clean_reviews?: boolean
- /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
- review_authored_prs?: boolean
- /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
- *
- * * `medium` - Medium
- * * `xhigh` - Extra high */
- flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnumApi
- /** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
- *
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix */
- urgency_threshold?: ReviewUserSettingsUrgencyThresholdEnumApi
- /** Whether reviews can be started from this project's Code review page. */
- readonly can_trigger_reviews?: boolean
- /** Whether to show Flash mode and settings for automatic, label-triggered, and Inbox reviews. */
- readonly show_internal_features?: boolean
+ /** Where each effective value comes from. A value equal to the inherited one is never stored, so writing the project default or the built-in default makes the source follow it again. */
+ readonly sources?: ReviewPreferenceSourcesApi
+ /** The project defaults the Full review preferences fall back to. */
+ readonly project_defaults?: ReviewProjectDefaultsApi
/** Whether this project has at least one synced, enabled Stamphog repository. When false, the stamphog_review_inbox_prs toggle has nothing to act on and the UI renders it disabled with a pointer to connect the Stamphog GitHub App. */
readonly stamphog_connected?: boolean
}
@@ -624,6 +1233,50 @@ export interface PatchedReviewValidatorConfigSelectApi {
active?: boolean
}
+export type ReviewHogRepositoryOverviewRetrieveParams = {
+ /**
+ * The GitHub App installation to list.
+ * @minLength 1
+ * @maxLength 64
+ */
+ installation_id: string
+ /**
+ * Entries per page (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number
+ /**
+ * Entries to skip.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Only repositories whose name contains this text.
+ */
+ search?: string
+ /**
+ * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), or 'mine' (with the requesting user's own choice).
+ *
+ * * `all` - All repositories
+ * * `in_project` - In this project
+ * * `exceptions` - With exceptions
+ * * `mine` - My choices
+ * @minLength 1
+ */
+ view?: ReviewHogRepositoryOverviewRetrieveView
+}
+
+export type ReviewHogRepositoryOverviewRetrieveView =
+ (typeof ReviewHogRepositoryOverviewRetrieveView)[keyof typeof ReviewHogRepositoryOverviewRetrieveView]
+
+export const ReviewHogRepositoryOverviewRetrieveView = {
+ All: 'all',
+ InProject: 'in_project',
+ Exceptions: 'exceptions',
+ Mine: 'mine',
+} as const
+
export type ReviewHogReviewsListParams = {
/**
* Maximum rows to return. The list grows this instead of paging by offset — in-progress rows reorder the list between refreshes, so offset pages would shift under the reader.
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 2591a684a288..5e011190cf70 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -10,17 +10,31 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
PatchedReviewBlindSpotsConfigSelectApi,
+ PatchedReviewInstallationClaimUpdateApi,
PatchedReviewPerspectiveConfigUpdateApi,
+ PatchedReviewProjectSettingsApi,
PatchedReviewResolutionConfigSelectApi,
PatchedReviewUserSettingsApi,
PatchedReviewValidatorConfigSelectApi,
ReviewBlindSpotsConfigApi,
ReviewDetailApi,
+ ReviewHogRepositoryOverviewRetrieveParams,
ReviewHogReviewsListParams,
ReviewHogReviewsPerspectiveStatsRetrieveParams,
+ ReviewInstallationClaimApi,
+ ReviewInstallationClaimCreateApi,
ReviewPerspectiveConfigApi,
ReviewPerspectiveStatsApi,
+ ReviewProjectSettingsApi,
ReviewRecentReviewsPageApi,
+ ReviewRepositoryApi,
+ ReviewRepositoryChoiceApi,
+ ReviewRepositoryChoiceWriteApi,
+ ReviewRepositoryChoiceWriteResponseApi,
+ ReviewRepositoryOverviewApi,
+ ReviewRepositoryPersonRequestApi,
+ ReviewRepositoryWriteApi,
+ ReviewRepositoryWriteResponseApi,
ReviewResolutionConfigApi,
ReviewTriggerRequestApi,
ReviewTriggerResponseApi,
@@ -85,6 +99,89 @@ export const reviewHogBlindSpotsPartialUpdate = async (
})
}
+export const getReviewHogInstallationClaimsListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/installation_claims/`
+}
+
+/**
+ * Which repositories of each connected GitHub installation this project reviews.
+ *
+ * Project members can read the claims. Only project admins can change them, and every change goes
+ * to the activity log. The project settings response lists every connected installation, also the
+ * ones without a claim.
+ */
+export const reviewHogInstallationClaimsList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ReviewInstallationClaimApi[]> => {
+ return apiMutator<ReviewInstallationClaimApi[]>(getReviewHogInstallationClaimsListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getReviewHogInstallationClaimsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/installation_claims/`
+}
+
+/**
+ * Choose which repositories of a connected GitHub installation this project reviews.
+ * @summary Claim a GitHub installation
+ */
+export const reviewHogInstallationClaimsCreate = async (
+ projectId: string,
+ reviewInstallationClaimCreateApi: ReviewInstallationClaimCreateApi,
+ options?: RequestInit
+): Promise<ReviewInstallationClaimApi> => {
+ return apiMutator<ReviewInstallationClaimApi>(getReviewHogInstallationClaimsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewInstallationClaimCreateApi),
+ })
+}
+
+export const getReviewHogInstallationClaimsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/review_hog/installation_claims/${id}/`
+}
+
+/**
+ * Switch between all repositories and only selected repositories. Switching to selected removes the exceptions of the repositories that leave this project. Personal choices stay.
+ * @summary Change a GitHub installation claim
+ */
+export const reviewHogInstallationClaimsPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedReviewInstallationClaimUpdateApi?: PatchedReviewInstallationClaimUpdateApi,
+ options?: RequestInit
+): Promise<ReviewInstallationClaimApi> => {
+ return apiMutator<ReviewInstallationClaimApi>(getReviewHogInstallationClaimsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedReviewInstallationClaimUpdateApi),
+ })
+}
+
+export const getReviewHogInstallationClaimsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/review_hog/installation_claims/${id}/`
+}
+
+/**
+ * Remove the claim, so this project reviews no repository of the installation. Its selected repositories and exceptions there are removed too. Personal choices stay.
+ * @summary Stop reviewing a GitHub installation
+ */
+export const reviewHogInstallationClaimsDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getReviewHogInstallationClaimsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getReviewHogPerspectivesListUrl = (projectId: string) => {
return `/api/projects/${projectId}/review_hog/perspectives/`
}
@@ -125,6 +222,281 @@ export const reviewHogPerspectivesPartialUpdate = async (
})
}
+export const getReviewHogProjectSettingsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/project_settings/`
+}
+
+/**
+ * The project rule for automatic Flash reviews, bot pull requests, the Full review defaults, and the connected GitHub installations.
+ * @summary Get the project's ReviewHog rule
+ */
+export const reviewHogProjectSettingsRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ReviewProjectSettingsApi> => {
+ return apiMutator<ReviewProjectSettingsApi>(getReviewHogProjectSettingsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getReviewHogProjectSettingsPartialUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/project_settings/`
+}
+
+/**
+ * Partially update the project rule. Only the provided fields change. Project admins only.
+ * @summary Update the project's ReviewHog rule
+ */
+export const reviewHogProjectSettingsPartialUpdate = async (
+ projectId: string,
+ patchedReviewProjectSettingsApi?: NonReadonly<PatchedReviewProjectSettingsApi>,
+ options?: RequestInit
+): Promise<ReviewProjectSettingsApi> => {
+ return apiMutator<ReviewProjectSettingsApi>(getReviewHogProjectSettingsPartialUpdateUrl(projectId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedReviewProjectSettingsApi),
+ })
+}
+
+export const getReviewHogProjectSettingsPeopleCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/project_settings/people/`
+}
+
+/**
+ * Add a project member to the project rule's 'listed' or 'excepted' list. Project admins only.
+ * @summary Add a person to a project rule list
+ */
+export const reviewHogProjectSettingsPeopleCreate = async (
+ projectId: string,
+ reviewRepositoryPersonRequestApi: ReviewRepositoryPersonRequestApi,
+ options?: RequestInit
+): Promise<ReviewProjectSettingsApi> => {
+ return apiMutator<ReviewProjectSettingsApi>(getReviewHogProjectSettingsPeopleCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewRepositoryPersonRequestApi),
+ })
+}
+
+export const getReviewHogProjectSettingsPeopleDestroyUrl = (projectId: string, personId: string) => {
+ return `/api/projects/${projectId}/review_hog/project_settings/people/${personId}/`
+}
+
+/**
+ * Remove one entry from the project rule's 'listed' or 'excepted' list. Project admins only.
+ * @summary Remove a person from a project rule list
+ */
+export const reviewHogProjectSettingsPeopleDestroy = async (
+ projectId: string,
+ personId: string,
+ options?: RequestInit
+): Promise<ReviewProjectSettingsApi> => {
+ return apiMutator<ReviewProjectSettingsApi>(getReviewHogProjectSettingsPeopleDestroyUrl(projectId, personId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getReviewHogRepositoriesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/repositories/`
+}
+
+/**
+ * The repositories this project has settings for: selected repositories and repository exceptions.
+ *
+ * Project members can read them. Only project admins can change them, and every change goes to the
+ * activity log. A repository has settings in one project at most.
+ */
+export const reviewHogRepositoriesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ReviewRepositoryApi[]> => {
+ return apiMutator<ReviewRepositoryApi[]>(getReviewHogRepositoriesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getReviewHogRepositoriesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/repositories/`
+}
+
+/**
+ * Include a repository into this project, remove it, or set or clear its exception. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.
+ * @summary Save a repository's settings
+ */
+export const reviewHogRepositoriesCreate = async (
+ projectId: string,
+ reviewRepositoryWriteApi: ReviewRepositoryWriteApi,
+ options?: RequestInit
+): Promise<ReviewRepositoryWriteResponseApi> => {
+ return apiMutator<ReviewRepositoryWriteResponseApi>(getReviewHogRepositoriesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewRepositoryWriteApi),
+ })
+}
+
+export const getReviewHogRepositoriesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/review_hog/repositories/${id}/`
+}
+
+/**
+ * Remove the repository from this project and clear its exception and lists. With an 'all repositories' claim the repository stays in the project and follows the project rule.
+ * @summary Remove a repository's settings
+ */
+export const reviewHogRepositoriesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getReviewHogRepositoriesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getReviewHogRepositoriesPeopleCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/review_hog/repositories/${id}/people/`
+}
+
+/**
+ * Add a project member to the 'listed' or 'excepted' list of the repository exception.
+ * @summary Add a person to a repository exception list
+ */
+export const reviewHogRepositoriesPeopleCreate = async (
+ projectId: string,
+ id: string,
+ reviewRepositoryPersonRequestApi: ReviewRepositoryPersonRequestApi,
+ options?: RequestInit
+): Promise<ReviewRepositoryApi> => {
+ return apiMutator<ReviewRepositoryApi>(getReviewHogRepositoriesPeopleCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewRepositoryPersonRequestApi),
+ })
+}
+
+export const getReviewHogRepositoriesPeopleDestroyUrl = (projectId: string, id: string, personId: string) => {
+ return `/api/projects/${projectId}/review_hog/repositories/${id}/people/${personId}/`
+}
+
+/**
+ * Remove one entry from the 'listed' or 'excepted' list of the repository exception.
+ * @summary Remove a person from a repository exception list
+ */
+export const reviewHogRepositoriesPeopleDestroy = async (
+ projectId: string,
+ id: string,
+ personId: string,
+ options?: RequestInit
+): Promise<ReviewRepositoryApi> => {
+ return apiMutator<ReviewRepositoryApi>(getReviewHogRepositoriesPeopleDestroyUrl(projectId, id, personId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getReviewHogRepositoryChoicesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/repository_choices/`
+}
+
+/**
+ * The requesting user's own automatic review choices for repositories of this project.
+ *
+ * Any project member can manage their own choices. A choice stores only what differs from what the
+ * user inherits, so picking the inherited value clears it.
+ */
+export const reviewHogRepositoryChoicesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ReviewRepositoryChoiceApi[]> => {
+ return apiMutator<ReviewRepositoryChoiceApi[]>(getReviewHogRepositoryChoicesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getReviewHogRepositoryChoicesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/review_hog/repository_choices/`
+}
+
+/**
+ * Set the requesting user's own automatic review for their pull requests in one repository. It wins over their default and over the repository and project rules.
+ * @summary Set my choice for a repository
+ */
+export const reviewHogRepositoryChoicesCreate = async (
+ projectId: string,
+ reviewRepositoryChoiceWriteApi: ReviewRepositoryChoiceWriteApi,
+ options?: RequestInit
+): Promise<ReviewRepositoryChoiceWriteResponseApi> => {
+ return apiMutator<ReviewRepositoryChoiceWriteResponseApi>(getReviewHogRepositoryChoicesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(reviewRepositoryChoiceWriteApi),
+ })
+}
+
+export const getReviewHogRepositoryChoicesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/review_hog/repository_choices/${id}/`
+}
+
+/**
+ * Clear the requesting user's own choice for one repository, so their default applies again.
+ * @summary Clear my choice for a repository
+ */
+export const reviewHogRepositoryChoicesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getReviewHogRepositoryChoicesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getReviewHogRepositoryOverviewRetrieveUrl = (
+ projectId: string,
+ params: ReviewHogRepositoryOverviewRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/review_hog/repository_overview/?${stringifiedParams}`
+ : `/api/projects/${projectId}/review_hog/repository_overview/`
+}
+
+/**
+ * Every repository the GitHub installation can see, with the project that reviews it, this project's settings, the requesting user's choice, and the automatic review the requesting user gets.
+ * @summary List the repositories of a GitHub installation with their review settings
+ */
+export const reviewHogRepositoryOverviewRetrieve = async (
+ projectId: string,
+ params: ReviewHogRepositoryOverviewRetrieveParams,
+ options?: RequestInit
+): Promise<ReviewRepositoryOverviewApi> => {
+ return apiMutator<ReviewRepositoryOverviewApi>(getReviewHogRepositoryOverviewRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getReviewHogResolutionListUrl = (projectId: string) => {
return `/api/projects/${projectId}/review_hog/resolution/`
}
@@ -254,7 +626,7 @@ export const getReviewHogReviewsTriggerCreateUrl = (projectId: string) => {
}
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it appears under their recent reviews. Resolution writes to the branch only when the pull request owner opted in, whoever asks. `run_mode` picks the variant: a review (which chains the resolution stage per the owner's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments and is refused after a published Full review. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const reviewHogReviewsTriggerCreate = async (
@@ -275,7 +647,7 @@ export const getReviewHogSettingsRetrieveUrl = (projectId: string) => {
}
/**
- * Fetch the requesting user's ReviewHog settings for this project, creating the row with defaults on first read.
+ * Fetch the requesting user's effective ReviewHog preferences for this project, and where each value comes from.
* @summary Get the user's ReviewHog settings
*/
export const reviewHogSettingsRetrieve = async (
@@ -293,7 +665,7 @@ export const getReviewHogSettingsPartialUpdateUrl = (projectId: string) => {
}
/**
- * Partially update the requesting user's ReviewHog settings for this project. Only the provided fields change.
+ * Partially update the requesting user's ReviewHog preferences for this project. Only the provided fields change. A value equal to the inherited one clears the user's own value.
* @summary Update the user's ReviewHog settings
*/
export const reviewHogSettingsPartialUpdate = async (
diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.ts
index 27f9c3fa11d1..265c50e701b5 100644
--- a/products/review_hog/frontend/generated/api.zod.ts
+++ b/products/review_hog/frontend/generated/api.zod.ts
@@ -22,6 +22,39 @@ export const ReviewHogBlindSpotsPartialUpdateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Choose which repositories of a connected GitHub installation this project reviews.
+ * @summary Claim a GitHub installation
+ */
+export const reviewHogInstallationClaimsCreateBodyInstallationIdMax = 64
+
+export const ReviewHogInstallationClaimsCreateBody = /* @__PURE__ */ zod.object({
+ installation_id: zod
+ .string()
+ .max(reviewHogInstallationClaimsCreateBodyInstallationIdMax)
+ .describe('The GitHub App installation id.'),
+ scope: zod
+ .enum(['all', 'selected'])
+ .describe('\* `all` - All repositories\n\* `selected` - Only selected repositories')
+ .describe(
+ "'all' reviews every repository of the installation that no other project selected. At most one project per installation can choose it. 'selected' reviews only selected repositories.\n\n\* `all` - All repositories\n\* `selected` - Only selected repositories"
+ ),
+})
+
+/**
+ * Switch between all repositories and only selected repositories. Switching to selected removes the exceptions of the repositories that leave this project. Personal choices stay.
+ * @summary Change a GitHub installation claim
+ */
+export const ReviewHogInstallationClaimsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ scope: zod
+ .enum(['all', 'selected'])
+ .describe('\* `all` - All repositories\n\* `selected` - Only selected repositories')
+ .optional()
+ .describe(
+ "'all' or 'selected'. Switching to 'selected' removes the exceptions of the repositories that leave the project.\n\n\* `all` - All repositories\n\* `selected` - Only selected repositories"
+ ),
+})
+
/**
* Toggle whether a `review-hog-perspective-*` skill runs on the requesting user's PR reviews. Only skills visible to the user — the canonicals plus the customs they authored — can be toggled; anything else 404s. Upserts the per-user config row, so enabling a freshly authored custom perspective works in one call. Rejected if it would leave the user with no enabled perspective.
* @summary Enable or disable a review perspective
@@ -33,6 +66,139 @@ export const ReviewHogPerspectivesPartialUpdateBody = /* @__PURE__ */ zod.object
.describe("Set true to run this perspective on the user's PR reviews, false to stop running it."),
})
+/**
+ * Partially update the project rule. Only the provided fields change. Project admins only.
+ * @summary Update the project's ReviewHog rule
+ */
+export const ReviewHogProjectSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ flash_for: zod
+ .enum(['everyone', 'listed', 'off'])
+ .describe(
+ '\* `everyone` - Automatic Flash for everyone\n\* `listed` - Automatic Flash for these people\n\* `off` - Automatic Flash opt-in only'
+ )
+ .optional()
+ .describe(
+ "Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the default). A repository exception or a person's own choice wins over it.\n\n\* `everyone` - Automatic Flash for everyone\n\* `listed` - Automatic Flash for these people\n\* `off` - Automatic Flash opt-in only"
+ ),
+ bot_prs: zod
+ .enum(['skip', 'run'])
+ .describe('\* `skip` - Not reviewed\n\* `run` - Automatic Flash')
+ .optional()
+ .describe(
+ "Pull requests from bots, and from authors who are not project members, in every repository this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the person who connected GitHub, with default settings and no changes to the pull request).\n\n\* `skip` - Not reviewed\n\* `run` - Automatic Flash"
+ ),
+ urgency_threshold: zod
+ .enum(['consider', 'should_fix', 'must_fix'])
+ .describe('\* `consider` - Consider (all)\n\* `should_fix` - Should fix\n\* `must_fix` - Must fix')
+ .optional()
+ .describe(
+ "Project default for the minimum priority a Full review publishes: 'consider' (all, the built-in default), 'should_fix', or 'must_fix'. A person's own value wins.\n\n\* `consider` - Consider (all)\n\* `should_fix` - Should fix\n\* `must_fix` - Must fix"
+ ),
+ celebrate_clean_reviews: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Project default for the image in a Full review that finds nothing to raise. On by default. A person's own value wins."
+ ),
+})
+
+/**
+ * Add a project member to the project rule's 'listed' or 'excepted' list. Project admins only.
+ * @summary Add a person to a project rule list
+ */
+export const ReviewHogProjectSettingsPeopleCreateBody = /* @__PURE__ */ zod.object({
+ user_id: zod.number().describe('Id of the project member to add. Must be an active member.'),
+ kind: zod
+ .enum(['listed', 'excepted'])
+ .describe('\* `listed` - Listed\n\* `excepted` - Excepted')
+ .describe(
+ "Which list to add the person to: 'listed' or 'excepted'.\n\n\* `listed` - Listed\n\* `excepted` - Excepted"
+ ),
+})
+
+/**
+ * Include a repository into this project, remove it, or set or clear its exception. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.
+ * @summary Save a repository's settings
+ */
+export const reviewHogRepositoriesCreateBodyInstallationIdMax = 64
+
+export const reviewHogRepositoriesCreateBodyFullNameMax = 200
+
+export const ReviewHogRepositoriesCreateBody = /* @__PURE__ */ zod.object({
+ installation_id: zod
+ .string()
+ .max(reviewHogRepositoriesCreateBodyInstallationIdMax)
+ .describe('The GitHub App installation that sees the repository, from the overview.'),
+ full_name: zod
+ .string()
+ .max(reviewHogRepositoriesCreateBodyFullNameMax)
+ .describe("GitHub repository in 'owner\/name' form, spelled as GitHub returns it."),
+ github_repo_id: zod
+ .number()
+ .min(1)
+ .optional()
+ .describe("GitHub's id of the repository, from the overview. Keeps renames."),
+ selected: zod
+ .boolean()
+ .optional()
+ .describe(
+ "True includes the repository into this project, also when another project takes all repositories of the installation. False removes it; with an 'only selected' claim its exception goes too."
+ ),
+ flash_for: zod
+ .union([
+ zod
+ .enum(['everyone', 'listed', 'off'])
+ .describe(
+ '\* `everyone` - Automatic Flash for everyone\n\* `listed` - Automatic Flash for these people\n\* `off` - Automatic Flash opt-in only'
+ ),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository follows the project rule again. Omit it to keep the current value.\n\n\* `everyone` - Automatic Flash for everyone\n\* `listed` - Automatic Flash for these people\n\* `off` - Automatic Flash opt-in only"
+ ),
+})
+
+/**
+ * Add a project member to the 'listed' or 'excepted' list of the repository exception.
+ * @summary Add a person to a repository exception list
+ */
+export const ReviewHogRepositoriesPeopleCreateBody = /* @__PURE__ */ zod.object({
+ user_id: zod.number().describe('Id of the project member to add. Must be an active member.'),
+ kind: zod
+ .enum(['listed', 'excepted'])
+ .describe('\* `listed` - Listed\n\* `excepted` - Excepted')
+ .describe(
+ "Which list to add the person to: 'listed' or 'excepted'.\n\n\* `listed` - Listed\n\* `excepted` - Excepted"
+ ),
+})
+
+/**
+ * Set the requesting user's own automatic review for their pull requests in one repository. It wins over their default and over the repository and project rules.
+ * @summary Set my choice for a repository
+ */
+export const reviewHogRepositoryChoicesCreateBodyInstallationIdMax = 64
+
+export const reviewHogRepositoryChoicesCreateBodyFullNameMax = 200
+
+export const ReviewHogRepositoryChoicesCreateBody = /* @__PURE__ */ zod.object({
+ installation_id: zod
+ .string()
+ .max(reviewHogRepositoryChoicesCreateBodyInstallationIdMax)
+ .describe('The GitHub App installation.'),
+ full_name: zod
+ .string()
+ .max(reviewHogRepositoryChoicesCreateBodyFullNameMax)
+ .describe("GitHub repository in 'owner\/name' form."),
+ github_repo_id: zod.number().min(1).optional().describe("GitHub's repository id."),
+ mode: zod
+ .enum(['flash', 'off'])
+ .describe('\* `flash` - Flash\n\* `off` - Off')
+ .describe(
+ "The requesting user's own automatic review for their pull requests in this repository: 'flash' or 'off'. A value equal to what the user inherits clears the choice instead.\n\n\* `flash` - Flash\n\* `off` - Off"
+ ),
+})
+
/**
* Make a `review-hog-resolution-*` skill the single criteria the resolution stage applies on the requesting user's PRs, switching the user's other resolution skills off in the same call. Only skills visible to the user — the canonical plus the customs they authored — can be selected; anything else 404s. Upserts the per-user config row, so selecting a freshly authored custom skill works in one call.
* @summary Select the active resolution criteria
@@ -47,7 +213,7 @@ export const ReviewHogResolutionPartialUpdateBody = /* @__PURE__ */ zod.object({
})
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it appears under their recent reviews. Resolution writes to the branch only when the pull request owner opted in, whoever asks. `run_mode` picks the variant: a review (which chains the resolution stage per the owner's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments and is refused after a published Full review. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const reviewHogReviewsTriggerCreateBodyRunModeDefault = `review`
@@ -61,68 +227,56 @@ export const ReviewHogReviewsTriggerCreateBody = /* @__PURE__ */ zod.object({
run_mode: zod
.enum(['review', 'review_only', 'resolve_only', 'flash'])
.describe(
- '\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash'
+ '\* `review` - Review\n\* `review_only` - Review only\n\* `resolve_only` - Resolve only\n\* `flash` - Flash'
)
.default(reviewHogReviewsTriggerCreateBodyRunModeDefault)
.describe(
- "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash"
+ "What to run on the pull request. 'review' (default) reviews it and, when the pull request owner's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads, which needs the owner's opt-in; 'flash' uses a lower-cost model for the review passes and validation, never resolves comments, and is refused once the PR has a published Full review. The owner is the PR's author, or the Inbox reviewer of a pull request the PostHog app opened.\n\n\* `review` - Review\n\* `review_only` - Review only\n\* `resolve_only` - Resolve only\n\* `flash` - Flash"
),
})
/**
- * Partially update the requesting user's ReviewHog settings for this project. Only the provided fields change.
+ * Partially update the requesting user's ReviewHog preferences for this project. Only the provided fields change. A value equal to the inherited one clears the user's own value.
* @summary Update the user's ReviewHog settings
*/
export const ReviewHogSettingsPartialUpdateBody = /* @__PURE__ */ zod.object({
- review_inbox_prs: zod
- .boolean()
- .optional()
- .describe(
- "Automatically review pull requests opened by self-driving implementations from the user's Inbox: ReviewHog reviews each one and posts its findings to the pull request."
- ),
- stamphog_review_inbox_prs: zod
- .boolean()
+ default_review_mode: zod
+ .enum(['follow', 'flash', 'off'])
+ .describe('\* `follow` - Follow each repository\n\* `flash` - Flash everywhere\n\* `off` - Off everywhere')
.optional()
.describe(
- "Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)."
+ "Automatic reviews of the user's own pull requests in every repository this project reviews: 'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' turns automatic Flash off everywhere. A choice for one repository wins over this default.\n\n\* `follow` - Follow each repository\n\* `flash` - Flash everywhere\n\* `off` - Off everywhere"
),
- review_labeled_prs: zod
+ resolve_comments: zod
.boolean()
.optional()
.describe(
- "Review the user's pull requests when the trigger label is added on GitHub. On by default; turning it off makes the label trigger skip PRs this user authored."
+ "After a Full review of the user's pull requests is published, run the resolution stage: triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. Off by default. Personal only: no project default applies."
),
- resolve_comments: zod
- .boolean()
+ urgency_threshold: zod
+ .enum(['consider', 'should_fix', 'must_fix'])
+ .describe('\* `consider` - Consider (all)\n\* `should_fix` - Should fix\n\* `must_fix` - Must fix')
.optional()
.describe(
- "After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing."
+ "Minimum priority a validated Full review finding needs to be published: 'consider' publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues. Without the user's own value the project default applies.\n\n\* `consider` - Consider (all)\n\* `should_fix` - Should fix\n\* `must_fix` - Must fix"
),
celebrate_clean_reviews: zod
.boolean()
.optional()
.describe(
- "Show a fun image in the review comment when a review of this user's pull requests finds nothing to raise. On by default; turning it off makes clean reviews end with the text summary only."
+ "Show a fun image in the review comment when a Full review of the user's pull requests finds nothing to raise. Without the user's own value the project default applies."
),
- review_authored_prs: zod
+ review_inbox_prs: zod
.boolean()
.optional()
.describe(
- 'Automatically review pull requests authored by this user in PostHog\/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments.'
- ),
- flash_reasoning_effort: zod
- .enum(['medium', 'xhigh'])
- .describe('\* `medium` - Medium\n\* `xhigh` - Extra high')
- .optional()
- .describe(
- "Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.\n\n\* `medium` - Medium\n\* `xhigh` - Extra high"
+ 'Review the pull requests the agent opens for Inbox reports assigned to the user: ReviewHog reviews each one and posts its findings to the pull request. Off by default.'
),
- urgency_threshold: zod
- .enum(['consider', 'should_fix', 'must_fix'])
- .describe('\* `consider` - Consider\n\* `should_fix` - Should Fix\n\* `must_fix` - Must Fix')
+ stamphog_review_inbox_prs: zod
+ .boolean()
.optional()
.describe(
- "Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.\n\n\* `consider` - Consider\n\* `should_fix` - Should Fix\n\* `must_fix` - Must Fix"
+ "Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)."
),
})
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
index 97b0a5006506..88328608428d 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -63,7 +63,6 @@ describe('reviewHogSettingsLogic', () => {
200,
{
review_inbox_prs: false,
- review_labeled_prs: true,
resolve_comments: true,
urgency_threshold: 'should_fix',
},
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index a1480df79061..561aa9dc25d4 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -1720,9 +1720,8 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# Hand a refused/escalated PR to ReviewHog only AFTER the refusal verdict wins the terminal save
# above — running it before would trigger ReviewHog for a stale refusal that a superseding delivery
- # then overrode (a newer run might approve the same head). Adding the ReviewHog trigger label fires
- # its workflow (review-hog.yml exempts stamphog[bot] from the bot-labeler-skip that would otherwise
- # strip it).
+ # then overrode (a newer run might approve the same head). Adding the ReviewHog trigger label starts
+ # its review (ReviewHog's label consumer accepts stamphog[bot] as a labeler and strips other bots' labels).
#
# Only self-driving runs hand off. A human PR has an author who reads the refusal and decides what
# to do about it, and in ALL mode the handoff would fire on PRs nobody asked stamphog to look at.
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index f65b1ba0b27b..3291a60b8293 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -38,10 +38,9 @@ STAMPHOG_BOT_EYES_MAX_AGE_SECONDS = 45 * 60
STAMPHOG_BOT_REVIEW_POLL_SECONDS = 30
STAMPHOG_BOT_REVIEW_MAX_POLLS = 10 # ~300s budget at 30s per poll, matching the engine's wait budget
-# The GitHub label Stamphog adds to hand a refused/escalated PR to ReviewHog. ``review-hog.yml``
-# routes this label (when applied by stamphog[bot] — the one sanctioned bot exempted from its
-# bot-labeler-skip) to the ReviewHog trigger endpoint. Kept here so the activity references the same
-# scalar the workflow gates on.
+# The GitHub label Stamphog adds to hand a refused/escalated PR to ReviewHog. ReviewHog's `labeled`
+# webhook consumer starts a review for it (stamphog[bot] is the one bot it accepts as a labeler).
+# Kept here so the activity references the same scalar ReviewHog gates on.
STAMPHOG_REVIEWHOG_LABEL = "reviewhog"
# The owners-yaml resolver package, expected by the engine as a sibling of its own dir
# (gates.py resolves `../owners` for the hogli-resolver ownership format). This stays a sibling of
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e13f3fd217cf..5a6f4410d3bf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13528,6 +13528,81 @@ export namespace Schemas {
sortText?: string | null;
}
+ /**
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only
+ */
+ export type AutomaticFlashForEnum = typeof AutomaticFlashForEnum[keyof typeof AutomaticFlashForEnum];
+
+
+ export const AutomaticFlashForEnum = {
+ Everyone: 'everyone',
+ Listed: 'listed',
+ Off: 'off',
+ } as const;
+
+ /**
+ * * `own_repository_choice` - Own choice for this repository
+ * * `own_default` - Own default
+ * * `repository_everyone` - The repository exception reviews everyone
+ * * `repository_excepted` - Excepted by the repository exception
+ * * `repository_listed` - Listed by the repository exception
+ * * `repository_not_listed` - Not listed by the repository exception
+ * * `repository_opt_in` - The repository exception reviews only people who opt in
+ * * `project_everyone` - The project reviews everyone
+ * * `project_excepted` - Excepted by the project
+ * * `project_listed` - Listed by the project
+ * * `project_not_listed` - Not listed by the project
+ * * `project_opt_in` - The project reviews only people who opt in
+ * * `bot_reviewed` - The project reviews bot pull requests
+ * * `bot_skipped` - The project does not review bot pull requests
+ * * `not_in_project` - This project does not review the repository
+ */
+ export type AutomaticReviewReasonEnum = typeof AutomaticReviewReasonEnum[keyof typeof AutomaticReviewReasonEnum];
+
+
+ export const AutomaticReviewReasonEnum = {
+ OwnRepositoryChoice: 'own_repository_choice',
+ OwnDefault: 'own_default',
+ RepositoryEveryone: 'repository_everyone',
+ RepositoryExcepted: 'repository_excepted',
+ RepositoryListed: 'repository_listed',
+ RepositoryNotListed: 'repository_not_listed',
+ RepositoryOptIn: 'repository_opt_in',
+ ProjectEveryone: 'project_everyone',
+ ProjectExcepted: 'project_excepted',
+ ProjectListed: 'project_listed',
+ ProjectNotListed: 'project_not_listed',
+ ProjectOptIn: 'project_opt_in',
+ BotReviewed: 'bot_reviewed',
+ BotSkipped: 'bot_skipped',
+ NotInProject: 'not_in_project',
+ } as const;
+
+ export interface AutomaticReviewDecision {
+ /** Whether the requesting user's own pull requests get automatic Flash reviews in this repository. */
+ flash: boolean;
+ /** Which rule decided: the user's own choice ('own_repository_choice', 'own_default'), the repository exception ('repository_*'), the project rule ('project_*'), or 'not_in_project' when this project does not review the repository.
+ *
+ * * `own_repository_choice` - Own choice for this repository
+ * * `own_default` - Own default
+ * * `repository_everyone` - The repository exception reviews everyone
+ * * `repository_excepted` - Excepted by the repository exception
+ * * `repository_listed` - Listed by the repository exception
+ * * `repository_not_listed` - Not listed by the repository exception
+ * * `repository_opt_in` - The repository exception reviews only people who opt in
+ * * `project_everyone` - The project reviews everyone
+ * * `project_excepted` - Excepted by the project
+ * * `project_listed` - Listed by the project
+ * * `project_not_listed` - Not listed by the project
+ * * `project_opt_in` - The project reviews only people who opt in
+ * * `bot_reviewed` - The project reviews bot pull requests
+ * * `bot_skipped` - The project does not review bot pull requests
+ * * `not_in_project` - This project does not review the repository */
+ reason: AutomaticReviewReasonEnum;
+ }
+
/**
* * `P0` - P0
* * `P1` - P1
@@ -34703,6 +34778,20 @@ export namespace Schemas {
Default: 'default',
} as const;
+ /**
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere
+ */
+ export type DefaultReviewModeEnum = typeof DefaultReviewModeEnum[keyof typeof DefaultReviewModeEnum];
+
+
+ export const DefaultReviewModeEnum = {
+ Follow: 'follow',
+ Flash: 'flash',
+ Off: 'off',
+ } as const;
+
export interface DeleteTileRequest {
/** ID of the dashboard tile to delete. Use dashboard-get to look up tile IDs. */
tile_id: number;
@@ -82554,11 +82643,143 @@ export namespace Schemas {
active?: boolean;
}
+ /**
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories
+ */
+ export type ReviewInstallationClaimScopeEnum = typeof ReviewInstallationClaimScopeEnum[keyof typeof ReviewInstallationClaimScopeEnum];
+
+
+ export const ReviewInstallationClaimScopeEnum = {
+ All: 'all',
+ Selected: 'selected',
+ } as const;
+
+ export interface PatchedReviewInstallationClaimUpdate {
+ /** 'all' or 'selected'. Switching to 'selected' removes the exceptions of the repositories that leave the project.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope?: ReviewInstallationClaimScopeEnum;
+ }
+
export interface PatchedReviewPerspectiveConfigUpdate {
/** Set true to run this perspective on the user's PR reviews, false to stop running it. */
enabled?: boolean;
}
+ /**
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash
+ */
+ export type ReviewProjectSettingsBotPullRequestsEnum = typeof ReviewProjectSettingsBotPullRequestsEnum[keyof typeof ReviewProjectSettingsBotPullRequestsEnum];
+
+
+ export const ReviewProjectSettingsBotPullRequestsEnum = {
+ Skip: 'skip',
+ Run: 'run',
+ } as const;
+
+ /**
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix
+ */
+ export type UrgencyThresholdEnum = typeof UrgencyThresholdEnum[keyof typeof UrgencyThresholdEnum];
+
+
+ export const UrgencyThresholdEnum = {
+ Consider: 'consider',
+ ShouldFix: 'should_fix',
+ MustFix: 'must_fix',
+ } as const;
+
+ /**
+ * * `listed` - Listed
+ * * `excepted` - Excepted
+ */
+ export type ReviewRepositoryPersonKindEnum = typeof ReviewRepositoryPersonKindEnum[keyof typeof ReviewRepositoryPersonKindEnum];
+
+
+ export const ReviewRepositoryPersonKindEnum = {
+ Listed: 'listed',
+ Excepted: 'excepted',
+ } as const;
+
+ export interface ReviewRepositoryPerson {
+ /** Id of this list entry. Use it to remove the person. */
+ readonly id: string;
+ /** The project member on the list. */
+ readonly user: UserBasic;
+ /** Which list: 'listed' (gets Flash when the rule reviews only listed people) or 'excepted' (skipped when the rule reviews everyone).
+ *
+ * * `listed` - Listed
+ * * `excepted` - Excepted */
+ readonly kind: ReviewRepositoryPersonKindEnum;
+ }
+
+ export interface ReviewProjectRef {
+ /**
+ * Id of the other project. Null when it belongs to another organization.
+ * @nullable
+ */
+ id: number | null;
+ /**
+ * Name of the other project. Null when it belongs to another organization.
+ * @nullable
+ */
+ name: string | null;
+ }
+
+ export interface ReviewInstallation {
+ /** The GitHub App installation id. */
+ installation_id: string;
+ /** The GitHub account (organization or user) of the installation. */
+ account_name: string;
+ /** Who connected the installation to this project. Automatic Flash reviews of bot pull requests run as this user. */
+ connected_by: UserBasic | null;
+ /**
+ * Id of this project's claim. Null when the project reviews nothing there.
+ * @nullable
+ */
+ claim_id: string | null;
+ /** Which repositories this project reviews: 'all' (every repository no other project selected, including future ones), 'selected' (only the selected ones), or null (none).
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope: ReviewInstallationClaimScopeEnum | null;
+ /** Another project that takes all repositories of the installation, if any. */
+ all_taken_by_project: ReviewProjectRef | null;
+ }
+
+ export interface PatchedReviewProjectSettings {
+ /** Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the default). A repository exception or a person's own choice wins over it.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnum;
+ /** Pull requests from bots, and from authors who are not project members, in every repository this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the person who connected GitHub, with default settings and no changes to the pull request).
+ *
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash */
+ bot_prs?: ReviewProjectSettingsBotPullRequestsEnum;
+ /** Project default for the minimum priority a Full review publishes: 'consider' (all, the built-in default), 'should_fix', or 'must_fix'. A person's own value wins.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnum;
+ /** Project default for the image in a Full review that finds nothing to raise. On by default. A person's own value wins. */
+ celebrate_clean_reviews?: boolean;
+ /** The people on the project rule's two lists. Only the list that matches flash_for has an effect. */
+ readonly people?: readonly ReviewRepositoryPerson[];
+ /** Every GitHub installation connected to this project, and which of its repositories this project reviews. */
+ readonly installations?: readonly ReviewInstallation[];
+ /** Whether the requesting user is a project admin and can change these settings. */
+ readonly can_edit?: boolean;
+ }
+
export interface PatchedReviewQueueItemUpdate {
/** Review queue ID that should own this pending trace. */
queue_id?: string;
@@ -82578,59 +82799,94 @@ export namespace Schemas {
}
/**
- * * `medium` - Medium
- * * `xhigh` - Extra high
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default
*/
- export type ReviewUserSettingsFlashReasoningEffortEnum = typeof ReviewUserSettingsFlashReasoningEffortEnum[keyof typeof ReviewUserSettingsFlashReasoningEffortEnum];
+ export type PreferenceSourceEnum = typeof PreferenceSourceEnum[keyof typeof PreferenceSourceEnum];
- export const ReviewUserSettingsFlashReasoningEffortEnum = {
- Medium: 'medium',
- Xhigh: 'xhigh',
+ export const PreferenceSourceEnum = {
+ User: 'user',
+ Project: 'project',
+ Default: 'default',
} as const;
- /**
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix
- */
- export type ReviewUserSettingsUrgencyThresholdEnum = typeof ReviewUserSettingsUrgencyThresholdEnum[keyof typeof ReviewUserSettingsUrgencyThresholdEnum];
-
+ export interface ReviewPreferenceSources {
+ /** Where the effective default_review_mode comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ default_review_mode: PreferenceSourceEnum;
+ /** Where the effective resolve_comments comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ resolve_comments: PreferenceSourceEnum;
+ /** Where the effective urgency_threshold comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ urgency_threshold: PreferenceSourceEnum;
+ /** Where the effective celebrate_clean_reviews comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ celebrate_clean_reviews: PreferenceSourceEnum;
+ /** Where the effective review_inbox_prs comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ review_inbox_prs: PreferenceSourceEnum;
+ /** Where the effective stamphog_review_inbox_prs comes from: 'user' (the user set it), 'project' (the project default), or 'default' (the built-in default).
+ *
+ * * `user` - Set by the user
+ * * `project` - Project default
+ * * `default` - Built-in default */
+ stamphog_review_inbox_prs: PreferenceSourceEnum;
+ }
- export const ReviewUserSettingsUrgencyThresholdEnum = {
- Consider: 'consider',
- ShouldFix: 'should_fix',
- MustFix: 'must_fix',
- } as const;
+ export interface ReviewProjectDefaults {
+ /** The project's default for the minimum priority a Full review publishes.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold: UrgencyThresholdEnum;
+ /** The project's default for the image in a Full review that finds nothing to raise. */
+ celebrate_clean_reviews: boolean;
+ }
export interface PatchedReviewUserSettings {
- /** Automatically review pull requests opened by self-driving implementations from the user's Inbox: ReviewHog reviews each one and posts its findings to the pull request. */
+ /** Automatic reviews of the user's own pull requests in every repository this project reviews: 'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' turns automatic Flash off everywhere. A choice for one repository wins over this default.
+ *
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere */
+ default_review_mode?: DefaultReviewModeEnum;
+ /** After a Full review of the user's pull requests is published, run the resolution stage: triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. Off by default. Personal only: no project default applies. */
+ resolve_comments?: boolean;
+ /** Minimum priority a validated Full review finding needs to be published: 'consider' publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues. Without the user's own value the project default applies.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnum;
+ /** Show a fun image in the review comment when a Full review of the user's pull requests finds nothing to raise. Without the user's own value the project default applies. */
+ celebrate_clean_reviews?: boolean;
+ /** Review the pull requests the agent opens for Inbox reports assigned to the user: ReviewHog reviews each one and posts its findings to the pull request. Off by default. */
review_inbox_prs?: boolean;
/** Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected). */
stamphog_review_inbox_prs?: boolean;
- /** Review the user's pull requests when the trigger label is added on GitHub. On by default; turning it off makes the label trigger skip PRs this user authored. */
- review_labeled_prs?: boolean;
- /** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
- resolve_comments?: boolean;
- /** Show a fun image in the review comment when a review of this user's pull requests finds nothing to raise. On by default; turning it off makes clean reviews end with the text summary only. */
- celebrate_clean_reviews?: boolean;
- /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
- review_authored_prs?: boolean;
- /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
- *
- * * `medium` - Medium
- * * `xhigh` - Extra high */
- flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnum;
- /** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
- *
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix */
- urgency_threshold?: ReviewUserSettingsUrgencyThresholdEnum;
- /** Whether reviews can be started from this project's Code review page. */
- readonly can_trigger_reviews?: boolean;
- /** Whether to show Flash mode and settings for automatic, label-triggered, and Inbox reviews. */
- readonly show_internal_features?: boolean;
+ /** Where each effective value comes from. A value equal to the inherited one is never stored, so writing the project default or the built-in default makes the source follow it again. */
+ readonly sources?: ReviewPreferenceSources;
+ /** The project defaults the Full review preferences fall back to. */
+ readonly project_defaults?: ReviewProjectDefaults;
/** Whether this project has at least one synced, enabled Stamphog repository. When false, the stamphog_review_inbox_prs toggle has nothing to act on and the UI renders it disabled with a pointer to connect the Stamphog GitHub App. */
readonly stamphog_connected?: boolean;
}
@@ -93914,6 +94170,20 @@ export namespace Schemas {
Readme: 'readme',
} as const;
+ /**
+ * * `this_project` - This project
+ * * `other_project` - Another project
+ * * `none` - No project
+ */
+ export type RepositoryOwnerKindEnum = typeof RepositoryOwnerKindEnum[keyof typeof RepositoryOwnerKindEnum];
+
+
+ export const RepositoryOwnerKindEnum = {
+ ThisProject: 'this_project',
+ OtherProject: 'other_project',
+ None: 'none',
+ } as const;
+
export interface ScanEvidence {
/** Number of files scanned */
filesScanned: number;
@@ -94939,6 +95209,44 @@ export namespace Schemas {
dismissed_findings: ReviewFinding[];
}
+ export interface ReviewHogSettingsError {
+ /** Why the request was rejected. */
+ error: string;
+ /** The project that already holds the repository or the installation, if any. */
+ conflicting_project: ReviewProjectRef | null;
+ }
+
+ export interface ReviewInstallationClaim {
+ /** Id of the claim. */
+ readonly id: string;
+ /** The GitHub App installation id. */
+ readonly installation_id: string;
+ /** 'all' (every repository no other project selected, including future ones) or 'selected'.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ readonly scope: ReviewInstallationClaimScopeEnum;
+ /** The GitHub account (organization or user) of the installation. */
+ readonly account_name: string;
+ /** Who made the claim. */
+ readonly created_by: UserBasic | null;
+ /** When the claim was made. */
+ readonly created_at: string;
+ }
+
+ export interface ReviewInstallationClaimCreate {
+ /**
+ * The GitHub App installation id.
+ * @maxLength 64
+ */
+ installation_id: string;
+ /** 'all' reviews every repository of the installation that no other project selected. At most one project per installation can choose it. 'selected' reviews only selected repositories.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ scope: ReviewInstallationClaimScopeEnum;
+ }
+
export interface ReviewPerspectiveConfig {
/** Name of the `review-hog-perspective-*` skill this row toggles (the perspective's identity). */
skill_name: string;
@@ -94968,6 +95276,34 @@ export namespace Schemas {
perspectives: ReviewPerspectiveStatItem[];
}
+ export interface ReviewProjectSettings {
+ /** Who gets automatic Flash reviews in the repositories this project reviews: 'everyone' (except the excepted people), 'listed' (only the listed people), or 'off' (only people who opt in, the default). A repository exception or a person's own choice wins over it.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnum;
+ /** Pull requests from bots, and from authors who are not project members, in every repository this project reviews: 'skip' (not reviewed, the default) or 'run' (automatic Flash that runs as the person who connected GitHub, with default settings and no changes to the pull request).
+ *
+ * * `skip` - Not reviewed
+ * * `run` - Automatic Flash */
+ bot_prs?: ReviewProjectSettingsBotPullRequestsEnum;
+ /** Project default for the minimum priority a Full review publishes: 'consider' (all, the built-in default), 'should_fix', or 'must_fix'. A person's own value wins.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnum;
+ /** Project default for the image in a Full review that finds nothing to raise. On by default. A person's own value wins. */
+ celebrate_clean_reviews?: boolean;
+ /** The people on the project rule's two lists. Only the list that matches flash_for has an effect. */
+ readonly people: readonly ReviewRepositoryPerson[];
+ /** Every GitHub installation connected to this project, and which of its repositories this project reviews. */
+ readonly installations: readonly ReviewInstallation[];
+ /** Whether the requesting user is a project admin and can change these settings. */
+ readonly can_edit: boolean;
+ }
+
export interface ReviewQueueCreate {
/**
* Human-readable queue name.
@@ -95084,6 +95420,211 @@ export namespace Schemas {
has_more: boolean;
}
+ export interface ReviewRepository {
+ /** Id of the repository entry. */
+ readonly id: string;
+ /** The GitHub App installation that sees it. */
+ readonly installation_id: string;
+ /**
+ * GitHub's id of the repository. Null until it is first seen.
+ * @nullable
+ */
+ readonly github_repo_id: number | null;
+ /** GitHub repository in 'owner/name' form. */
+ readonly full_name: string;
+ /** Whether this project selected the repository. A selected repository belongs to this project even when another project takes all repositories of the installation. */
+ readonly selected: boolean;
+ /** The repository exception: 'everyone', 'listed', or 'off' (opt-in only). Null when the repository follows the project rule.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ readonly flash_for: AutomaticFlashForEnum | null;
+ /** The people on the exception's two lists. Only the list that matches flash_for has an effect. */
+ readonly people: readonly ReviewRepositoryPerson[];
+ /** Who added the repository. */
+ readonly created_by: UserBasic | null;
+ /** When the repository was added. */
+ readonly created_at: string;
+ }
+
+ /**
+ * * `flash` - Flash
+ * * `off` - Off
+ */
+ export type ReviewUserRepositoryChoiceModeEnum = typeof ReviewUserRepositoryChoiceModeEnum[keyof typeof ReviewUserRepositoryChoiceModeEnum];
+
+
+ export const ReviewUserRepositoryChoiceModeEnum = {
+ Flash: 'flash',
+ Off: 'off',
+ } as const;
+
+ export interface ReviewRepositoryChoice {
+ /** Id of the choice. Use it to clear the choice. */
+ readonly id: string;
+ /** The GitHub App installation. */
+ readonly installation_id: string;
+ /**
+ * GitHub's repository id.
+ * @nullable
+ */
+ readonly github_repo_id: number | null;
+ /** GitHub repository in 'owner/name' form. */
+ readonly full_name: string;
+ /** 'flash' or 'off' for the user's own pull requests in this repository.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ readonly mode: ReviewUserRepositoryChoiceModeEnum;
+ }
+
+ export interface ReviewRepositoryChoiceWrite {
+ /**
+ * The GitHub App installation.
+ * @maxLength 64
+ */
+ installation_id: string;
+ /**
+ * GitHub repository in 'owner/name' form.
+ * @maxLength 200
+ */
+ full_name: string;
+ /**
+ * GitHub's repository id.
+ * @minimum 1
+ */
+ github_repo_id?: number;
+ /** The requesting user's own automatic review for their pull requests in this repository: 'flash' or 'off'. A value equal to what the user inherits clears the choice instead.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ mode: ReviewUserRepositoryChoiceModeEnum;
+ }
+
+ export interface ReviewRepositoryChoiceWriteResponse {
+ /** The stored choice. Null when the value equals the inherited one. */
+ choice: ReviewRepositoryChoice | null;
+ /** What the requesting user's own pull requests get in this repository after the write. */
+ my_result: AutomaticReviewDecision;
+ }
+
+ export interface ReviewRepositoryException {
+ /** The exception's rule: 'everyone', 'listed', or 'off'.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for: AutomaticFlashForEnum;
+ /** The people on the exception's two lists. */
+ people: ReviewRepositoryPerson[];
+ }
+
+ export interface ReviewRepositoryOverviewEntry {
+ /** GitHub repository in 'owner/name' form. */
+ full_name: string;
+ /**
+ * GitHub's repository id.
+ * @nullable
+ */
+ github_repo_id: number | null;
+ /** Which project reviews the repository: 'this_project', 'other_project', or 'none'.
+ *
+ * * `this_project` - This project
+ * * `other_project` - Another project
+ * * `none` - No project */
+ owner: RepositoryOwnerKindEnum;
+ /** The other project that reviews the repository, when owner is 'other_project'. */
+ owner_project: ReviewProjectRef | null;
+ /** Whether this project reviews the repository. */
+ in_project: boolean;
+ /** Whether this project selected the repository explicitly. */
+ selected: boolean;
+ /**
+ * Id of this project's repository entry, for the people list endpoints.
+ * @nullable
+ */
+ repository_id: string | null;
+ /** This project's repository exception. Null when the repository follows the project. */
+ exception: ReviewRepositoryException | null;
+ /** The requesting user's own choice for this repository: 'flash', 'off', or null.
+ *
+ * * `flash` - Flash
+ * * `off` - Off */
+ my_choice: ReviewUserRepositoryChoiceModeEnum | null;
+ /**
+ * Id of that choice, to clear it.
+ * @nullable
+ */
+ my_choice_id: string | null;
+ /** What the requesting user's own pull requests get here, and the rule that decided it. */
+ my_result: AutomaticReviewDecision;
+ }
+
+ export interface ReviewRepositoryOverview {
+ /** The listed GitHub App installation. */
+ installation_id: string;
+ /** This project's claim on the installation: 'all', 'selected', or null.
+ *
+ * * `all` - All repositories
+ * * `selected` - Only selected repositories */
+ claim_scope: ReviewInstallationClaimScopeEnum | null;
+ /** One page of repositories. */
+ results: ReviewRepositoryOverviewEntry[];
+ /** Repositories that match the search and the view. */
+ total: number;
+ /** Whether more entries follow this page. */
+ has_more: boolean;
+ /**
+ * Offset of the next page, or null.
+ * @nullable
+ */
+ next_offset: number | null;
+ }
+
+ export interface ReviewRepositoryPersonRequest {
+ /** Id of the project member to add. Must be an active member. */
+ user_id: number;
+ /** Which list to add the person to: 'listed' or 'excepted'.
+ *
+ * * `listed` - Listed
+ * * `excepted` - Excepted */
+ kind: ReviewRepositoryPersonKindEnum;
+ }
+
+ export interface ReviewRepositoryWrite {
+ /**
+ * The GitHub App installation that sees the repository, from the overview.
+ * @maxLength 64
+ */
+ installation_id: string;
+ /**
+ * GitHub repository in 'owner/name' form, spelled as GitHub returns it.
+ * @maxLength 200
+ */
+ full_name: string;
+ /**
+ * GitHub's id of the repository, from the overview. Keeps renames.
+ * @minimum 1
+ */
+ github_repo_id?: number;
+ /** True includes the repository into this project, also when another project takes all repositories of the installation. False removes it; with an 'only selected' claim its exception goes too. */
+ selected?: boolean;
+ /** The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository follows the project rule again. Omit it to keep the current value.
+ *
+ * * `everyone` - Automatic Flash for everyone
+ * * `listed` - Automatic Flash for these people
+ * * `off` - Automatic Flash opt-in only */
+ flash_for?: AutomaticFlashForEnum | null;
+ }
+
+ export interface ReviewRepositoryWriteResponse {
+ /** The repository entry after the write. Null when nothing is left to store, so the entry was deleted and the repository follows the project rule or left the project. */
+ repository: ReviewRepository | null;
+ /** The project that took all repositories of the installation, when this write took the repository from it. */
+ taken_from_project: ReviewProjectRef | null;
+ }
+
/**
* Request body for asking stamphog to review one pull request.
*/
@@ -95097,6 +95638,20 @@ export namespace Schemas {
pr_number: number;
}
+ /**
+ * * `flash_after_full` - Flash after a published Full review
+ * * `resolution_not_opted_in` - The pull request owner has not opted in to resolution
+ * * `internal_feature` - Not available in this project
+ */
+ export type ReviewRequestRefusalEnum = typeof ReviewRequestRefusalEnum[keyof typeof ReviewRequestRefusalEnum];
+
+
+ export const ReviewRequestRefusalEnum = {
+ FlashAfterFull: 'flash_after_full',
+ ResolutionNotOptedIn: 'resolution_not_opted_in',
+ InternalFeature: 'internal_feature',
+ } as const;
+
/**
* The review run a request points at.
*/
@@ -95128,13 +95683,19 @@ export namespace Schemas {
export interface ReviewTriggerError {
/** Human-readable explanation of why the trigger was rejected. */
error: string;
+ /** Why the request was refused, for a client that shows its own reason: 'flash_after_full' (the PR already has a published Full review), 'resolution_not_opted_in' (the PR owner has not turned on resolving comments), 'internal_feature' (the run mode is not available in this project). Absent for other errors.
+ *
+ * * `flash_after_full` - Flash after a published Full review
+ * * `resolution_not_opted_in` - The pull request owner has not opted in to resolution
+ * * `internal_feature` - Not available in this project */
+ code?: ReviewRequestRefusalEnum;
}
/**
- * * `review` - review
- * * `review_only` - review_only
- * * `resolve_only` - resolve_only
- * * `flash` - flash
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Flash
*/
export type ReviewTriggerRequestRunModeEnum = typeof ReviewTriggerRequestRunModeEnum[keyof typeof ReviewTriggerRequestRunModeEnum];
@@ -95149,12 +95710,12 @@ export namespace Schemas {
export interface ReviewTriggerRequest {
/** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */
pr_url: string;
- /** What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.
+ /** What to run on the pull request. 'review' (default) reviews it and, when the pull request owner's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads, which needs the owner's opt-in; 'flash' uses a lower-cost model for the review passes and validation, never resolves comments, and is refused once the PR has a published Full review. The owner is the PR's author, or the Inbox reviewer of a pull request the PostHog app opened.
*
- * * `review` - review
- * * `review_only` - review_only
- * * `resolve_only` - resolve_only
- * * `flash` - flash */
+ * * `review` - Review
+ * * `review_only` - Review only
+ * * `resolve_only` - Resolve only
+ * * `flash` - Flash */
run_mode?: ReviewTriggerRequestRunModeEnum;
}
@@ -95166,33 +95727,30 @@ export namespace Schemas {
}
export interface ReviewUserSettings {
- /** Automatically review pull requests opened by self-driving implementations from the user's Inbox: ReviewHog reviews each one and posts its findings to the pull request. */
+ /** Automatic reviews of the user's own pull requests in every repository this project reviews: 'follow' (default) uses each repository's rule, 'flash' gives automatic Flash everywhere, and 'off' turns automatic Flash off everywhere. A choice for one repository wins over this default.
+ *
+ * * `follow` - Follow each repository
+ * * `flash` - Flash everywhere
+ * * `off` - Off everywhere */
+ default_review_mode?: DefaultReviewModeEnum;
+ /** After a Full review of the user's pull requests is published, run the resolution stage: triage the unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. Off by default. Personal only: no project default applies. */
+ resolve_comments?: boolean;
+ /** Minimum priority a validated Full review finding needs to be published: 'consider' publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues. Without the user's own value the project default applies.
+ *
+ * * `consider` - Consider (all)
+ * * `should_fix` - Should fix
+ * * `must_fix` - Must fix */
+ urgency_threshold?: UrgencyThresholdEnum;
+ /** Show a fun image in the review comment when a Full review of the user's pull requests finds nothing to raise. Without the user's own value the project default applies. */
+ celebrate_clean_reviews?: boolean;
+ /** Review the pull requests the agent opens for Inbox reports assigned to the user: ReviewHog reviews each one and posts its findings to the pull request. Off by default. */
review_inbox_prs?: boolean;
/** Also have hosted Stamphog review those same Inbox pull requests: an approve-first review that posts a real GitHub approval when the change passes, and a comment when it doesn't. Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected). */
stamphog_review_inbox_prs?: boolean;
- /** Review the user's pull requests when the trigger label is added on GitHub. On by default; turning it off makes the label trigger skip PRs this user authored. */
- review_labeled_prs?: boolean;
- /** After a review of the user's pull requests is published, run the resolution stage: triage the PR's unresolved review threads, implement the worth-and-safe fixes on the PR branch, and reply on every thread. On by default; turning it off makes reviews stop at publishing. */
- resolve_comments?: boolean;
- /** Show a fun image in the review comment when a review of this user's pull requests finds nothing to raise. On by default; turning it off makes clean reviews end with the text summary only. */
- celebrate_clean_reviews?: boolean;
- /** Automatically review pull requests authored by this user in PostHog/posthog in Flash mode. Off by default. Flash reviews post findings without resolving comments. */
- review_authored_prs?: boolean;
- /** Reasoning effort for this user's automatic and manually requested Flash reviews: 'medium' (default) or 'xhigh'. Applies to both review and validation. Saved independently of the automatic-review toggle.
- *
- * * `medium` - Medium
- * * `xhigh` - Extra high */
- flash_reasoning_effort?: ReviewUserSettingsFlashReasoningEffortEnum;
- /** Minimum priority a validated finding needs to be published: 'consider' (default) publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only blocking issues.
- *
- * * `consider` - Consider
- * * `should_fix` - Should Fix
- * * `must_fix` - Must Fix */
- urgency_threshold?: ReviewUserSettingsUrgencyThresholdEnum;
- /** Whether reviews can be started from this project's Code review page. */
- readonly can_trigger_reviews: boolean;
- /** Whether to show Flash mode and settings for automatic, label-triggered, and Inbox reviews. */
- readonly show_internal_features: boolean;
+ /** Where each effective value comes from. A value equal to the inherited one is never stored, so writing the project default or the built-in default makes the source follow it again. */
+ readonly sources: ReviewPreferenceSources;
+ /** The project defaults the Full review preferences fall back to. */
+ readonly project_defaults: ReviewProjectDefaults;
/** Whether this project has at least one synced, enabled Stamphog repository. When false, the stamphog_review_inbox_prs toggle has nothing to act on and the UI renders it disabled with a pointer to connect the Stamphog GitHub App. */
readonly stamphog_connected: boolean;
}
@@ -115845,6 +116403,9 @@ export namespace Schemas {
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
+ * * `ReviewRepository` - ReviewRepository
+ * * `ReviewProjectSettings` - ReviewProjectSettings
+ * * `ReviewInstallationClaim` - ReviewInstallationClaim
* @minLength 1
*/
scope?: ActivityLogListScope;
@@ -115951,6 +116512,9 @@ export namespace Schemas {
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
+ ReviewRepository: 'ReviewRepository',
+ ReviewProjectSettings: 'ReviewProjectSettings',
+ ReviewInstallationClaim: 'ReviewInstallationClaim',
} as const;
/**
@@ -116043,6 +116607,9 @@ export namespace Schemas {
* * `Billing` - Billing
* * `Loop` - Loop
* * `StamphogRepoConfig` - StamphogRepoConfig
+ * * `ReviewRepository` - ReviewRepository
+ * * `ReviewProjectSettings` - ReviewProjectSettings
+ * * `ReviewInstallationClaim` - ReviewInstallationClaim
*/
export type ActivityLogListScopesItem = typeof ActivityLogListScopesItem[keyof typeof ActivityLogListScopesItem];
@@ -116137,6 +116704,9 @@ export namespace Schemas {
Billing: 'Billing',
Loop: 'Loop',
StamphogRepoConfig: 'StamphogRepoConfig',
+ ReviewRepository: 'ReviewRepository',
+ ReviewProjectSettings: 'ReviewProjectSettings',
+ ReviewInstallationClaim: 'ReviewInstallationClaim',
} as const;
export type AdvancedActivityLogsListParams = {
@@ -125180,6 +125750,50 @@ export namespace Schemas {
offset?: number;
};
+ export type ReviewHogRepositoryOverviewRetrieveParams = {
+ /**
+ * The GitHub App installation to list.
+ * @minLength 1
+ * @maxLength 64
+ */
+ installation_id: string;
+ /**
+ * Entries per page (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number;
+ /**
+ * Entries to skip.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Only repositories whose name contains this text.
+ */
+ search?: string;
+ /**
+ * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), or 'mine' (with the requesting user's own choice).
+ *
+ * * `all` - All repositories
+ * * `in_project` - In this project
+ * * `exceptions` - With exceptions
+ * * `mine` - My choices
+ * @minLength 1
+ */
+ view?: ReviewHogRepositoryOverviewRetrieveView;
+ };
+
+ export type ReviewHogRepositoryOverviewRetrieveView = typeof ReviewHogRepositoryOverviewRetrieveView[keyof typeof ReviewHogRepositoryOverviewRetrieveView];
+
+
+ export const ReviewHogRepositoryOverviewRetrieveView = {
+ All: 'all',
+ InProject: 'in_project',
+ Exceptions: 'exceptions',
+ Mine: 'mine',
+ } as const;
+
export type ReviewHogReviewsListParams = {
/**
* Maximum rows to return. The list grows this instead of paging by offset — in-progress rows reorder the list between refreshes, so offset pages would shift under the reader.
diff --git a/services/mcp/src/generated/review_hog/api.ts b/services/mcp/src/generated/review_hog/api.ts
index f39073d5c9bb..8e679cb14df2 100644
--- a/services/mcp/src/generated/review_hog/api.ts
+++ b/services/mcp/src/generated/review_hog/api.ts
@@ -56,7 +56,7 @@ export const ReviewHogReviewsRetrieveParams = () => zod.object({
})
/**
- * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, urgency threshold, and resolution criteria drive the run, and it appears under their recent reviews. `run_mode` picks the variant: a review (which chains the resolution stage per the user's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it appears under their recent reviews. Resolution writes to the branch only when the pull request owner opted in, whoever asks. `run_mode` picks the variant: a review (which chains the resolution stage per the owner's resolve_comments setting), a review without resolving, resolution only, or a lower-cost Flash review that never resolves comments and is refused after a published Full review. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run (resolve_only skips that check — settling threads on a reviewed head is its whole point), and triggering a PR whose run is currently in flight joins that run. Otherwise non-blocking: returns the Temporal workflow id immediately while the run executes in the worker.
* @summary Start a review of a pull request
*/
export const ReviewHogReviewsTriggerCreateParams = () => zod.object({
@@ -78,10 +78,10 @@ export const ReviewHogReviewsTriggerCreateBody = () => zod.object({
run_mode: zod
.enum(['review', 'review_only', 'resolve_only', 'flash'])
.describe(
- '\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash'
+ '\* `review` - Review\n\* `review_only` - Review only\n\* `resolve_only` - Resolve only\n\* `flash` - Flash'
)
.default(reviewHogReviewsTriggerCreateBodyRunModeDefault)
.describe(
- "What to run on the pull request. 'review' (default) reviews it and, when the requesting user's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads; 'flash' uses a lower-cost model for the review passes and validation, and never resolves comments.\n\n\* `review` - review\n\* `review_only` - review_only\n\* `resolve_only` - resolve_only\n\* `flash` - flash"
+ "What to run on the pull request. 'review' (default) reviews it and, when the pull request owner's resolve_comments setting is on, chains the resolution stage; 'review_only' reviews without resolving regardless of that setting; 'resolve_only' skips the review and only runs the resolution stage on the PR's existing unresolved review threads, which needs the owner's opt-in; 'flash' uses a lower-cost model for the review passes and validation, never resolves comments, and is refused once the PR has a published Full review. The owner is the PR's author, or the Inbox reviewer of a pull request the PostHog app opened.\n\n\* `review` - Review\n\* `review_only` - Review only\n\* `resolve_only` - Resolve only\n\* `flash` - Flash"
),
})