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): route reviewer effort by PR origin and signal priority (#90567)

Alex Lebedev3ffcddbb24d3
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 9c10eeeec2a2..db2ecd5d5f46 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -171,7 +171,6 @@
1 products/review_hog/backend/reviewer/persistence.py
1 products/review_hog/backend/reviewer/tests/test_select_perspectives.py
1 products/review_hog/backend/reviewer/tools/publish_review.py
-1 products/review_hog/backend/temporal/types.py
1 products/review_hog/backend/tests/test_prompt_injection_guards.py
1 products/signals/backend/scout_harness/inactivity.py
1 products/signals/backend/scout_harness/tools/report.py
@@ -1504,7 +1503,7 @@
2 products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
2 products/web_analytics/backend/path_cleaning_suggestions/service.py
22 products/batch_exports/backend/service.py
-26 products/review_hog/backend/temporal/activities.py
+23 products/review_hog/backend/temporal/activities.py
3 ee/api/vercel/types.py
3 ee/clickhouse/views/test/test_clickhouse_trends.py
3 posthog/api/app_metrics2.py
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 43ca53bb2320..9c647fdc5329 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -338,9 +338,15 @@ pr_metadata.head_branch` is threaded (as explicit kwargs, alongside `team_id` /
whose threshold it was (the author's / the requester's / the default, from `resolved_from`) plus a
"View them in PostHog" deep link to the exact report (`/project/<team>/code-review?review=<report id>`,
a **permanent public contract** — the frontend URL sync and `report_deep_link` must keep agreeing on it).
- After the publish stage the workflow captures a **`reviewhog_review_completed`** product-analytics event —
- one per finalized turn (published or stored), carrying repository / PR / trigger / finding-count / PR-size
- properties (`track_review_completed_activity`). Best-effort: telemetry can never fail a review.
+ The workflow captures one **`reviewhog_review_started`** product-analytics event per turn that passed every
+ gate (`track_review_started_activity`) and, after the publish stage, one **`reviewhog_review_completed`** per
+ finalized turn (published or stored), carrying repository / PR / trigger / finding-count / PR-size properties
+ (`track_review_completed_activity`); a dead turn gets `reviewhog_review_failed` instead. All three, and the
+ per-finding `reviewhog_finding_outcome`, carry `review_routing_properties` (`reviewer/telemetry.py`): the tier,
+ the reviewer arm as resolved for that report, and the validator / resolver pins, so every event says which
+ model and effort the review spent. Started carries the arm as the turn began; completed the arm at the end,
+ which differs when a person's trigger lifted the tier mid-turn or, rarely, when the registry dropped the
+ arm's model mid-turn (`review_arm_fallback`). Best-effort: telemetry can never fail a review.
---
@@ -384,17 +390,31 @@ only separates the fleet's Modal cost from user-driven runs.
persists the full agent log at `task_run.log_url` (S3 / Tasks UI), so the executor never copies it locally.
The perspective review (the blind-spot sweep rides the same activity) runs on a different model family than the
-rest — **OpenAI Codex `gpt-5.6-sol` @ `xhigh`**, with `initial_permission_mode="full-access"`. The pins are per
-**report**, not per process: each `ReviewReport` persists a **review arm** (adapter / model / effort / permission
-mode), drawn once at report creation from the weighted `REVIEW_EXPERIMENT_ARMS` (`constants.py`; currently the
-single default arm above) and kept for the report's life, so a model A/B never mixes arms within one report.
-`load_review_arm` → `resolve_review_arm` honors a persisted assignment only while it stays a registry-supported
-combo — anything else falls back to the default pins and stamps `review_arm_fallback` on the run's analytics
-events — so reports assigned an arm that later left the lineup keep running it while its combo stays registered.
-Chunking, dedup, and the validator stay on Claude. See [DECISIONS.md](./DECISIONS.md) for the Sonnet-vs-Sol
-production A/B that picked this default (and the `full-access` permission-mode gotcha headless Codex needs), and
-[Selecting the sandbox model & reasoning effort](#selecting-the-sandbox-model--reasoning-effort) below for the
-two-repo path that applies these knobs.
+rest — **OpenAI Codex `gpt-5.6-sol`**, with `initial_permission_mode="full-access"`, at an effort set by the
+report's **review tier**. The pins are per **report**, not per process: each `ReviewReport` persists a **review
+arm** (adapter / model / effort / permission mode) plus the tier it was chosen from (`review_tier`, and for agent
+PRs the Signals priority that placed it there, `review_signal_priority`), decided once at report creation and kept
+for the report's life, so a report never mixes arms across turns. The tier table (`REVIEW_ARMS_BY_TIER`,
+`constants.py`): a person's PR → `human` (xhigh); an **agent PR** — a report created with a Signals link, which
+only the inbox trigger passes — routes by the report's priority **as it stood when the implementation task was
+created** (the inbox receiver reads the latest `priority_judgment` with a `created_at < task.created_at` cut-off via
+`persisted_report_priority` and passes it into the workflow inputs; the implementation agent can append judgments
+through the artefact API, so a later one must not pick its own review's effort): P0/P1 → xhigh, P2 → medium,
+P3/P4 → low, no readable judgment
+→ `agent_unprioritized` at xhigh with a warning. One exception to stickiness: a person's trigger (label / UI /
+CLI) that starts a **review** of a report in a cheaper tier lifts it to `human` for that and every later turn,
+never the reverse; a resolve-only run upserts the same row but does not lift (`lift_tier_on_human_trigger`). A
+person's trigger that lands while the report's review is still running joins that run (`USE_EXISTING`), so the
+trigger endpoints write the lift themselves (`lift_review_tier_for_joined_trigger`) and answer
+`joined_running_review`: the turn's remaining units and every later turn run at human strength. The
+cheaper arms are rolled out per team through the `REVIEWHOG_TEAM_IDS` dogfood gate; other teams 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
+pins; the resolution stage runs the validator's model (`claude-opus-5` @ xhigh). See [DECISIONS.md](./DECISIONS.md)
+for the Sonnet-vs-Sol production A/B that picked Sol (and the `full-access` permission-mode gotcha headless Codex
+needs) and for the tier decision, and [Selecting the sandbox model & reasoning
+effort](#selecting-the-sandbox-model--reasoning-effort) below for the path that applies these knobs.
`backend/reviewer/sandbox/code_context.py` is pure-local: `prepare_code_context(chunk_filenames, pr_files)`
emits Claude-Code-style `@path#Lstart-end` references for the changed line ranges of each file (merging
@@ -427,18 +447,19 @@ that any future merge must preserve: `MultiTurnSession.start(prompt, context, mo
### Selecting the sandbox model & reasoning effort
-Read this before testing another model (Sonnet, a new Codex model, a different effort). It is a **two-repo path**:
-`posthog/posthog` _sets_ the knobs and the `@posthog/agent` package _applies_ them. A pinned run is three values —
+Read this before testing another model (Sonnet, a new Codex model, a different effort). It is a **two-package
+path**: the Django side _sets_ the knobs and the `@posthog/agent` package _applies_ them. A pinned run is three values —
`runtime_adapter` + `model` + `reasoning_effort`; `provider` is _derived_ from the adapter (`claude → anthropic`,
`codex → openai`), never set by hand.
-**`posthog/posthog` — where the knobs are set + validated.**
+**The Django side — where the knobs are set + validated.**
- **Pick the values (ReviewHog):** `reviewer/constants.py` `REVIEW_{RUNTIME_ADAPTER,MODEL,REASONING_EFFORT,INITIAL_PERMISSION_MODE}`
- feed `DEFAULT_REVIEW_ARM`; `review_chunk_activity` loads the report's persisted arm (`load_review_arm` →
- `resolve_review_arm`) and passes it as kwargs to `run_sandbox_review` (`reviewer/sandbox/executor.py`), which
- threads them onto the `CustomPromptSandboxContext`. To change the reviewer fleet-wide, change the pins; to A/B
- another model, add a weighted arm to `REVIEW_EXPERIMENT_ARMS` (the executor kwargs exist for every single-turn stage).
+ feed `DEFAULT_REVIEW_ARM` (the `human` tier's arm), and `REVIEW_ARMS_BY_TIER` derives the cheaper tiers from it;
+ `review_chunk_activity` loads the report's persisted arm (`load_review_arm` → `resolve_review_arm`) and passes it
+ as kwargs to `run_sandbox_review` (`reviewer/sandbox/executor.py`), which threads them onto the
+ `CustomPromptSandboxContext`. To change the reviewer fleet-wide, change the pins; to change one tier, change its
+ entry in `REVIEW_ARMS_BY_TIER` (the executor kwargs exist for every single-turn stage).
- **The registry (source of truth for what's allowed)** — `products/tasks/backend/temporal/process_task/utils.py`,
re-exported framework-free from the facade `products/tasks/backend/facade/run_config.py` (import from the facade):
`RuntimeAdapter` (`claude|codex`), `LLMProvider`, `ReasoningEffort`, `RUNTIME_PROVIDER_BY_ADAPTER`,
@@ -452,24 +473,32 @@ reasoning_effort}]` → `get_task_processing_context` reads it back → `start_a
`build_agent_runtime_env_prefix` (`logic/services/sandbox.py`) emits
`POSTHOG_CODE_{RUNTIME_ADAPTER,PROVIDER,MODEL,REASONING_EFFORT}` env prefixed onto the agent launch command.
-**`@posthog/agent` — where they are consumed + applied** (the PostHog Desktop monorepo, _not_ this repo; clone via
-`LOCAL_POSTHOG_CODE_MONOREPO_ROOT`, package `packages/agent`, baked into `Dockerfile.sandbox-base`).
+**`@posthog/agent` — where they are consumed + applied** (`products/desktop/packages/agent` in this repo). The sandbox
+image (`products/tasks/backend/sandbox/images/Dockerfile.sandbox-base`) installs the _published_ package by default, so
+an agent-side fix reaches reviews only once it is published and the image rebuilt; set
+`LOCAL_POSTHOG_CODE_MONOREPO_ROOT` to build the local package into the image instead.
- **Entry `src/server/bin.ts`** reads + zod-validates `POSTHOG_CODE_{RUNTIME_ADAPTER,MODEL,REASONING_EFFORT}`, guards
with `isSupportedReasoningEffort` (`src/adapters/reasoning-effort.ts` — the agent-side mirror of the Python
registry; hard-errors server startup on an unsupported combo), then constructs the `AgentServer`.
-- **Adapter split `src/server/agent-server.ts`:** Codex → `src/adapters/codex/spawn.ts::buildConfigArgs` pushes
- `-c model="…"` **and** `-c model_reasoning_effort="…"` onto the Codex CLI (this is the line that applies `xhigh` to
- `gpt-5.6-sol`); Claude → `buildClaudeCodeSessionMeta` sets `options.model` + `options.effort` (effort only for the
- claude adapter). `agent.ts` fetches the gateway model allow-list and **silently drops the model if it isn't served**
- (`sanitizedModel` / `allowedModelIds`), so a typo'd/unavailable model falls back to a default rather than erroring —
- verify `$ai_model` on every run when switching.
+- **Adapter split:** Codex → `src/adapters/codex-app-server/session-config.ts::collaborationModeForTurn` sends
+ `{ mode, settings: { model, reasoning_effort } }` as the per-turn `collaborationMode` (codex applies a provided
+ collaboration mode as is and ignores the turn's `effort` param when one is sent, so the pinned effort has to ride
+ along here or every turn runs at the model's default effort — this is the line that applies a tier's effort to
+ `gpt-5.6-sol`); Claude → the claude adapter's session config sets the model and effort (effort only for the claude
+ adapter). Startup validation (`bin.ts` + `isSupportedReasoningEffort`) checks the model/effort combo against the
+ registry, but **not** that the gateway actually serves the model. The sandbox reviewer path has no allow-list fallback:
+ `_doInitializeSession` → `createAcpConnection` passes the pinned `model` straight to codex (no `gatewayModels`, so
+ `SessionConfigState.allowedModelIds` stays unset), so a pin to an unserved model **fails review turns instead of
+ falling back to a default**. The `sanitizedModel` / `allowedModelIds` downgrade lives only in `agent.ts::Agent.run`
+ (the local desktop path); the claude adapter's `resolveInitialModelId` fallback covers Claude but not the codex
+ reviewer arm — verify `$ai_model` **and `$ai_effort`** on the review generations whenever a pin changes.
**Recipe — testing e.g. Sonnet.** Set `runtime_adapter = "claude"`, `model` a key in `CLAUDE_REASONING_EFFORTS_BY_MODEL`,
and an effort that model supports; provider auto-derives to `anthropic`. For a new Codex model: `runtime_adapter =
"codex"`, `model` in `CODEX_MODELS`, effort in `CODEX_REASONING_EFFORTS` (`xhigh`/`max` only for models in the
-`CODEX_XHIGH/MAX_REASONING_MODELS` tiers). A brand-new model/effort must be added to the registry in **both** repos (`utils.py`
-here + `reasoning-effort.ts` / the gateway model list in `@posthog/agent`) or startup validation rejects it on one side.
+`CODEX_XHIGH/MAX_REASONING_MODELS` tiers). A brand-new model/effort must be added to the registry on **both** sides
+(`utils.py` + `reasoning-effort.ts` / the gateway model list in `@posthog/agent`) or startup validation rejects it on one side.
---
@@ -560,9 +589,10 @@ IDOR rule) via `class X(UUIDModel, TeamScopedRootMixin)`:
fetched metadata every turn — powers the "For you" scope's authored-PRs match), `run_urgency_threshold` (the
gate the last **completed** turn's body/publish ran under, stamped at finalize alongside `run_count` — what
the drawer buckets findings by; null for pre-column turns), the persisted review arm
- (`review_runtime_adapter` / `review_model` / `review_reasoning_effort` / `review_initial_permission_mode`,
- drawn once at creation — see [Sandbox execution layer](#sandbox-execution-layer)), and the
- `signal_report_id` / `trigger_source` provenance.
+ (`review_runtime_adapter` / `review_model` / `review_reasoning_effort` / `review_initial_permission_mode`) with
+ the tier it came from (`review_tier`, `review_signal_priority` — decided once at creation, lifted only by a
+ person's trigger; see [Sandbox execution layer](#sandbox-execution-layer)), and the `signal_report_id` /
+ `trigger_source` provenance.
- **`ReviewReportArtefact`** — the append-only work log mirroring `SignalReportArtefact`, with a funnel that
derives `type` from the content-model class and maps `ArtefactAttribution` → `created_by_id` / `task_id`.
`ArtefactType`: `issue_finding`, `validation_verdict`, `task_run`, `commit`, `code_reference`, `note`, plus
@@ -615,7 +645,9 @@ See [DECISIONS.md](./DECISIONS.md) for the "reuse the leaf, own the model" bound
**Triggers.** Five entry points drive the same `ReviewPRWorkflow`: the `run_review` CLI (manual / eval), the
`reviewhog` **label** on a `PostHog/posthog` PR (a thin GitHub Action → `POST /api/review_hog/trigger`), a **UI**
"Review this PR" field in the Code review scene (any installation-accessible PR), an **inbox** trigger (a
-`TaskRun` receiver auto-reviews self-driving Signals implementations), and **MCP tools**
+`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), and **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. The UI and
MCP paths are one surface: the viewset carries the grantable `review_hog` scope (`review_hog:read` for list /
diff --git a/products/review_hog/CONTEXT.md b/products/review_hog/CONTEXT.md
index 54991d397e45..8d0471950f9f 100644
--- a/products/review_hog/CONTEXT.md
+++ b/products/review_hog/CONTEXT.md
@@ -10,6 +10,8 @@ Vocabulary settled while working on the product. Pure vocabulary — no spec, no
- **Verify, don't restate** — the rule for validator argumentation: it is the _verification delta_ (what was checked, what was found with file:line evidence, confirmed impact, priority rationale), never a restatement of the finding body's claim. Safe because the full body always travels with the argumentation — every consumer, human or LLM, receives both in the same comment or payload.
- **Adopted skill** — a review skill created by copying an existing team skill under a `review-hog-<kind>-` prefixed name (the "Use an existing skill" flow), as opposed to one authored by the "Create your own" agent task. A fork, not a reference: edits to the source skill do not reach the copy, and the adopting user is the copy's author (see ADR 0002).
- **Report status (`active` / `idle` / `closed`)** — the report-level at-work flag: `active` while any run (a review turn or a resolution run) is working the report, `idle` at rest, `closed` retired. A publishing turn holds `active` through the GitHub publish, so `idle` always implies the published state is final. The UI reads a row as in-progress from `active` plus recent activity, so a crashed run ages out of view instead of reading as running forever.
+- **Agent PR** — a PR opened by a self-driving implementation of a Signals report, recognized by the report link present when the review report is created (only the inbox trigger passes one). An agent PR a person triggers by label or from the UI counts as a person's PR.
+- **Review tier** — the routing bucket a report's reviewer arm is chosen from, decided once when the report is created: `human` for a person's PR, `agent_p0_p1` / `agent_p2` / `agent_p3_p4` for an agent PR by its report's priority, `agent_unprioritized` when that priority cannot be read. A tier names the bucket, not the arm: the table maps buckets to efforts and may change while the labels stay. Sticky for the report's life, with one exception: a person's trigger lifts a cheaper tier to `human`, never the reverse.
## Resolution stage (the "implement the fixes" flow)
diff --git a/products/review_hog/DECISIONS.md b/products/review_hog/DECISIONS.md
index 12e8a07e018f..354131bf7328 100644
--- a/products/review_hog/DECISIONS.md
+++ b/products/review_hog/DECISIONS.md
@@ -198,6 +198,56 @@ read `FINAL_REPORT.md` there first (config glossary + coverage matrix + ranking)
rate drops materially (toward ≤50%) on frozen-PR evals with the valid-finding set intact (item 5's
coverage matrix as the guard); kill if valid findings drop with the noise.
+### ✅ BUILT 2026-08-27 — reviewer tier by PR origin and Signals priority (agent PRs review cheaper; branch-only inbox reviews retired; resolver on Opus 5)
+
+- **What.** The reviewer's effort is no longer one fleet-wide pin. Each `ReviewReport` is placed in a **review
+ tier** when it is created (`select_review_tier`, `REVIEW_ARMS_BY_TIER` in `reviewer/constants.py`): a person's
+ PR → `human` (Sol @ xhigh); an **agent PR** (a report created with a Signals link, which only the inbox trigger
+ passes) → by the report's latest priority judgment, P0/P1 → xhigh, P2 → medium, P3/P4 → low, no readable
+ judgment → `agent_unprioritized` at xhigh with a warning. The priority is the one the report carried when the
+ implementation task was created: the inbox receiver reads it with a `created_at < task.created_at` cut-off
+ (`persisted_report_priority`) and passes it into the workflow inputs, so the implementation agent — which holds
+ the `task:write` artefact tool that appends judgments — cannot lower the effort of its own review (ReviewHog
+ finding on the PR). The tier and the priority used are persisted
+ beside the arm (`review_tier`, `review_signal_priority`; migration 0031) and labeled on the review events
+ (`review_tier`, `signal_priority`, `signal_report_id`, plus `turn_trigger_source`, the trigger of THIS turn —
+ the row only remembers the trigger that created it). The validator stays Opus 5 @ xhigh for every tier.
+- **Why.** The 2026-08 validator/reviewer experiment (`eval/experiments/2026-08-validator-model-sol/`) showed the
+ reviewer's effort is the one knob that trades findings for cost predictably: medium keeps about half of xhigh's
+ real findings, low about a third, and only xhigh surfaces issues nobody reported before. Most reviews are agent
+ PRs and most of those sit at P2 or below, where a cheaper review is an acceptable trade; a person's PR, and the
+ agent PRs a person asks about, keep the full review. Start simple, then iterate on the tier telemetry.
+- **Rules that were grilled (2026-08-27; the record with the options that lost is in the maintainer's playground
+ notes, the outcomes here):** the agent-PR predicate is the Signals link at creation, so label/UI-triggered
+ agent PRs route as human in v1 (the branch-name lookup through the tasks facade is the first iteration). The
+ tier is decided **once** at creation (a per-turn re-decision would feed a cheap turn's findings into a stronger
+ turn's "already covered" injection), with one exception: a person's trigger (`HUMAN_TRIGGER_SOURCES`: label,
+ UI, CLI) that starts a review of a cheaper tier **lifts** it to `human` for that and every later turn, never
+ the reverse — the accepted cost is that the lifted turn treats the cheap findings as already covered. The lift
+ is the review fetch's opt-in (`lift_tier_on_human_trigger`), because the resolution stage upserts the same row
+ under the person's trigger and a resolve-only request reviews nothing (found in review). A person's trigger
+ that lands while the review is still running joins it (`USE_EXISTING`) and never reaches that fetch, so the
+ trigger endpoints write the lift themselves and answer `joined_running_review` (ReviewHog finding on the PR:
+ stamphog's refusal hand-off adds the label minutes in, inside that window). A missing priority fails
+ expensive under its own label. The table lives in code, not in per-user or per-team settings (the "single
+ existing threshold knob, no separate inbox threshold" precedent from Stage 6 applies to model choice too), and
+ the cheaper arms roll out per team through the existing `REVIEWHOG_TEAM_IDS` dogfood gate (other teams record
+ their tier but run the default arm). No A/B: the weighted arm draw (`REVIEW_EXPERIMENT_ARMS`) is gone, model
+ selection is deterministic.
+- **Also in this change.** The inbox trigger no longer reviews a pushed branch before its PR opens: a review of a
+ branch whose PR never opens is spend with no reader, and the PR save re-fires the receiver, so waiting costs
+ only the head start (the workflow/client keep their branch-target support; the receiver just never uses it).
+ The resolution stage moves from Opus 4.8 to **Opus 5** @ xhigh (validated outside this repo; a plain pin
+ change, not tiered).
+- **Watch.** Dashboard 1922705 splits reviews, cost per review, and valid findings by `review_tier`, and an
+ executed-effort tile reads the gateway's `$ai_effort` on the review generations — the pinned effort and the
+ executed effort are two different facts (the 2026-08 Tasks effort bug ran every Sol review at `low` for weeks
+ while the pin said xhigh), so a silent regression shows on day one.
+- **Backlog, in order.** (1) Route label/UI-triggered agent PRs by priority too (branch-name lookup through the
+ tasks facade). (2) Skip the blind-spot sweep on P3/P4. (3) A daily budget guard that drops new agent PRs one
+ tier. (4) Only with an experiment: validator at `high` on P3/P4. Parked: a PR-size axis, dollar-value bumps.
+ Excluded: resolver tiering.
+
### ✅ DECIDED 2026-08-21 — label trigger moves onto the GitHub App webhook (additive handler, no second inlet)
- **What.** The `reviewhog` label add reaches ReviewHog as a `pull_request` handler registered in core's
@@ -2794,7 +2844,10 @@ trigger_source=TRIGGER_UI)` → `202 {workflow_id, status}`. The URL is canonica
> fetch, empty-diff skip, branch-keyed rows + PR upgrade) for callers that know a real head branch;
> the receiver rejoins once tasks records the pushed head branch. **→ It rejoined 2026-07-03:
> `output.head_branch` (agent-server-synced pushed head) is that trustworthy carrier — see the
-> 🔁 trigger-redesign note above. The `TaskRun.branch` FIELD stays banned.**
+> 🔁 trigger-redesign note above. The `TaskRun.branch` FIELD stays banned.** **→ Retired again
+> 2026-08-27: the receiver fires on `output.pr_url` only (a review of a branch whose PR never opens
+> is spend with no reader); the client/workflow branch-target support stays. See the reviewer-tier
+> decision near the top.**
>
> **2026-07-03 adversarial review (7 finder dimensions × 3-skeptic refutation panels, findings in
> `/tmp/reviewhog-signals-combination-adversarial-review.md`) — 4 fixes applied:** (1) the confirmed
@@ -2972,10 +3025,12 @@ fleet-level control during alpha).
3. ✅ **The trigger** — the `TaskRun` receiver behind the settings gate. REDESIGNED 2026-07-03
(see the 🔁 note above): fires on the `output`-recording save — `output.pr_url` (PR leg) else
`output.head_branch` (branch leg) — never on completion (successful runs stay `in_progress`
- forever) and never on the `TaskRun.branch` field.
+ forever) and never on the `TaskRun.branch` field. **→ Since 2026-08-27 the receiver fires on
+ `output.pr_url` only; the branch leg is retired (reviewer-tier decision near the top).**
4. ✅ **Branch targets** — PR-by-branch resolve in fetch, the compare fallback (empty diff →
- self-skip), nullable `pr_number` identity + the branch workflow id. Receiver-reachable again
- via `output.head_branch` since the 2026-07-03 trigger redesign.
+ self-skip), nullable `pr_number` identity + the branch workflow id. Receiver-reachable via
+ `output.head_branch` from the 2026-07-03 trigger redesign until 2026-08-27; client/workflow
+ support only since then.
5. ✅ **Dogfood e2e — RAN 2026-07-03** — synthetic report + real Inbox "Create PR" click + real
PR #68141: receiver fired on the `pr_url` save, inbox workflow with creation-time provenance,
single-chunk pipeline, zero findings on the clean typo PR → publish self-skipped → receipt
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index 31cc2c3d32c2..1732364b8ea5 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -30,7 +30,12 @@ from products.review_hog.backend.reviewer.artefact_content import (
from products.review_hog.backend.reviewer.constants import effective_priority
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
-from products.review_hog.backend.reviewer.persistence import load_chunk_set, load_findings_bundle, load_turn_findings
+from products.review_hog.backend.reviewer.persistence import (
+ lift_review_tier_for_joined_trigger,
+ load_chunk_set,
+ load_findings_bundle,
+ load_turn_findings,
+)
from products.review_hog.backend.reviewer.progress import (
IN_PROGRESS_STALE_AFTER,
RESOLUTION_RESOLVING,
@@ -270,7 +275,9 @@ class ReviewTriggerResponseSerializer(serializers.Serializer):
)
status = serializers.CharField(
help_text="Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the "
- "pull request's current commit already has a published review (no new run starts)."
+ "pull request's current commit already has a published review (no new run starts), "
+ "'joined_running_review' when a review was already in flight (no new run starts; a report in a "
+ "cheaper tier is lifted to human strength for the rest of that review and every later one)."
)
@@ -833,6 +840,11 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
ReviewTriggerResponseSerializer({"workflow_id": "", "status": "already_reviewed"}).data,
status=status.HTTP_200_OK,
)
+ # Probed before the start: a same-id start joins the running turn, whose inputs keep the
+ # original trigger, so the requester'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=pr_owner, repo=pr_repo, pr_number=pr_number)
+ )
workflow_id = start_review_pr_workflow(
pr_url=pr_url,
team_id=team_id,
@@ -843,6 +855,15 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
# None = the requester's resolve_comments setting decides; review_only pins it off.
resolve_comments=False if run_mode == RUN_MODE_REVIEW_ONLY else None,
)
+ if joins_running_review:
+ lifted = lift_review_tier_for_joined_trigger(team_id=team_id, repository=repository, pr_number=pr_number)
+ logger.info(
+ f"ReviewHog UI trigger joined running workflow {workflow_id} for {pr_url} (tier lifted={lifted})"
+ )
+ return Response(
+ ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "joined_running_review"}).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
logger.info(f"ReviewHog UI trigger started workflow {workflow_id} for {pr_url} by user {requester_id}")
return Response(
ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,
diff --git a/products/review_hog/backend/api/trigger.py b/products/review_hog/backend/api/trigger.py
index e7d3b54f5fde..f53442e52ad6 100644
--- a/products/review_hog/backend/api/trigger.py
+++ b/products/review_hog/backend/api/trigger.py
@@ -13,6 +13,7 @@ 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,
@@ -53,7 +54,11 @@ class ReviewHogResolveRequestSerializer(serializers.Serializer):
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.")
+ 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 (no new run starts; a report in a cheaper tier is "
+ "lifted to human strength for the rest of that review and every later one)."
+ )
class ReviewHogTriggerErrorSerializer(serializers.Serializer):
@@ -217,6 +222,11 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):
# 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,
@@ -224,6 +234,17 @@ class ReviewHogTriggerViewSet(viewsets.ViewSet):
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,
diff --git a/products/review_hog/backend/migrations/0031_reviewreport_review_signal_priority_and_more.py b/products/review_hog/backend/migrations/0031_reviewreport_review_signal_priority_and_more.py
new file mode 100644
index 000000000000..0fdaad992a4e
--- /dev/null
+++ b/products/review_hog/backend/migrations/0031_reviewreport_review_signal_priority_and_more.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-08-27 20:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("review_hog", "0030_callable_choices"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="reviewreport",
+ name="review_signal_priority",
+ field=models.CharField(blank=True, max_length=4, null=True),
+ ),
+ migrations.AddField(
+ model_name="reviewreport",
+ name="review_tier",
+ field=models.CharField(blank=True, max_length=32, null=True),
+ ),
+ ]
diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txt
index ab60b2f13b18..93239dcc1b47 100644
--- a/products/review_hog/backend/migrations/max_migration.txt
+++ b/products/review_hog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0030_callable_choices
+0031_reviewreport_review_signal_priority_and_more
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index 9f5c9d1b6504..40dbd4ab8d20 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -105,14 +105,20 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
signal_report_id = models.UUIDField(null=True, blank=True)
# Which trigger created this report ("label" / "inbox" / "manual" / "ui"); stamped on create only.
trigger_source = models.CharField(max_length=20, default="manual")
- # Reviewer-model experiment assignment, drawn once at creation and sticky for the report's life
- # (see `REVIEW_EXPERIMENT_ARMS`). Adapter/model/effort/permission-mode persist as one bundle
- # because a model without its adapter can't be routed. NULL on pre-experiment rows; reads
- # resolve through `resolve_review_arm`, which falls back to the REVIEW_* pins.
+ # The reviewer arm, chosen once at creation from the report's tier (see `REVIEW_ARMS_BY_TIER`)
+ # and sticky for the report's life. Adapter/model/effort/permission-mode persist as one bundle
+ # because a model without its adapter can't be routed. NULL on rows created before arms were
+ # persisted; reads resolve through `resolve_review_arm`, which falls back to the REVIEW_* pins.
review_runtime_adapter = models.CharField(max_length=32, null=True, blank=True)
review_model = models.CharField(max_length=128, null=True, blank=True)
review_reasoning_effort = models.CharField(max_length=32, null=True, blank=True)
review_initial_permission_mode = models.CharField(max_length=32, null=True, blank=True)
+ # The routing bucket the arm was chosen from (a `ReviewTier` value) and, for agent PRs, the
+ # Signals priority ("P0".."P4") that placed it there. Stamped with the arm at creation; a
+ # person's trigger can lift the tier later, never lower it. The priority is the value the
+ # decision used, kept because the report's judgment can change afterwards. NULL on pre-tier rows.
+ review_tier = models.CharField(max_length=32, null=True, blank=True)
+ review_signal_priority = models.CharField(max_length=4, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/review_hog/backend/receivers.py b/products/review_hog/backend/receivers.py
index cde3dff83cd1..6107f774f81e 100644
--- a/products/review_hog/backend/receivers.py
+++ b/products/review_hog/backend/receivers.py
@@ -16,22 +16,19 @@ is why it only counts when it maps into the assigned set.
The assigned reviewers carry a second, independent toggle: `stamphog_review_inbox_prs` sends the PR
to hosted Stamphog for an approve-first review with a real GitHub approval, through the stamphog
-facade (`queue_inbox_pr_review`). Only when there is a PR, because stamphog's verdict is a GitHub
-review and a bare pushed branch gives it nothing to post to. Any assigned reviewer's opt-in is
-enough, unlike the acting-reviewer gate above: stamphog reads no per-user options, so narrowing it
-to one reviewer would only drop reviews the other assignees asked for. That call queues the first
-review only; later pushes are re-reviewed by stamphog's own webhook path, which re-checks the same
-toggle through the resolver registered in `connect()` (stamphog cannot import review_hog back
-without a dependency cycle).
-
-Review targets, in priority order:
-- `output.pr_url` → the PR leg: full review, published to the PR. Written by the agent server when
- it observes the agent open the PR, or by the GitHub-webhook backstop (`tasks/webhooks.py`).
-- `output.head_branch` → the branch leg: the pushed work branch, synced by the agent server at the
- end of every agent turn whose current branch changed (`syncCloudBranchMetadata`). The review is
- computed and stored (receipt `outcome="stored"`); there is no PR to publish to. When the PR opens
- later, the `pr_url` save re-fires this receiver and the branch-keyed review upgrades to the PR —
- resume at the same head skips recompute and goes straight to publish.
+facade (`queue_inbox_pr_review`). Any assigned reviewer's opt-in is enough, unlike the
+acting-reviewer gate above: stamphog reads no per-user options, so narrowing it to one reviewer
+would only drop reviews the other assignees asked for. That call queues the first review only;
+later pushes are re-reviewed by stamphog's own webhook path, which re-checks the same toggle
+through the resolver registered in `connect()` (stamphog cannot import review_hog back without a
+dependency cycle).
+
+The review target is `output.pr_url`, written by the agent server when it observes the agent open
+the PR, or by the GitHub-webhook backstop (`tasks/webhooks.py`). A pushed branch without a PR
+(`output.head_branch`, synced at the end of every agent turn) is not a target: a review of a branch
+whose PR never opens is spend with no reader, and the PR save re-fires this receiver, so waiting
+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.
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.
@@ -47,7 +44,9 @@ from django.db import transaction
from django.db.models.signals import post_save
from products.review_hog.backend.models import ReviewUserSettings
+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
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.stamphog.backend.facade.inbox_hooks import register_inbox_acting_reviewer_resolver
@@ -72,13 +71,13 @@ def connect() -> None:
def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs: Any) -> None:
- """Start an inbox review when a signals-origin implementation run records a PR or pushed branch.
+ """Start an inbox review when a signals-origin implementation run records its PR.
Fires on every TaskRun save (a hot model), so the checks run cheapest-first and the whole body is
exception-proof — this executes inside tasks' save path and must never raise into it. Repeat
saves with an unchanged target re-fire it deliberately: the deterministic workflow id +
- USE_EXISTING collapse duplicates while a review runs, a same-head re-trigger costs one fetch
- (early-exit), and a transient base-branch `head_branch` self-skips on the empty diff.
+ USE_EXISTING collapse duplicates while a review runs, and a same-head re-trigger costs one fetch
+ (early-exit).
"""
try:
if created:
@@ -93,8 +92,7 @@ def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs:
return
output = instance.output if isinstance(instance.output, dict) else {}
pr_url = output.get("pr_url") or None
- head_branch = output.get("head_branch") or None
- if pr_url is None and head_branch is None:
+ if pr_url is None:
return
task = instance.task # first DB hit
if task.signal_report_id is None:
@@ -109,10 +107,6 @@ def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs:
if (instance.state or {}).get("ai_stage") != "implementation":
return
repository = (task.repository or "").strip() or None
- if pr_url is None and repository is None:
- # The branch leg needs an explicit repo to compare in; the PR leg carries it in the URL.
- logger.info("review_hog_inbox_trigger_skipped: run %s has a branch target but no repository", instance.id)
- return
resolved = _resolve_assigned_reviewers(instance.team_id, task.signal_report_id)
if not resolved:
return
@@ -122,20 +116,24 @@ def handle_task_run_saved(sender: type, instance: Any, created: bool, **kwargs:
# 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.
if settings_by_user[acting_user_id].review_inbox_prs:
+ # The priority as it stood when the implementation task was created. The agent can append
+ # judgments through the artefact API, so a later one may be its own vote on its review.
+ signal_priority = persisted_report_priority(
+ team_id=instance.team_id, report_id=str(task.signal_report_id), before=task.created_at
+ )
transaction.on_commit(
lambda: _start_review(
pr_url=pr_url,
- repository=repository,
- head_branch=head_branch,
team_id=instance.team_id,
user_id=acting_user_id,
signal_report_id=str(task.signal_report_id),
+ signal_priority=signal_priority,
+ repository=repository,
),
robust=True,
)
- if pr_url is not None and stamphog_user_id is not None and repository is not None:
- # Only when there is a PR: stamphog posts a GitHub review, and a bare branch gives it
- # nothing to post to. Queuing a Celery task keeps this save path fast.
+ if stamphog_user_id is not None and repository is not None:
+ # Queuing a Celery task keeps this save path fast.
stamphog_pr_url, stamphog_repository = pr_url, repository
transaction.on_commit(
lambda: _start_stamphog_review(
@@ -264,19 +262,20 @@ def _start_stamphog_review(
def _start_review(
*,
- pr_url: str | None,
- repository: str | None,
- head_branch: str | None,
+ pr_url: str,
team_id: int,
user_id: int,
signal_report_id: str,
+ signal_priority: ReportPriority | None,
+ repository: str | None,
) -> None:
"""Fire-and-forget the review workflow; Temporal being down must never surface into the saver.
- The PR leg wins when both targets are present — the client accepts exactly one, and a PR is the
- strictly better target (publishable, and its head IS the pushed branch). The PR leg also honors
- the busy-guard, the same refusal the trigger/resolve endpoints apply, so an inbox review never
- starts while this PR's resolution run is still committing to the branch.
+ Binds the PR to the task's own repository: `output.pr_url` is written by whoever controls the
+ run, the sandbox agent included, so an unbound URL could aim the team's GitHub credential at any
+ PR the installation reaches (the stamphog leg applies the same rule). Then honors the busy-guard,
+ the same refusal the trigger/resolve endpoints apply, so an inbox review never starts while this
+ PR's resolution run is still committing to the branch.
"""
# Function-local: importing the temporal client executes the review_hog temporal package, whose
# activity registration reaches temporalio, modal, openai, and anthropic — all four forbidden at
@@ -286,47 +285,45 @@ def _start_review(
from products.review_hog.backend.temporal.types import TRIGGER_INBOX, resolve_pr_workflow_id # noqa: PLC0415
try:
- if pr_url is not None:
- # Busy-guard (CONTEXT.md): a published inbox review chains its own resolution, which
- # commits to the branch for minutes — starting a fresh review meanwhile races those
- # pushes and re-reviews threads mid-settlement. Only the PR leg needs it (resolution
- # needs a pr_url, so the branch leg can't collide); the chained hand-off starts
- # resolution as a child workflow, never through this path, so it stays exempt.
- pr_info = PRParser().parse_github_pr_url(pr_url)
- if workflow_running(
- resolve_pr_workflow_id(
- team_id=team_id,
- owner=str(pr_info["owner"]),
- repo=str(pr_info["repo"]),
- pr_number=int(pr_info["pr_number"]),
- )
- ):
- logger.info(
- "review_hog_inbox_review_skipped_busy: resolution still running for %s (signal report %s)",
- pr_url,
- signal_report_id,
- )
- return
- workflow_id = start_review_pr_workflow(
- team_id=team_id,
- user_id=user_id,
- publish=True,
- acting_user_id=user_id,
- trigger_source=TRIGGER_INBOX,
- signal_report_id=signal_report_id,
- pr_url=pr_url,
+ pr_info = PRParser().parse_github_pr_url(pr_url)
+ pr_repository = f"{pr_info['owner']}/{pr_info['repo']}"
+ # GitHub slugs are case-insensitive; the task row lowercases its own.
+ if repository is None or pr_repository.lower() != repository.lower():
+ logger.warning(
+ "review_hog_inbox_review_skipped_repository_mismatch: %s is not in task repository %s (signal report %s)",
+ pr_url,
+ repository,
+ signal_report_id,
)
- else:
- workflow_id = start_review_pr_workflow(
+ return
+ # Busy-guard (CONTEXT.md): a published inbox review chains its own resolution, which
+ # commits to the branch for minutes — starting a fresh review meanwhile races those
+ # pushes and re-reviews threads mid-settlement. The chained hand-off starts resolution
+ # as a child workflow, never through this path, so it stays exempt.
+ if workflow_running(
+ resolve_pr_workflow_id(
team_id=team_id,
- user_id=user_id,
- publish=True,
- acting_user_id=user_id,
- trigger_source=TRIGGER_INBOX,
- signal_report_id=signal_report_id,
- repository=repository or "",
- head_branch=head_branch or "",
+ owner=str(pr_info["owner"]),
+ repo=str(pr_info["repo"]),
+ pr_number=int(pr_info["pr_number"]),
+ )
+ ):
+ logger.info(
+ "review_hog_inbox_review_skipped_busy: resolution still running for %s (signal report %s)",
+ pr_url,
+ signal_report_id,
)
+ return
+ workflow_id = start_review_pr_workflow(
+ team_id=team_id,
+ user_id=user_id,
+ publish=True,
+ acting_user_id=user_id,
+ trigger_source=TRIGGER_INBOX,
+ signal_report_id=signal_report_id,
+ signal_priority=signal_priority,
+ pr_url=pr_url,
+ )
logger.info("review_hog_inbox_review_started: workflow %s for signal report %s", workflow_id, signal_report_id)
except Exception:
logger.exception("review_hog_inbox_review_start_failed")
diff --git a/products/review_hog/backend/reviewer/constants.py b/products/review_hog/backend/reviewer/constants.py
index 7e2d70b054b6..ec4e23b63a80 100644
--- a/products/review_hog/backend/reviewer/constants.py
+++ b/products/review_hog/backend/reviewer/constants.py
@@ -1,8 +1,9 @@
-import random
import logging
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
+from enum import StrEnum
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority
+from products.signals.backend.enums import ReportPriority
from products.tasks.backend.facade.run_config import (
ReasoningEffort,
RuntimeAdapter,
@@ -36,7 +37,7 @@ REVIEW_MCP_SCOPES: list[str] = ["llm_skill:read", "user:read"]
@dataclass(frozen=True)
class ReviewArm:
- """One reviewer configuration the model experiment can assign to a report.
+ """One reviewer configuration a report's review units run on.
The four fields travel as one bundle: provider routing is derived from the adapter, so a model
handed over without its adapter silently falls back to the agent server's default, and Codex
@@ -56,22 +57,83 @@ DEFAULT_REVIEW_ARM = ReviewArm(
initial_permission_mode=REVIEW_INITIAL_PERMISSION_MODE,
)
-# The reviewer-model arm draw: each new report draws its arm once at creation and keeps it for
-# life, because a per-turn redraw would feed one arm's findings into the other arm's
-# "already covered" injection. Weights are relative shares (`random.choices` normalizes them).
-# Run a model experiment by adding weighted arms here; end it by dropping arms HERE, never by
-# deregistering the model in products/tasks: persisted assignments resolve against the live
-# registry per unit, so a mid-experiment deregistration silently falls in-flight turns back to
-# the default pins, unit by unit. Reports that drew a now-dropped arm keep running it while its
-# combo stays registered, by design.
-REVIEW_EXPERIMENT_ARMS: tuple[tuple[float, ReviewArm], ...] = ((1.0, DEFAULT_REVIEW_ARM),)
+class ReviewTier(StrEnum):
+ """The routing bucket a report's reviewer arm is chosen from; persisted as `ReviewReport.review_tier`.
-def draw_review_arm() -> ReviewArm:
- """The weighted arm draw for a newly created report; persisted once, never redrawn."""
- arms = [arm for _, arm in REVIEW_EXPERIMENT_ARMS]
- weights = [weight for weight, _ in REVIEW_EXPERIMENT_ARMS]
- return random.choices(arms, weights=weights, k=1)[0]
+ Named after the bucket, not the arm it maps to, so a dashboard split by tier keeps reading the
+ same way when the table below moves a bucket to another effort.
+ """
+
+ # A person's PR, or any PR a person explicitly asked to review.
+ HUMAN = "human"
+ # Agent PRs (a self-driving implementation of a Signals report), by the report's priority.
+ AGENT_P0_P1 = "agent_p0_p1"
+ AGENT_P2 = "agent_p2"
+ AGENT_P3_P4 = "agent_p3_p4"
+ # An agent PR whose report carries no readable priority judgment.
+ AGENT_UNPRIORITIZED = "agent_unprioritized"
+
+
+# The tier table. A report is placed in a tier once, when it is created (`upsert_review_report`),
+# and keeps that arm for life: a per-turn re-decision would feed a cheap turn's findings into a
+# stronger turn's "already covered" injection. Lower-priority agent PRs trade findings for cost:
+# in the 2026-08 reviewer experiment (eval/experiments/2026-08-validator-model-sol/FINAL_REPORT.md)
+# medium kept about half of xhigh's real findings, low about a third, and only xhigh surfaced
+# issues nobody reported before. A missing priority fails expensive on purpose, because an
+# over-review costs dollars and an under-review costs a missed bug. The validator runs its own pins
+# for every tier. Change a bucket's arm HERE, never by deregistering the model in products/tasks:
+# persisted arms resolve against the live registry per unit, so a deregistration silently falls
+# in-flight turns back to the default pins, unit by unit.
+REVIEW_ARMS_BY_TIER: dict[ReviewTier, ReviewArm] = {
+ ReviewTier.HUMAN: DEFAULT_REVIEW_ARM,
+ ReviewTier.AGENT_P0_P1: DEFAULT_REVIEW_ARM,
+ ReviewTier.AGENT_P2: replace(DEFAULT_REVIEW_ARM, reasoning_effort=ReasoningEffort.MEDIUM),
+ ReviewTier.AGENT_P3_P4: replace(DEFAULT_REVIEW_ARM, reasoning_effort=ReasoningEffort.LOW),
+ ReviewTier.AGENT_UNPRIORITIZED: DEFAULT_REVIEW_ARM,
+}
+
+_TIER_BY_PRIORITY: dict[ReportPriority, ReviewTier] = {
+ ReportPriority.P0: ReviewTier.AGENT_P0_P1,
+ ReportPriority.P1: ReviewTier.AGENT_P0_P1,
+ ReportPriority.P2: ReviewTier.AGENT_P2,
+ ReportPriority.P3: ReviewTier.AGENT_P3_P4,
+ ReportPriority.P4: ReviewTier.AGENT_P3_P4,
+}
+
+
+# The trigger sources (`temporal/types.py`) that carry an explicit ask for a review: a label, the
+# CLI, or the Code review scene and its MCP tool (both stamped `ui`, so an agent driving the MCP
+# tool on someone's behalf counts as that person asking). Only the inbox trigger fires with nobody
+# asking, and a trigger from this set on an inbox-created report lifts its tier
+# (`upsert_review_report`). Spelled out here because persistence cannot import the temporal
+# package (its `__init__` imports the activities, which import persistence); `test_constants.py`
+# locks the set to the trigger constants.
+HUMAN_TRIGGER_SOURCES = frozenset({"label", "manual", "ui"})
+
+
+def select_review_tier(*, agent_pr: bool, signal_priority: ReportPriority | None) -> ReviewTier:
+ """The tier a new report reviews on, from who opened the PR and how important its report is.
+
+ `agent_pr` is decided by the caller (a Signals report link present at creation). The priority
+ only matters for agent PRs: a person's PR reviews at full strength whatever the report says.
+ """
+ if not agent_pr:
+ return ReviewTier.HUMAN
+ if signal_priority is None:
+ return ReviewTier.AGENT_UNPRIORITIZED
+ return _TIER_BY_PRIORITY[signal_priority]
+
+
+def is_below_human_tier(tier: ReviewTier) -> bool:
+ """Whether a person's re-trigger of a report in `tier` lifts it to the human tier.
+
+ Compared on the arm's effort, so a tier that already runs the human arm (P0/P1, unprioritized)
+ keeps its label: the lift exists to buy a person the stronger review, not to relabel the PR.
+ """
+ efforts = list(ReasoningEffort) # declared weakest first in the tasks registry
+ human_effort = REVIEW_ARMS_BY_TIER[ReviewTier.HUMAN].reasoning_effort
+ return efforts.index(REVIEW_ARMS_BY_TIER[tier].reasoning_effort) < efforts.index(human_effort)
def resolve_review_arm(
@@ -82,10 +144,11 @@ def resolve_review_arm(
) -> ReviewArm:
"""The arm a report's review units actually run on: its persisted assignment, else the pins.
- Missing fields (pre-experiment rows) fall back silently. An assignment that is no longer a
- registry-supported combo also falls back, with a warning, so a persisted model that outlives
- its registration degrades to the default reviewer instead of burning sandbox turns on a
- rejected model.
+ Missing fields (rows created before arms were persisted) fall back silently. An assignment that
+ is no longer a registry-supported combo also falls back, with a warning, so a persisted model
+ that outlives its registration degrades to the default reviewer instead of burning sandbox
+ turns on a rejected model. The fallback is the full-strength arm, so a broken cheap tier costs
+ money rather than findings; the analytics events flag it as `review_arm_fallback`.
"""
if not (runtime_adapter and model and reasoning_effort):
return DEFAULT_REVIEW_ARM
@@ -129,9 +192,9 @@ VALIDATION_INITIAL_PERMISSION_MODE: str | None = None
# RESOLUTION MODEL
# Pins for the resolution stage's warm per-PR session (assess + implement, one thread per turn).
-# Starts on the validator's setup — resolution is judgment + careful editing, the validator's tier.
+# The validator's model and effort: resolution is judgment plus careful editing, the validator's job.
RESOLUTION_RUNTIME_ADAPTER: RuntimeAdapter | None = RuntimeAdapter.CLAUDE
-RESOLUTION_MODEL: str | None = "claude-opus-4-8"
+RESOLUTION_MODEL: str | None = "claude-opus-5"
RESOLUTION_REASONING_EFFORT: ReasoningEffort | None = ReasoningEffort.XHIGH
RESOLUTION_INITIAL_PERMISSION_MODE: str | None = None
diff --git a/products/review_hog/backend/reviewer/outcomes/classify.py b/products/review_hog/backend/reviewer/outcomes/classify.py
index 12a8718fbb59..b8ba924a48d7 100644
--- a/products/review_hog/backend/reviewer/outcomes/classify.py
+++ b/products/review_hog/backend/reviewer/outcomes/classify.py
@@ -62,6 +62,7 @@ from products.review_hog.backend.reviewer.outcomes.github_fetch import fetch_com
from products.review_hog.backend.reviewer.outcomes.judge import judge_finding
from products.review_hog.backend.reviewer.outcomes.line_proximity import parse_compare_files, touched_near
from products.review_hog.backend.reviewer.persistence import load_findings_bundle
+from products.review_hog.backend.reviewer.telemetry import review_routing_properties
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError
from products.signals.backend.artefact_attribution import ArtefactAttribution
@@ -401,6 +402,7 @@ async def _emit_and_mark(
"classification_method": oc.method,
"reviewed_head": oc.reviewed_head,
"final_head": oc.final_head,
+ **review_routing_properties(report),
},
)
if flush is not None:
diff --git a/products/review_hog/backend/reviewer/persistence.py b/products/review_hog/backend/reviewer/persistence.py
index 87e1fc6a188c..44b03c7f8dcd 100644
--- a/products/review_hog/backend/reviewer/persistence.py
+++ b/products/review_hog/backend/reviewer/persistence.py
@@ -27,6 +27,7 @@ import logging
from collections.abc import Sequence
from dataclasses import dataclass, field
+from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
from django.utils import timezone
@@ -46,7 +47,16 @@ from products.review_hog.backend.reviewer.artefact_content import (
ValidationVerdict,
parse_artefact_content,
)
-from products.review_hog.backend.reviewer.constants import ReviewArm, draw_review_arm, resolve_review_arm
+from products.review_hog.backend.reviewer.constants import (
+ DEFAULT_REVIEW_ARM,
+ HUMAN_TRIGGER_SOURCES,
+ REVIEW_ARMS_BY_TIER,
+ ReviewArm,
+ ReviewTier,
+ is_below_human_tier,
+ resolve_review_arm,
+ select_review_tier,
+)
from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuesReview
@@ -54,6 +64,7 @@ from products.review_hog.backend.reviewer.models.perspective_selection import Pe
from products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksList
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import Commit
+from products.signals.backend.enums import ReportPriority
logger = logging.getLogger(__name__)
@@ -66,6 +77,8 @@ def upsert_review_report(
pr_metadata: PRMetadata,
signal_report_id: str | None = None,
trigger_source: str | None = None,
+ signal_priority: ReportPriority | None = None,
+ lift_tier_on_human_trigger: bool = False,
) -> str:
"""Create or fetch the living report for this review target and return its id.
@@ -77,6 +90,14 @@ def upsert_review_report(
turn. Provenance (`signal_report_id`, `trigger_source`) is stamped on create; on update
`signal_report_id` is only filled when missing and `trigger_source` is never overwritten — a
label re-trigger of an inbox PR must not erase where the report came from, nor vice versa.
+
+ The review tier (and with it the reviewer arm) is decided on create from the same provenance:
+ a report created with a Signals link is an agent PR and routes by `signal_priority`; anything
+ else is a person's PR. It stays for the report's life with one exception: a person's trigger
+ (`HUMAN_TRIGGER_SOURCES`) on a report in a cheaper tier lifts it to the human tier, for that
+ turn and every later one. Never the other way round. Only a review turn asks for the lift
+ (`lift_tier_on_human_trigger`): the resolution stage upserts the same row under the person's
+ trigger too, and a resolve-only request buys nobody a stronger review.
Goes through `for_team` because the orchestrator runs outside request context and `ReviewReport`
is fail-closed.
"""
@@ -87,9 +108,14 @@ def upsert_review_report(
qs, repository=repository, pr_number=pr_number, head_branch=pr_metadata.head_branch
)
if report is None:
- # The experiment arm is drawn exactly once, here: the update path below never touches
- # these fields, so every later turn of the report reviews on the same model.
- arm = draw_review_arm()
+ tier = select_review_tier(agent_pr=signal_report_id is not None, signal_priority=signal_priority)
+ if tier is ReviewTier.AGENT_UNPRIORITIZED:
+ logger.warning(
+ "Signal report %s has no readable priority judgment; reviewing %s#%s at full strength",
+ signal_report_id,
+ repository,
+ pr_number,
+ )
create_kwargs: dict[str, object] = {
"team_id": team_id,
"repository": repository,
@@ -100,10 +126,8 @@ def upsert_review_report(
"author_login": pr_metadata.author or None,
"status": ReviewReport.Status.ACTIVE,
"signal_report_id": signal_report_id,
- "review_runtime_adapter": arm.runtime_adapter.value,
- "review_model": arm.model,
- "review_reasoning_effort": arm.reasoning_effort.value,
- "review_initial_permission_mode": arm.initial_permission_mode,
+ "review_signal_priority": signal_priority.value if signal_priority is not None else None,
+ **_review_tier_fields(team_id, tier),
}
if trigger_source is not None:
create_kwargs["trigger_source"] = trigger_source
@@ -136,10 +160,76 @@ def upsert_review_report(
updates["author_login"] = pr_metadata.author
if report.signal_report_id is None and signal_report_id is not None:
updates["signal_report_id"] = signal_report_id
+ persisted_tier = _parse_persisted_tier(report.review_tier)
+ if (
+ lift_tier_on_human_trigger
+ and trigger_source in HUMAN_TRIGGER_SOURCES
+ and persisted_tier is not None
+ and is_below_human_tier(persisted_tier)
+ ):
+ # Accepted cost of the lift: this turn treats the cheap turn's findings as already
+ # covered, the same as any re-turn. Rare enough (a person asking about an agent PR)
+ # that quality for the person wins over a clean re-review.
+ updates.update(_review_tier_fields(team_id, ReviewTier.HUMAN))
qs.filter(pk=report.pk).update(**updates)
return str(report.id)
+def _parse_persisted_tier(value: str | None) -> ReviewTier | None:
+ """The stored tier as a `ReviewTier`, or None if it is empty or a value this deploy doesn't know.
+
+ A tier a newer deploy wrote must not crash an older deploy's upsert, so an unparseable value
+ degrades to None with a warning instead of raising — the same degrade-don't-crash contract the
+ arm read (`resolve_review_arm`) and the artefact reads (`load_chunk_set`, `_load_working_state`)
+ already follow. This read runs on every update-path upsert, so a raise would fail the turn (and
+ its retries) before the review starts. Degrading to None only skips the human-trigger lift for
+ that turn; the persisted tier column is left untouched.
+ """
+ if not value:
+ return None
+ try:
+ return ReviewTier(value)
+ except ValueError:
+ logger.warning("Unknown persisted review tier %r; skipping the human-trigger lift this turn", value)
+ return None
+
+
+def lift_review_tier_for_joined_trigger(*, team_id: int, repository: str, pr_number: int) -> bool:
+ """Lift a report in a cheaper tier to `human` when a person's trigger joins its running review.
+
+ A same-id start joins the in-flight turn (`USE_EXISTING`), so the trigger's source never reaches
+ the fetch upsert and the in-turn lift cannot fire. Written directly instead: the turn's remaining
+ units load the arm per unit, so they already run at human strength, and every later turn does.
+ Returns whether a lift happened.
+ """
+ qs = ReviewReport.objects.for_team(team_id)
+ report = qs.filter(repository__iexact=repository, pr_number=pr_number).first()
+ if report is None:
+ return False
+ persisted_tier = _parse_persisted_tier(report.review_tier)
+ if persisted_tier is None or not is_below_human_tier(persisted_tier):
+ return False
+ qs.filter(pk=report.pk).update(**_review_tier_fields(team_id, ReviewTier.HUMAN))
+ return True
+
+
+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
+ 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
+ return {
+ "review_tier": tier.value,
+ "review_runtime_adapter": arm.runtime_adapter.value,
+ "review_model": arm.model,
+ "review_reasoning_effort": arm.reasoning_effort.value,
+ "review_initial_permission_mode": arm.initial_permission_mode,
+ }
+
+
def load_review_arm(*, team_id: int, report_id: str) -> ReviewArm:
"""The arm this report's review units run on: its persisted assignment resolved with fallback.
diff --git a/products/review_hog/backend/reviewer/telemetry.py b/products/review_hog/backend/reviewer/telemetry.py
new file mode 100644
index 000000000000..36035602efc2
--- /dev/null
+++ b/products/review_hog/backend/reviewer/telemetry.py
@@ -0,0 +1,49 @@
+"""The model and effort labels every ReviewHog analytics event carries."""
+
+from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.constants import (
+ RESOLUTION_MODEL,
+ RESOLUTION_REASONING_EFFORT,
+ VALIDATION_MODEL,
+ VALIDATION_REASONING_EFFORT,
+ resolve_review_arm,
+)
+
+
+def review_routing_properties(report: ReviewReport) -> dict[str, str | bool | None]:
+ """The tier, the reviewer arm, and the fixed validator and resolver pins of a report's reviews.
+
+ Every review event (started, completed, failed, finding outcome) spreads this in, so a dashboard
+ can split any of them by what actually ran. The reviewer arm is resolved, not raw: pre-arm rows
+ carry NULLs but their reviews run on the default pins, and the event must say what ran. The tier
+ and priority are raw: they are the decision as recorded, and NULL means the row predates tiers.
+ The values are the row's as of the call: a per-turn event reads them at that point of the turn,
+ and the finding-outcome event reads the report's arm when the outcome is classified, not the
+ arm of the turn that produced the finding. The validator and resolver are module pins, not per
+ report; they are included so one event names every model a turn spent on.
+ """
+ persisted = (
+ report.review_runtime_adapter,
+ report.review_model,
+ report.review_reasoning_effort,
+ report.review_initial_permission_mode,
+ )
+ arm = resolve_review_arm(*persisted)
+ resolved = (arm.runtime_adapter.value, arm.model, arm.reasoning_effort.value, arm.initial_permission_mode)
+ return {
+ "review_tier": report.review_tier,
+ "signal_priority": report.review_signal_priority,
+ "signal_report_id": str(report.signal_report_id) if report.signal_report_id else None,
+ "review_runtime_adapter": arm.runtime_adapter.value,
+ "review_model": arm.model,
+ "review_reasoning_effort": arm.reasoning_effort.value,
+ # True when a persisted assignment failed resolution and the turn ran the fallback pins
+ # instead of its tier's arm; per-tier dashboards must exclude these contaminated turns.
+ # The whole bundle is compared because a failed assignment can share the default arm's model
+ # string while differing on adapter or effort. Pre-arm rows (all NULL) stay False.
+ "review_arm_fallback": any(persisted) and resolved != persisted,
+ "validator_model": VALIDATION_MODEL,
+ "validator_reasoning_effort": VALIDATION_REASONING_EFFORT.value if VALIDATION_REASONING_EFFORT else None,
+ "resolution_model": RESOLUTION_MODEL,
+ "resolution_reasoning_effort": RESOLUTION_REASONING_EFFORT.value if RESOLUTION_REASONING_EFFORT else None,
+ }
diff --git a/products/review_hog/backend/reviewer/tests/test_constants.py b/products/review_hog/backend/reviewer/tests/test_constants.py
index a78ba701a682..0a094d3f889e 100644
--- a/products/review_hog/backend/reviewer/tests/test_constants.py
+++ b/products/review_hog/backend/reviewer/tests/test_constants.py
@@ -2,6 +2,7 @@ import pytest
from posthog.temporal.oauth import has_write_scopes, resolve_scopes
+import products.review_hog.backend.temporal.types as trigger_types
from products.review_hog.backend.reviewer.constants import (
CHUNKING_MODEL,
CHUNKING_REASONING_EFFORT,
@@ -10,7 +11,11 @@ from products.review_hog.backend.reviewer.constants import (
DEDUP_REASONING_EFFORT,
DEDUP_RUNTIME_ADAPTER,
DEFAULT_REVIEW_ARM,
- REVIEW_EXPERIMENT_ARMS,
+ HUMAN_TRIGGER_SOURCES,
+ RESOLUTION_MODEL,
+ RESOLUTION_REASONING_EFFORT,
+ RESOLUTION_RUNTIME_ADAPTER,
+ REVIEW_ARMS_BY_TIER,
REVIEW_MCP_SCOPES,
REVIEW_MODEL,
REVIEW_REASONING_EFFORT,
@@ -19,9 +24,13 @@ from products.review_hog.backend.reviewer.constants import (
VALIDATION_REASONING_EFFORT,
VALIDATION_RUNTIME_ADAPTER,
ReviewArm,
- draw_review_arm,
+ ReviewTier,
+ is_below_human_tier,
resolve_review_arm,
+ select_review_tier,
)
+from products.review_hog.backend.temporal.types import TRIGGER_INBOX
+from products.signals.backend.enums import ReportPriority
from products.tasks.backend.facade.run_config import (
LLMProvider,
ReasoningEffort,
@@ -40,14 +49,23 @@ def test_review_runtime_is_a_registry_supported_combo() -> None:
assert get_provider_for_runtime_adapter(REVIEW_RUNTIME_ADAPTER) == LLMProvider.OPENAI
-def test_validation_runtime_is_a_registry_supported_combo_when_pinned() -> None:
- # Same lock as the review combo, for the validation-session pins. An unsupported combo here
- # hard-errors the agent server only AFTER the whole review stage has been paid for. All-None
- # (agent default) is a valid configuration and asserts nothing.
- if VALIDATION_MODEL is None:
- assert VALIDATION_REASONING_EFFORT is None
+ "adapter,model,effort",
+ [
+ pytest.param(VALIDATION_RUNTIME_ADAPTER, VALIDATION_MODEL, VALIDATION_REASONING_EFFORT, id="validation"),
+ pytest.param(RESOLUTION_RUNTIME_ADAPTER, RESOLUTION_MODEL, RESOLUTION_REASONING_EFFORT, id="resolution"),
+ ],
+)
+def test_warm_session_runtime_is_a_registry_supported_combo_when_pinned(
+ adapter: RuntimeAdapter | None, model: str | None, effort: ReasoningEffort | None
+) -> None:
+ # Same lock as the review combo, for the validation and resolution session pins. An unsupported
+ # combo here hard-errors the agent server only AFTER the whole review stage has been paid for.
+ # All-None (agent default) is a valid configuration and asserts nothing.
+ if model is None:
+ assert effort is None
return
- assert get_reasoning_effort_error(VALIDATION_RUNTIME_ADAPTER, VALIDATION_MODEL, VALIDATION_REASONING_EFFORT) is None
+ assert get_reasoning_effort_error(adapter, model, effort) is None
@pytest.mark.parametrize(
@@ -66,25 +84,78 @@ def test_sandbox_fallback_runtime_is_a_registry_supported_combo(
assert get_provider_for_runtime_adapter(adapter) == LLMProvider.ANTHROPIC
[email protected]("arm", [pytest.param(arm, id=arm.model) for _, arm in REVIEW_EXPERIMENT_ARMS])
-def test_experiment_arm_is_a_registry_supported_combo(arm: ReviewArm) -> None:
- # Same lock as the pinned combos, per experiment arm: a bad combo is drawn onto half the fleet's
- # reports and fails only mid-review in prod. A Codex arm without "full-access" stalls every
[email protected]("arm", [pytest.param(arm, id=tier.value) for tier, arm in REVIEW_ARMS_BY_TIER.items()])
+def test_tier_arm_is_a_registry_supported_combo(arm: ReviewArm) -> None:
+ # Same lock as the pinned combos, per tier: a bad combo is persisted onto every report in the
+ # tier and fails only mid-review in prod. A Codex arm without "full-access" stalls every
# headless unit on MCP approval — the exact failure the bundle exists to prevent. Membership is
- # asserted because resolve_review_arm enforces it: an off-list arm would be drawn, persisted,
- # and then silently resolved back to the default pins on every unit.
+ # asserted because resolve_review_arm enforces it: an off-list arm would be persisted and then
+ # silently resolved back to the default pins (xhigh) on every unit, so a typo'd cheap tier
+ # costs money instead of failing.
assert arm.model in get_models_for_runtime_adapter(arm.runtime_adapter)
assert get_reasoning_effort_error(arm.runtime_adapter, arm.model, arm.reasoning_effort) is None
if arm.runtime_adapter == RuntimeAdapter.CODEX:
assert arm.initial_permission_mode == "full-access"
-def test_draw_review_arm_draws_from_the_arm_list() -> None:
- # random.choices accepts a zero weight without complaint, so a typo'd weight would silently
- # starve one arm for weeks while the experiment collects nothing on it. The membership check
- # also locks the (weight, arm) tuple orientation the draw's unpacking depends on.
- assert all(weight > 0 for weight, _ in REVIEW_EXPERIMENT_ARMS)
- assert draw_review_arm() in {arm for _, arm in REVIEW_EXPERIMENT_ARMS}
+def test_every_tier_has_an_arm() -> None:
+ # A tier the table forgets raises KeyError at report creation, after the PR was fetched.
+ assert set(REVIEW_ARMS_BY_TIER) == set(ReviewTier)
+
+
+ "agent_pr,priority,expected_tier,expected_effort",
+ [
+ pytest.param(False, None, ReviewTier.HUMAN, ReasoningEffort.XHIGH, id="human"),
+ # A person's PR reviews at full strength whatever a linked report might say.
+ pytest.param(False, ReportPriority.P4, ReviewTier.HUMAN, ReasoningEffort.XHIGH, id="human-ignores-priority"),
+ pytest.param(True, ReportPriority.P0, ReviewTier.AGENT_P0_P1, ReasoningEffort.XHIGH, id="agent-p0"),
+ pytest.param(True, ReportPriority.P1, ReviewTier.AGENT_P0_P1, ReasoningEffort.XHIGH, id="agent-p1"),
+ pytest.param(True, ReportPriority.P2, ReviewTier.AGENT_P2, ReasoningEffort.MEDIUM, id="agent-p2"),
+ pytest.param(True, ReportPriority.P3, ReviewTier.AGENT_P3_P4, ReasoningEffort.LOW, id="agent-p3"),
+ pytest.param(True, ReportPriority.P4, ReviewTier.AGENT_P3_P4, ReasoningEffort.LOW, id="agent-p4"),
+ # No readable judgment fails expensive, under its own label so it stays visible.
+ pytest.param(True, None, ReviewTier.AGENT_UNPRIORITIZED, ReasoningEffort.XHIGH, id="agent-unprioritized"),
+ ],
+)
+def test_select_review_tier_follows_the_tier_table(
+ agent_pr: bool, priority: ReportPriority | None, expected_tier: ReviewTier, expected_effort: ReasoningEffort
+) -> None:
+ # The table IS the product decision (which PRs get the cheaper reviewer); a swapped bucket
+ # silently changes review quality and spend for a whole class of PRs.
+ tier = select_review_tier(agent_pr=agent_pr, signal_priority=priority)
+ assert tier is expected_tier
+ assert REVIEW_ARMS_BY_TIER[tier].reasoning_effort is expected_effort
+ assert REVIEW_ARMS_BY_TIER[tier].model == REVIEW_MODEL
+
+
+def test_every_report_priority_maps_to_a_tier() -> None:
+ # A priority the table forgets raises KeyError at report creation, after the PR was fetched.
+ for priority in ReportPriority:
+ select_review_tier(agent_pr=True, signal_priority=priority)
+
+
+ "tier,expected",
+ [
+ pytest.param(ReviewTier.AGENT_P3_P4, True, id="low-lifts"),
+ pytest.param(ReviewTier.AGENT_P2, True, id="medium-lifts"),
+ # Already on the human arm: the lift buys a person a stronger review, not a relabel.
+ pytest.param(ReviewTier.AGENT_P0_P1, False, id="xhigh-keeps-its-label"),
+ pytest.param(ReviewTier.AGENT_UNPRIORITIZED, False, id="unprioritized-keeps-its-label"),
+ pytest.param(ReviewTier.HUMAN, False, id="human-is-the-ceiling"),
+ ],
+)
+def test_only_tiers_cheaper_than_human_lift_on_a_human_trigger(tier: ReviewTier, expected: bool) -> None:
+ assert is_below_human_tier(tier) is expected
+
+
+def test_human_triggers_cover_every_trigger_but_the_inbox() -> None:
+ # The set is spelled out in constants.py (persistence cannot import the temporal package). A
+ # trigger added to types.py but not here would leave a person's ask on a cheap tier, so the
+ # expected set is derived from the module rather than spelled out a second time.
+ every_trigger = {value for name, value in vars(trigger_types).items() if name.startswith("TRIGGER_")}
+ assert HUMAN_TRIGGER_SOURCES == every_trigger - {TRIGGER_INBOX}
# A registry-valid arm that differs from the default pins on every field, so honored-verbatim
diff --git a/products/review_hog/backend/temporal/__init__.py b/products/review_hog/backend/temporal/__init__.py
index 84792ed2f76f..478d2d681077 100644
--- a/products/review_hog/backend/temporal/__init__.py
+++ b/products/review_hog/backend/temporal/__init__.py
@@ -19,6 +19,7 @@ from products.review_hog.backend.temporal.activities import (
sync_review_skills_activity,
track_review_completed_activity,
track_review_failed_activity,
+ track_review_started_activity,
validate_chunk_activity,
validate_github_integration_activity,
)
@@ -68,6 +69,7 @@ ACTIVITIES = [
fail_status_comment_activity,
track_review_completed_activity,
track_review_failed_activity,
+ track_review_started_activity,
append_code_review_artefact_activity,
discover_outcome_teams_activity,
classify_team_outcomes_activity,
diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.py
index ff1887e9ddbd..ef1da6f85941 100644
--- a/products/review_hog/backend/temporal/activities.py
+++ b/products/review_hog/backend/temporal/activities.py
@@ -19,11 +19,13 @@ import logging
import datetime
from collections import Counter
from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
import posthoganalytics
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.models.integration import GitHubIntegration, Integration
from posthog.models.team.team import Team
@@ -46,7 +48,6 @@ from products.review_hog.backend.reviewer.constants import (
VALIDATION_RUNTIME_ADAPTER,
effective_priority,
published_priorities_for,
- resolve_review_arm,
)
from products.review_hog.backend.reviewer.lazy_seed import (
sync_canonical_authoring,
@@ -103,6 +104,7 @@ from products.review_hog.backend.reviewer.status_comment import (
finalize_status_comment,
maybe_refresh_status_comment,
)
+from products.review_hog.backend.reviewer.telemetry import review_routing_properties
from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request
from products.review_hog.backend.reviewer.tools.github_meta import (
PRFetcher,
@@ -137,9 +139,13 @@ from products.review_hog.backend.reviewer.tools.split_pr_into_chunks import (
from products.review_hog.backend.temporal.types import TRIGGER_LABEL, TRIGGER_MANUAL
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import CodeReview, CodeReviewCounts
+from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+if TYPE_CHECKING:
+ from products.review_hog.backend.reviewer.artefact_content import PRSnapshotArtefact
+
logger = logging.getLogger(__name__)
@@ -151,7 +157,7 @@ class ValidateIntegrationInput:
team_id: int
-@dataclass
+@frozen
class FetchPRDataInput:
team_id: int
user_id: int
@@ -165,6 +171,8 @@ class FetchPRDataInput:
# Provenance stamped onto the ReviewReport at upsert (see `upsert_review_report`).
signal_report_id: str | None = None
trigger_source: str = TRIGGER_MANUAL
+ # `ReportPriority` value the trigger read before the implementation agent could write its own.
+ signal_priority: str | None = None
@dataclass
@@ -398,7 +406,7 @@ class AppendCodeReviewArtefactInput:
review_url: str | None = None
-@dataclass
+@frozen
class TrackReviewCompletedInput:
"""One `reviewhog_review_completed` analytics event per finalized review turn."""
@@ -410,15 +418,31 @@ class TrackReviewCompletedInput:
# The workflow's start_time (ISO 8601) — one turn is one workflow execution, so this anchors
# the event's turn duration.
workflow_started_at: str
+ # Which trigger started THIS turn. The report row only remembers the trigger that created it,
+ # and a person's re-trigger of an inbox report is the case the tier telemetry has to see.
+ # Defaulted so in-flight payloads from before the field still deserialize.
+ turn_trigger_source: str | None = None
-@dataclass
+@frozen
+class TrackReviewStartedInput:
+ """One `reviewhog_review_started` analytics event per review turn that passed every gate."""
+
+ team_id: int
+ report_id: str
+ head_sha: str
+ run_index: int
+ turn_trigger_source: str | None
+
+
+@frozen
class TrackReviewFailedInput:
"""One `reviewhog_review_failed` analytics event per failed review turn."""
team_id: int
report_id: str
run_index: int
+ turn_trigger_source: str | None = None
@dataclass
@@ -546,6 +570,9 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:
pr_metadata=pr_metadata,
signal_report_id=input.signal_report_id,
trigger_source=input.trigger_source,
+ # Only the creating turn routes on it: the upsert is what knows whether the row exists.
+ signal_priority=ReportPriority(input.signal_priority) if input.signal_priority is not None else None,
+ lift_tier_on_human_trigger=True,
)
# Read the report's watermark BEFORE persist_commit_snapshot advances it, so the parent can decide
# whether this turn has anything to do. `published_head_sha == head_sha` means we already reviewed
@@ -951,9 +978,10 @@ async def review_chunk_activity(input: ReviewChunkInput) -> bool:
if input.blind_spot_check
else f"issues-review-p{input.pass_number}-c{input.chunk_id}"
)
- # The report's persisted experiment arm, not the module pins. Each unit resolves it against the
- # live registry, so all units of a turn agree unless a deploy deregisters the model mid-turn —
- # which is why experiment teardown drops arms from REVIEW_EXPERIMENT_ARMS, never the registry.
+ # The report's persisted arm (its tier's, decided at creation), not the module pins. Each unit
+ # resolves it against the live registry, so all units of a turn agree unless a deploy
+ # deregisters the model mid-turn — which is why a tier's arm changes in REVIEW_ARMS_BY_TIER,
+ # never by deregistering the model.
arm = await database_sync_to_async(load_review_arm, thread_sensitive=False)(
team_id=input.team_id, report_id=input.report_id
)
@@ -1285,37 +1313,86 @@ def _review_event_identity(report: ReviewReport) -> str:
return str(acting_distinct_id) if acting_distinct_id else str(report.team.uuid)
-def _review_arm_properties(report: ReviewReport) -> dict[str, str | bool]:
- """The model-experiment labels on every review analytics event (the model name is the arm).
+def _turn_event_properties(
+ report: ReviewReport, *, run_index: int, turn_trigger_source: str | None
+) -> dict[str, str | int | None]:
+ """The identity every per-turn review event shares: which report, which turn, and who asked for it.
- Resolved, not raw: pre-experiment rows carry NULLs but their reviews run on the default pins,
- and the event must say what actually ran.
+ `trigger_source` is the trigger that created the report; `turn_trigger_source` is the trigger
+ of this turn, which differs when a person re-triggers an inbox report.
"""
- persisted = (
- report.review_runtime_adapter,
- report.review_model,
- report.review_reasoning_effort,
- report.review_initial_permission_mode,
- )
- arm = resolve_review_arm(*persisted)
- resolved = (arm.runtime_adapter.value, arm.model, arm.reasoning_effort.value, arm.initial_permission_mode)
return {
- "review_runtime_adapter": arm.runtime_adapter.value,
- "review_model": arm.model,
- "review_reasoning_effort": arm.reasoning_effort.value,
- # True when a persisted assignment failed resolution and the turn ran the fallback pins
- # instead of its drawn arm; per-arm dashboards must exclude these contaminated turns.
- # The whole bundle is compared because a failed assignment can share the default arm's model
- # string while differing on adapter or effort. Pre-experiment rows (all NULL) stay False.
- "review_arm_fallback": any(persisted) and resolved != persisted,
+ "report_id": str(report.id),
+ "team_id": report.team_id,
+ "repository": report.repository,
+ "pr_number": report.pr_number,
+ "run_index": run_index,
+ "trigger_source": report.trigger_source,
+ "turn_trigger_source": turn_trigger_source,
+ "author_login": report.author_login,
+ }
+
+
+def _pr_size_properties(snapshot: "PRSnapshotArtefact | None") -> dict[str, int | None]:
+ """PR size as fetched for the turn; every value is None when the turn's snapshot is unavailable."""
+ pr_meta = snapshot.pr_metadata if snapshot is not None else None
+ return {
+ "pr_additions": pr_meta.additions if pr_meta is not None else None,
+ "pr_deletions": pr_meta.deletions if pr_meta is not None else None,
+ "pr_changed_files": pr_meta.changed_files if pr_meta is not None else None,
+ "pr_commits": pr_meta.commits if pr_meta is not None else None,
+ # Added lines ReviewHog actually reviews (lockfiles/tests/generated filtered out), which is
+ # the honest denominator for per-line cost.
+ "pr_reviewable_additions": count_reviewable_additions(snapshot.pr_files) if snapshot is not None else None,
}
+def _track_review_started(input: TrackReviewStartedInput) -> None:
+ report = ReviewReport.objects.for_team(input.team_id).select_related("acting_user", "team").get(id=input.report_id)
+ snapshot = load_pr_snapshot(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha)
+ posthoganalytics.capture(
+ distinct_id=_review_event_identity(report),
+ event="reviewhog_review_started",
+ # Deterministic per turn, like the completed event: a parent retry re-runs the gates and
+ # re-captures the same uuid, so a turn starts once however many attempts it takes.
+ uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_started:{input.report_id}:{input.run_index}")),
+ properties={
+ **_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
+ **review_routing_properties(report),
+ **_pr_size_properties(snapshot),
+ },
+ groups=groups(team=report.team),
+ send_feature_flags=True,
+ )
+
+
+def _track_review_started_safe(input: TrackReviewStartedInput) -> None:
+ # Analytics must never fail a review: any load/capture failure is logged, not raised.
+ try:
+ _track_review_started(input)
+ except Exception:
+ logger.exception("Failed to capture reviewhog_review_started for report %s; continuing", input.report_id)
+
+
+@scoped_temporal()
+@close_db_connections
+async def track_review_started_activity(input: TrackReviewStartedInput) -> None:
+ """Capture the turn's `reviewhog_review_started` product-analytics event.
+
+ Fires once every gate has passed and the turn is about to spend sandboxes, so it counts turns
+ that actually run. It carries the arm as it stood when the turn began: a person's trigger that
+ joins a cheaper turn lifts the row mid-run, so the completed event alone would show the lifted
+ arm for a turn whose units mostly ran on the cheap one. Started versus completed is how a
+ dashboard sees that lift. Best-effort: any failure is logged, not raised.
+ """
+ await database_sync_to_async(_track_review_started_safe, thread_sensitive=False)(input)
+
+
def _track_review_completed(input: TrackReviewCompletedInput) -> None:
report = ReviewReport.objects.for_team(input.team_id).select_related("acting_user", "team").get(id=input.report_id)
findings = load_turn_findings(team_id=input.team_id, report_id=input.report_id, run_index=input.run_index)
snapshot = load_pr_snapshot(team_id=input.team_id, report_id=input.report_id, head_sha=input.head_sha)
- pr_meta = snapshot.pr_metadata if snapshot is not None else None
duration_seconds = round(
(
datetime.datetime.now(tz=datetime.UTC) - datetime.datetime.fromisoformat(input.workflow_started_at)
@@ -1335,28 +1412,15 @@ def _track_review_completed(input: TrackReviewCompletedInput) -> None:
# same event uuid, so ingestion dedupes it instead of double-counting the review.
uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_completed:{input.report_id}:{input.run_index}")),
properties={
- "report_id": str(report.id),
- "team_id": report.team_id,
- "repository": report.repository,
- "pr_number": report.pr_number,
- "run_index": input.run_index,
- "trigger_source": report.trigger_source,
- "author_login": report.author_login,
+ **_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
"published": input.published,
"findings_total": len(findings),
"findings_valid": sum(1 for _, verdict in findings if verdict is not None and verdict.is_valid),
"findings_must_fix": valid_by_priority.get(IssuePriority.MUST_FIX, 0),
"findings_should_fix": valid_by_priority.get(IssuePriority.SHOULD_FIX, 0),
"findings_consider": valid_by_priority.get(IssuePriority.CONSIDER, 0),
- **_review_arm_properties(report),
- # PR size as fetched for this turn; None when the turn's snapshot is unavailable.
- "pr_additions": pr_meta.additions if pr_meta is not None else None,
- "pr_deletions": pr_meta.deletions if pr_meta is not None else None,
- "pr_changed_files": pr_meta.changed_files if pr_meta is not None else None,
- "pr_commits": pr_meta.commits if pr_meta is not None else None,
- # Added lines ReviewHog actually reviews (lockfiles/tests/generated filtered out) —
- # the honest denominator for per-line cost.
- "pr_reviewable_additions": count_reviewable_additions(snapshot.pr_files) if snapshot is not None else None,
+ **review_routing_properties(report),
+ **_pr_size_properties(snapshot),
"duration_seconds": duration_seconds,
},
groups=groups(team=report.team),
@@ -1396,14 +1460,8 @@ def _track_review_failed(input: TrackReviewFailedInput) -> None:
# completion rate counts turns, not attempts.
uuid=str(uuid.uuid5(uuid.NAMESPACE_URL, f"reviewhog_review_failed:{input.report_id}:{input.run_index}")),
properties={
- "report_id": str(report.id),
- "team_id": report.team_id,
- "repository": report.repository,
- "pr_number": report.pr_number,
- "run_index": input.run_index,
- "trigger_source": report.trigger_source,
- "author_login": report.author_login,
- **_review_arm_properties(report),
+ **_turn_event_properties(report, run_index=input.run_index, turn_trigger_source=input.turn_trigger_source),
+ **review_routing_properties(report),
},
groups=groups(team=report.team),
send_feature_flags=True,
diff --git a/products/review_hog/backend/temporal/client.py b/products/review_hog/backend/temporal/client.py
index 2a5a0abd6882..58775d2d9ec6 100644
--- a/products/review_hog/backend/temporal/client.py
+++ b/products/review_hog/backend/temporal/client.py
@@ -48,6 +48,7 @@ from products.review_hog.backend.temporal.types import (
review_branch_workflow_id,
review_pr_workflow_id,
)
+from products.signals.backend.enums import ReportPriority
logger = logging.getLogger(__name__)
@@ -91,6 +92,7 @@ def _build_inputs(
repository: str | None,
head_branch: str | None,
resolve_comments: bool | None = None,
+ signal_priority: ReportPriority | None = None,
) -> tuple[ReviewPRWorkflowInputs, str]:
"""Validate the review target, the team, and build the workflow inputs + deterministic id.
@@ -124,6 +126,7 @@ def _build_inputs(
acting_user_id=acting_user_id,
trigger_source=trigger_source,
signal_report_id=signal_report_id,
+ signal_priority=signal_priority.value if signal_priority is not None else None,
head_branch=head_branch,
resolve_comments=resolve_comments,
)
@@ -191,6 +194,7 @@ def start_review_pr_workflow(
acting_user_id: int | None = None,
trigger_source: str = TRIGGER_MANUAL,
signal_report_id: str | None = None,
+ signal_priority: ReportPriority | None = None,
repository: str | None = None,
head_branch: str | None = None,
resolve_comments: bool | None = None,
@@ -214,6 +218,7 @@ def start_review_pr_workflow(
acting_user_id=acting_user_id,
trigger_source=trigger_source,
signal_report_id=signal_report_id,
+ signal_priority=signal_priority,
pr_url=pr_url,
repository=repository,
head_branch=head_branch,
diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.py
index 8eb30ff3ab8c..698efbe56df2 100644
--- a/products/review_hog/backend/temporal/types.py
+++ b/products/review_hog/backend/temporal/types.py
@@ -4,8 +4,6 @@ Lives apart from `workflow.py` so the client (and any sync trigger) can build th
input without importing the workflow code (which pulls in the heavy activity dependencies).
"""
-from dataclasses import dataclass
-
from posthog.dataclasses import frozen
# How a review run was triggered. Gates are trigger-aware: label → `review_labeled_prs`,
@@ -18,7 +16,7 @@ TRIGGER_MANUAL = "manual"
TRIGGER_UI = "ui"
-@dataclass
+@frozen
class ReviewPRWorkflowInputs:
"""Input for one single-turn `ReviewPRWorkflow`.
@@ -54,6 +52,9 @@ class ReviewPRWorkflowInputs:
# The signals report whose implementation this run reviews (inbox trigger only): stamped onto the
# ReviewReport as provenance, and the target of the `code_review` artefact receipt.
signal_report_id: str | None = None
+ # The report's priority (a `ReportPriority` value) as the inbox trigger read it, before the
+ # implementation agent could write its own. Decides the tier of a new report; None otherwise.
+ 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
diff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.py
index ea7605c37dec..6d16e410a46c 100644
--- a/products/review_hog/backend/temporal/workflow.py
+++ b/products/review_hog/backend/temporal/workflow.py
@@ -57,6 +57,7 @@ from products.review_hog.backend.temporal.activities import (
SyncReviewSkillsInput,
TrackReviewCompletedInput,
TrackReviewFailedInput,
+ TrackReviewStartedInput,
ValidateChunkInput,
ValidateChunkResult,
ValidateIntegrationInput,
@@ -80,6 +81,7 @@ from products.review_hog.backend.temporal.activities import (
sync_review_skills_activity,
track_review_completed_activity,
track_review_failed_activity,
+ track_review_started_activity,
validate_chunk_activity,
validate_github_integration_activity,
)
@@ -415,6 +417,7 @@ class ReviewPRWorkflow:
head_branch=inputs.head_branch,
signal_report_id=inputs.signal_report_id,
trigger_source=inputs.trigger_source,
+ signal_priority=inputs.signal_priority,
),
start_to_close_timeout=_FETCH_TIMEOUT,
retry_policy=_RETRY,
@@ -482,6 +485,25 @@ class ReviewPRWorkflow:
return report_id
acting_user_id = acting.acting_user_id
+ # The turn passed every gate and is about to spend sandboxes: one started event per turn,
+ # the counterpart of the completed/failed pair below. Best-effort like both of them.
+ if workflow.patched("track-review-started-2026-09"):
+ try:
+ await workflow.execute_activity(
+ track_review_started_activity,
+ TrackReviewStartedInput(
+ team_id=inputs.team_id,
+ report_id=report_id,
+ head_sha=head_sha,
+ run_index=meta.run_index,
+ turn_trigger_source=inputs.trigger_source,
+ ),
+ start_to_close_timeout=_QUICK_TIMEOUT,
+ retry_policy=_RETRY,
+ )
+ except ActivityError:
+ workflow.logger.warning("Could not capture the review-started analytics event")
+
# One gate, three consumers: the status comment, finalize's deferred idle write, and the
# stage-7 publish dispatch all key off "this run publishes to a PR".
publishes_to_pr = inputs.publish and meta.pr_number is not None
@@ -652,7 +674,12 @@ class ReviewPRWorkflow:
try:
await workflow.execute_activity(
track_review_failed_activity,
- TrackReviewFailedInput(team_id=inputs.team_id, report_id=report_id, run_index=meta.run_index),
+ TrackReviewFailedInput(
+ team_id=inputs.team_id,
+ report_id=report_id,
+ run_index=meta.run_index,
+ turn_trigger_source=inputs.trigger_source,
+ ),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
)
@@ -673,6 +700,7 @@ class ReviewPRWorkflow:
run_index=meta.run_index,
published=posted,
workflow_started_at=workflow.info().start_time.isoformat(),
+ turn_trigger_source=inputs.trigger_source,
),
start_to_close_timeout=_QUICK_TIMEOUT,
retry_policy=_RETRY,
diff --git a/products/review_hog/backend/tests/test_fetch_review_tier.py b/products/review_hog/backend/tests/test_fetch_review_tier.py
new file mode 100644
index 000000000000..ff4cbedd277b
--- /dev/null
+++ b/products/review_hog/backend/tests/test_fetch_review_tier.py
@@ -0,0 +1,66 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from products.review_hog.backend.models import ReviewReport
+from products.review_hog.backend.reviewer.models.github_meta import PRMetadata
+from products.review_hog.backend.temporal.activities import FetchPRDataInput, _fetch_and_persist
+from products.review_hog.backend.temporal.types import TRIGGER_INBOX
+from products.signals.backend.models import SignalReport
+
+_MODULE = "products.review_hog.backend.temporal.activities"
+
+
+def _pr_metadata() -> PRMetadata:
+ return PRMetadata(
+ number=9,
+ title="t",
+ state="open",
+ draft=False,
+ created_at="",
+ updated_at="",
+ author="posthog[bot]",
+ base_branch="main",
+ head_branch="posthog-code/fix",
+ head_sha="sha1",
+ commits=1,
+ additions=1,
+ deletions=0,
+ changed_files=1,
+ )
+
+
+class TestFetchDecidesTheTier(BaseTest):
+ @patch(f"{_MODULE}._installation_auth", return_value=("tok", "9876543"))
+ @patch(f"{_MODULE}.PRFetcher")
+ def test_inbox_fetch_routes_a_new_report_by_its_signal_reports_priority(self, mock_fetcher, _auth) -> None:
+ # The tier is only as good as this wiring: a fetch that forgets to hand the trigger's
+ # priority to the upsert routes every agent PR as unprioritized, which is silently xhigh.
+ signal_report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.IN_PROGRESS, signal_count=1, total_weight=1.0
+ )
+ mock_fetcher.return_value.fetch_pr_data.return_value = (_pr_metadata(), [], [], "")
+
+ with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ meta = _fetch_and_persist(
+ FetchPRDataInput(
+ team_id=self.team.id,
+ user_id=1,
+ repository="o/r",
+ owner="o",
+ repo="r",
+ pr_number=9,
+ pr_url="https://github.com/o/r/pull/9",
+ signal_report_id=str(signal_report.id),
+ trigger_source=TRIGGER_INBOX,
+ signal_priority="P3",
+ )
+ )
+
+ row = ReviewReport.objects.for_team(self.team.id).get(id=meta.report_id)
+ assert (row.review_tier, row.review_signal_priority, row.review_reasoning_effort) == (
+ "agent_p3_p4",
+ "P3",
+ "low",
+ )
diff --git a/products/review_hog/backend/tests/test_inbox_trigger.py b/products/review_hog/backend/tests/test_inbox_trigger.py
index 56e3f61da007..911612f9fe31 100644
--- a/products/review_hog/backend/tests/test_inbox_trigger.py
+++ b/products/review_hog/backend/tests/test_inbox_trigger.py
@@ -1,4 +1,5 @@
import json
+from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -15,6 +16,7 @@ from posthog.models.user import User
import products.review_hog.backend.temporal.client # noqa: F401
from products.review_hog.backend.models import ReviewUserSettings
from products.review_hog.backend.receivers import resolve_stamphog_acting_reviewer
+from products.signals.backend.enums import ReportPriority
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.tasks.backend.models import Task, TaskRun
@@ -32,7 +34,7 @@ _HEAD_BRANCH = "posthog-code/fix-the-thing"
class TestInboxTrigger(BaseTest):
def setUp(self) -> None:
super().setUp()
- # The PR leg now probes the busy-guard before starting; default it idle so the existing
+ # The trigger probes the busy-guard before starting; default it idle so the existing
# cases exercise the review path without a live Temporal, and the busy case overrides it.
busy_patcher = patch(_WORKFLOW_RUNNING, return_value=False)
self.addCleanup(busy_patcher.stop)
@@ -148,7 +150,7 @@ class TestInboxTrigger(BaseTest):
run = self._run(task)
self._record_output(run, {"pr_url": _PR_URL, "head_branch": _HEAD_BRANCH}, update_fields=update_fields)
- # The PR leg wins over the branch leg when both targets are present.
+ # `head_branch` rides along in real output; only the PR is a review target.
mock_start.assert_called_once_with(
team_id=self.team.id,
user_id=self.alice.id,
@@ -156,37 +158,37 @@ class TestInboxTrigger(BaseTest):
acting_user_id=self.alice.id,
trigger_source="inbox",
signal_report_id=str(task.signal_report_id),
+ signal_priority=None,
pr_url=_PR_URL,
)
@patch(_START, return_value="wf-1")
- def test_branch_only_output_starts_a_branch_review(self, mock_start) -> None:
- # `output.head_branch` is synced by the agent server as soon as the work branch exists —
- # before (or without) a PR. The branch leg reviews and stores; publish needs the PR leg.
+ def test_review_routes_on_the_priority_from_before_the_implementation_task(self, mock_start) -> None:
+ # The agent can append a priority_judgment through the artefact API while it works; only the
+ # judgment the report carried when its task was created may pick the review tier.
self._mock_start = mock_start
self._suggest_reviewers(["alice"])
self._opt_in(self.alice)
task = self._task()
- self._record_output(self._run(task), {"head_branch": _HEAD_BRANCH})
+ for priority, offset in (("P1", -timedelta(minutes=5)), ("P4", timedelta(minutes=5))):
+ artefact = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=self.signal_report,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content=json.dumps({"explanation": "x", "priority": priority}),
+ )
+ SignalReportArtefact.objects.filter(pk=artefact.pk).update(created_at=task.created_at + offset)
- mock_start.assert_called_once_with(
- team_id=self.team.id,
- user_id=self.alice.id,
- publish=True,
- acting_user_id=self.alice.id,
- trigger_source="inbox",
- signal_report_id=str(task.signal_report_id),
- # Task.save lowercases the repository slug — the receiver forwards it as stored.
- repository="posthog/posthog",
- head_branch=_HEAD_BRANCH,
- )
+ self._record_output(self._run(task), {"pr_url": _PR_URL})
+
+ assert mock_start.call_args.kwargs["signal_priority"] is ReportPriority.P1
@patch(_START, return_value="wf-1")
def test_pr_review_is_skipped_while_the_prs_resolution_is_running(self, mock_start) -> None:
# Busy-guard: a published inbox review chains its own resolution, and a later TaskRun save
# re-fires this receiver. Without the guard that second review races the resolution's pushes
# and re-reviews threads it is mid-way through settling — the exact collision the endpoints
- # already refuse. The branch leg can't collide, so only the PR leg is guarded.
+ # already refuse.
self._mock_start = mock_start
self._suggest_reviewers(["alice"])
self._opt_in(self.alice)
@@ -195,18 +197,6 @@ class TestInboxTrigger(BaseTest):
mock_start.assert_not_called()
- @patch(_START, return_value="wf-1")
- def test_branch_review_ignores_the_resolution_busy_guard(self, mock_start) -> None:
- # A branch-only target has no PR for a resolution to run against, so a "busy" probe must not
- # block it — the branch leg reviews regardless.
- self._mock_start = mock_start
- self._suggest_reviewers(["alice"])
- self._opt_in(self.alice)
- with patch(_WORKFLOW_RUNNING, return_value=True):
- self._record_output(self._run(self._task()), {"head_branch": _HEAD_BRANCH})
-
- mock_start.assert_called_once()
-
@patch(_START, return_value="wf-1")
def test_run_creation_with_a_target_does_not_trigger(self, mock_start) -> None:
# Creation saves are ignored: runs exist before the agent does anything, and a target on a
@@ -336,7 +326,13 @@ class TestInboxTrigger(BaseTest):
("nobody_opted_in", True, False, ["alice"], False, {"pr_url": _PR_URL}, "o/r"),
("empty_output", True, False, ["alice"], True, {}, "o/r"),
("output_without_a_target", True, False, ["alice"], True, {"other": "x"}, "o/r"),
- ("branch_target_without_a_repository", True, False, ["alice"], True, {"head_branch": "b"}, None),
+ # A pushed branch is not a target: a review of a branch whose PR never opens is spend
+ # with no reader, and the PR save re-fires the receiver.
+ ("pushed_branch_without_a_pr", True, False, ["alice"], True, {"head_branch": _HEAD_BRANCH}, "o/r"),
+ # `output.pr_url` is written by whoever controls the run; a PR outside the task's own
+ # repository must not get the team's GitHub credential pointed at it.
+ ("pr_in_another_repository", True, True, ["alice"], True, {"pr_url": _PR_URL}, "o/r"),
+ ("task_without_a_repository", True, True, ["alice"], True, {"pr_url": _PR_URL}, None),
]
)
@patch(_START, return_value="wf-1")
@@ -441,19 +437,6 @@ class TestInboxTrigger(BaseTest):
# the next push, with bob still opted in.
assert resolve_stamphog_acting_reviewer(self.team.id, str(self.signal_report.id), None) == bob.id
- @patch(_STAMPHOG_QUEUE)
- @patch(_START, return_value="wf-1")
- def test_stamphog_leg_needs_a_pr_target(self, mock_start, mock_queue) -> None:
- # A bare pushed branch reviews on the ReviewHog side (stored), but stamphog's verdict is a
- # GitHub review — with no PR to post to, queueing a stamphog run would only burn a sandbox.
- self._mock_start = mock_start
- self._suggest_reviewers(["alice"])
- self._opt_in(self.alice, review_inbox_prs=True, stamphog_review_inbox_prs=True)
- self._record_output(self._run(self._task()), {"head_branch": _HEAD_BRANCH})
-
- mock_start.assert_called_once()
- mock_queue.assert_not_called()
-
@patch(_STAMPHOG_QUEUE, side_effect=RuntimeError("broker down"))
@patch(_START, return_value="wf-1")
def test_stamphog_queue_failure_never_raises_into_the_save_path(self, mock_start, mock_queue) -> None:
diff --git a/products/review_hog/backend/tests/test_outcome_classify.py b/products/review_hog/backend/tests/test_outcome_classify.py
index 2af9c41ad3e3..a6e9b1b410f1 100644
--- a/products/review_hog/backend/tests/test_outcome_classify.py
+++ b/products/review_hog/backend/tests/test_outcome_classify.py
@@ -26,6 +26,7 @@ from products.review_hog.backend.reviewer.constants import (
OUTCOME_JUDGE_FAILURE_STREAK,
OUTCOME_JUDGE_REASONING_MAX_CHARS,
OUTCOME_MAX_JUDGE_CALLS_PER_REPORT,
+ VALIDATION_MODEL,
)
from products.review_hog.backend.reviewer.models.issues_review import IssuePriority, LineRange
from products.review_hog.backend.reviewer.outcomes.classify import (
@@ -127,6 +128,27 @@ class TestClassifyReportDecision:
assert captured[0]["properties"]["outcome"] == "ignored"
assert captured[0]["properties"]["classification_method"] == "judge_rejected"
+ def test_the_outcome_event_carries_the_review_arm(self):
+ # Per-tier precision splits this event by the report's arm as it stands when the outcome is
+ # classified: a row in a cheaper tier must label its findings with that tier and effort, not
+ # the default pins.
+ report = ReviewReport(
+ repository="o/r",
+ pr_number=7,
+ review_tier="agent_p2",
+ review_runtime_adapter="codex",
+ review_model="gpt-5.6-sol",
+ review_reasoning_effort="medium",
+ review_initial_permission_mode="full-access",
+ )
+ captured, _judge = self._run(inputs=self._inputs(comment=None, compare_files=_TOUCHING), report=report)
+ props = captured[0]["properties"]
+ assert props["review_tier"] == "agent_p2"
+ assert props["review_model"] == "gpt-5.6-sol"
+ assert props["review_reasoning_effort"] == "medium"
+ assert props["review_arm_fallback"] is False
+ assert props["validator_model"] == VALIDATION_MODEL
+
def test_the_judges_reasoning_is_persisted_with_the_outcome(self):
# The ruling is the only record of why a finding was classified as it was; the diff it read
# has moved on by the time anyone asks. It goes in the artefact rather than the event so the
diff --git a/products/review_hog/backend/tests/test_persistence.py b/products/review_hog/backend/tests/test_persistence.py
index ed7bd4688226..9f412446581f 100644
--- a/products/review_hog/backend/tests/test_persistence.py
+++ b/products/review_hog/backend/tests/test_persistence.py
@@ -2,7 +2,8 @@ import uuid
from typing import TypeVar
from posthog.test.base import BaseTest
-from unittest.mock import patch
+
+from django.test import override_settings
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.reviewer.artefact_content import (
@@ -11,7 +12,7 @@ from products.review_hog.backend.reviewer.artefact_content import (
ValidationVerdict,
parse_artefact_content,
)
-from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, ReviewArm
+from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_ARMS_BY_TIER, ReviewTier
from products.review_hog.backend.reviewer.models.github_meta import PRComment, PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, IssuesReview, LineRange
@@ -36,9 +37,10 @@ from products.review_hog.backend.reviewer.persistence import (
persist_verdicts,
upsert_review_report,
)
+from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_LABEL, TRIGGER_UI
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import Commit
-from products.tasks.backend.facade.run_config import ReasoningEffort, RuntimeAdapter
+from products.signals.backend.enums import ReportPriority
_ContentT = TypeVar("_ContentT")
@@ -126,43 +128,123 @@ class TestUpsertReviewReport(BaseTest):
assert report.status == ReviewReport.Status.ACTIVE
assert report.run_count == 1 # the turn still finalizes fully; only the idle write is deferred
- def test_review_arm_is_drawn_once_and_sticky_across_turns(self) -> None:
- # Sticky-per-report is the arm draw's core invariant: a redraw on the update path would
- # flip a report's reviewer between turns, poisoning per-arm metrics and feeding one arm's
- # findings into the other's "already covered" injection. The drawn arm deliberately differs
- # from the default pins on every field so a loader that silently falls back cannot pass.
- sonnet = ReviewArm(
- runtime_adapter=RuntimeAdapter.CLAUDE,
- model="claude-sonnet-5",
- reasoning_effort=ReasoningEffort.XHIGH,
- initial_permission_mode=None,
- )
- with patch("products.review_hog.backend.reviewer.persistence.draw_review_arm", return_value=sonnet):
+ def _routing(self, report_id: str) -> tuple[str | None, str | None, str | None]:
+ report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
+ return report.review_tier, report.review_signal_priority, report.review_reasoning_effort
+
+ def test_review_tier_is_decided_at_creation_and_only_a_human_trigger_lifts_it(self) -> None:
+ # The tier's invariants: decided once from the creating turn's provenance (a Signals link
+ # makes it an agent PR, routed by the priority handed in), sticky across re-turns even when
+ # the report is re-judged, and lifted only when a person asks. A re-decision on the update
+ # 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]):
report_id = upsert_review_report(
- team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata()
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ signal_report_id=signal_report_id,
+ trigger_source=TRIGGER_INBOX,
+ signal_priority=ReportPriority.P2,
)
- report = ReviewReport.objects.for_team(self.team.id).get(id=report_id)
- assert (
- report.review_runtime_adapter,
- report.review_model,
- report.review_reasoning_effort,
- report.review_initial_permission_mode,
- ) == ("claude", "claude-sonnet-5", "xhigh", None)
- # Through the real loader, not just the raw columns: the values_list → resolve positional
- # coupling would otherwise silently fall every off-default report back to the default pins.
- assert load_review_arm(team_id=self.team.id, report_id=report_id) == sonnet
- assert load_review_arm(team_id=self.team.id, report_id=str(uuid.uuid4())) == DEFAULT_REVIEW_ARM
-
- with patch(
- "products.review_hog.backend.reviewer.persistence.draw_review_arm", return_value=DEFAULT_REVIEW_ARM
- ) as redraw:
+ assert self._routing(report_id) == ("agent_p2", "P2", "medium")
+ # Through the real loader, not just the raw columns: the values_list → resolve positional
+ # coupling would otherwise silently fall every off-default report back to the default pins.
assert (
- upsert_review_report(team_id=self.team.id, repository="o/r", pr_url="u", pr_metadata=_pr_metadata())
- == report_id
+ load_review_arm(team_id=self.team.id, report_id=report_id) == REVIEW_ARMS_BY_TIER[ReviewTier.AGENT_P2]
+ )
+ assert load_review_arm(team_id=self.team.id, report_id=str(uuid.uuid4())) == DEFAULT_REVIEW_ARM
+
+ # An inbox re-turn after a re-judgment keeps the tier and the priority the decision used.
+ upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ signal_report_id=signal_report_id,
+ trigger_source=TRIGGER_INBOX,
+ signal_priority=ReportPriority.P0,
+ )
+ assert self._routing(report_id) == ("agent_p2", "P2", "medium")
+
+ # The resolution stage upserts under the person's trigger too; a resolve-only request
+ # reviews nothing, so without the review turn's opt-in the tier must hold.
+ upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ trigger_source=TRIGGER_UI,
+ )
+ assert self._routing(report_id) == ("agent_p2", "P2", "medium")
+
+ # A person's label review lifts the report to the human tier for this and every later turn...
+ upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ trigger_source=TRIGGER_LABEL,
+ lift_tier_on_human_trigger=True,
+ )
+ assert self._routing(report_id) == ("human", "P2", "xhigh")
+ assert load_review_arm(team_id=self.team.id, report_id=report_id) == DEFAULT_REVIEW_ARM
+
+ # ...and a later inbox turn never lowers it back.
+ upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ signal_report_id=signal_report_id,
+ trigger_source=TRIGGER_INBOX,
+ signal_priority=ReportPriority.P3,
+ lift_tier_on_human_trigger=True,
+ )
+ assert self._routing(report_id) == ("human", "P2", "xhigh")
+
+ def test_unknown_persisted_tier_degrades_instead_of_crashing_the_upsert(self) -> None:
+ # `review_tier` is an unconstrained column, so a newer deploy can persist a tier value this
+ # deploy can't parse. The update-path read runs on every turn, before the lift condition, so
+ # a raise would fail the turn and its retries. It must degrade to "no lift", not crash.
+ report_id = upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ trigger_source=TRIGGER_INBOX,
+ )
+ ReviewReport.objects.for_team(self.team.id).filter(id=report_id).update(review_tier="agent_p9_from_the_future")
+
+ upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ trigger_source=TRIGGER_LABEL,
+ lift_tier_on_human_trigger=True,
+ )
+ # The unparseable value is left as-is: the lift is skipped rather than raising or relabeling.
+ assert ReviewReport.objects.for_team(self.team.id).get(id=report_id).review_tier == "agent_p9_from_the_future"
+
+ def test_tiered_arms_stay_on_the_default_outside_the_rollout_teams(self) -> None:
+ # 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]):
+ report_id = upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url="u",
+ pr_metadata=_pr_metadata(),
+ signal_report_id=str(uuid.uuid4()),
+ trigger_source=TRIGGER_INBOX,
+ signal_priority=ReportPriority.P3,
)
- assert redraw.call_count == 0 # the update path must not even draw
- report.refresh_from_db()
- assert report.review_model == "claude-sonnet-5"
+ assert self._routing(report_id) == ("agent_p3_p4", "P3", "xhigh")
+ assert load_review_arm(team_id=self.team.id, report_id=report_id) == DEFAULT_REVIEW_ARM
def test_author_login_is_stamped_on_create_and_refreshed_each_turn(self) -> None:
# The "For you" scope's authored-PRs match rides this stamp. It must track the PR's current
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 ddd3a97672bc..0e7eee84923b 100644
--- a/products/review_hog/backend/tests/test_review_completed_tracking.py
+++ b/products/review_hog/backend/tests/test_review_completed_tracking.py
@@ -1,12 +1,20 @@
+import uuid
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
-from products.review_hog.backend.reviewer.constants import DEFAULT_REVIEW_ARM, REVIEW_MODEL
+from products.review_hog.backend.reviewer.constants import (
+ DEFAULT_REVIEW_ARM,
+ REVIEW_MODEL,
+ VALIDATION_MODEL,
+ VALIDATION_REASONING_EFFORT,
+)
from products.review_hog.backend.reviewer.models.github_meta import PRFile, PRMetadata
from products.review_hog.backend.reviewer.models.issue_validation import IssueValidation
from products.review_hog.backend.reviewer.models.issues_review import Issue, IssuePriority, LineRange
@@ -19,10 +27,14 @@ from products.review_hog.backend.reviewer.persistence import (
from products.review_hog.backend.temporal.activities import (
TrackReviewCompletedInput,
TrackReviewFailedInput,
+ TrackReviewStartedInput,
_track_review_completed,
_track_review_completed_safe,
_track_review_failed,
+ _track_review_started,
)
+from products.review_hog.backend.temporal.types import TRIGGER_INBOX, TRIGGER_LABEL
+from products.signals.backend.enums import ReportPriority
_PR_URL = "https://github.com/o/r/pull/7"
@@ -60,14 +72,26 @@ def _issue(issue_id: str) -> Issue:
class TestTrackReviewCompleted(BaseTest):
- def _review_report(self) -> str:
- # The upsert draws a random experiment arm; pin it so arm-property assertions are deterministic.
- with patch("products.review_hog.backend.reviewer.persistence.draw_review_arm", return_value=DEFAULT_REVIEW_ARM):
- return upsert_review_report(
- team_id=self.team.id, repository="o/r", pr_url=_PR_URL, pr_metadata=_pr_metadata()
- )
+ def _review_report(
+ self,
+ *,
+ signal_report_id: str | None = None,
+ trigger_source: str | None = None,
+ signal_priority: ReportPriority | None = None,
+ ) -> str:
+ return upsert_review_report(
+ team_id=self.team.id,
+ repository="o/r",
+ pr_url=_PR_URL,
+ pr_metadata=_pr_metadata(),
+ signal_report_id=signal_report_id,
+ trigger_source=trigger_source,
+ signal_priority=signal_priority,
+ )
- def _tracking_input(self, report_id: str, *, published: bool = True) -> TrackReviewCompletedInput:
+ def _tracking_input(
+ self, report_id: str, *, published: bool = True, turn_trigger_source: str = "manual"
+ ) -> TrackReviewCompletedInput:
return TrackReviewCompletedInput(
team_id=self.team.id,
report_id=report_id,
@@ -75,6 +99,7 @@ class TestTrackReviewCompleted(BaseTest):
run_index=1,
published=published,
workflow_started_at=(datetime.now(UTC) - timedelta(seconds=90)).isoformat(),
+ turn_trigger_source=turn_trigger_source,
)
@parameterized.expand([(True,), (False,)])
@@ -122,6 +147,7 @@ class TestTrackReviewCompleted(BaseTest):
assert props["pr_number"] == 7
assert props["run_index"] == 1
assert props["trigger_source"] == "manual"
+ assert props["turn_trigger_source"] == "manual"
assert props["author_login"] == "octocat"
assert props["published"] is published
assert props["findings_total"] == 2
@@ -133,6 +159,9 @@ class TestTrackReviewCompleted(BaseTest):
assert props["review_runtime_adapter"] == DEFAULT_REVIEW_ARM.runtime_adapter.value
assert props["review_reasoning_effort"] == DEFAULT_REVIEW_ARM.reasoning_effort.value
assert props["review_arm_fallback"] is False
+ assert props["review_tier"] == "human"
+ assert props["signal_priority"] is None
+ assert props["signal_report_id"] is None
assert props["pr_additions"] == 120
assert props["pr_deletions"] == 30
assert props["pr_changed_files"] == 7
@@ -154,15 +183,32 @@ class TestTrackReviewCompleted(BaseTest):
assert props["pr_reviewable_additions"] is None
assert props["findings_total"] == 0
- def test_event_uuid_is_stable_across_retries(self) -> None:
+ @parameterized.expand([("completed",), ("failed",), ("started",)])
+ def test_event_uuid_is_stable_across_retries(self, event: str) -> None:
# A Temporal retry after a successful capture re-emits the event; a stable uuid lets
- # ingestion dedupe it instead of double-counting the review.
+ # ingestion dedupe it instead of double-counting the turn.
report_id = self._review_report()
- tracking_input = self._tracking_input(report_id)
+ emit = {
+ "completed": lambda: _track_review_completed(self._tracking_input(report_id)),
+ "failed": lambda: _track_review_failed(
+ TrackReviewFailedInput(
+ team_id=self.team.id, report_id=report_id, run_index=1, turn_trigger_source="manual"
+ )
+ ),
+ "started": lambda: _track_review_started(
+ TrackReviewStartedInput(
+ team_id=self.team.id,
+ report_id=report_id,
+ head_sha="sha1",
+ run_index=1,
+ turn_trigger_source="manual",
+ )
+ ),
+ }[event]
with patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture:
- _track_review_completed(tracking_input)
- _track_review_completed(tracking_input)
+ emit()
+ emit()
first, second = capture.call_args_list
assert first.kwargs["uuid"]
@@ -208,6 +254,58 @@ class TestTrackReviewCompleted(BaseTest):
# would make ingestion dedupe a real failure against a later success of the same turn.
assert failed.kwargs["uuid"] != completed.kwargs["uuid"]
+ def test_events_carry_the_tier_and_report_link_of_an_agent_pr(self) -> None:
+ # The per-tier dashboards split on these: an event that drops the tier, the priority, or
+ # the report link makes a cheap agent review indistinguishable from a full one, and the
+ # turn's own trigger is what tells a person's re-trigger of an inbox report apart from
+ # 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]):
+ report_id = self._review_report(
+ signal_report_id=signal_report_id, trigger_source=TRIGGER_INBOX, signal_priority=ReportPriority.P3
+ )
+
+ with patch("products.review_hog.backend.temporal.activities.posthoganalytics.capture") as capture:
+ _track_review_completed(self._tracking_input(report_id, turn_trigger_source=TRIGGER_LABEL))
+ _track_review_failed(
+ TrackReviewFailedInput(
+ team_id=self.team.id, report_id=report_id, run_index=1, turn_trigger_source=TRIGGER_INBOX
+ )
+ )
+ _track_review_started(
+ TrackReviewStartedInput(
+ team_id=self.team.id,
+ report_id=report_id,
+ head_sha="sha1",
+ run_index=1,
+ turn_trigger_source=TRIGGER_INBOX,
+ )
+ )
+
+ completed, failed, started = capture.call_args_list
+ assert started.kwargs["event"] == "reviewhog_review_started"
+ expected_validator_effort = VALIDATION_REASONING_EFFORT.value if VALIDATION_REASONING_EFFORT else None
+ for call in (completed, failed, started):
+ props = call.kwargs["properties"]
+ assert props["review_tier"] == "agent_p3_p4"
+ assert props["signal_priority"] == "P3"
+ assert props["signal_report_id"] == signal_report_id
+ assert props["trigger_source"] == "inbox"
+ assert props["review_model"] == "gpt-5.6-sol"
+ assert props["review_reasoning_effort"] == "low"
+ assert props["review_arm_fallback"] is False
+ # The validator and resolver are fixed pins, but the event is where a cost dashboard
+ # reads them, so every event names them next to the reviewer arm.
+ assert props["validator_model"] == VALIDATION_MODEL
+ assert props["validator_reasoning_effort"] == expected_validator_effort
+ assert completed.kwargs["properties"]["turn_trigger_source"] == "label"
+ assert failed.kwargs["properties"]["turn_trigger_source"] == "inbox"
+ assert started.kwargs["properties"]["turn_trigger_source"] == "inbox"
+ # Three events per turn, three uuid namespaces: a shared one would dedupe a start or a
+ # failure against the completion of the same turn.
+ assert len({call.kwargs["uuid"] for call in (completed, failed, started)}) == 3
+
@parameterized.expand(
[
("stale_model", "codex", "gpt-9-vanished", "high", "full-access"),
diff --git a/products/review_hog/backend/tests/test_temporal_workflow.py b/products/review_hog/backend/tests/test_temporal_workflow.py
index c162175e1ae7..93f756f4f229 100644
--- a/products/review_hog/backend/tests/test_temporal_workflow.py
+++ b/products/review_hog/backend/tests/test_temporal_workflow.py
@@ -42,7 +42,9 @@ from products.review_hog.backend.temporal.activities import (
ReviewMeta,
SelectPerspectivesInput,
SyncReviewSkillsInput,
+ TrackReviewCompletedInput,
TrackReviewFailedInput,
+ TrackReviewStartedInput,
ValidateChunkInput,
ValidateChunkResult,
ValidateIntegrationInput,
@@ -277,14 +279,26 @@ async def _run_full_review_pr_workflow(
async def fail_status(input) -> None:
return None
- # Records the failed-turn analytics event's run_index — the completion-rate denominator the
- # model experiment relies on; the patched block is swallowed best-effort, so without this stub
- # deleting it would leave every test green.
- track_failed_calls: list[int] = []
+ # Records the analytics events' run_index and the turn's trigger — the completion-rate
+ # denominator and the per-tier split rely on them; all three captures are swallowed best-effort
+ # in the workflow, so without these stubs deleting any of them would leave every test green.
+ track_failed_calls: list[tuple[int, str | None]] = []
+ track_completed_calls: list[tuple[int, str | None]] = []
+ track_started_calls: list[tuple[int, str | None]] = []
@activity.defn(name="track_review_failed_activity")
async def track_failed(input: TrackReviewFailedInput) -> None:
- track_failed_calls.append(input.run_index)
+ track_failed_calls.append((input.run_index, input.turn_trigger_source))
+ return None
+
+ @activity.defn(name="track_review_completed_activity")
+ async def track_completed(input: TrackReviewCompletedInput) -> None:
+ track_completed_calls.append((input.run_index, input.turn_trigger_source))
+ return None
+
+ @activity.defn(name="track_review_started_activity")
+ async def track_started(input: TrackReviewStartedInput) -> None:
+ track_started_calls.append((input.run_index, input.turn_trigger_source))
return None
result: str | None = None
@@ -322,6 +336,8 @@ async def _run_full_review_pr_workflow(
finalize_status,
fail_status,
track_failed,
+ track_completed,
+ track_started,
],
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
):
@@ -372,6 +388,8 @@ async def _run_full_review_pr_workflow(
"thresholds": threshold_calls,
"finalize_status": finalize_status_calls,
"track_failed": track_failed_calls,
+ "track_completed": track_completed_calls,
+ "track_started": track_started_calls,
"resolve_dispatches": list(StubResolvePRWorkflow.dispatches),
}
@@ -525,6 +543,7 @@ async def test_review_pr_workflow_early_exits_when_already_published():
assert recorded["review"] == []
assert recorded["validate"] == []
assert recorded["publish"] == []
+ assert recorded["track_started"] == [] # a skipped turn never counts as started
@pytest.mark.asyncio
@@ -537,6 +556,7 @@ async def test_review_pr_workflow_skips_when_author_maps_to_no_user():
assert recorded["review"] == []
assert recorded["validate"] == []
assert recorded["publish"] == []
+ assert recorded["track_started"] == []
@parameterized.expand(
@@ -575,11 +595,14 @@ async def test_review_pr_workflow_trigger_aware_gates(
if expect_ran:
assert recorded["split"] == [1]
assert recorded["receipts"] == [("stored", None)]
+ assert recorded["track_started"] == [(1, trigger_source)]
else:
assert recorded["split"] == []
assert recorded["review"] == []
assert recorded["publish"] == []
assert recorded["receipts"] == []
+ # The started event counts turns that passed every gate, so a gated-off turn must not fire it.
+ assert recorded["track_started"] == []
@pytest.mark.asyncio
@@ -592,6 +615,8 @@ async def test_review_pr_workflow_appends_published_receipt_with_review_url():
assert recorded["publish"] == [7]
assert recorded["receipts"] == [("published", _REVIEW_URL)]
assert recorded["track_failed"] == [] # a completed turn must not also count as failed
+ assert recorded["track_completed"] == [(1, "inbox")] # this turn's trigger, not the report's
+ assert recorded["track_started"] == [(1, "inbox")] # once, after the gates, before any sandbox
@pytest.mark.asyncio
@@ -610,7 +635,11 @@ async def test_review_pr_workflow_appends_failed_receipt_and_still_fails():
assert recorded["receipts"] == [("failed", None)]
# The failed-turn analytics event fires exactly once with the turn's run_index — the completion
# rate's denominator; it is best-effort-swallowed in the workflow, so only this assert guards it.
- assert recorded["track_failed"] == [1]
+ assert recorded["track_failed"] == [(1, "inbox")]
+ assert recorded["track_completed"] == []
+ # The turn had started (the gates passed) before dedup killed it, so started + failed is the
+ # honest pair for an abandoned turn.
+ assert recorded["track_started"] == [(1, "inbox")]
@pytest.mark.asyncio
@@ -662,6 +691,7 @@ async def test_review_pr_workflow_early_exits_on_empty_branch_diff():
assert recorded["split"] == []
assert recorded["review"] == []
assert recorded["receipts"] == []
+ assert recorded["track_started"] == []
def test_review_pr_workflow_inputs_deserialize_old_payloads():
diff --git a/products/review_hog/backend/tests/test_trigger_api.py b/products/review_hog/backend/tests/test_trigger_api.py
index eb1cf95f5ca2..f4d70de77ca2 100644
--- a/products/review_hog/backend/tests/test_trigger_api.py
+++ b/products/review_hog/backend/tests/test_trigger_api.py
@@ -11,6 +11,8 @@ 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"
@@ -203,6 +205,34 @@ class TestReviewHogTriggerApi(APIBaseTest):
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
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 d2d4f355ab6d..df35ec397b27 100644
--- a/products/review_hog/backend/tests/test_ui_trigger_api.py
+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py
@@ -151,6 +151,34 @@ class TestReviewHogUiTriggerApi(APIBaseTest):
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_trigger_during_a_running_cheaper_review_lifts_the_tier_and_says_so(
+ self, mock_start, _mock_access, _mock_meta
+ ):
+ # Same join as the label path: the requester's source never reaches the fetch upsert, so the
+ # lift is written here and the UI is told no new run started.
+ report = ReviewReport.objects.for_team(self.team.id).create(
+ team=self.team,
+ repository="posthog/posthog.com",
+ pr_number=123,
+ pr_url="https://github.com/PostHog/posthog.com/pull/123",
+ head_branch="fix",
+ base_branch="master",
+ review_tier="agent_p2",
+ review_reasoning_effort="medium",
+ )
+ self.mock_busy.side_effect = lambda workflow_id: workflow_id.startswith("review-pr:")
+ with override_settings(REVIEWHOG_TEAM_IDS=[self.team.id]):
+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123")
+
+ self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)
+ self.assertEqual(resp.json(), {"workflow_id": "wf-ui-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(_ACCESS, return_value=object())
@patch(_START_RESOLUTION)
@patch(_START)
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 82ec6c23753f..3c582956fa34 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -497,7 +497,7 @@ export interface ReviewTriggerRequestApi {
export interface ReviewTriggerResponseApi {
/** Temporal workflow id for the started review run; empty when no run was started. */
workflow_id: string
- /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts; a report in a cheaper tier is lifted to human strength for the rest of that review and every later one). */
status: string
}
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
index 32f4927c7844..f33b86456f69 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -186,13 +186,13 @@ describe('reviewHogSettingsLogic', () => {
expect(requestBody).toMatchObject({ run_mode: 'resolve_only' })
})
- it('an already-reviewed PR informs without arming the watch', async () => {
+ it.each([
+ ['already_reviewed', 200, ''],
+ ['joined_running_review', 202, 'wf-running'],
+ ])('a %s response informs without arming the watch', async (status, code, workflowId) => {
useMocks({
post: {
- '/api/projects/:team_id/review_hog/reviews/trigger/': () => [
- 200,
- { workflow_id: '', status: 'already_reviewed' },
- ],
+ '/api/projects/:team_id/review_hog/reviews/trigger/': () => [code, { workflow_id: workflowId, status }],
},
})
logic.mount()
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.ts
index 5bab06815e05..9f04fc087605 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts
@@ -1448,6 +1448,11 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
lemonToast.info(
'This pull request was already reviewed at its current commit. Find it under recent reviews.'
)
+ } else if (response.status === 'joined_running_review') {
+ // No run started — the request joined the review already in flight.
+ lemonToast.info(
+ 'A review is already running on this pull request. Trigger it again after it finishes to run a full review.'
+ )
} else if (runMode === ReviewTriggerRequestRunModeEnumApi.ResolveOnly) {
// Resolve-only runs don't create the report activity the review watch polls for,
// so a toast is the feedback: progress shows up on the pull request itself.
diff --git a/products/signals/backend/report_generation/priority.py b/products/signals/backend/report_generation/priority.py
new file mode 100644
index 000000000000..2f132337edbd
--- /dev/null
+++ b/products/signals/backend/report_generation/priority.py
@@ -0,0 +1,39 @@
+from datetime import datetime
+
+from pydantic import ValidationError
+
+from products.signals.backend.artefact_schemas import PriorityAssessment
+from products.signals.backend.enums import ReportPriority
+from products.signals.backend.models import SignalReportArtefact
+
+
+def persisted_report_priority(*, team_id: int, report_id: str, before: datetime) -> ReportPriority | None:
+ """The priority from the report's latest ``priority_judgment`` written before ``before``, or ``None``.
+
+ ``before`` is the trust cut-off. The implementation agent holds the artefact tool that appends
+ judgments, so a caller that routes on the priority reads it as of the moment that agent's task
+ was created, before the agent could vote on how hard its own PR gets reviewed.
+
+ Latest-wins, because re-research and the artefact API append new judgments instead of editing
+ the old one. The ``-id`` tiebreak keeps the pick deterministic when two judgments share a
+ ``created_at``: the routed effort tier is decided once and sticky, so an arbitrary tie-break
+ could otherwise pin a report to a stale priority. Content that does not parse (a legacy non-JSON
+ row, a hand-edited artefact) reads as missing, so a caller that keys a decision on the priority
+ fails safe instead of crashing.
+ """
+ artefact = (
+ SignalReportArtefact.objects.filter(
+ team_id=team_id,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ created_at__lt=before,
+ )
+ .order_by("-created_at", "-id")
+ .first()
+ )
+ if artefact is None:
+ return None
+ try:
+ return PriorityAssessment.model_validate_json(artefact.content).priority
+ except ValidationError:
+ return None
diff --git a/products/signals/backend/test/test_report_priority.py b/products/signals/backend/test/test_report_priority.py
new file mode 100644
index 000000000000..12212e0bf2fd
--- /dev/null
+++ b/products/signals/backend/test/test_report_priority.py
@@ -0,0 +1,79 @@
+import json
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.signals.backend.enums import ReportPriority
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.report_generation.priority import persisted_report_priority
+
+
+class TestPersistedReportPriority(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.IN_PROGRESS, signal_count=1, total_weight=1.0
+ )
+
+ def _judge(self, content: str, *, age: timedelta = timedelta()) -> None:
+ artefact = SignalReportArtefact.objects.create(
+ team=self.team,
+ report=self.report,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content=content,
+ )
+ # Pin the order explicitly: two rows created in the same test can share a timestamp.
+ SignalReportArtefact.objects.filter(pk=artefact.pk).update(created_at=timezone.now() - age)
+
+ def _priority(self, *, before: timedelta = timedelta(seconds=1)) -> ReportPriority | None:
+ return persisted_report_priority(
+ team_id=self.team.id, report_id=str(self.report.id), before=timezone.now() + before
+ )
+
+ def test_latest_judgment_wins(self) -> None:
+ # Re-research and the artefact API append judgments; a reader that takes the first one
+ # routes on a priority the team already changed.
+ self._judge(json.dumps({"explanation": "core flow broken", "priority": "P1"}), age=timedelta(minutes=5))
+ self._judge(json.dumps({"explanation": "narrower than thought", "priority": "P3"}))
+
+ assert self._priority() is ReportPriority.P3
+
+ def test_judgments_after_the_cut_off_are_ignored(self) -> None:
+ # The implementation agent can append a judgment through the artefact API; a reader without
+ # the cut-off would let it lower the effort of its own review.
+ self._judge(json.dumps({"explanation": "core flow broken", "priority": "P1"}), age=timedelta(minutes=5))
+ self._judge(json.dumps({"explanation": "turned out minor", "priority": "P4"}))
+
+ assert self._priority(before=-timedelta(minutes=1)) is ReportPriority.P1
+
+ @parameterized.expand(
+ [
+ ("no_judgment", None),
+ ("legacy_plain_text", "P1 because the checkout is broken"),
+ ("unknown_priority", json.dumps({"explanation": "x", "priority": "P9"})),
+ ]
+ )
+ def test_missing_or_unreadable_judgment_reads_as_none(self, _name: str, content: str | None) -> None:
+ # Callers key routing on this; an exception here would fail the caller instead of letting
+ # it fall back.
+ if content is not None:
+ self._judge(content)
+
+ assert self._priority() is None
+
+ def test_scoped_to_the_team(self) -> None:
+ self._judge(json.dumps({"explanation": "x", "priority": "P0"}))
+ other_team = Team.objects.create(organization=self.organization)
+
+ assert (
+ persisted_report_priority(
+ team_id=other_team.id, report_id=str(self.report.id), before=timezone.now() + timedelta(seconds=1)
+ )
+ is None
+ )
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 84daf3d4312e..8d7a5ec1e166 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -75466,7 +75466,7 @@ export namespace Schemas {
export interface ReviewTriggerResponse {
/** Temporal workflow id for the started review run; empty when no run was started. */
workflow_id: string;
- /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts). */
+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts), 'joined_running_review' when a review was already in flight (no new run starts; a report in a cheaper tier is lifted to human strength for the rest of that review and every later one). */
status: string;
}