: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(review-hog): record the reviewer-model bake-off (rounds 1-6) (#75964)
Alex Lebedev3ca6dea511e5
diff --git a/products/review_hog/eval/RUN_LOG.md b/products/review_hog/eval/RUN_LOG.mdindex b0036e37698d..19c3979fe536 100644--- a/products/review_hog/eval/RUN_LOG.md+++ b/products/review_hog/eval/RUN_LOG.md@@ -238,3 +238,35 @@ chars`. Publish gated off.| # | perspective | prio | file:line | finding | verdict || --- | ------------------- | ---------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- || 1 | Logic & Correctness | should_fix | hogql/database/database.py:1478 | remapped `timestamp_field` now triggers `get_table` for view-namespace tables that previously skipped it → `DoesNotExist` turns a successful build into a hard failure | ✅ kept · bug |++## 2026-07-23 · GLM 5.2 vs Sonnet 5 as perspective reviewer — PR #72680 @ `1341596e`++- **Experiment:** `experiments/2026-07-reviewer-model-glm52/` (PLAN + FINAL_REPORT + 4 dumps + judge JSONs).+- **Design:** adaptive pairs (A1/B1 split → A2/B2), pinned 4-chunk split, zero-comment clean room,+ every post-dedup finding independently adversarially verified against the PR worktree, 3-lens blind panel.+- **Result:** judges 2-1 for GLM on lenses (recall-reliability, impact) but Sonnet wins precision;+ **verdict: keep sonnet-5 @ xhigh** — Sonnet: 14/44 verified-real (31.8%), stable, cheaper (caching);+ GLM: 7/36 (19.4%) but owns 3 of 4 confirmed must_fix incl. the flagship `task.internal` bug in BOTH runs.+- **Side yields:** 2 confirmed must_fix bugs in the target PR; tasks-runner false-success bug (auth-failed+ sandbox → validated-empty IssuesReview, defeats the failure floor); `review_hog` gateway product routing+ (agent + allowlist, kept); per-stage timing table in `dump_result.py` (kept); Sonnet-arm Opus-fallback+ contamination (~20% of finder gens, every Sonnet run) quantified.++## 2026-07-24 · 4-way extension: + gpt-5.5 (Codex) & Opus 4.8 — PR #72680 @ `1341596e`++- **Experiment:** same folder (`experiments/2026-07-reviewer-model-glm52/`), overnight autonomous extension:+ arm C = gpt-5.5 @ xhigh via Codex ("full-access"), arm D = opus-4-8 @ xhigh via Claude; identical harness+ (pinned chunks, comment mock, Opus validator), 2 runs each, per-finding adversarial verification, clusters+ extended over all 8 sets, 3-lens blind panel over 4 anonymous models (`judge-fourway.json`).+- **Result: keep sonnet-5 @ xhigh — confirmed against four models.** Scoreboard (verified-real):+ Sonnet 14/44 (31.8%) · GLM 7/36 (19.4%) · gpt-5.5 3/17 (17.6%) · Opus 5/30 (16.7%).+ Panel: recall M2>M1>M3>M4 · precision M1>M2>M3>M4 · impact M2>M1>M3>M4 — **Opus last on all three+ lenses** despite the fastest review stage of the experiment (24–26m vs Sonnet’s 30–45m) and clean ops; it+ missed the flagship `task.internal` must_fix in both runs. gpt-5.5 = operational DNF: **17/17+ first-attempt provider refusals** on this PR's security-heavy chunks (C1 hard-failed, C2 recovered on+ a 3rd-attempt ladder with 4/8 units skill-less from Codex MCP flake) — yet its one valid run was the+ only single run to catch BOTH heavy must_fixes.+- **Side yields (product bugs):** refusal→30-min-hang in `poll_for_turn` (refusal not terminal); Codex+ sandboxes intermittently get no MCP tools and review without their skill; Codex OpenAI cache reads+ invisible to `$ai_generation` (cost over-attribution); 120MB handoff-pack uploads always fail in+ Modal sandboxes.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/FINAL_REPORT.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/FINAL_REPORT.mdnew file mode 100644index 000000000000..9c1cd251e7e0--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/FINAL_REPORT.md@@ -0,0 +1,452 @@+# FINAL REPORT — reviewer-model comparison for the perspective-review step++**Question:** is `@cf/zai-org/glm-5.2` better than `claude-sonnet-5` at applying ReviewHog's review+perspectives? Everything else held constant (validator Opus 4.8 @ xhigh, one-shots Sonnet, pinned+4-chunk split, zero-comment clean room, PR frozen at `1341596e`). Setup and decisions: [PLAN.md](./PLAN.md).++> **Extended overnight 2026-07-24 to a 4-way comparison** — two more arms on the identical setup:+> `gpt-5.5` @ xhigh via Codex (arm C) and `claude-opus-4-8` @ xhigh via Claude (arm D), 2 runs each.+> The A/B analysis below is unchanged; the extension is in [§ 4-way extension](#4-way-extension-2026-07-24-gpt-55-codex-and-opus-48)+> and the recommendation at the end covers all four models. **The 4-way verdict does not change the+> A/B one: `claude-sonnet-5` @ xhigh stays.** Opus 4.8 is ~1.5× faster but ranked last by all three+> blind judges; gpt-5.5 is operationally unusable in this pipeline (provider-side refusals).++**Verdict: not better — different, and on balance Sonnet 5 stays.** The blind panel split 2-1 for GLM+on lenses (recall-reliability and impact for GLM, precision for Sonnet, all moderate margins), but the+trade-off it describes favors keeping Sonnet as the sole perspective reviewer today: Sonnet finds twice+the confirmed-real breadth at ~1.6× the precision, run-stably, and materially cheaper. GLM's genuine+edge — repeatably landing the deepest catches — is real but comes wrapped in an 80% noise rate and a+40-100% higher finder-stage cost (no prompt caching on the Cloudflare path). Recommendation and the+conditions that would flip it are at the end.++## Runs++Two runs per arm (adaptive design: round 1 split → round 2 triggered). Labels map to dumps in `runs/`.++| | A1 (Sonnet) | A2 (Sonnet) | B1 (GLM) | B2 (GLM) |+| ------------------------------------ | ----------- | ----------- | -------- | -------- |+| Finder units | 13 | 12 | 12 | 13 |+| Raw → dedup → pipeline-valid | 25→20→3 | 26→24→5 | 21→17→2 | 24→19→2 |+| **Independently verified real** | **7/20** | **7/24** | **3/17** | **4/19** |+| …of which must_fix / should_fix | 0 / 4 | 1 / 1 | 1 / 0 | 2 / 0 |+| Review stage (selection→last finder) | 44m38s | 30m11s | 42m41s | 65m39s |+| Finder-stage cost | ~$28.92¹ | ~$30¹ | $41.62² | $49.51² |+| Total run cost | $46.52 | $56.47 | ~$55.04 | ~$63.92 |+| Model purity (finder gens) | ~80%³ | ~80%³ | **100%** | **100%** |+| Turn parse failures (retried) | 1 | 3 | 0 | 0 |++¹ Includes Opus-fallback bleed (see caveats). ² GLM is unpriced at the gateway (`gw $0.00`); computed+from token counts × litellm CF pricing ($1.40/M in, $4.40/M out) — **zero cache reads**, all input fresh.+³ 3 units per Sonnet run silently switched to Opus mid-session (SDK `fallbackModel` rescue).++## Verification & judging method++Every post-dedup finding (73 total) was independently adversarially verified by its own agent against+the real PR tree (worktree at the reviewed head), refutation-first. A cross-set clusterer grouped the+73 findings into 53 underlying issues. Three blind judges (recall-reliability / precision / impact)+scored model "S" vs "G" over both runs each, weighting repeatable catches over single-run luck.+Evidence: `judge-round1.json`, `judge-setP.json`, `judge-final.json`.++## What the evidence says++**Sonnet = breadth + precision + stability.** 14 confirmed-real findings across 44 (31.8% precision)+vs GLM's 7 across 36 (19.4%). Rate is stable per run (7/20, 7/24 vs 3/17, 4/19). Six distinct+confirmed must_fix/should_fix issues vs GLM's four confirmations over three issues.++**GLM = repeatable depth.** GLM owns 3 of the pool's 4 confirmed must_fix verdicts, and caught the+single most valuable bug — the `task.internal` predicate that dead-ends the webhook re-review leg for+100% of production self-driving PRs, with the PR's own tests locking the broken behavior in — in+**both** of its runs (Y5, Q5). Sonnet caught it in only one of two (P12; A1 missed it). GLM's Q18+(receiver-leg linkage spoofing via agent-controlled `output.pr_url`) is the other unique-depth+must_fix; Sonnet's matching finding (X20) reached should_fix framing.++**Low overlap.** Only 16 of 53 issue clusters were found by both models; the finder sets are largely+complementary. The union of both models' confirmed-real issues is materially larger than either alone.++**Pipeline validator vs independent verification.** The strict Opus validator passed 3/5/2/2 findings+per run; the independent verifiers confirmed 7/7/3/4 as real. The validator's picks only partially+track verified-real — worth its own calibration experiment (see follow-ups).++## Confirmed real issues in PR #72680 (act on these regardless of the experiment)++- **must_fix — `task.internal` kills the webhook re-review leg** (Y5/Q5/P12): `find_signal_implementation_run`+ rejects `internal=True` tasks, but production self-driving runs are created with `internal=True`+ (`signals/backend/auto_start.py`); tests fixture `internal=False`, masking it.+- **must_fix — receiver leg stamps `inbox_review` with no positive PR↔run linkage** (Q18/X20/P10):+ agent-controlled `output.pr_url` (branch-matched webhook backstop) can bind a human-authored PR into+ the trusted self-driving path (X3 confirmed the downstream: `_format_self_driving` then renders false+ TRUSTED provenance claims on a path that mints real approvals).+- **should_fix** — X7, X9, P8 (see `judge-round1.json` / `judge-setP.json` for evidence), plus the+ confirmed considers (P4, P13, P17, P19, X12, X17, X19, Q12, Q19).++## Caveats++- **Opus contamination in the Sonnet arm**: every Sonnet run had ~3 units partially rescued onto+ Opus 4.8 by the SDK's always-on `fallbackModel` (~20% of finder gens). Sonnet's numbers are+ strictly "Sonnet with prod's rescue behavior"; pure-Sonnet would likely be slightly weaker. GLM ran+ 100% pure both times.+- **Effort pin unverified for GLM**: the CF/Modal translation sets `drop_params=True`; `MAX` vs `HIGH`+ may be cosmetic. Not resolved in this experiment.+- **GLM cost has no gateway pricing**: `$ai_total_cost_usd` is 0.00 for GLM gens — dashboards will+ under-report; fixed only when the gateway prices `@cf/` models in the callback.+- Selection is not pinned, so unit rosters varied 12-13 across runs (chunk split was pinned).+- Single PR, single repo, N=2 per arm. Directional, not definitive.++## Incidents during the experiment (fixes/bugs worth follow-up)++1. **Tainted first A1** (`A-sonnet5-xhigh-1-tainted.md`): nodemon worker restarts mid-run double-executed+ every wave unit (zombie sandboxes kept billing). Lesson: never touch repo `*.py` while a run is live.+2. **False-success empty reviews**: B1's first attempt "finished" green with 0 findings while every+ unit had failed with `403 Model not allowed for product 'background_agents'` — the tasks runner+ returned a validated-empty `IssuesReview` from auth-failed sessions, defeating ReviewHog's+ failure floor. **Real bug, needs a fix in the tasks runner / executor contract.**+3. **`background_agents` allowlist drift**: it lacks `gpt-5.5` too — the old Codex review pin would+ 403→silently-fall-back-to-Opus in prod today. The routing fix (below) sidesteps it for ReviewHog.++## Durable changes shipped with this experiment (kept in tree)++- Gateway: `review_hog` product now has an explicit model allowlist (glm-5.2, sonnet-5, opus-4-8, gpt-5.5).+- Agent (`posthog/code` repo): `resolveGatewayProduct` routes `originProduct === "review_hog"` to the+ `review_hog` gateway product instead of piggybacking `background_agents`.+- `eval/scripts/dump_result.py`: per-stage wall-clock timing table (+ `review_stage` in `DUMP_OK`).++## 4-way extension (2026-07-24): gpt-5.5 (Codex) and Opus 4.8++Overnight extension on the identical harness (same PR @ `1341596e`, same pinned chunks, same+zero-comment mock, same Opus validator). Arm C = `CODEX`/`gpt-5.5`/`XHIGH`/`"full-access"`; arm D =+`CLAUDE`/`claude-opus-4-8`/`XHIGH`. Blind sets R (C1), T (C2), U (D1), V (D2); one adversarial+verifier per finding against the PR worktree (same protocol as rounds 1–2, verdicts in+[judge-fourway.json](./judge-fourway.json)); clusters extended incrementally over all 8 sets+(56 clusters, 127+80 ids); 3-lens blind panel over four anonymous models M1=X+P, M2=Y+Q, M3=R+T,+M4=U+V. Per-run ops detail: [night-notes-2026-07-24.md](./night-notes-2026-07-24.md).++### Arm C was a partial DNF: gpt-5.5 refuses the review turn++Every failed arm-C perspective unit ended with ACP `stopReason: "refusal"` ~90–130s into the turn —+gpt-5.5's provider-side safety layer declining ReviewHog's review prompt. **First-attempt refusal+rate: 17/17** across both runs; chunks 1–2 (the PR's provenance/security code) refused 8/8 in C1.+Refusals are attempt-stochastic, not content-absolute: C2's retry ladder reached a third attempt and+all remaining units completed, giving C2 full coverage. C1 never recovered chunks 1–2 → hard fail+(dump kept as evidence; its set R still entered judging). Compounding caveats in C2: 4 of 8+perspective units ran in sandboxes that never got MCP (Codex MCP flake) and reviewed **without their+perspective skill**; unit reviews were assembled across refusal-interrupted resumed sessions.++### Runs C/D++| | C1 (gpt-5.5) | C2 (gpt-5.5) | D1 (Opus 4.8) | D2 (Opus 4.8) |+| ------------------------------------ | ------------------------------- | ---------------- | ------------- | ------------- |+| Status | **hard fail** (chunks 1–2 lost) | valid w/ caveats | valid, clean | valid, clean |+| Finder units | 7 | 12 | 13 | 12 |+| Raw → dedup → pipeline-valid | 10→7→0 | 14→10→2 | 14→14→1 | 16→16→1 |+| **Independently verified real** | **0/7** | **3/10** | **2/14** | **3/16** |+| …of which must_fix / should_fix | 0 / 0 | 2 / 0 | 0 / 1 | 0 / 1 |+| Review stage (selection→last finder) | 63m35s¹ | 69m01s¹ | **26m22s** | **24m16s** |+| Finder-stage cost | $13.28² | $24.26² | $44.37 | $40.40 |+| Total run cost | ~$21 | ~$36 | $57.52 | $52.26 |+| Model purity (finder gens) | 100% | 100% | 100%³ | 100%³ |+| Unit retries | 8 (refusals) | 14 (refusals) | 0 | 0 |++¹ Dominated by the refusal→poll-timeout product bug (below), not review work.+² Gateway-priced; overstated — OpenAI-side cache reads (~90% of input on warm turns) never reach+`$ai_generation` (telemetry gap below), and `true $` can't price gpt-5.5 at all.+³ For arm D, silent SDK fallback is `claude-opus-4-8` too — indistinguishable by construction.++### 4-way scoreboard (identical counting rule across all 8 runs)++| model | verified real | precision | must_fix / should_fix / consider | review stage | finder cost/run |+| ----------------- | ------------- | --------- | -------------------------------- | ------------ | --------------- |+| M1 Sonnet 5 (X+P) | 14/44 | 31.8% | 1 / 5 / 8 | 30–45m | ~$29–31 |+| M2 GLM 5.2 (Y+Q) | 7/36 | 19.4% | 3 / 1 / 3 | 43–66m | ~$42–50 |+| M3 gpt-5.5 (R+T) | 3/17 | 17.6% | 2 / 0 / 1 | n/a¹ | ~$13–24² |+| M4 Opus 4.8 (U+V) | 5/30 | 16.7% | 0 / 2 / 2⁴ | **24–26m** | ~$40–44 |++⁴ Plus one anomalous verdict (V13: `is_real=true` + severity `not_an_issue` — real-but-trivial).++**Blind panel (3 lenses over M1–M4):**++- **Recall & reliability:** M2 > M1 > M3 > M4 (M2>M1 narrow — M1 wins raw recall, M2 owns the only+ must_fix caught reliably in both runs).+- **Precision:** M1 > M2 > M3 > M4 (decisive for M1: 31.8% vs 19.4%, stable across runs).+- **Impact & actionability:** M2 > M1 > M3 > M4 (narrow, contested).++**M4 (Opus) ranked last on all three lenses** despite being the fastest and 100%-clean operationally:+it is selective (≈1 raw finding/unit, zero dedup merges) but its selections mostly failed verification,+it produced zero confirmed must_fix, and it missed the flagship `task.internal` bug in both runs+(cluster `Y5/P12/Q5/T10`). Its reliable catches (receiver-linkage `U2/V3`, config double-resolve,+carve-out retry blocking) were mostly shared with other models.++**M3 (gpt-5.5) is a paradox:** its one valid run caught BOTH heavy must_fix bugs (T7 receiver-linkage,+T10 `task.internal`) — the only single run to do so — but its other run verified 0/7 real, and the+operational failure mode (refusals, MCP flake) makes it unusable in this pipeline regardless.++### New product bugs found by the extension (independent of verdict)++1. **Model refusal → 30-min hang:** `poll_for_turn` (`products/tasks/.../custom_prompt_internals.py`,+ `MAX_POLL_SECONDS=1800`) doesn't treat a turn completed with `stopReason: "refusal"` as terminal;+ each refused ~90s turn burned a full 1800s poll window before the retry fired. A refusal should+ fail the turn immediately.+2. **Codex MCP flakiness:** 9/21 Codex sandboxes in C1 (and several in C2) never got the `posthog`+ MCP server's tools (`posthog/exec` absent; agent logs "MCP skill reader is not exposed in this+ session") and silently reviewed without the perspective skill, falling back to local+ `.agents/skills`. Needs a hard preflight: no MCP tools → fail the turn, don't improvise.+3. **Codex cache-telemetry gap:** agent-side usage reports OpenAI cached reads (e.g. 65,920 of+ 71,483 input tokens) but `$ai_generation` records `cache_read=0` for every gpt-5.5 gen — cost+ attribution over-prices Codex runs and hides caching efficiency.+4. **120MB handoff-pack uploads fail:** every Codex turn log ends with `Direct artifact upload+failed … fetch failed` + `Discarding handoff checkpoint (packBytes≈120MB)` — the handoff+ checkpoint never survives; worth a look independent of this experiment.++## Recommendation++Keep **`claude-sonnet-5` @ `xhigh`** as the perspective reviewer — now confirmed against four models.+For the two new arms specifically:++- **Opus 4.8 @ xhigh: no.** The speed win is real (24–26 min review stage vs Sonnet’s 30–45; ~45 min full runs vs ~67–85;+ fastest wall-clock runs of the experiment at ~45 min) and it runs operationally clean, but as a+ _reviewer_ it delivered the worst verified yield of the four (5/30, zero must_fix, flagship bug+ missed twice) at ~40% higher finder cost than Sonnet. All three blind judges ranked it last. If+ review latency ever becomes the binding constraint, revisit with a recall-oriented prompt/skill+ tune — selectivity, not capability, looks like the limiter.+- **gpt-5.5 via Codex: no, on operational grounds.** 17/17 first-attempt refusals on this PR's+ security-heavy content, plus Codex MCP flakiness, make it unusable in this pipeline today. Its+ depth-per-finding when it does run (both heavy must_fixes in one run) suggests re-testing only+ after the refusal behavior changes upstream and the runner fails fast on refusals (bug 1 above).++Revisit GLM 5.2 if any of these change:++1. **Prompt caching lands on the GLM path** — the cost disadvantage (its biggest practical negative)+ inverts: GLM's raw token flow is smaller than Sonnet's.+2. **A "deep-catch" slot exists** — GLM as an _additional_ blind-spot/perspective lens (not a+ replacement) is the strongest configuration this data supports: low overlap + repeatable depth+ means the union catches more; cost of one extra unit per chunk is the trade.+3. **Validator calibration improves** — GLM's noise (80%) currently survives dedup and burns validator+ time; a cheaper pre-validator triage would change its economics.++## Round 4 (2026-07-30): GPT 5.6 Luna and Terra++Same frozen diff, new target: **PR #75215**, a draft copy of #72680 frozen at `1341596e` (the+original PR moved on to fixes). Same pinned chunks, same zero-comment mock, same Opus validator.+Arm G = `CODEX`/`gpt-5.6-luna`/`XHIGH`/`"full-access"`, arm H = `CODEX`/`gpt-5.6-terra` (same+config). Blind sets M (G1), K (G2), J (H1), L (H2); one adversarial refutation-first verifier per+finding against the worktree (verdicts in [judge-round4.json](./judge-round4.json)); clusters+extended incrementally over all 12 sets (56 → 62); 3-lens blind panel over six anonymous models.+This round ran with working local `$ai_generation` telemetry (see ops notes), so Codex costs are+cache-aware for the first time — `true $` below prices OpenAI cache reads properly.++### Runs G/H++| | G1 (Luna) | G2 (Luna) | H1 (Terra) | H2 (Terra) |+| ------------------------------- | ------------- | ------------- | ------------ | ------------- |+| Status | valid¹ | valid | valid² | valid |+| Raw → dedup → pipeline-valid | 16→14→3 | 16→14→2 | 8→6→3 | 11→10→3 |+| **Independently verified real** | **3/14** | **1/14** | **2/6** | **4/10** |+| …of which must_fix | 0 | 1 | 1 | 3 |+| Review stage | 41m39s¹ | 19m49s | 33m19s² | **8m04s** |+| Total run cost (true / gw) | $11.82/$16.20 | $13.84/$17.67 | $8.88/$14.34 | $12.47/$18.17 |+| Unit retries (fake refusals) | 24 | ~9 | 9 | ~0 |++¹ ² Wall-clock inflated by one gen-silent retry riding the 30-min poll budget (G1 `p2-c1`, H1+`p3-c1`; H1's unit was lost, 8/9 — under the fan-out floor). Clean-path Terra (H2) reviewed the+whole PR in **8 minutes**.++### Six-model blind scoreboard (verified findings, both runs pooled)++| Model | Real/Total | Precision | must_fix | Clusters (of 62) | ~Review time | ~Cost/run |+| ------------ | ---------- | --------- | -------- | ---------------- | ------------ | --------- |+| M1 Sonnet 5 | 14/44 | 31.8% | 1 | **36** | ~35m | ~$50 |+| M2 GLM 5.2 | 7/36 | 19.4% | 3 | 31 | ~55m | ~$60 |+| M3 gpt-5.5 | 3/17 | 17.6% | 2 | 13 | ~30m | ~$25 |+| M4 Opus 4.8 | 4/30 | 13.3% | 0 | 17 | ~25m | ~$55 |+| M5 **Luna** | 4/28 | 14.3% | 1 | 17 | ~25m | **~$13** |+| M6 **Terra** | 6/16 | **37.5%** | **4** | 11 | **~15m** | **~$11** |++Time and cost are close-enough normalized estimates, not exact: representative clean-path review+time (gpt-5.5's excludes the since-fixed refusal-hang tax; the 5.6 arms' one-straggler runs ran+longer) and roughly de-distorted per-run cost (rounds 1–3 were gateway/list-priced with known+skews; Luna/Terra are cache-aware `true $`). Exact per-run figures live in each round's run table.++Judge rankings (blind, one lens each):++- **Recall:** M1 > M2 > M6 > M5 ≈ M4 > M3 — Sonnet still dominates coverage (14 reals over 14+ distinct clusters, 5 of them solo catches).+- **Precision:** **M6 > M1** > M2 > M3 > M5 > M4 — Terra is the panel's best signal-to-noise:+ 16 findings emitted, 6 real.+- **Impact:** **M6 > M2** > M1 > M3 > M5 > M4 — Terra's 4 verified must_fix from 16 findings is+ the densest heavy-catch rate ever recorded in this experiment, including the receiver-leg+ approval-redirect hole from both sides (L4 dispatch + L6 worker) and a migration-leaf CI blocker+ (J5 + L3, shared only with Luna's K6) that all four earlier models missed.++### What round 4 changes++- **Terra is the new runner-up and the efficiency frontier.** Best precision, best impact, ~$10/run+ (3–5× cheaper than the Claude arms), and the fastest clean review ever (8m04s). Its weakness is+ recall (11 clusters) — it finds little, but what it finds is disproportionately real and heavy.+- **Luna is not competitive despite the price.** Its Sonnet-like volume (16 raw/run) collapsed+ under adversarial verification (4/28 real, second-worst precision). The pipeline validator's+ "valid" counts (3/2) flattered it; the deeper verifier pass did not.+- **Sonnet 5 @ xhigh stays the default reviewer.** Recall is the pipeline's primary job and Sonnet's+ 36-cluster coverage is untouched; it is also second on precision.+- **The "gpt-5.5 refusal storm" was never a safety refusal.** Round 4 proved the mechanism: the+ codex-app-server maps `TurnStatus:"failed"` → ACP `"refusal"`, and BOTH 5.6 arms had ~100% of+ first attempts "refuse" simultaneously ~90s in with **zero tokens billed** — a client-side+ failure (likely the MCP-connect race at boot, amplified by 9 concurrent sandboxes), which+ staggered retries then clear. The round-3 C-arm narrative should be read accordingly. The+ refusal fail-fast fix (landed this round in products/tasks, with regression tests) is what makes+ Codex arms viable at all: each fake refusal now costs ~90s instead of a 30-minute poll timeout.+- **Config worth exploring next:** Terra as a cheap high-signal second-opinion unit (or blind-spot+ lens) alongside Sonnet's wave — the union would have caught every verified must_fix this round+ at a fraction of a second Sonnet pass.++## Round 5 (2026-07-31): Sonnet 5 stability check + GPT 5.6 Sol++Same frozen target (**PR #75215** @ `1341596e`), same pinned chunks, zero-comment mock, and Opus+validator. Two questions: **(1)** were Sonnet's round-1 numbers two lucky rolls? — answered with two+fresh Sonnet runs (A3/A4, blind sets N/O) verified and clustered but **excluded from the panel** so+every ranked model keeps a uniform 2-run basis; **(2)** does GPT 5.6 Sol justify its price at xhigh?+— arm I = `CODEX`/`gpt-5.6-sol`/`XHIGH`/`"full-access"` (sets S/W), full protocol, panel re-ranked+with Sol as the seventh model. One refutation-first verifier per finding against the frozen worktree+(73 verifiers, 0 errors); clusters extended 62 → 74; verdicts in+[judge-round5.json](./judge-round5.json).++### Runs A3/A4 (Sonnet stability) and I1/I2 (Sol)++| | A3 (Sonnet) | A4 (Sonnet) | I1 (Sol) | I2 (Sol) |+| ------------------------------- | ----------- | ----------- | ------------ | ------------- |+| Status | valid¹ | valid | valid | valid |+| Raw → dedup → pipeline-valid | 28→23→2 | 30→26→4 | 14→11→2 | 14→13→4 |+| **Independently verified real** | **7/23** | **7/26** | **4/11** | **4/13** |+| …of which must_fix | 2 | 1 | 1 | 2 |+| Review stage | n/a¹ | 31m58s | **7m02s** | 8m58s |+| Total run cost (true / gw) | $38.62 | $38.68 | $9.40/$17.31 | $12.91/$19.71 |+| Unit retries (fake refusals) | — | — | 17 | 16 |++¹ The host machine slept ~6.5h mid-run; Temporal recovered the interrupted unit on wake and the run+completed cleanly. Findings and cost are valid; wall-clock is meaningless and excluded. A4 ran on a+healthy stack and carries the representative Sonnet timings.++### Sonnet stability annex: the round-1 numbers were not luck++Four Sonnet runs now exist across two rounds, and the verified-real count is **exactly 7 in every+one of them**: X 7/20, P 7/24, N 7/23, O 7/26 — pooled 28/93 (30.1%), with the original pair at+31.8% and the stability pair at 28.6%. Volume (20–26 findings post-dedup), precision class, and+cluster coverage (36 for X+P vs 33 for N+O, 18 shared) all reproduce. The half-shared cluster+overlap is partly run-to-run variance in _which_ issues Sonnet surfaces and partly **target drift**:+rounds 1–3 reviewed live #72680 before the freeze, where some of today's issues did not exist.++The drift matters for one round-4 claim: the migration-0019 leaf conflict (CI blocker) that round 4+called a Terra/Luna exclusive was caught by **both** Sonnet stability runs as must_fix (N9, O7) —+rounds 1–3 models never saw it because it post-dates their review target. On the frozen PR, Sonnet+catches it. A3 also caught the receiver-leg linkage hole as must_fix (N10); A4's touch on that+cluster did not survive verification.++### Seven-model blind scoreboard (verified findings, both runs pooled)++| Model | Real/Total | Precision | must_fix | Clusters (of 74) | ~Review time | ~Cost/run |+| ----------- | ---------- | --------- | -------- | ---------------- | ------------ | --------- |+| M1 Sonnet 5 | 14/44 | 31.8% | 1 | **36** | ~35m | ~$40 |+| M2 GLM 5.2 | 7/36 | 19.4% | 3 | 31 | ~55m | ~$60 |+| M3 gpt-5.5 | 3/17 | 17.6% | 2 | 13 | ~30m | ~$25 |+| M4 Opus 4.8 | 4/30 | 13.3% | 0 | 17 | ~25m | ~$55 |+| M5 Luna | 4/28 | 14.3% | 1 | 17 | ~25m | ~$13 |+| M6 Terra | 6/16 | **37.5%** | **4** | 11 | ~15m | ~$11 |+| M7 **Sol** | 8/24 | 33.3% | 3 | 16 | **~8m** | **~$11** |++Same normalization caveats as round 4. Sonnet's ~cost drops from ~$50 to ~$40: the two cache-aware+stability runs both priced at $38.6 true, showing the round-1 estimate carried list-price skew.+Sol's ~8m is honest — both runs were straggler-free (7m02s / 8m58s review stage).++Judge rankings (blind, one lens each; M1..M6 verified data unchanged from round 4):++- **Recall:** M1 > **M7** > M2 > M6 > M4 > M5 > M3 — Sonnet remains the runaway winner (14 reals+ over 14 distinct real clusters, 5 solo); Sol takes second with 8 reals over 7 real clusters,+ beating GLM.+- **Precision:** M6 > **M7** > M1 > M2 > M3 > M5 > M4 — Terra keeps the crown (37.5%), Sol close+ behind (33.3%), Sonnet third; the judge singled out the bottom four for fabricated findings,+ which Sol avoided entirely.+- **Impact:** **M7 > M6** > M2 > M1 > M3 > M5 > M4 — no model owns an exclusive must_fix; every+ must_fix maps to three heavy clusters (A: dead carve-out `internal=True` leg; B: receiver-leg+ provenance/no-PR-linkage; C: migration-0019 conflict). **Sol is the only model with verified+ findings on all three** (S2+W4 must_fix on C in both runs, W6 must_fix on B, W11 should_fix on+ A) plus the unique security-adjacent S10 (branch fallback binding an unrelated run as+ self-driving).++### What round 5 changes++- **Sonnet 5 @ xhigh is confirmed, not lucky.** Four runs, four times exactly 7 verified reals,+ stable volume, stable precision class, untouched recall crown. It stays the default reviewer.+- **Sol displaces Terra as the Codex champion and the efficiency frontier.** Same ~$11 true cost+ class, faster still (~8m clean in both runs), better recall than Terra (16 vs 11 clusters),+ near-Terra precision, and the panel's #1 impact — the only model to touch all three heavy+ clusters with verified findings. Terra's remaining edge is pure precision density (4 must_fix in+ 16 emissions).+- **Round-4 correction:** the migration-0019 CI blocker was never a 5.6-family exclusive — Sonnet+ catches it on the frozen target (both stability runs, must_fix). The claim was an artifact of+ rounds 1–3 reviewing the pre-freeze PR.+- **The second-opinion slot now belongs to Sol.** The round-4 idea (Terra as a cheap high-signal+ lens beside Sonnet's wave) upgrades: Sonnet + Sol union covers every verified must_fix cluster+ this round at ~$11 over Sonnet's ~$40, with Sol also contributing the unique S10 catch.+- **Codex boot-storm tax persists but is survivable:** 17 and 16 fake-refusal first attempts per+ Sol run, all cleared by the fail-fast retries with zero straggler runs — the fix landed in+ round 4 is doing its job.++## Round 6 (2026-07-31): sequential Sol — does injected memory make a second run additive?++Round 5 showed a blind second Sol run mostly re-treads the first (S2→W4 dup, ~3 new reals). Round 6+tests the production shape instead: **arm J** ran Sol twice on the same report with **no DB wipe**,+separated by an empty commit (`a7fb363`, identical tree — the real "new commits → new turn"+trigger), so turn 2 ran as `run_index=2` with the pipeline's **native prior-findings injection**+(`<already_covered_findings_for_chunk>`, DB-sourced, publication-independent — verified present in+all 9 of J2's unit prompts before the wave spent money). Blind sets Z (J1) and E (J2, own-turn+findings only; the dump funnel is cumulative across turns). Verdicts in+[judge-round6.json](./judge-round6.json); clusters 74 → 76.++### Runs J1/J2++| | J1 (Sol, blind) | J2 (Sol + injected memory) |+| ------------------------------- | --------------- | -------------------------- |+| Own-turn raw → dedup → valid | 11→10→3 | 4→4→3¹ |+| **Independently verified real** | 3/10 | **3/4 (75%)** |+| …of which must_fix | 1 | **2** |+| Re-reports of turn 1 | — | **0** |+| Review stage | 6m59s | 8m23s |+| True cost | $9.56 | **$6.10** |++¹ The J2 dump's funnel line reads cumulatively across turns (15→14→6); turn-2's own emissions were+4 raw, all surviving dedup, 3 passing the pipeline validator.++### What the sequential pair found++J2's three verified reals all land in clusters J1 never touched — zero overlap, zero anchoring:++- **E1 (must_fix, brand-new cluster):** the webhook carve-out accepts **any** GitHub bot as the+ self-driving author (`_is_bot_authored` any-Bot floor) — no prior run-set across all seven+ models had surfaced it (cluster #75 of 76).+- **E2 (must_fix):** the migration-0019 CI conflict — which J1's blind pass had _missed_ this+ time; the injection filled J1's gap rather than confining J2 to J1's map.+- **E4 (should_fix):** receiver-leg dedupe excludes FAILED runs → persistent retry loop —+ previously caught only by Sonnet.++J1's own reals: Z8 (must_fix, receiver-leg linkage hole), Z3 (should_fix, the single-acting-+reviewer gate contradicting the PR's thrice-stated any-opted-in spec), Z6 (consider, stale draft+sentence). Pair union: **6 distinct real clusters, 3 must_fix, $15.66 true, ~48 min wall.**++### What round 6 changes++- **The injection works exactly as intended.** Blind repeat runs duplicate (round 5); with memory,+ emission-level duplication was zero and the second turn went where the first hadn't. The+ "5.6 reach limit" hypothesis from round 5 is dead — the reach limit was per-run, not per-model.+- **Marginal Sol turns are absurdly cheap signal:** turn 2 cost $6.10 and returned 3 verified+ reals including 2 must_fix — the best verified-real-per-dollar of the whole experiment+ (0.49 reals/$; one Sonnet run is ~0.18).+- **"Run Sol until dry" becomes a plausible deep-review mode**, and the production re-review path+ already does this for free on every new push — each re-review turn should be expected to add,+ not repeat.+- Caveats: J1 was the weakest blind Sol single yet (3/10 vs 4/11 and 4/13) — single PR, single+ pair, so the per-run variance is real; and the pair's union recall (6 clusters) still sits+ below a single Sonnet run's 7 reals — Sonnet's breadth remains unmatched per-run.++### Updated recommendation++Unchanged core: **Sonnet 5 @ xhigh keeps the wave.** The second-opinion slot stays **Sol**, now+with evidence that its turns compound under the pipeline's native memory: Sonnet wave + Sol lens+on the first review, and Sol's re-review turns keep paying for themselves on every subsequent push.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/PLAN.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/PLAN.mdnew file mode 100644index 000000000000..91bb65c37c27--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/PLAN.md@@ -0,0 +1,338 @@+# Experiment: GLM 5.2 vs Sonnet 5 as the perspective-review model++> **ROUND 6 — EXECUTED 2026-07-31, verdict: PASS — injected memory makes Sol turns additive.**+> J2 (turn 2, native `<already_covered_findings_for_chunk>` injection verified in all 9 unit+> prompts): 3/4 verified real (75%), 2 must_fix, ZERO re-reports of J1 — incl. **E1, a brand-new+> must_fix cluster (any-GitHub-bot author floor) no prior set across 7 models found**, and E2+> re-catching the migration blocker J1's blind pass missed (no anchoring). Pair: 6 distinct real+> clusters / 3 must_fix at $15.66 true (~48m); marginal turn = $6.10 → 3 reals, best+> reals-per-dollar of the experiment. The round-5 "5.6 reach limit" was per-RUN, not per-model.+> Caveats: J1 = weakest blind Sol single (3/10); pair recall 6 < one Sonnet run's 7. Empty commit+> `a7fb363` (signed — unsigned commit-tree pushes bounce off the repo ruleset) moved the head;+> clusters 74 → 76; data in FINAL_REPORT § Round 6 + judge-round6.json. Original spec below.+>+> **ROUND 6 spec (2026-07-31): sequential Sol with prior-findings injection.**+> Question: round 5 showed a blind second Sol run wastes budget re-finding run 1's issues (S2→W4+> dup, ~3 new distinct reals). Does a second Sol run that KNOWS run 1's findings push into new+> territory instead — and does 2×Sol-with-memory then rival one Sonnet run (7 reals, ~$40) at ~$25?+>+> **Arm J** = `CODEX`/`gpt-5.6-sol`/`XHIGH`/`"full-access"`, same frozen PR #75215 @ `1341596e`,+> same chunk pin + Opus validator. Labels `J-gpt56sol-seq-{1,2}`, blind sets Z (J1) and E (J2).+> Protocol: wipe → J1 (blind, identical to round-5 arm I) → dump → **NO wipe** → push an **empty+> commit** to the frozen branch (new head SHA, diff byte-identical — the production "new commits →+> new turn" trigger shape, with zero review-content change) → J2 (sees J1's findings) → dump →+> revert + wipe.+>+> **Context injection is NATIVE — no harness changes beyond round 5's.** The pipeline already+> injects prior turns' findings from the ReviewHog DB into every review unit's prompt as+> `<already_covered_findings_for_chunk>` (`load_prior_findings_with_verdicts` keyed by+> `before_run_index`, publication-independent — "some … were never posted as inline comments"),+> and the same set joins the dedup gate as an enforcement backstop. The round-3+> `fetch_pr_comments` clean-room mock (`return []`) stays exactly as-is: it only suppresses the+> real GitHub comments (the frozen PR carries other bots' noise), which is still wanted.+>+> **Mechanics (verified against the code 2026-07-31):**+>+> - The empty-commit head bump makes the whole turn-2 path production-shaped: `run_index =+report.run_count + 1` (run_count bumped at J1's finalize) gives turn 2 naturally, and unit+> resume is head_sha-scoped (`load_perspective_results` keys `(report, head_sha) → (pass,+chunk)`), so the new head misses turn-1 artefacts organically — no scrubbing, no same-SHA+> special-casing. An earlier draft of this spec scrubbed working-state artefacts to force a+> same-SHA re-review; dropped as unrealistic — prod re-reviews only ever happen on a moved head.+> - The chunk pin and the verification worktree stay valid because the empty commit leaves the+> diff byte-identical; dumps will just record the new head_sha.+> - The pushed empty commit needs Alex's go (or Alex pushes it) — experiment sessions never push.+> - Verify J2's kickoff prompt actually contains the injected findings (spot-check one unit's+> rendered context) before letting the wave spend money.+>+> **Measurement:** adversarially verify J1 and J2 (same refutation-first protocol, worktree @+> `1341596e`); extend clusters. Read out: (1) duplicate rate J2-vs-J1 — injection efficacy,+> expect ≈0 vs the blind pair's re-finds; (2) NEW distinct verified reals J2 adds beyond J1;+> (3) union(J1, J2) vs one Sonnet run (7 reals) and vs the blind Sol pair (8 reals / 7 distinct);+> (4) anchoring check — does J2 merely extend/validate run-1 areas. Verdict rule: J2 adds ≥3 new+> distinct verified reals with ≈0 dups → sequential-Sol-with-memory is a real config, promote the+> DB-backed injection idea; J2 rehashes despite injection → the 5.6 reach limit is confirmed and+> the Sonnet-wave + single-Sol-lens combo stands as the endgame.+>+> **ROUND 5 — EXECUTED overnight 2026-07-30 → 31, all 4 runs + judging completed.** Two arms:+> Sonnet stability (A3/A4, sets N/O — verified + clustered, excluded from the panel) and+> **GPT 5.6 Sol** (arm I = `CODEX`/`gpt-5.6-sol`/`XHIGH`/`"full-access"`, sets S/W, full protocol,+> panel re-ranked with Sol as M7). Verdict: **Sonnet's numbers were not luck** — four runs across+> two rounds each produced exactly 7 verified reals (7/20, 7/24, 7/23, 7/26); default unchanged.+> **Sol displaces Terra as the Codex champion**: 8/24 real (33.3%), 3 must_fix, 16 clusters,+> panel #1 on impact (only model touching all three heavy clusters), #2 on recall AND precision,+> ~$11 true and ~8m clean review in both runs. Round-4 correction: the migration-0019 CI blocker+> was target drift, not a Sonnet blind spot — both stability runs catch it as must_fix on the+> frozen PR. Full data: FINAL_REPORT § Round 5 + judge-round5.json (clusters 62 → 74).+> Ops: A3 survived a ~6.5h host sleep mid-run (Temporal recovered on wake; timings excluded,+> findings/cost valid). Preflight lesson applied: product-path probe for `gpt-5.6-sol` 200'd+> before launch (allowlist extended in gateway config.py — kept, like the round-4 additions).+> Sol's fake-refusal boot storms (17 and 16 first-attempt failures) fully absorbed by the+> fail-fast retries; zero stragglers, zero rescue. Harness reverted to the master baseline+> (byte-identical via merge-base checkout) and staged the same night.+>+> **ROUND 4 — EXECUTED 2026-07-30, all 4 runs completed same day.** Verdict: **Terra** wins+> precision (6/16 real) and impact (4 must_fix, densest ever) at ~$10/run with an 8-minute clean+> review; **Luna** not competitive (4/28 real); **Sonnet keeps the default** on recall. Full data:+> FINAL_REPORT § Round 4 + judge-round4.json. Harness reverted to baseline the same day.+>+> **ROUND 4 (2026-07-30) — GPT 5.6 (Luna, Terra), supersedes round 3.** Round 3's arms are dropped:+> arm E (gpt-5.5 retest) is superseded by the 5.6 family (faster, and Luna far cheaper); arm F+> (GLM via Modal) is shelved — the Modal deployment 503'd under the 9-session fan-out on 2026-07-24,+> and GLM is slow regardless. Of the arm-E prerequisites, #2 landed this round as a real product fix:+> `_check_logs`/`poll_for_turn` now treat `stopReason:"refusal"` as terminal (fail fast → in-session+> nudge retry → activity retry), so a refusal costs seconds, not 30 minutes.+>+> **Target: PR #75215** — a frozen copy of #72680 at `1341596e` (same branch content, opened as its+> own draft PR because #72680's head moved on to the fixes). Diff content is byte-identical to what+> rounds 1–3 reviewed, so the pinned chunks and zero-comment mock carry over unchanged; run dumps+> carry the new PR number.+>+> | Arm | Adapter | REVIEW_MODEL | Effort | Permission mode | Runs | Labels |+> | --- | ------- | --------------- | ------- | --------------- | ---- | -------------------------- |+> | G | `CODEX` | `gpt-5.6-luna` | `XHIGH` | `"full-access"` | ≤2 | `G-gpt56luna-xhigh-{1,2}` |+> | H | `CODEX` | `gpt-5.6-terra` | `XHIGH` | `"full-access"` | ≤2 | `H-gpt56terra-xhigh-{1,2}` |+>+> Effort: `xhigh`, matching Sonnet/Opus/gpt-5.5 (GLM-at-MAX stays the outlier); 5.6 also supports a+> new `max` tier — a later curiosity repeat, not part of this round. Order interleaved+> G1 → H1 → G2 → H2, wipe DB + verify PR head before each run. Repeat gate per arm: a run that+> DNFs after the retry ladder or needs heavy operational rescue = technical shitshow → skip the+> repeat, record "no verdict — infra" (not a model judgment); completes with 0 validated findings =+> model shitshow → skip the repeat, it IS the data point; weak-but-complete → repeat happens.+> Judging: incremental, same machinery as the 4-way — blind the new sets, one adversarial verifier+> per finding against the worktree @ `1341596e`, extend the existing cluster set, fresh 3-lens+> panel over all six anonymized models reusing the old sets' verdicts.+> Preflight 2026-07-30: gateway probes `gpt-5.6-luna` + `gpt-5.6-terra` → 200/completed; django+> tunnel probed from Modal's network → 200; fresh local DB (user 1 / team 1 / GitHub integration+> installed). End state unchanged: revert mock + pin + constants to the Sonnet baseline.+>+> **G1 attempt 1 (2026-07-30 ~12:00) failed on a gateway allowlist gap, not the model.** All 8+> units died in ~30 min with `stopReason:"refusal"` at 0 tokens. ngrok's request inspector showed+> every sandbox call as `POST /review_hog/v1/responses → 403`: the gateway's `review_hog` product+> allowlist lacked the 5.6 family (only glm-5.2 / sonnet-5 / opus-4-8 / gpt-5.5). Fixed by adding+> `gpt-5.6-luna` + `gpt-5.6-terra` to `services/llm-gateway/.../products/config.py`; uvicorn+> `--reload` picked it up; product-path probes then 200'd. Two durable lessons: (1) preflight must+> probe the **product-scoped** path (`/review_hog/v1/responses`), not the generic `/v1/responses` —+> the generic path runs under the allow-everything `llm_gateway` product; (2) codex-app-server maps+> codex `TurnStatus:"failed"` → ACP `"refusal"` (`mapTurnStopReason`), so "refusal" in our logs+> means "turn failed", not necessarily a safety refusal — which casts doubt on whether round-3's+> gpt-5.5 "refusal storm" was ever a content refusal (its refusals arrived ~90s in with the model+> allowlisted, so that one did reach the API; mechanism still unconfirmed).+>+> **CONFIRMED during G1/H1 (2026-07-30): Codex first attempts fail systematically, and it is not+> the model.** In both G1 (Luna) and H1 (Terra), **all 9 first-attempt review units failed within+> seconds of each other**, ~90s after session start, labeled `stopReason:"refusal"`, with **zero+> tokens billed** — the requests never reached OpenAI, so this is not a content/safety refusal and+> not chunk-specific. Staggered retries then succeed (G1: 24 failed attempts hidden inside a+> "clean" run; H1: 8/9 attempt-2s recovered immediately). Blind-spot and validation stages (4+> concurrent, later boot) never hit it. Working theory: the codex-app-server MCP-connect race at+> sandbox boot, amplified by 9 simultaneous first-boots — the same mechanism as round 3's C1+> "17/17 refusal storm", now effectively proven. The refusal pre-fix is what makes this survivable:+> each failed attempt costs ~90s instead of a 30-min poll timeout. Residual cost: units whose retry+> goes gen-silent still ride the 30-min poll budget (G1's p2-c1, H1's p3-c1) — that is the real+> wall-clock tax on Codex arms. Adapter-level fix (await MCP ready before the first prompt, or+> fail-fast + instant retry) belongs in posthog/code, not this experiment.+>+> **G1 attempt 2 (healthy, ~40 min in) was terminated by Alex's call: it ran with zero cost/token+> telemetry**, and cost/token is a hard requirement. The fresh stack loses every local+> `$ai_generation` in two stacked ways: the gateway process never received the+> `LLM_GATEWAY_POSTHOG_*` env from `bin/mprocs.yaml` (capture disabled entirely — fixed via repo+> `.env` + gateway restart), and once enabled, the SDK's AI lane (`/i/v0/ai/batch/`) 200-ACKs+> events that `ingestion-ai` then drops (its forwarder 401s on `localhost:8010/batch/` and shuts+> down). Local bypass in the gateway callback: `_use_ai_lane=False` **and**+> `_enable_multimodal_capture=False` (multimodal implies the lane) — marked EXPERIMENT, revert+> both. E2E verified: gateway probe → luna gen with cost in local ClickHouse. Cleanup: 15 orphan+> Modal sandboxes terminated, DB wiped. G1 attempt 3 is the first run with full telemetry.++> **ROUND 3 (planned 2026-07-24, not started — Alex present for these; SUPERSEDED by round 4).** Two follow-up arms, prompted+> by the round-2 findings and Alessandro's Slack comment that GLM was supposed to run on **Modal+> inference** (which supports caching and reportedly runs faster than Opus), not Cloudflare:+>+> | Arm | What | Config | Runs | Labels |+> | --- | ------------------------------- | -------------------------------------------------------------------------------------- | ---- | ------------------------ |+> | E | gpt-5.5 retest, done properly | `CODEX`/`gpt-5.5`/`XHIGH`/`"full-access"` — after the fixes below | 2 | `E-gpt55-xhigh-{1,2}` |+> | F | GLM 5.2 via **Modal inference** | `CLAUDE`/`@cf/zai-org/glm-5.2`/`MAX` + gateway routed to Modal (`zai-org/GLM-5.2-FP8`) | 2 | `F-glm52modal-max-{1,2}` |+>+> **Why round 2's arm C was not a fair gpt-5.5 test:** 17/17 first-attempt provider refusals+> (`stopReason:"refusal"` ~90s in), each amplified into a 30-min hang by the `poll_for_turn` bug;+> ~43% of Codex sandboxes silently got no MCP tools and reviewed without their perspective skill.+> C1 hard-failed; C2 recovered only via a 3rd-attempt ladder. Details: FINAL_REPORT § 4-way extension.+>+> **Arm E prerequisites (fix/diagnose first, with Alex present):**+>+> 1. Reproduce the refusal cheaply outside the pipeline: replay a failed unit's exact `session/prompt`+> text (saved in the S3 turn logs) against gpt-5.5 directly through the gateway — distinguishes+> model-refuses-content from a Codex-adapter/harness artifact. Iterate on whatever it shows.+> 2. Make `poll_for_turn` treat a refusal-completed turn as terminal (products/tasks+> `custom_prompt_internals.py`) — otherwise every experiment iteration costs 30 min per refusal.+> Real product bug; worth landing regardless.+> 3. Diagnose Codex MCP flakiness (9/21 sessions in C1 had no `posthog/exec`) — likely a connect race+> at session start; a turn without MCP tools should fail fast, not improvise skill-less.+> **Arm F prerequisites:**+> 4. Local gateway needs the Modal inference creds: `LLM_GATEWAY_MODAL_API_BASE`,+> `LLM_GATEWAY_MODAL_KEY`, `LLM_GATEWAY_MODAL_SECRET` (Alex fetches, same place as the CF keys).+> 5. Force the Modal route with `LLM_GATEWAY_GLM_MODAL_TRAFFIC_FRACTION=1.0` (routing precondition:+> all three Modal creds set, else `_route_to_modal` short-circuits to Cloudflare). Verify with a+> probe request + gateway logs BEFORE run 1; also verify the cache signature — Modal/vLLM prefix+> caching should show as non-zero cached tokens, which the CF path never had.+> 6. Cost accounting decision: Modal is self-hosted (no per-token list price; gateway will price+> $0.00) — report raw token flow + wall-clock, and compare CF-list-priced tokens as an upper bound.+> **Shared harness (re-apply for the runs, revert after — all three were reverted post-round-2):**+> comment mock (`fetch_pr_comments → []`), chunk pin (constants loader + `split_chunks_activity`+> hook, `pinned_chunks.json` still in this folder), arm constants. PR 72680 must still be at+> `1341596e` — verify before each run; if the head moved, stop and re-plan (results would not be+> comparable with rounds 1–2).+> **Carry-over caveat for arm F conclusions:** round-2's GLM cost (+50–100%) and speed (slower)+> findings are Cloudflare-path artifacts (zero caching); only the quality numbers (7/36 verified+> real, must_fix ownership, ~30% Sonnet overlap) are expected to carry over.++> **EXTENDED 2026-07-23 night → 4-way model comparison.** After the A/B verdict (see FINAL_REPORT.md),+> two more arms run overnight on the identical setup (same PR @ `1341596e`, same pinned chunks, same+> zero-comment clean room, same validator):+>+> | Arm | Adapter | REVIEW_MODEL | Effort | Permission mode | Runs | Labels |+> | --- | -------- | ----------------- | ------- | --------------------------------------------------------- | ---- | ---------------------- |+> | C | `CODEX` | `gpt-5.5` | `XHIGH` | `"full-access"` (headless Codex stalls on MCP without it) | 2 | `C-gpt55-xhigh-{1,2}` |+> | D | `CLAUDE` | `claude-opus-4-8` | `XHIGH` | `None` | 2 | `D-opus48-xhigh-{1,2}` |+>+> Order C1 → C2 → D1 → D2 (one constants flip between arms), dump → wipe after every run.+> Arm-C failure policy: if a C run hard-fails, retry once; if the arm fails twice, skip to D and+> report — don't burn the night. Note for D: Opus 4.8 IS the SDK fallbackModel, so fallback+> contamination is undetectable-by-construction for that arm (note it, don't chase it).+> Judging: blind sets R (C1), T (C2), U (D1), V (D2) via `blind_prep.py`; verify every finding+> against the PR worktree; cluster across all 8 sets; 3-lens panel over four anonymous models.+> End state: revert mock + pin + constants to the Sonnet baseline; extend FINAL_REPORT.md to the+> 4-way verdict; RUN_LOG + memory + Slack summary (/tmp).++**Question:** is `@cf/zai-org/glm-5.2` better than `claude-sonnet-5` at applying ReviewHog's review perspectives?+Everything else in the pipeline is held constant.++Follows the shared on-pipeline protocol (`../2026-07-reviewer-topology/PLAN.md` §"The dump/reset harness",+`../../POTENTIAL_EXPERIMENTS.md` §"Shared protocol for all on-pipeline runs"), with a fresh target PR.++## Arms++| Arm | REVIEW_MODEL | REVIEW_REASONING_EFFORT | Runs | Labels |+| -------------------------------------- | --------------------- | ----------------------- | ----------------- | ----------------------- |+| A (baseline = prod config, zero edits) | `claude-sonnet-5` | `XHIGH` | 1 (+1 if unclear) | `A-sonnet5-xhigh-{1,2}` |+| B | `@cf/zai-org/glm-5.2` | `MAX` | 1 (+1 if unclear) | `B-glm52-max-{1,2}` |++**Adaptive pairs** (decision 9): run A1 → B1, judge head-to-head; only if the verdict is unclear run+A2 → B2 and re-judge over all four. "Clear" = one arm wins on validated-finding quality with no red+flags (schema/parse failures, model fallback, lost wave units); thin or mixed margins → second pair.++Effort note: GLM 5.2 registers only `HIGH`/`MAX` (no `XHIGH`), so effort parity with the baseline is+impossible. Decision: each model at its strongest registered setting — the question is "would GLM beat+what we run in prod today", not a same-label comparison. Caveat recorded below (drop_params).++## What changes vs prod (all in the working tree, per-arm)++1. **Gateway allowlist** (`services/llm-gateway/src/llm_gateway/products/config.py`, `review_hog` entry):+ `allowed_models=None` → `frozenset({"@cf/zai-org/glm-5.2", "claude-sonnet-5", "claude-opus-4-8", "gpt-5.5"})`.+ Deliberately the _simple_ shape — no `allowed_application_ids`/`requires_server_credential` hardening+ (stamphog-style) yet; the one-shot direct calls authenticate through this product and must keep working.+2. **Agent-side routing** (code repo, `packages/agent/src/utils/gateway.ts`): add `"review_hog"` to the+ `GatewayProduct` union + an `originProduct === "review_hog"` case in `resolveGatewayProduct`, before the+ `isInternal` catch-all. Without this, sandbox reviews route to `background_agents`, whose allowlist lacks+ GLM → 403 → the Claude-SDK `fallbackModel` silently reruns on `claude-opus-4-8` (see the documented+ incident in `../2026-07-pipeline-models/FINAL_REPORT.md`). First sandbox after the edit pays a+ MODAL_DOCKER image rebuild (image bakes from `LOCAL_POSTHOG_CODE_MONOREPO_ROOT`).+3. **Comment mock** (`backend/reviewer/tools/github_meta.py`): `return []` at the top of+ `PRFetcher.fetch_pr_comments`. The target PR already carries bot/human/prod-ReviewHog comments; this is+ the single choke point where comments enter the pipeline. Active for ALL 4 runs → both arms see zero+ comments. Experiment-only hack.+4. **Chunk pin** (`backend/reviewer/`): re-add a minimal `EXPERIMENT_PINNED_CHUNKS` (the mechanism was+ deliberately deleted from the tree after the topology round — see `../../POTENTIAL_EXPERIMENTS.md` header).+ Run A1 chunks naturally (one-shot, Sonnet 5); its split becomes the pin for A2/B1/B2, so all four runs+ review identical chunks. Experiment-only hack.+5. **Arm B constants** (`backend/reviewer/constants.py:6-7`): `REVIEW_MODEL = "@cf/zai-org/glm-5.2"`,+ `REVIEW_REASONING_EFFORT = ReasoningEffort.MAX`. Adapter stays `CLAUDE` (GLM is driven through the+ claude adapter; the gateway translates the `@cf/` id upstream). This flips the blind-spot sweep too —+ decision: the blind-spot check is a perspective, same approach applies; whole finder wave = one model+ per arm.++Held constant in both arms: validation (`claude-opus-4-8` @ xhigh — same judge for both arms), one-shot+calls (chunking / perspective selection / dedup, `claude-sonnet-5` @ xhigh), all prompts and skills+(re-seeded defaults after each wipe).++## Target PR++`https://github.com/PostHog/posthog/pull/72680` (own PR — open, non-draft, non-fork,+head `posthog-code/stamphog-reviews-inbox-prs`). ~742 reviewable additions after filters → one-shot+chunking path. **Frozen for the duration: no pushes to the branch until the experiment is done.**+Runs never use `--publish`; with a fresh `ReviewReport` row each run, zero GitHub writes (the mid-run+status-comment refresh is a no-op when `status_comment_id` is NULL).++## Per-run loop (serial, adaptive: A1 → B1 → judge → [A2 → B2])++1. Set constants for the arm; confirm the temporal-worker hot-reloaded (never flip mid-flight).+2. `date +%s` → RUN_START_EPOCH.+3. `flox activate -- bash -c "SANDBOX_PROVIDER=MODAL_DOCKER DJANGO_SETTINGS_MODULE=posthog.settings \+python manage.py run_review --pr-url https://github.com/PostHog/posthog/pull/72680 --team-id 1 --user-id 1"`+4. Dump: `LABEL=<label> RUN_SECONDS=<s> RUN_START_EPOCH=<epoch> \+OUT_DIR=products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs \+python manage.py shell -c "exec(open('products/review_hog/eval/scripts/dump_result.py').read())"`+5. **Model-integrity check (mandatory, per run):** the dump's spend table must show the arm's model on+ every `issues-review-*` / `blind-spots-*` gen — `$ai_model` is the only trustworthy signal; a 403'd or+ unlisted model silently falls back to Opus with no warning. For B1, additionally probe `$ai_generation`+ in ClickHouse mid-run as soon as the first review units start and abort early if Opus appears.+6. Wipe: `DEBUG=1 python manage.py reset_review_hog --yes` (dump ALWAYS before reset). Wipes all four+ review_hog tables across all teams; skill configs re-seed to defaults → identical roster every run.+7. Next run.++Initial state: run the wipe once before A1 (clean slate).++## Preflight (before A1)++- **Local telemetry prerequisite (required for ANY experiment run on a local stack):**+ the local ingestion-ai forwarder 401s on `/batch/` and silently drops every AI-lane `$ai_generation` event.+ Add `LLM_GATEWAY_POSTHOG_AI_LANE_CAPTURE=false` to the repo `.env` (gitignored) and restart the local gateway,+ or none of the run's generations get tracked and every cost/token number is unrecoverable.+- temporal-worker + backend running (phrocs); worker start-time > last constants edit.+- ngrok tunnels up: `django` → :8010, `gateway` → :3308, `mcp` → :8787.+- Local gateway restarted after the allowlist edit (verify it serves the edited config).+- GLM servable: gateway `/review_hog/v1/models` lists `@cf/zai-org/glm-5.2` (requires Cloudflare or Modal+ creds on the local gateway — `_glm_backend_configured`) + a tiny direct Messages probe returns from GLM.+- Code-repo routing edit in place (`resolveGatewayProduct`).+- No `ReviewReport` row for PR 72680 / team 1.+- DEBUG=1.++## Scoring (after all 4 dumps)++- **Primary:** blind head-to-head LLM-judge over the four dumps' post-dedup validated findings — which arm+ surfaces more real, higher-impact issues on identical chunks; contested findings adversarially verified+ against the repo by hand.+- **Secondary:** funnel stats (raw → post-dedup → validator pass-rate), true-$ spend per arm,+ schema/parse-failure count, run-to-run stability within each arm, and **per-stage wall-clock** from+ the dump's "Stage timing" section — the **review-stage duration** (selection → last finder unit,+ wave + blind-spot) is the headline Sonnet-vs-GLM speed metric.+- Verdict + caveats → `FINAL_REPORT.md` in this folder.++## Known caveats (record in FINAL_REPORT)++- **Effort pin may be cosmetic for GLM:** both the Cloudflare and Modal gateway translations set+ `drop_params=True`, which strips Anthropic-style effort/thinking params — `MAX` vs `HIGH` may not reach+ the backend. Check gateway logs during the B1 smoke; report either way.+- The `background_agents` allowlist also lacks `gpt-5.5` (the old Codex review pin) — prod Codex reviews+ would hit the same silent-fallback path today. Follow-up regardless of this experiment's outcome.+- ARCHITECTURE.md §Sandbox execution layer still says the perspective review runs on Codex `gpt-5.5` —+ stale; current master pins `claude-sonnet-5` @ xhigh. Fix with the routing change when it lands.+- Generated type files (`api.schemas.ts`, `api.zod.ts`, MCP `generated.ts`, ~27 adds) survive the+ reviewable-file filters by design gap and will consume review attention in both arms equally.++## Decisions log++1. GLM @ MAX vs Sonnet @ XHIGH — each model at its strongest registered setting (no XHIGH for GLM).+2. Unblock GLM via a dedicated `review_hog` gateway product route (two-sided: gateway allowlist ++ agent-side `resolveGatewayProduct` case) — not by widening `background_agents`.+3. Gateway entry keeps the simple shape (allowlist only); stamphog-style hardening is a separate follow-up.+4. Blind-spot sweep switches with the arm (it's a perspective).+5. Comments mocked to `[]` for all runs (clean-room; PR was already reviewed by other bots + prod ReviewHog).+6. Chunks pinned from A1's natural split for all subsequent runs.+7. Serial runs; wipe after every dump; PR frozen; no publish; team 1 / user 1.+8. End state: the infra edits (gateway allowlist, agent-side routing) STAY in the working tree — they're+ the durable enablement, committed if GLM wins. The experiment hacks (comment mock, chunk pin, arm-B+ constants flip) are reverted; `REVIEW_*` returns to the Sonnet baseline pending the verdict.+9. Adaptive pairs instead of fixed 2+2: A1 → B1 → judge; second pair only when the 1v1 verdict is+ unclear (cheaper in expectation, same worst case; a 1v1 gap must be large to count as clear since+ single runs carry unmeasured variance).diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/blind_prep.py b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/blind_prep.pynew file mode 100644index 000000000000..1532a5bfe99a--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/blind_prep.py@@ -0,0 +1,37 @@+"""Blind a run dump's findings section for judge agents.++Strips validator verdicts/argumentation and the model-identifying header prefix, keeping the+finder's own priority + location + body. Usage:++ python blind_prep.py <dump.md> <SET_LABEL> <out_dir>++Writes <out_dir>/set<SET_LABEL>.md with findings renumbered <SET_LABEL>1..N.+"""++import re+import sys+++def blind(dump_path: str, label: str, out_dir: str) -> int:+ text = open(dump_path).read()+ section = text.split("## Findings (post-dedup) with validator verdict", 1)[1]+ blocks = re.split(r"\n(?=### )", section)+ out: list[str] = []+ n = 0+ for b in blocks:+ if not b.startswith("### "):+ continue+ n += 1+ header = b.split("\n", 1)[0]+ m = re.match(r"### \[[^\]]*\] (\S+)(?: \(validator→[^)]*\))?(?: · [^—]*)?— (.+)", header)+ prio, loc = (m.group(1), m.group(2)) if m else ("?", header)+ body = b.split("\n", 1)[1]+ body = re.sub(r"- \*\*Validator:\*\*.*(?:\n(?!- \*\*|### ).*)*", "", body)+ out.append(f"### {label}{n} — {prio} — {loc}\n{body.strip()}\n")+ with open(f"{out_dir}/set{label}.md", "w") as fh:+ fh.write(f"# Finding set {label} ({n} findings)\n\n" + "\n".join(out))+ return n+++if __name__ == "__main__":+ print(f"set{sys.argv[2]} = {blind(sys.argv[1], sys.argv[2], sys.argv[3])} findings") # noqa: T201diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-final.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-final.jsonnew file mode 100644index 000000000000..e0252ff3f7c8--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-final.json@@ -0,0 +1,392 @@+{+ "qVerdicts": [+ {+ "id": "Q1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "PR diff (pr72680.diff lines 95-101) changes products/review_hog/backend/migrations/max_migration.txt: \"-0018_backfill_urgency_threshold_to_consider\" / \"+0019_reviewusersettings_stamphog_review_inbox_prs\". The head tree file pr72680_tree/products/review_hog/backend/migrations/max_migration.txt reads \"0019_reviewusersettings_stamphog_review_inbox_prs\".",+ "notes": "The finding claims max_migration.txt was left at 0018, but the PR itself bumps it to 0019 in the same change; the reviewer apparently missed the second hunk in the diff. Nothing to fix."+ },+ {+ "id": "Q2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "reviewer.py:636-683 indeed never checks self_driving in _format_familiarity, but the contradictory prompt is unreachable: (1) Action path \u2014 review_pr.py:984 builds Pipeline without self_driving (defaults False at line 196), so the self-driving block is always \"\" there; (2) hosted path \u2014 review_local.py:301-303 leaves familiarity None unless context[\"author_pr_numbers\"] is truthy, and activities.py:237-238 forces author_pr_numbers=[] whenever output.inbox_review is set, the exact same run.output key that line 451 uses for self_driving_review; inbox_review is stamped at run creation (tasks.py:1064, 1229), before fetch_review_context, so no ordering race exists.",+ "notes": "The invariant is enforced at a single documented source of truth on the server (comments at activities.py:234-237 and 448-450) and asserted by the PR's own tests (self_driving_review True with author_pr_numbers []). Reaching the contradiction requires a hypothetical future caller or server regression, and even then the damage is a mildly self-contradictory trusted prompt block \u2014 soft LLM-quality degradation, not correctness/security/data-loss. Engine-side suppression would be optional defense-in-depth hardening, not a fix for a real defect."+ },+ {+ "id": "Q3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/receivers.py: the deferred import `from products.stamphog.backend.facade.api import queue_inbox_pr_review` is at line 222, OUTSIDE the `try:` that starts at line 224 \u2014 the try wraps only the `queue_inbox_pr_review(...)` call, refuting the claim that import-time failures are swallowed. Broker/publish failures are caught and logged with a distinct `logger.exception(\"review_hog_stamphog_inbox_review_queue_failed\")` (line 234), not silent. The ReviewHog leg's on_commit is registered at line 116 before the stamphog leg's at line 131, so it runs first and a stamphog broker failure cannot block it \u2014 the invariant the title asks to verify holds by construction.",+ "notes": "The finding is a \"verify this is intentional\" ask plus a metrics suggestion, and its one concrete factual premise (import inside the try) is wrong. No defect exists: the broker-down invariant holds two independent ways, failures are logged with a greppable message, and the residual \"add a counter on the queue-failed path\" is an optional observability refinement, not a reliability bug. Drop."+ },+ {+ "id": "Q4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:822 \u2014 `_capture_review_completed` properties begin with `**analytics_extra_properties()` (STAMPHOG_EXTRA_PROPERTIES env). products/stamphog/backend/temporal/activities.py:176 \u2014 hosted server sets `extra_properties[\"stamphog_self_driving_review\"] = True` when `(run.output or {}).get(\"inbox_review\")`, the same source as the engine flag `self_driving_review=bool(output.get(\"inbox_review\"))` (activities.py:451). So hosted self-driving events already carry the marker (asserted by test_integration.py:1419). review_pr.py:200-209 \u2014 `self_driving` defaults False and the Action runtime never sets it, so the Action emits no self-driving events; the suggested engine prop would be constant False there.",+ "notes": "The finding's central claim \u2014 that a self-driving engine event is \"indistinguishable from a normal human-PR event\" \u2014 is false on the hosted path, the only path where self-driving runs occur, because the engine spreads the server's extra-properties hook (carrying stamphog_self_driving_review) into the same event. The Action-path gap is vacuous since Action never runs self-driving reviews. What survives is a request to duplicate an existing marker as insurance against a hypothetical future decoupling of two signals that derive from one source today; the per-run audit trail already exists in to_dict() (review_pr.py:938). Pure telemetry-redundancy suggestion with no user-affecting consequence."+ },+ {+ "id": "Q5",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "facade/api.py:508 rejects `task.internal`, but the only production creator of the run it must identify \u2014 products/signals/backend/auto_start.py:244-262 (maybe_autostart_implementation_task) \u2014 passes `internal=True` alongside `signal_report_id` and `interaction_origin=\"signal_report\"` (the path that opens the draft PR); the PR does not modify auto_start.py. webhooks.py:29-59 find_task_run matches by output__pr_url with no internal filter, so it returns exactly that internal run and the guard discards it. stamphog/backend/tasks/tasks.py:191-201 then gets None and returns an empty _InboxCarveOut(), so the webhook-leg re-review never fires for any real self-driving PR. Only dev seeders (seed_inbox_data.py:279, seed_refund_test_data.py:136) use internal=False. Tests mask it: test_webhooks.py:1244 defaults `internal=False` in _make_run, and the parameterized case (\"internal_pipeline_task\", {\"internal\": True}, {}) at ~1290 asserts rejection of the production shape.",+ "notes": "Feature leg is dead-on-arrival for 100% of production self-driving PRs \u2014 later deliveries (synchronize/reopen/base retarget) fall through to the ordinary bot-refusal path, so re-reviews never happen while tests stay green. Fix is to drop the `task.internal` term (or reconcile with auto_start's internal=True) and add a test whose fixture matches the real creator's flags."+ },+ {+ "id": "Q6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Both trigger legs persist exactly the documented key: products/stamphog/backend/tasks/tasks.py:1064 (webhook leg, `output={\"inbox_review\": inbox_review} if inbox_review is not None else {}`) and tasks.py:1229 (receiver leg, `output={\"inbox_review\": inbox_review}`). The server sets the engine flag solely from it: products/stamphog/backend/temporal/activities.py:451 `self_driving_review=bool(output.get(\"inbox_review\"))`. `trigger` is a nested field inside the inbox_review dict (tasks.py:210 `\"trigger\": \"webhook\"`, tasks.py:1177 `\"trigger\": \"inbox\"`), and `stamphog_self_driving_review` (activities.py:175-176) is an analytics extra-property gated on `output.get(\"inbox_review\")` \u2014 neither is a competing top-level provenance key.",+ "notes": "The finding's premise \u2014 that the AGENTS.md carve-out may document a nonexistent key \u2014 is contradicted by the implementation. The doc (products/stamphog/AGENTS.md:92-95) names `ReviewRun.output[\"inbox_review\"]`, which is exactly what both stamping paths write and what the server reads. The `trigger` field and the `stamphog_self_driving_review` analytics property mentioned in the PR description coexist with (and depend on) the documented key rather than replacing it, so there is no doc/implementation drift and no audit that would silently return nothing."+ },+ {+ "id": "Q7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "/private/tmp/claude-501/-Users-woutut-Documents-Code-posthog/6b02ce00-9d8e-46e2-88ba-281e0843a672/scratchpad/pr72680_tree/products/stamphog/AGENTS.md lines 81-115: the \"## The self-driving inbox carve-out\" section sits between the egress bullets (ending L79) and \"## Trust boundaries\" (L117), exactly as the finding describes. The section is self-contained, accurate, and its content is unaffected by ordering.",+ "notes": "Pure documentation-organization taste. The finding's only claim is that section placement \"reads as a detour\" between egress and trust-boundaries prose. Section order in an AGENTS.md has no behavioral, correctness, security, contract, or reliability effect; the carve-out earning its own top-level heading is a defensible editorial choice (it is the one deliberate exception to a repeated refusal invariant and cross-references the stale-approval invariant preceding it). No user-affecting damage under any reading; fails the keep bar as style/taste."+ },+ {+ "id": "Q8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Premise is true but the feared consequence is already handled. (1) Drift premise: products/review_hog/backend/receivers.py:180-188 \u2014 _resolve_assigned_reviewer keys off the report's latest suggested_reviewers artefact (.order_by(\"-created_at\").first()), so reassignment can change the acting reviewer between the initial review and a later push. (2) Consequence refuted: products/stamphog/backend/tasks/tasks.py:205-207 \u2014 a None from the registered resolver (opted-out R2, or no reviewer resolving) returns _InboxCarveOut(opted_out=True), not a silent drop. tasks.py:881-903 \u2014 for skip_reason set and action in _HEAD_CHANGING_ACTIONS, the caller runs _retract_stale_approvals_on_skip(..., _INBOX_OPT_OUT_DISMISS_MESSAGE if carve_out.opted_out else ...), wrapped in retry-on-exception so a transient blip cannot leave the approval standing. (3) tasks.py:483-509 \u2014 _retract_stale_approvals_on_skip calls dismiss_stale_approvals_for_head keyed on the repo_config/PR row and head sha, i.e. the App's standing approval, independent of which user the resolver would return \u2014 so the draft-time approval authorized under R1 is dismissed on the pushed head regardless of the R1\u2192R2 drift. (4) The residual behavior (current assignee's toggle governs re-review) is explicitly documented as intended: receivers.py:159-173 docstring (\"Assignment = the report's latest suggested_reviewers artefact \u2014 the exact set the Inbox 'For you' filter matches\") and tasks.py:163-165 (\"A toggle switched off mid-PR lands in the caller's skip path, whose head-changing retraction still dismisses the stale approval \u2014 safety is never preference-gated\").",+ "notes": "The finding's actionable suggestion was \"confirm a None return still triggers dismiss_stale_approvals for a head-changing push\" \u2014 verification confirms it does, with a dedicated opt-out dismissal message for exactly this case. The alternative design it floats (pinning the acting reviewer to persisted run provenance instead of re-resolving) is a policy preference contradicting the PR's documented assignment model, not a defect. No unsafe state is reachable: an opt-out or reassignment can only skip a new stamphog review while retracting the old approval, never leave a stale approval pinned to an unreviewed head."+ },+ {+ "confidence": "high",+ "evidence": "Producer chain always emits a genuine JSON boolean: activities.py:451 passes bool(output.get(\"inbox_review\")); logic/reviewer.py:101 types the param `self_driving_review: bool = False` and line 131 inserts it verbatim into the json.dumps'd context. Consumer review_local.py:321 does bool(context.get(\"self_driving_review\")) \u2014 identity for a bool, False for absent key (Action contexts). The integration test asserts `context[\"self_driving_review\"] is True` (identity check), so any producer that stringified the flag would fail the test suite before reaching the gate. The claimed failure (bool(\"false\") \u2192 True) has no reachable trigger in the tree.",+ "id": "Q9",+ "is_real": false,+ "notes": "Pure defensive-hardening suggestion against a hypothetical future server change; the finding itself admits the current serialization is a real boolean. The suggested `is True` guard changes no current behavior, and the type contract is already pinned by the producer-side bool() coercion, the typed builder signature, and an identity-check integration test. Speculative, not user-affecting.",+ "severity": "not_an_issue"+ },+ {+ "id": "Q10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "has_reviewable_repo_config (products/stamphog/backend/facade/api.py:112-125) indeed has no repository filter (project-level any-repo check), and queue_inbox_pr_review (:126-141) documents the per-PR repo-config resolution as a \"silent no-op without one\" \u2014 the finding's mechanics are accurate. But the serializer copy is not overstated: stamphog_review_inbox_prs help_text (products/review_hog/backend/api/settings.py, diff hunk) uses necessary-condition phrasing (\"Only takes effect when the project has a synced, enabled Stamphog repository\"), and stamphog_connected help_text says \"at least one synced, enabled Stamphog repository\" \u2014 exactly the project-level semantics implemented. Neither promises every inbox PR gets reviewed.",+ "notes": "The finding self-identifies as \"not a hard bug\" (behavior matches the PR's stated design) and requests only a help_text wording tweak with no code-path change. The per-repo downstream gating is intentional and documented in the facade docstring. At most this is optional copy polish; there is no correctness, contract, security, or reliability damage, so it falls below the keep bar."+ },+ {+ "id": "Q11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: `_inbox_rereview_carve_out` resolves the config at line 179 (`repo_config = _resolve_repo_config(installation_id, repo)`); when the carve-out succeeds the main path re-resolves at line 918, and the opted-out skip branch re-resolves at line 891. So the duplicate-lookup premise is factually accurate. But `_resolve_repo_config` is a single-row lookup on the uniquely-constrained (provider, installation_id, repository) key, executed at most one extra time per webhook delivery, and only on the rare branch that survives lines 167-178 (bot-authored, repo-native, head-changing/base-retarget self-driving PR \u2014 every human/fork/non-inbox delivery returns before the DB touch). The finding itself concedes it is \"purely a wasted query, not a correctness hazard.\"",+ "notes": "Not user-affecting: no N+1, no loop, no hot path \u2014 one duplicate cheap indexed query per rare delivery. The separate call sites are also not accidental: each sits in its own try/except with distinct retry logging (lines 875-879 carve-out, 890-903 skip-dismiss, 917-921 main path), and re-resolving keeps each branch's freshness and failure semantics independent. Threading the resolved config through `_InboxCarveOut` would add DTO coupling to save a negligible query. Micro-optimization noise, correctly self-described as such in the finding text; drop it."+ },+ {+ "id": "Q12",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: line 49 (`_HEAD_CHANGING_ACTIONS` excludes \"edited\"); lines 853-863 + 435-438/470-472 (base retarget dismisses with generic retarget copy, unconditionally, before the carve-out); line 167 (carve-out admits base_retargeted, so opted_out=True is reachable on \"edited\"); lines 887-898 (`_INBOX_OPT_OUT_DISMISS_MESSAGE` gated on _HEAD_CHANGING_ACTIONS, never posts on retarget); line 908 (log reason=\"inbox_opt_out\"). Mechanics confirmed exactly as described.",+ "notes": "Premise is accurate but consequence-free: the approval IS retracted (invariant holds), and both the GitHub retarget copy and the inbox_opt_out log reason are true statements about different sub-events, so there is no contradiction that changes any outcome. The only user-visible imprecision \u2014 retarget copy promising \"Stamphog re-reviews automatically\" when an opted-out PR will not be re-reviewed \u2014 predates this PR for every other skip-reason PR on a retarget and occurs only on a very narrow compound path. Pure log/copy clarity; at most a wording tweak or comment, no code-path defect. Borderline not_an_issue; kept at consider because the mechanics are verified real and the \"re-reviews automatically\" promise is genuinely false for the new opted-out state."+ },+ {+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:51-55,74-84 \u2014 stamphog_connected is a SerializerMethodField, so the PATCH branch (Response(serializer.data), ~line 140) does trigger it; products/stamphog/backend/facade/api.py:112-125 \u2014 the read is one .exists() on a small per-team config table, wrapped fail-soft behind the fail-fast circuit breaker. Endpoint is a human-triggered settings save (cold path); the GET side already runs heavier work (seed_canonicals_tolerantly, line 145).",+ "id": "Q13",+ "is_real": false,+ "notes": "Premise is technically true (one cross-DB existence check per settings PATCH serialize) but there is no user-affecting damage: single cheap indexed query, fail-soft with circuit-breaker fail-fast on outage, low-frequency human-triggered path. Proposed fixes (write-only serializer variant / memoization) add complexity and break response-shape parity to save a negligible query; keeping the field on PATCH also gives the UI a fresh connected flag. Micro-optimization nit, drop under precision-over-recall.",+ "severity": "not_an_issue"+ },+ {+ "id": "Q14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:74-82 \u2014 the broad except is deliberate, comment-documented fail-soft for an informational UI flag; logger.exception preserves the full stack trace under the unique key \"review_hog_stamphog_connected_check_failed\", so failures are fully observable and identifiable. has_reviewable_repo_config (products/stamphog/backend/facade/api.py:112-126) is a single indexed .exists() query. The endpoint degrades gracefully (200 + toggle disabled), and log volume is bounded by human settings-tab loads.",+ "notes": "The finding concedes the safety posture is correct and only asks to split log levels for transient (circuit-breaker-open) vs unexpected failures. That is log-hygiene taste, not a defect: no user-affecting damage in any failure mode, and the fix would couple review_hog to stamphog's internal exception taxonomy across the facade boundary to reduce noise on a low-frequency endpoint. Drop under precision-over-recall."+ },+ {+ "confidence": "high",+ "evidence": "tasks.py: the `get_inbox_acting_reviewer_resolver() is None` check (~line 201) does run after `_resolve_repo_config` (~182) and `find_signal_implementation_run` (~193), so the ordering claim is factually true. However review_hog/backend/apps.py:11-13 + receivers.py:69 register the resolver in AppConfig.ready(), and stamphog and review_hog ship together in the monorepo deployment \u2014 the resolver is never None on a real webhook delivery, so the hoist saves nothing in production.",+ "id": "Q15",+ "is_real": false,+ "notes": "Speculative micro-optimization for a configuration (stamphog installed without review_hog) that does not exist in the real deployment. Even there, the saved cost is two indexed single-row lookups on a rare path (bot-authored, head-changing, repo-native, synced+enabled), and semantics are identical either way (both fail closed). No user-affecting correctness, reliability, or performance impact.",+ "severity": "not_an_issue"+ },+ {+ "id": "Q16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1155-1162 \u2014 the pre-dedupe get_pr is explicitly documented as required (\"the dedupe keys on the PR's current head, which only GitHub knows\") with explicit GitHubRateLimitError handling (retry countdown=max(retry_after,60), warning log). products/review_hog/backend/receivers.py:77-79 documents the same-head refire cost as an accepted tradeoff; receivers.py:85-96 filters non-output saves cheaply; the path is gated by the off-by-default stamphog_review_inbox_prs toggle and scoped to one PR per signal report.",+ "notes": "The fetch-per-refire mechanic is real but is a consciously accepted, comment-documented design necessity: the dedupe key (current head) only exists on GitHub, and the suggested head-cache would reintroduce the lost-synchronize gap this leg exists to close. Volume is bounded (single PR, toggle-gated) and far below installation rate limits. The \"silent loss after retry exhaustion\" scenario requires a sustained rate-limit window outlasting three >=60s retries AND no later refires \u2014 but the repeated output-save refires the finding complains about are themselves the redelivery backstop, and the rate-limit path is logged, not silent. The suggestion reduces to \"confirm an assumption\", not a fix for a demonstrated defect."+ },+ {+ "id": "Q17",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Resolver runs inside Celery task process_pull_request_event (products/stamphog/backend/tasks/tasks.py:809 @shared_task; carve-out call ~line 876), after webhook ACK \u2014 no request-path latency. It fires only after cheap gates: head-changing action, bot-authored payload check (humans exit with zero DB work), repo-native branch, enabled repo config, and a positive find_signal_implementation_run match (tasks.py:170-215) \u2014 i.e. only for identified self-driving PRs on a new push. Per-call cost is bounded: one indexed SignalReportArtefact .first() (receivers.py:184-192) plus resolve_org_github_login_to_users (resolve_reviewers.py:304-332) = 1 Team lookup, 3 candidate-narrowing queries, 1 batched User query \u2014 no N+1. Fresh re-resolution is the documented design: receivers.py:148-150 \"stamphog's webhook path calls it before re-reviewing ... so switching the toggle off mid-PR stops new stamphog runs\"; the suggested TTL cache would serve stale toggle decisions and break that safety property.",+ "notes": "The finding's mechanics are accurately described (the resolver does re-run per push), but the impact is speculative: a handful of indexed queries on a low-volume async branch is not user-affecting performance damage, and the \"redundant\" work is an intentional safety re-check (mid-PR opt-out must take effect; reviewer assignment can also change via a newer suggested_reviewers artefact). The proposed caching fix conflicts with the design invariant. Premature optimization / by-design behavior, not a defect."+ },+ {+ "id": "Q18",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1109-1245) trusts the caller-supplied pr_url entirely: after URL parse (1130), team-scoped config lookup for the parsed repo (1140-1147), state==open (1166) and head_sha (1170) checks, it stamps output={\"inbox_review\": {...}} (1176-1181, 1229) from caller-supplied signal_report_id/task_run_id/acting_user_id \u2014 with no find_signal_implementation_run, no _is_bot_authored, no draft check. The webhook leg's carve-out (tasks.py:144-215) enforces all of these (bot author 169-172, fork-safety 176-178, run linkage + team recheck 191-200). activities.py:451 derives self_driving_review=bool(output.get(\"inbox_review\")), which the engine uses to skip the bot-author refusal and draft prerequisite (logic/reviewer.py), and the receiver leg never runs the webhook path's review_mode/write-permission gates (tasks.py:944/968) at all. pr_url originates from TaskRun.output written via set_output (tasks presentation/views/api.py:1101-1121, task:write) validated only against the task's json_schema (facade/api.py:2123-2136); sandbox agents get posthog_mcp_scopes=\"full\" (models.py:731); the review_hog receiver (receivers.py:93,126-139) forwards it unvalidated. The comment at stamphog/backend/temporal/activities.py:448-450 claiming both trigger paths positively link the PR is false for this leg.",+ "notes": "Confirmed as written. A prompt-injected or buggy signals implementation agent (or any task:write caller) can point output.pr_url at any open PR in any repo the team has a synced+enabled Stamphog config for \u2014 including a human-authored ready PR \u2014 and Stamphog will bypass the bot/draft/review_mode/write-permission gates and post a real head-pinned GitHub approval capable of satisfying required reviews. Prerequisites (synced config, opted-in acting reviewer, one signals run) are the feature's normal operating conditions, and an end-to-end test exercises exactly this chain. Fix is cheap and matches the codebase's own stated invariant: mirror find_signal_implementation_run linkage (require the match's signal_report_id to equal the caller's) or at minimum assert the fetched PR is bot-authored and draft before stamping inbox_review; also correct the false comment at activities.py:448-450."+ },+ {+ "id": "Q19",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:49 includes \"reopened\" in _HEAD_CHANGING_ACTIONS (pre-existing, comment at :48 says it doesn't move the head); :70-74 new _INBOX_OPT_OUT_DISMISS_MESSAGE opens with \"New commits were pushed\"; :897 selects it for any head-changing action when carve_out.opted_out \u2014 so a reopen posts a comment falsely claiming commits were pushed.",+ "notes": "Premise confirmed, but impact is cosmetic copy imprecision only: the dismissal action itself is correct and intentional on reopen, and the identical false opener already exists in both pre-existing sibling messages (:58-66) fired under the same gate, so the PR adds no new class of inaccuracy. Valid low-stakes polish (branch copy on action or narrow the gate), not a behavioral/correctness problem."+ }+ ],+ "clusters": {+ "clusters": [+ {+ "issue": "find_signal_implementation_run rejects internal=True tasks but production self-driving implementation tasks are always internal=True, so the webhook carve-out leg is dead",+ "members": ["Y5", "P12", "Q5"]+ },+ {+ "issue": "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "members": ["X20", "P10", "Q18"]+ },+ {+ "issue": "self_driving_review read from context JSON with truthy bool() coercion instead of a strict `is True` check",+ "members": ["X10", "Y12", "P3", "Q9"]+ },+ {+ "issue": "Engine does not gate familiarity computation/rendering on self_driving, relying on the server omitting author_pr_numbers",+ "members": ["X14", "Y17", "P5", "P14", "Q2"]+ },+ {+ "issue": "_format_self_driving renders TRUSTED provenance claims (machine author / verified-by-task-linkage) solely off the self_driving flag with no engine-side verification",+ "members": ["X3", "Y3"]+ },+ {+ "issue": "Draft/bot gate relaxations in Pipeline are keyed only on self_driving, not coupled to pr.author_is_bot",+ "members": ["X9", "P15"]+ },+ {+ "issue": "stamphog_connected SerializerMethodField does an uncached cross-product-DB read on every settings serialization (GET and PATCH)",+ "members": ["X15", "Y6", "P6", "Q13"]+ },+ {+ "issue": "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "members": ["X12", "Q10"]+ },+ {+ "issue": "process_inbox_pr_review performs a live GitHub get_pr on every receiver refire before any dedupe",+ "members": ["X16", "P19", "Q16"]+ },+ {+ "issue": "Carve-out path resolves the same StamphogRepoConfig twice (or thrice) per delivery",+ "members": ["Y14", "P7", "Q11"]+ },+ {+ "issue": "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "members": ["X11", "Q8"]+ },+ {+ "issue": "Webhook-leg toggle re-check repeats the multi-query reviewer-resolution chain on every synchronize/reopen push (performance)",+ "members": ["P18", "Q17"]+ },+ {+ "issue": "_parse_pr_url regex is not host-anchored, so lookalike domains/embedded github.com substrings parse as valid GitHub PR URLs",+ "members": ["Y10", "P1"]+ },+ {+ "issue": "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "members": ["Y2", "P2"]+ },+ {+ "issue": "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "members": ["X4", "P23"]+ },+ {+ "issue": "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "members": ["X13", "Q3"]+ },+ {+ "issue": "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "members": ["X1"]+ },+ {+ "issue": "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "members": ["X2"]+ },+ {+ "issue": "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "members": ["X5"]+ },+ {+ "issue": "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "members": ["X6"]+ },+ {+ "issue": "find_signal_implementation_run still matches cancelled/failed runs and soft-deleted tasks, extending the carve-out past the automation's lifetime",+ "members": ["X7"]+ },+ {+ "issue": "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "members": ["X8"]+ },+ {+ "issue": "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "members": ["X17"]+ },+ {+ "issue": "Relaxed gates leave no trace in logs/gate messages/posted review comment that the self-driving carve-out fired",+ "members": ["X18"]+ },+ {+ "issue": "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "members": ["X19"]+ },+ {+ "issue": "stamphog_review_inbox_prs is PATCH-writable without a server-side stamphog_connected precondition validator",+ "members": ["Y1"]+ },+ {+ "issue": "Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled-state copy in the UI",+ "members": ["Y4"]+ },+ {+ "issue": "Second synchronous Celery broker publish on the on_commit path with no bounded publish timeout against a hung broker",+ "members": ["Y7"]+ },+ {+ "issue": "Carve-out exception retry path can block the stale-approval safety dismissal for head-changing bot PRs",+ "members": ["Y8"]+ },+ {+ "issue": "AGENTS.md carve-out section conflicts with the file's 'every invariant earned through a real review finding' preamble framing",+ "members": ["Y9"]+ },+ {+ "issue": "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "members": ["Y11"]+ },+ {+ "issue": "Claimed stranding of QUEUED runs because on_commit workflow restart supposedly runs after the Celery task returns (disproven Django semantics)",+ "members": ["Y13"]+ },+ {+ "issue": "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "members": ["Y15"]+ },+ {+ "issue": "Alleged \\\\s character-class typo in _parse_pr_url making repos containing 's' unparseable (fabricated/misquoted regex)",+ "members": ["Y16"]+ },+ {+ "issue": "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "members": ["P4"]+ },+ {+ "issue": "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "members": ["P8"]+ },+ {+ "issue": "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "members": ["P9"]+ },+ {+ "issue": "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "members": ["P11"]+ },+ {+ "issue": "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "members": ["P13"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer has no try/except guard despite being invoked from another product's webhook path",+ "members": ["P16"]+ },+ {+ "issue": "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "members": ["P17"]+ },+ {+ "issue": "Alleged check-then-act race in process_inbox_pr_review's dedupe allowing duplicate runs under concurrent refires (serialized by PR row lock)",+ "members": ["P20"]+ },+ {+ "issue": "repository__iexact lookup cannot use StamphogRepoConfig's case-sensitive indexes",+ "members": ["P21"]+ },+ {+ "issue": "stamphog_inbox_pr_create_run_failed log omits the error=str(e) structured field its siblings include",+ "members": ["P22"]+ },+ {+ "issue": "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy",+ "members": ["P24"]+ },+ {+ "issue": "Claim that max_migration.txt was not bumped to the new 0019 migration (false against PR head)",+ "members": ["Q1"]+ },+ {+ "issue": "Engine's stamphog_review_completed analytics event lacks a self-driving marker property",+ "members": ["Q4"]+ },+ {+ "issue": "AGENTS.md provenance key name (inbox_review vs trigger/stamphog_self_driving_review) suspected of not matching the implementation",+ "members": ["Q6"]+ },+ {+ "issue": "AGENTS.md carve-out section placement splits the egress-to-trust-boundaries document flow",+ "members": ["Q7"]+ },+ {+ "issue": "Opt-out dismissal copy/log mismatch on a base-retarget delivery (retarget message posted while log says inbox_opt_out)",+ "members": ["Q12"]+ },+ {+ "issue": "Broad except in get_stamphog_connected collapses transient circuit-breaker failures and real bugs into one error-level log",+ "members": ["Q14"]+ },+ {+ "issue": "Carve-out pays repo-config and tasks-DB lookups before the cheap resolver-is-None short-circuit",+ "members": ["Q15"]+ },+ {+ "issue": "Opt-out dismissal message claims 'New commits were pushed' on a reopened PR where no commits were pushed",+ "members": ["Q19"]+ }+ ]+ },+ "judges": [+ {+ "winner": "glm_sets",+ "margin": "moderate",+ "rationale": "Under the recall-and-reliability lens, Model G (sets Y+Q) wins on every top-weighted criterion. (1) Reliable catches: the single most valuable finding in the entire exercise \u2014 the confirmed must_fix that the task.internal predicate in find_signal_implementation_run kills the webhook re-review leg for 100% of production self-driving PRs, with the PR's own tests locking the broken behavior in \u2014 was caught by G in BOTH runs (Y5, Q5), each independently verified must_fix with root cause and fix. Model S (sets X+P) caught it in only one run (P12), and its other run actively rationalized the bug: X8 examined the exact predicate and blessed it as 'the codebase's actual precedent', giving a maintainer false reassurance about the merge-blocking defect. That is the worst possible reliability failure for a reviewer: a single-run consumer of S has a coin flip between catching the feature-killing bug and being steered away from it. (2) Confirmed must_fix count: G has two distinct confirmed must_fix (Y5/Q5 plus Q18 \u2014 the receiver-leg approval-forging hole where any task:write caller can point output.pr_url at an arbitrary open PR and mint a real head-pinned GitHub approval, verified end-to-end with the injection chain). S has one (P12). On the same receiver-leg cluster, S's X20 verified only at should_fix with a narrower scenario, and its P run restatement (P10) was refuted outright \u2014 another cross-run inconsistency. (3) Run-to-run consistency overall: G has 1 reliably repeated confirmed issue; S has zero \u2014 every one of S's 14 confirmed findings appears in exactly one run, and on three clusters S's two runs directly disagree (X20 confirmed vs P10 refuted; X9 confirmed vs P15 refuted; X16 refuted vs P19 kept). S's counterweights are genuine but sit in the lighter-weighted tiers the lens de-prioritizes: broader confirmed payload (5 distinct should_fix \u2014 X3, X7, X9, X20, P8, though X3/X9/X20 are facets of roughly two fixes \u2014 plus 8 considers vs G's Y8 should_fix and 3 considers), and a better precision ratio (68% noise across 44 findings vs 81% across 36). Noise toxicity roughly cancels: G's worst item is the fabricated Y16 regex must_fix (self-evidently checkable), but S produced four refuted must_fix claims (X4, X14, P10, P24) and eleven refuted should_fix claims, and its X8 false-blessing is more damaging than any of G's noise. A team running G catches the dead-feature must_fix every time and the top security hole half the time, both at accurate severity; a team running S gets a wider spread of mid-tier hardening catches but only luck-dependent coverage of the issues that actually block the merge. Margin is moderate rather than decisive because S's aggregate confirmed recall is genuinely about twice G's and includes unique real should_fix issues (X7 cancelled-task carve-out window, P8 cross-leg double-review) that G never surfaced in either run."+ },+ {+ "winner": "sonnet_sets",+ "margin": "moderate",+ "rationale": "Under the precision lens, Model S (sets X+P) wins on every aggregate metric. Precision: S landed 14 confirmed-real findings out of 44 (31.8%, noise 68.2%) vs G's 7 of 36 (19.4%, noise 80.6%) \u2014 S's per-finding hit rate is ~1.6x G's, and it is run-to-run stable (7/20 in X, 7/24 in P) where G is stably low (3/17 in Y, 4/19 in Q). Confirmed high-severity payload: S has 6 must_fix/should_fix confirmations across ~6 distinct issues (P12 must_fix; X3, X7, X9, X20, P8 should_fix) vs G's 4 confirmations across only 3 distinct issues (Y5 and Q5 are the same internal=True bug caught twice; Q18 must_fix; Y8 should_fix at medium confidence). S also has 8 confirmed considers vs G's 3. Noise quality favors S too: G's 29 not_an_issue findings include the most attention-wasting class \u2014 Y16, a must_fix built on a fabricated/misquoted regex empirically disproven; Y13, a should_fix resting on incorrect Django on_commit semantics; and Q1, a should_fix claiming max_migration.txt wasn't bumped when the reviewed diff itself contains the bump \u2014 confidently-false factual claims a maintainer must disprove empirically. S's 30 noise findings are mostly hedged speculative-hardening/micro-opt suggestions (X1, X10, X14, P3, P5...) that a triager can dismiss cheaply, though S's own worst failure is label inflation (only 1 of 8 claimed must_fix confirmed at level; X4, X14, P24 outright false at must_fix) plus P24's meta-noise. What keeps the margin moderate rather than decisive is G's genuine strengths: it reliably caught the single most impactful bug in the PR in BOTH runs (Y5/Q5 \u2014 the task.internal predicate makes the webhook re-review leg dead for 100% of production self-driving PRs, with false-green tests), while S caught it in only one run (P12) and in the other run actively rationalized the exact predicate as intentional (X8, not_an_issue) \u2014 a dangerous false reassurance. G's Q18 also drew the strongest severity confirmation on the receiver-leg approval-forgery hole (prompt-injectable pr_url \u2192 real GitHub approval bypassing bot/draft/write-permission gates), and G's must_fix label discipline was better (3/4 exact vs S's 1/8). But S surfaced that same receiver-leg issue in both runs (X20 confirmed should_fix end-to-end; P10 raised, one verifier of three dismissed it), won both contested overlap matchups in round 1 (X3 over Y3, X17 over Y15), and uniquely confirmed the cancelled/deleted-task authorization-window gap (X7), the draft-gate coupling (X9), and the duplicate-review dedupe gap (P8). Aggregated over both runs, S delivers roughly double the confirmed real findings at a meaningfully lower noise rate with fewer fabricated premises; G delivers one brilliant, reliable catch plus one high-severity lucky catch buried in an 81% noise stream. On the stated precision-weighted criteria, S is the better perspective-reviewer, moderately."+ },+ {+ "winner": "glm_sets",+ "margin": "moderate",+ "rationale": "Model G (sets Y+Q) wins on the criteria that matter most: confirmed high-severity impact and run-to-run reliability. G owns 3 of the pool's 4 confirmed must_fix findings \u2014 Y5 and Q5 (the internal=True predicate that kills the entire webhook re-review leg for every production self-driving PR, with the PR's own tests locking the broken behavior in) and Q18 (receiver leg stamps inbox_review with no positive PR-to-run linkage, letting an agent-controlled output.pr_url redirect a real head-pinned GitHub approval onto any PR in a configured repo). Crucially, G caught the merge-blocking internal=True bug in BOTH runs at must_fix \u2014 a reliable catch \u2014 while Model S (sets X+P) caught it in only one run (P12); S's other run not only missed it but X8 examined the exact guilty predicate and blessed it as intentional, giving a maintainer false reassurance on the one bug that ships a dead feature. G's top-severity labels are also trustworthy (3/4 claimed must_fix confirmed) versus S's 1/8 (X4, X14, P10, P24 all dismissed at must_fix; X7/X9/P8 downgraded), and G's noise skews quiet consider-labels while S's 30 dismissed findings include 4 false must_fix and ~8 false should_fix. S's genuine strengths keep this from being decisive: higher aggregate precision (14/44 = 32% vs 7/36 = 19%), more confirmed should_fix findings (X3/X9/X20 \u2014 layers of one receiver-leg vulnerability S raised in both runs \u2014 plus unique catches X7 cancelled-task carve-out window and P8 cross-leg double-review), and 8 confirmed considers vs G's 3. G also has the worst per-item accuracy failures (Y16's fabricated regex misquote at must_fix, Q1's false max_migration premise, Y13's wrong on_commit semantics \u2014 misreadings rather than S's mere severity inflation). But S's confirmed findings show near-zero overlap between its two runs (its reliable repeats are mostly noise clusters like X10/P3 and X14/P5/P14), so its value per single run is luck-dependent, whereas a single G run delivered the merge-blocker at correct severity both times. Weighing confirmed must_fix heaviest and consistency as instructed, G is the better perspective-reviewer by a moderate margin."+ }+ ],+ "_meta": {+ "blinding": "S = sonnet (X=A1,P=A2), G = glm (Y=B1,Q=B2)"+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-fourway.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-fourway.jsonnew file mode 100644index 000000000000..41eb2060fac6--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-fourway.json@@ -0,0 +1,639 @@+{+ "verdicts": {+ "R": [+ {+ "id": "R1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/temporal/activities.py:176 sets extra_properties[\"stamphog_self_driving_review\"] = True for inbox reviews and serializes it into STAMPHOG_EXTRA_PROPERTIES (line 178); tools/pr-approval-agent/gateway.py:17-33 (analytics_extra_properties) reads that env var; tools/pr-approval-agent/review_pr.py:822 spreads it into the stamphog_review_completed event properties, and reviewer.py:328,354 spread it into LLM-trace events. The key collides with no hardcoded base property, so it survives the \"base props win\" merge. The diff also contains a test asserting the env var carries stamphog_self_driving_review is True.",+ "notes": "The finding's premise \u2014 that the self-driving flag only lives in to_dict()[\"classification\"][\"self_driving\"] (review_pr.py:938) and analytics cannot segment relaxed-gate runs \u2014 is false. The PR delivers the stamp via a single server-side injection point (STAMPHOG_EXTRA_PROPERTIES \u2192 analytics_extra_properties spread), which covers the completed event AND both LLM-trace events. The suggested fix (adding the property only in _capture_review_completed) would be strictly narrower than the existing mechanism. Wrong / already handled elsewhere."+ },+ {+ "id": "R2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680.diff lines 95-100 show max_migration.txt changed in this PR: -0018_backfill_urgency_threshold_to_consider / +0019_reviewusersettings_stamphog_review_inbox_prs. PR tree file products/review_hog/backend/migrations/max_migration.txt at head contains exactly \"0019_reviewusersettings_stamphog_review_inbox_prs\", matching the new migration 0019_reviewusersettings_stamphog_review_inbox_prs.py in the same directory.",+ "notes": "The finding's premise is false: the PR already bumps the max migration marker in the same change, exactly as suggested. The reviewer saw a partial chunk that excluded max_migration.txt and inferred it was missing. Nothing to fix; no preflight or migration-conflict tooling would trip."+ },+ {+ "id": "R3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1110) is reachable only via queue_inbox_pr_review (products/stamphog/backend/facade/api.py:128-149), whose sole production caller _start_stamphog_review (products/review_hog/backend/receivers.py:207-231) is invoked only from handle_task_run_saved (receivers.py:72-142). That receiver derives all five params directly from the just-saved TaskRun (pr_url=instance.output['pr_url'], task_run_id=str(instance.id), signal_report_id=str(task.signal_report_id), team_id=instance.team_id) after enforcing status not FAILED/CANCELLED, task.signal_report_id is not None, not task.internal, and the acting reviewer's stamphog toggle \u2014 so re-resolving the run by task_run_id/team_id and checking it matches these values would verify data against its own source. Inside the task, repo config resolution is team-scoped (StamphogRepoConfig.objects.for_team(team_id), tasks.py ~1140), so only the same team's synced+enabled repos are reachable; stale output is handled by fresh GitHub fetch, open-state check, head-sha bail, stale-snapshot guard, and head-keyed dedupe (tasks.py:1155+).",+ "notes": "The requested re-validation is tautological given the single call site: every parameter originates from the TaskRun the finding wants re-verified, established by construction. The webhook-vs-receiver asymmetry is deliberate \u2014 the webhook leg resolves a run from an untrusted GitHub payload, while the receiver leg starts from the trusted just-committed run; re-running find_signal_implementation_run would pass trivially and would not catch a wrong-but-self-consistent pr_url (an upstream agent-server concern shared with the pre-existing ReviewHog leg). The only remaining trigger, a hypothetical future internal caller misusing the facade, is speculative; worst case is a review on a PR in the same team's own configured repo \u2014 no cross-tenant or user-affecting damage. Defense-in-depth suggestion, not a real defect."+ },+ {+ "id": "R4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "facade/api.py:504-508 does delegate to an unscoped find_task_run and post-filter by team_id, but the sole caller (stamphog tasks.py:191-196) always passes the webhook PR's html_url, and the pr_url leg of find_task_run (webhooks.py:29-56) matches output__pr_url filtered by repository \u2014 a globally unique PR URL recorded only by the run that opened the PR, so no other team's run can win that leg. The branch fallback is reached only when pr_url matched nothing, yet the carve-out fires only on synchronize/reopen/retarget (tasks.py:168-169), after pr_url is recorded; masking there would also need two teams sharing a repo with identical random-suffixed generated branch names (test_webhooks.py:966).",+ "notes": "Even in the theoretical collision, the outcome is a fail-closed skipped re-review (empty _InboxCarveOut, tasks.py:200-202 rechecks team_id) \u2014 no tenant-isolation breach, and the initial draft-time review already ran. The cross-team masking scenario is practically unreachable and its consequence is low and safe; the suggested team-scoped query is optional hygiene, not a fix for real user-affecting damage. Agrees with the judge's dismissal."+ },+ {+ "id": "R5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/receivers.py:224-235 \u2014 the only production caller wraps queue_inbox_pr_review (including the deferred task import) in try/except Exception + logger.exception(\"review_hog_stamphog_inbox_review_queue_failed\"); receivers.py:131 dispatches it via transaction.on_commit so it runs after the TaskRun save commits; products/review_hog/backend/tests/test_inbox_trigger.py:358-369 regression-tests the exact broker-down scenario (side_effect=RuntimeError(\"broker down\"), save must not raise).",+ "notes": "The finding's premise is conditional (\"if the receiver does not catch this\") and the condition is false: the sole call site catches broadly, logs with context, runs post-commit, and is covered by a dedicated test. Adding a second try/except inside the facade would be redundant defensive coding; the docstring/ownership nit is style at most."+ },+ {+ "id": "R6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_local.py:321 does `self_driving=bool(context.get(\"self_driving_review\"))`, but the value is produced exclusively by products/stamphog/backend/logic/reviewer.py:101,131 (`self_driving_review: bool = False` written into the context dict, serialized via json.dumps at build_reviewer_invocation's return) whose sole caller products/stamphog/backend/temporal/activities.py:451 passes `bool(output.get(\"inbox_review\"))` \u2014 a genuine Python bool. review_local.py:396 loads the context with json.loads, so the field is only ever JSON true/false or absent (None); for True/False/None, `bool(x)` equals `x is True` exactly. The Action runtime never sets the key, so it defaults closed (review_local.py:316-320 comment + test_review_local.py:283).",+ "notes": "The claimed attack values (\"false\", \"0\" strings) are unreachable: they would require the trusted server to violate its own typed-bool contract or a developer to hand-author a malformed --context file for the local tool, which is manual misuse, not a security boundary. The flag derives from server-stamped inbox provenance (run.output[\"inbox_review\"]), not from the reviewed PR's author, diff, or metadata, so no untrusted input reaches it. Strict `is True` parsing would change behavior for zero reachable inputs \u2014 this is defensive-coding preference, and the must_fix security severity is unwarranted."+ },+ {+ "id": "R7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_local.py:321 (only place self_driving=True originates, from context[\"self_driving_review\"]); review_local.py:292-303 _attach_familiarity early-returns when context[\"author_pr_numbers\"] is empty, leaving familiarity=None (review_pr.py:474 default); reviewer.py _format_familiarity returns \"\" for None. Server coupling: products/stamphog/backend/temporal/activities.py:237-238 sets author_pr_numbers=[] when inbox_review, and line 451 sets self_driving_review from the same run.output[\"inbox_review\"] flag \u2014 so self_driving=True forces familiarity absent. Online path: review_pr.py:984 CLI never passes self_driving, so self_driving is always False there and _format_self_driving (reviewer.py:692) returns \"\".",+ "notes": "The claimed contradiction (familiarity block + self-driving provenance block in one prompt) is unreachable: the hosted server couples both signals to one flag, and the offline engine's tier/PR-numbers gate independently blocks familiarity when author_pr_numbers is empty. review_pr.py's ungated _maybe_compute_familiarity only runs on the CLI path where self_driving is hardwired False. The suggested guard is defensive hardening against a state no caller can produce; at most a nice-to-have invariant assertion, not a defect."+ }+ ],+ "T": [+ {+ "id": "T1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The PR diff itself adds the exact entry the finding says is missing: the tach.toml hunk (`@@ -620,6 +620,9 @@ depends_on = [`) inserts `\"products.stamphog\"` (plus a facade-only comment) into the `products.review_hog` module's `depends_on`. In the head tree, /pr72680_tree/tach.toml:617-627 shows `path = \"products.review_hog\"` with `\"products.stamphog\"` at line 625. The interface check also passes: stamphog's `[[interfaces]]` block (tach.toml:1098-1105) exposes `backend\\.facade.*`, and the new imports in products/review_hog/backend/api/settings.py and receivers.py all go through `products.stamphog.backend.facade.*`.",+ "notes": "The finding's premise (\"tach.toml currently does not list products.stamphog in review_hog's depends_on\") is factually wrong against the reviewed head commit \u2014 the dependency declaration and the imports land in the same PR, so `tach check` passes on both the dependencies and interfaces axes. The reviewer appears to have evaluated the chunk in isolation without seeing the tach.toml hunk elsewhere in the same diff. No user-affecting or CI-affecting problem exists."+ },+ {+ "id": "T2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The flag is a genuine bool at every hop: products/stamphog/backend/temporal/activities.py:451 passes self_driving_review=bool(output.get(\"inbox_review\")) (the only non-test producer); products/stamphog/backend/logic/reviewer.py:101 types it `bool = False` and json.dumps serializes it (line 138) as JSON true/false; tools/pr-approval-agent/review_local.py:396 json.loads it back to a Python bool; so at review_local.py:321 bool(context.get(\"self_driving_review\")) only ever sees True/False/None, and None fails closed. The string-\"false\" scenario cannot occur in the actual code.",+ "notes": "The finding is self-describedly hypothetical (\"if the context producer ever serializes this as a string\"). No string-typed or attacker-controllable path to this key exists: the context is server-assembled and typed. Even in the malformed/hostile-context hypothetical, the suggested `is True` check adds no security \u2014 an attacker writing the context file would write a real JSON true. Tests (test_review_local.py:278-283, stamphog test_integration.py:1413) already pin the boolean contract. Classic defensive-coding / speculative what-if; drop."+ },+ {+ "id": "T3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:111 and :151 both call the same _resolve_assigned_reviewer(team_id, signal_report_id, task_created_by_id); the receiver leg re-fires on every output-touching TaskRun save, so there is no pinned \"initial acting reviewer\" to diverge from \u2014 both legs are latest-wins by construction. receivers.py:162-163 documents assignment as the report's latest suggested_reviewers artefact (\"the exact set the Inbox 'For you' filter matches\"), and receivers.py:147-149 documents the webhook-leg mid-PR re-check as intentional. stamphog tasks.py:163-165 shows stale-approval dismissal is never preference-gated, and acting_user_id feeds only the toggle gate + provenance (tasks.py:208-215) \u2014 reviews post via the GitHub App, so a reviewer switch confers no permissions.",+ "notes": "The finding accurately describes the mechanism (latest-artefact recomputation) but mislabels the documented design as a broken gate. The \"intended per-user gate\" it claims to protect \u2014 a fixed initial actor \u2014 does not exist anywhere in the code; assignment follows the current suggested_reviewers set on both trigger legs and on the Inbox/Slack surfaces. The proposed fix (persist acting_user_id, fail closed) would diverge from the documented latest-wins contract. Worst case is an advisory review produced/skipped for whoever is currently assigned after a rare mid-PR artefact edit; no correctness, security, or data-loss impact."+ },+ {+ "id": "T4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:116-139 registers ReviewHog then Stamphog on_commit callbacks (serial order is real), but _start_review at receivers.py:261-273 wraps sync_connect()+start_workflow in try/except Exception and only logs \u2014 it never re-raises, so a Temporal outage cannot prevent Django from running the Stamphog callback, whose _start_stamphog_review (receivers.py:224-234) is identically guarded. posthog/temporal/common/client.py:59 uses stock temporalio Client.connect, which fails unreachable hosts in bounded time; no unbounded-hang path exists, and a hypothetical hang would stall the whole saver thread regardless of callback order.",+ "notes": "The finding's severe outcome (\"Stamphog never queued\") is unreachable because exceptions are swallowed in the first callback. Its suggested fix (reorder callbacks) is a no-op for independence \u2014 Django runs commit hooks serially in one thread either way, so reordering only swaps which best-effort dispatch waits behind the other's bounded network call. The only genuine residual is a seconds-scale delay of a fire-and-forget Celery broker publish during a Temporal infra outage, on a post-commit path where the TaskRun save has already committed and nothing user-facing is blocked. The robust remedy (durable outbox) is heavyweight overengineering for two advisory review triggers."+ },+ {+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:75-85 in the PR tree: get_stamphog_connected catches Exception around has_reviewable_repo_config(instance.team_id), calls logger.exception, returns False \u2014 with an inline comment documenting the fail-soft intent. The log fires only when the stamphog product DB read raises (outage/circuit-open); in steady state the except path never executes. The endpoint is a per-scene-mount settings read on a page whose trigger UI is alpha-gated to REVIEWHOG_TEAM_ID (get_can_trigger_reviews, same file), so outage-time emission is a handful of traces, not a flood.",+ "id": "T5",+ "is_real": false,+ "notes": "The code behaves as the finding describes, but the behavior is deliberate and correct: loud logging plus safe False degradation during a real dependency outage. Rate is bounded by low-frequency settings reads on an alpha-gated page, so \"log noise obscures the outage\" is speculative. The suggested TTL-throttled, tiered logging is overengineering for an informational UI flag; the only valid fragment (add team_id to log context) is a trivial nit. No user-affecting damage in any category.",+ "severity": "not_an_issue"+ },+ {+ "id": "T6",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "Engine premise confirmed: tools/pr-approval-agent/review_pr.py ~line 225 relaxes the bot-author refusal on `if self.pr.author_is_bot and not self.self_driving`, and _check_prerequisites (~line 590) relaxes the draft gate on `if pr.draft and not self.self_driving` \u2014 no binding of the flag to pr.author_is_bot anywhere in the engine. Flag flows: review_local.py:321 `self_driving=bool(context.get(\"self_driving_review\"))` \u2190 activities.py:451 `self_driving_review=bool(output.get(\"inbox_review\"))`. The webhook leg does positively gate bot authorship (products/stamphog/backend/tasks/tasks.py:169 `if not _is_bot_authored(pr): return _InboxCarveOut()` plus repo-native-head check at :177-178), but the receiver leg process_inbox_pr_review (tasks.py:1110-1240) stamps `output={\"inbox_review\": ...}` (tasks.py:1229) with NO bot-author, draft-shape, or run-linkage check \u2014 its \"bot-authored by construction\" docstring rests on the caller-controlled pr_url (the confirmed T7 gap). So a human-authored draft PR reaching the engine with self_driving=True is reachable today, but only via T7's server-side hole.",+ "notes": "T6 is real as a code fact and its scenario is currently reachable, but it is derivative of T7 (the must_fix in this set): the root cause and correct fix is server-side re-attestation in process_inbox_pr_review, not the engine. The suggested engine-level `self_driving and author_is_bot` bind would only block the human-authored-draft variant of the exploit while leaving the worse variant (unearned approval of an arbitrary bot-authored PR, e.g. dependabot) open, and becomes redundant once T7 is fixed. It does align with the codebase's stated defense-in-depth stance (tasks.py `_review_skip_reason` comment: \"The engine keeps the same bot/draft refusals as defense in depth\") and PR data is already in hand, so it is a valid, cheap hardening \u2014 worth a consider, not a standalone should/must_fix. The prior verifier's \"unreachable through actual call sites\" rebuttal in setT.md is wrong because it accepted the receiver leg's \"bot-authored by construction\" docstring, which T7's verified analysis (same document) refutes."+ },+ {+ "id": "T7",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1110-1246) parses the repo FROM the agent-controlled pr_url (_parse_pr_url, L1130), resolves any enabled StamphogRepoConfig for that repo (L1140-1147), fetches whatever PR the URL names (L1159), and stamps output={\"inbox_review\": ...} at L1229 with NO re-attestation \u2014 it never calls find_signal_implementation_run, never checks bot-author/draft/fork-safety, and never verifies pr_url belongs to task_run_id (which it receives but only echoes into provenance at L1179). The webhook leg _inbox_rereview_carve_out (L144-215) performs exactly these checks (fork-safety L176-178, find_signal_implementation_run L191-196, team-scope recheck L199) and its own comment calls the recheck \"belt and braces for the boundary a compromised or refactored facade would otherwise silently widen.\" pr_url is caller-controlled: _apply_caller_output (products/tasks/backend/facade/api.py:1773-1788) protects only pr_merged, and the set_output/PATCH surfaces are gated by task:write which INTERNAL_SCOPES grants the sandbox (posthog/temporal/oauth.py:37-38). Downstream activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")), which in the engine bypasses the bot-author refusal (tools/pr-approval-agent/review_pr.py:225) and draft gate (review_pr.py:590); the workflow posts a real head-pinned GitHub APPROVE.",+ "notes": "The receiver leg is a new approval-capable entry point with a clear trust-boundary asymmetry versus the webhook leg. A prompt-injected self-driving agent (the exact threat the carve-out gating exists to defend against) can set output.pr_url to another PR in any Stamphog-enabled repo for its team and obtain an unearned Stamphog approval, bypassing the bot-author/draft gates that normally refuse such PRs and satisfying required reviews with zero human in the loop \u2014 breaking the PR's own \"positively identified carve-out rather than a trigger-side bypass\" invariant. Preconditions are elevated (compromised agent + opted-in reviewer + enabled repo), which caps blast radius, but the consequence is a security-control (approval) bypass on a path whose webhook sibling is deliberately hardened, so it clears the security/auth-gap keep bar. Fix: re-attest team_id/task_run_id/signal_report_id/repository/pr_url describe the same non-internal signal implementation run (and mirror the webhook PR-shape checks) before stamping inbox_review; at minimum constrain the parsed repo to task.repository."+ },+ {+ "id": "T8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/tasks/backend/facade/api.py (find_signal_implementation_run): `run = find_task_run(pr_url=pr_url, branch=head_branch, repository=repository); if run is None or run.team_id != team_id: return None` \u2014 team check is post-selection, as claimed. webhooks.py:29-101 (find_task_run): pr_url leg filters `output__pr_url` + `task__repository__iexact`; branch leg filters `branch` + repo + `state__wizard_head_branch__isnull=True`; no team filter. However: (a) the post-check is fail-closed \u2014 foreign-team runs are rejected, never returned, and the api.py docstring documents this as the intended tenant boundary; (b) shadowing a valid same-team run requires two teams to hold runs with the same pr_url+repo or same branch+repo \u2014 pr_url is written only by the single run that opened that PR, so at most one run legitimately holds it, and the branch leg is only consulted when no run recorded the pr_url and needs cross-team identical branch names on a shared repo; (c) even in that contrived collision the outcome is a skipped re-review (fail-closed), not wrong binding or a leak.",+ "notes": "The finding's structural premise is accurate (unscoped lookup, team filter applied after), but the concrete failure it alleges \u2014 a valid requested-team run nondeterministically shadowed by a foreign-team match \u2014 requires a cross-team pr_url or branch collision that real data flows do not produce. In the one plausible team-mismatch variant (config team differs from the team whose run opened the PR), returning None is the intended fail-closed behavior and the suggested team-scoped query would return None there too, so the fix changes nothing observable. Pushing team_id into the queryset is at most a defense-in-depth style improvement, not a user-affecting bug."+ },+ {+ "id": "T9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "reviewer.py:568 does render {familiarity_block}{self_driving_block} with no engine suppression, but the two blocks are mutually exclusive by construction: review_local.py:301-303 leaves familiarity None unless context[\"author_pr_numbers\"] is truthy, and the sole producer (products/stamphog/backend/temporal/activities.py:237-238, 451) sets author_pr_numbers=[] and self_driving_review=True from the same inbox_review flag. test_integration.py:1413-1415 asserts both self_driving_review is True and author_pr_numbers == [] in the same sandbox context. The Action CLI (review_pr.py:984) never passes self_driving, so the path that computes familiarity always renders an empty self-driving block.",+ "notes": "The finding's factual premise (no engine-level suppression) is correct, but its damage scenario requires a hypothetical future change: either the server populating author_pr_numbers on an inbox review (contradicting its own documented, test-asserted suppression at activities.py:233-238) or a new non-sandbox caller enabling self_driving=True. Both are explicitly acknowledged hedges in the finding itself. Engine-level suppression would be defense-in-depth, at most a style preference \u2014 not a reachable conflicting-trust-signal bug. must_fix rating is unwarranted."+ },+ {+ "confidence": "high",+ "evidence": "facade/api.py:508 rejects `task.internal` tasks, but the production self-driving implementation task is created with `internal=True` (auto_start.py:261, comment \"Internal so the run stays out of the default task list\"), forwarded unchanged through create_and_run_task (api.py:881/903) into Task.internal (models.py:735/768) with no later mutation. Git commit 0da0b8dcb7f (#68752, \"mark auto-started implementation task as internal\") is when the assumption in receivers.py:100-103 went stale; this PR codified the stale assumption. Sole caller stamphog/backend/tasks/tasks.py:191-202 therefore gets None for every real self-driving PR and falls back to the bot-author refusal. PR tests mask it: test_webhooks.py _make_run defaults internal=False (diff L1796) and the internal=True case is asserted as a skip (diff L1841).",+ "id": "T10",+ "is_real": true,+ "notes": "Confirmed end-to-end, including the historical root cause: #68752 flipped auto-start implementation tasks to internal=True after the receivers.py comment claiming they were the \"only non-internal signal-report task\" was written; this PR inherited that stale assumption into the new facade filter. The webhook carve-out (leg 2, the PR's core deliverable) is inert against production data \u2014 every genuine self-driving PR resolves to the empty carve-out and later pushes are skipped as bot-authored. Fix direction in the finding is sound: discriminate by the actual production shape (e.g. ai_stage/interaction_origin or the signals implementation artefact) instead of `not task.internal`. Note the same stale gate pre-exists in review_hog receivers.py:104 (leg 1), which is outside this PR's diff but worth flagging to the author.",+ "severity": "must_fix"+ }+ ],+ "U": [+ {+ "confidence": "high",+ "evidence": "Field is writable without validate_* (settings.py:27-32), but the claimed consequence is prevented downstream: process_inbox_pr_review resolves StamphogRepoConfig with team-scoped enabled+connected+installation_id gating and returns early (stamphog_inbox_pr_repo_not_reviewable) at tasks.py:1137-1150, and the webhook leg re-checks both repo config and the toggle (receivers.py:154). The finding's own fallback ask \u2014 document the no-op \u2014 is already met by the field's help_text (\"Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)\", settings.py:29-32).",+ "id": "U1",+ "is_real": false,+ "notes": "The finding concedes it is defense-in-depth, not an active vulnerability. The toggle is per-user, per-team, self-scoped (no boundary crossed), and enabling it before connecting a repo is a benign pre-set preference that no-ops until a repo config exists \u2014 a state the downstream Celery task and webhook leg both independently enforce. Adding serializer-side rejection would only block an already-documented, already-guarded no-op and would force users to re-set the preference after connecting. Speculative/defensive; drop.",+ "severity": "not_an_issue"+ },+ {+ "id": "U2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1109-1130,1176-1181 \u2014 leg 1 does stamp caller-supplied provenance without re-identification, as claimed. But its sole caller, review_hog's handle_task_run_saved (products/review_hog/backend/receivers.py:93-128, facade call at 222-231), performs exactly the identification the finding wants: fires only for non-internal (receivers.py:104) TaskRuns carrying a signal_report_id (receivers.py:98), with pr_url taken from that same run's own output (receivers.py:93), team_id from instance.team_id, and the acting reviewer's toggle checked. Leg 1 is also fully team-scoped (tasks.py:1140-1147 for_team + enabled + connected + installation_id filter; ReviewRun.objects.for_team), so a wrong pr_url can only resolve within a repo the team itself connected, else no-op (tasks.py:1151). No external input path reaches the facade.",+ "notes": "The finding's code-level premise is true but its harm scenario is explicitly conditioned on a hypothetical future bug/refactor in the upstream receiver (\"the inputs are internal today\"). The identification is handled by the single production caller, tenant isolation holds throughout leg 1, and the webhook leg's inline find_signal_implementation_run exists because its entry point is an untrusted external GitHub payload \u2014 the asymmetry is justified by entry-point trust. The suggested duplication of find_signal_implementation_run in leg 1 is legitimate defense-in-depth hardening a team could choose to adopt, but there is no currently reachable defect."+ },+ {+ "id": "U3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "facade/api.py:120-125 omits provider=\"github\" while tasks.py:1143 and tasks.py:301 include it \u2014 the divergence exists. But every row passing has_reviewable_repo_config must have a non-blank installation_id, and installation_id is read-only on the serializer (presentation/serializers.py:98-99: \"Set only by the verified sync_installation flow; ignored on direct writes\"); both sync-flow writers hardcode provider=\"github\" (presentation/views.py:88 and :307-309). Therefore every qualifying row is provider=\"github\" and the function's result is provably identical with or without the filter under all current input paths.",+ "notes": "The finding itself concedes \"Today GitHub is the only provider so the result is identical\" and conditions harm entirely on a future non-GitHub provider being added (models.py:26-29 confirms GitHub is the only implemented provider). That is future-proofing/consistency polish, not a reachable user-affecting defect. Also, the \"unlike its two siblings\" framing is partial: get_repo_config (facade/api.py:108) omits the provider filter as well. Adding provider=\"github\" would be a harmless one-liner if a maintainer wants lockstep with the review-path predicate, but nothing breaks today without it."+ },+ {+ "id": "U4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The cited non-determinism exists (webhooks.py:61-76 branch leg uses .first() with no order_by vs the ordered pr_url leg at :54), but find_task_run is byte-identical pre-existing code \u2014 the PR diff touches products/tasks/backend/tests/test_webhooks.py, not webhooks.py. The only new caller, _inbox_rereview_carve_out (products/stamphog/backend/tasks/tasks.py:193-198), always passes pr_url=pr.get(\"html_url\") and fires only on synchronize/reopen/base-retarget of an already-open PR whose output.pr_url is bound, so the deterministic pr_url leg matches first. Worst case a wrong branch-leg pick fails the team_id filter in find_signal_implementation_run (facade/api.py:506) and returns None \u2014 fail-closed skip preserving today's behavior, not a wrong approval or cross-tenant bind.",+ "notes": "The finding is honest about its own weakness (\"Impact is low for the current caller\") and is motivated by reuse/future callers \u2014 future-proofing documentation for a hypothetical call pattern, on unmodified pre-existing code. Adding .order_by(\"-created_at\") to the branch leg would be a harmless one-line hardening, but it does not fix any reachable defect in this PR."+ },+ {+ "id": "U5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Premise verified: tools/pr-approval-agent/review_pr.py:590-593 skips the draft prerequisite when self_driving, leaving `pr.mergeable_state == \"dirty\"` as the only conflict guard; github.py:592 and review_local.py:198 forward GitHub's raw mergeable_state, which is \"draft\" (not \"dirty\") for draft PRs, so the guard is inert for self-driving drafts. But no user-affecting damage exists: (1) GitHub itself refuses to merge both draft and dirty PRs regardless of approvals; (2) resolving a conflict necessarily changes the head SHA, and stale-approval dismissal for the self-driving/hosted path is never preference-gated (dismiss_stale_approvals_for_head in products/stamphog/backend/tasks/tasks.py, pinned by test_inbox_carve_out_toggle_off_still_dismisses_stale_approvals); dismiss_check.py classifies conflict-resolution merges as NON_TRIVIAL (non-empty cc-diff in _is_clean_merge_from_base) and rebases as NON_LINEAR_HISTORY, both \u2192 dismiss_and_review; (3) the reviewed diff is base_sha..head_sha via git, well-defined regardless of mergeability.",+ "notes": "The finding's factual claim about the inert check is correct, and its own suggestion concedes the fallback remedy is a one-line clarifying comment. Conflict safety is fully handled elsewhere (GitHub merge blocking + head-change dismissal preserved by this PR), so the head-pinned approval on a conflicted self-driving draft can never enable merging conflicted code. Residual value is documentation only \u2014 below the actionable-defect bar."+ },+ {+ "id": "U6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Both signals derive from one source of truth in the same activity module: activities.py:237-238 sets author_pr_numbers=[] when bool(run.output.get(\"inbox_review\")), and activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")). With author_pr_numbers empty, _attach_familiarity (review_local.py:301-303) returns before computing anything, familiarity stays None, and _format_familiarity renders nothing \u2014 so the provenance block's \"familiarity carries no signal\" claim holds in all reachable states. The non-stamphog Action path never sets self_driving, so no conflict is possible there either.",+ "notes": "The finding's factual description of the code is accurate (the engine does not gate familiarity on the self_driving flag), but the failure it warns about requires a hypothetical future server-side change or refactor \u2014 its own text says so. That is speculative defensive hardening, not a defect in the reviewed code. The suggested self_driving early-return in _attach_familiarity would be harmless belt-and-braces, but nothing user-affecting exists today; the invariant is single-sourced and documented in comments on both sides (activities.py:233-236 and 448-450)."+ },+ {+ "id": "U7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:71-81 \u2014 get_stamphog_connected does call has_reviewable_repo_config on every GET/PATCH serialization, but products/stamphog/backend/facade/api.py:120-125 shows it is a single team-scoped indexed .exists() (no loop, no N+1). The endpoint is human-paced (one GET per Code review tab load, PATCH only on manual toggle flips) for an alpha, UI-gated product, and the same GET request already runs the heavier seed_canonicals_tolerantly (settings.py:142) before serializing. Error/latency blowup is already contained by the fail-soft try/except (settings.py:77-81).",+ "notes": "The finding's mechanics are factually correct (uncached cross-DB read serialized on every response), but the marginal cost is one cheap indexed existence query per occasional human-initiated request \u2014 no realistic scale where it bites. The proposed short-TTL cache or read/write serializer split is caching infrastructure for a cold path (adds staleness and complexity to save milliseconds). Micro-optimization suggestion, not real user-affecting damage."+ },+ {+ "id": "U8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: process_inbox_pr_review resolves StamphogRepoConfig and returns at \"stamphog_inbox_pr_repo_not_reviewable\" BEFORE StamphogGitHubClient(...).get_pr(...), so the finding's central claim (disconnected team pays a GitHub fetch per save) is false \u2014 cost is one broker publish plus one indexed DB query. products/review_hog/backend/receivers.py: handle_task_run_saved already early-outs on update_fields without \"output\", on created, and on failed/cancelled, and its docstring explicitly documents the deliberate re-fire and its one-fetch cost \u2014 the finding's \"document the cost\" fallback is already satisfied.",+ "notes": "The suggested receiver-side last-dispatched-head guard is unimplementable as proposed (the receiver never sees the GitHub head; only the downstream fetch reveals it) and would defeat the intentional lost-synchronize recovery documented in process_inbox_pr_review's docstring. Residual cost for connected teams is a bounded, single-digit number of single PR fetches per PR on an opt-in, low-volume flow with rate-limit backoff \u2014 not user-affecting performance damage. Wrong central premise + already-handled/documented behavior + design-conflicting fix \u2192 not an issue."+ },+ {+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:~1155-1165 \u2014 get_pr does run before the head-keyed dedup, but a code comment documents why: the dedup keys on the current head \"which only GitHub knows\". products/review_hog/backend/receivers.py:85-89 \u2014 receiver early-outs when update_fields is set and excludes \"output\"; products/tasks/backend/temporal/process_task/activities/update_task_run_status.py:70 saves with update_fields=[\"status\",\"error_message\",\"completed_at\",\"updated_at\"], so frequent status writes never re-fire the receiver. Only rare genuine output writes (pr_url written ~once per run) dispatch, and Celery retries cap at max_retries=3. tasks.py:~1162 already handles GitHubRateLimitError with backoff (countdown >= 60s).",+ "id": "U9",+ "is_real": false,+ "notes": "The finding's burst scenario is structurally prevented by the receiver's update_fields guard; realistic get_pr amplification is single-digit calls per PR against a per-installation budget of thousands/hour, dwarfed by the review workflow's own GitHub traffic. The fetch-before-dedupe ordering is a deliberate, documented tradeoff (dedup needs the current head SHA), and the suggested TTL cache would suppress the explicitly designed lost-synchronize recovery. Speculative performance concern with no realistic scale where it bites.",+ "severity": "not_an_issue"+ },+ {+ "id": "U10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The claimed unguarded escape does not exist: the resolver's only production call site is _inbox_rereview_carve_out (products/stamphog/backend/tasks/tasks.py:201-205), and its sole caller wraps it in try/except at tasks.py:874-879, logging via logger.exception(\"stamphog_pr_event_inbox_carve_out_failed\") and converting any exception into a Celery retry, with a comment explaining the deliberate retry-don't-drop design (\"the webhook is already ACKed\"). Furthermore, the suggested fix (catch and return None) would be a regression: the caller maps resolver-returned-None to _InboxCarveOut(opted_out=True) (tasks.py:206-207), and the opted-out skip path runs _retract_stale_approvals_on_skip (tasks.py:894-898), dismissing the standing GitHub approval \u2014 so a transient DB blip would silently dismiss a legitimate approval instead of retrying.",+ "notes": "The finding's premise conflates two different exception contracts. receivers.py's \"never raise into the caller\" invariant protects the tasks post_save path (handle_task_run_saved and the on_commit starters), where raising would break an unrelated product's save. resolve_stamphog_acting_reviewer runs in a different context \u2014 stamphog's Celery webhook task \u2014 whose documented contract is the opposite: raise so the delivery retries, because the webhook is already ACKed and a swallowed error would silently drop a legitimate re-review (or, worse via the opted_out mapping, dismiss an approval). Verified only one production caller exists via grep of get_inbox_acting_reviewer_resolver across the tree. The concern is handled at the call site and the recommendation would actively regress behavior."+ },+ {+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_local.py:321 does use bool(context.get(\"self_driving_review\")), but the field has exactly one producer: products/stamphog/backend/logic/reviewer.py:86-140 (build_reviewer_invocation, param annotated `self_driving_review: bool = False`, line 101; placed in context at line 131; serialized via json.dumps) called only from products/stamphog/backend/temporal/activities.py:451 with `self_driving_review=bool(output.get(\"inbox_review\"))` \u2014 a genuine Python bool. JSON preserves boolean type, so the engine only ever sees True/False/None (absent for Action-shaped contexts per review_local.py:316-320). For every reachable value, bool(x) == (x is True).",+ "id": "U11",+ "is_real": false,+ "notes": "The claimed fail-open (\"false\", \"0\", non-empty strings coerce truthy) requires the trusted server to serialize a string into a field it always fills with bool(...) \u2014 that path does not exist, and no GitHub-controlled data reaches this key (pr/files/discussion flow into separate context keys). The only remaining actor is a trusted operator hand-crafting a --context file, who could set true directly anyway. The suggested `x is True` is harmless hardening against an unreachable input: speculative defensive-coding, not a real vulnerability.",+ "severity": "not_an_issue"+ },+ {+ "id": "U12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Flag has exactly one setter, fully server-derived: products/stamphog/backend/temporal/activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")) from the ReviewRun DB row. inbox_review is stamped only by two provenance-verified paths: the inbox trigger (tasks.py:1176-1229) and _inbox_rereview_carve_out (tasks.py:144-217), which enforces fork-safety (head repo must equal base repo, tasks.py:177-179), enabled+synced config, a team-scoped tasks-facade match with an explicit run.team_id == repo_config.team_id recheck (tasks.py:201-202), and an opted-in acting reviewer. No GitHub-controlled field (pr.title/body/reviews/discussion) flows into the flag; those are separate context keys built server-side. The engine-side gates (review_pr.py:225, review_local.py:321-326) do trust the flag, but the sandbox is tokenless by design and the server is the documented trust authority.",+ "notes": "The finding concedes its own emptiness: \"No reachable vulnerability exists today\" and \"defense-in-depth around a deliberate design decision, not a claim the current server derivation is wrong.\" The entire risk is conditioned on a hypothetical future caller setting the flag or a future refactor sourcing it from GitHub data \u2014 ruled out by the single, well-commented, provenance-keyed setter in current code. The \"expanded untrusted-content surface\" (bot PRs reaching the LLM) is the intended feature, already covered by _sanitize_untrusted and the anti-injection notice per the finding itself. Speculative future-proofing, not a current defect."+ },+ {+ "id": "U13",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: _inbox_rereview_carve_out resolves repo config at ~line 179 (`repo_config = _resolve_repo_config(installation_id, repo)`); on a carved-out re-review (provenance set) the skip block is bypassed and the main body resolves again at ~line 918 (`repo_config = _resolve_repo_config(installation_id, repo)` in the \"first DB touch on the main path\" try block); base-retarget deliveries add a third call at ~line 855 (`retarget_config = _resolve_repo_config(...)`). All are writer-pinned via `.using(router.db_for_write(...))` in _resolve_repo_config (~line 186), which filters on the model's (provider, installation_id, repository) unique index.",+ "notes": "The duplicate-query claim is factually accurate, so the finding is not wrong \u2014 but the impact is negligible: 1-2 extra sub-millisecond unique-index point lookups per event on a cold, opt-in, low-frequency path (bot-authored self-driving PR synchronize/reopen/base-retarget) that subsequently runs a full sandbox review with many GitHub calls. Not a hot path, not N+1, not unbounded. The suggested fix also couples _InboxCarveOut to main-body branches that use the config differently (disabled-repo and non-carve-out paths). Valid but low-stakes cleanup only; no user-affecting damage."+ },+ {+ "id": "U14",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:875-879 \u2014 `_inbox_rereview_carve_out` runs before the skip dismissal and re-raises as Celery retry on any exception, making `_retract_stale_approvals_on_skip` (:894) unreachable when the carve-out throws. The carve-out (:144-215) calls the tasks facade `find_signal_implementation_run` (:191) and the review_hog resolver (:205) unguarded \u2014 cross-product code only reached for bot-authored PRs (:169 early-return for humans). With `max_retries=3, default_retry_delay=5` (:809) and the webhook already ACKed, a tasks-side failure lasting ~15s exhausts retries and drops the dismissal permanently for that delivery. The PR diff confirms master ran the dismissal directly under `if skip_reason is not None:` with no such gate, and confirms bot self-driving PRs are newly approvable (test asserts APPROVED verdict + commit_id-pinned approval), so the hole is introduced by this change. The `_retract_stale_approvals_on_skip` docstring (:489) explicitly states the invariant being gated.",+ "notes": "One overstatement: base-retarget deliveries are protected \u2014 `_retract_approvals_on_base_retarget` runs at :857-863 before the carve-out, so exposure is synchronize/reopened only. Otherwise all claims verified. Severity is should_fix, not must_fix: trigger requires an approved self-driving PR + head push + persistent cross-product failure during the ~15s retry budget, and the stale approval self-heals on the next head-changing event; but the codebase treats every other head-changing skip dismissal as retry-guarded invariant-critical, and the fix (attempt dismissal even when the carve-out throws, before retrying for the re-review) is cheap."+ }+ ],+ "V": [+ {+ "id": "V1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "facade/api.py:120-125 indeed omits provider=\"github\" that tasks/tasks.py:1143 includes. But every writer of non-blank installation_id + connected_by_user_id hardcodes provider=\"github\" (tasks/tasks.py:649/659/668 sync-add flow); the manual create path (presentation/views.py:196-203) can set another provider but installation_id is serializer-read-only so stays \"\" and the row is excluded by the flag's .exclude(installation_id=\"\"). No reachable row can have non-github provider AND non-blank installation_id AND a connecting user, so the two predicates are extensionally identical on all current and adversarially-creatable data.",+ "notes": "The textual predicate divergence is real, but it has zero behavioral effect unless an entirely new SCM provider is implemented (out of scope; the finding itself labels it \"latent\"). Even in that hypothetical the consequence is an enabled toggle + silent no-op, a minor UX issue. Adding provider=\"github\" to the flag's filter would be harmless one-line hygiene, but as a review finding it is speculative future-proofing, below the surfacing bar."+ },+ {+ "id": "V2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The resolver (products/review_hog/backend/receivers.py:144-156) can raise, but its only production consumer is get_inbox_acting_reviewer_resolver() called at products/stamphog/backend/tasks/tasks.py:201 inside _inbox_rereview_carve_out, whose sole caller wraps it at tasks.py:876-879: `except Exception as e: logger.exception(...); raise ...retry(exc=e)`. A raised exception leaves carve_out at the default _InboxCarveOut() (provenance=None) and halts the task via Celery retry before any run creation or approval; on retry exhaustion the task fails with no review. No code path turns a resolver exception into an approval.",+ "notes": "The finding's fail-open scenario rests on a conditional (\"if stamphog's webhook caller treats a raising hook as anything other than skip\") that the actual caller refutes \u2014 it fails closed with retry semantics. The suggested fix (swallow exception, return None) would be a net regression: it maps a transient DB blip to opted_out=True, dismissing the standing approval (tasks.py:897, _INBOX_OPT_OUT_DISMISS_MESSAGE) and permanently skipping the re-review, whereas the current retry path recovers. Defense-in-depth against hypothetical future callers is speculative and handled at the existing boundary."+ },+ {+ "id": "V3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1176-1181 does stamp inbox_review from task params, but the sole call chain (facade/api.py:149 \u2190 receivers.py:126-139) fires only after handle_task_run_saved verifies the authoritative TaskRun itself: output.pr_url present (receivers.py:93), task.signal_report_id not None (:98), not task.internal (:104), acting reviewer resolved (:111) and toggle on (:126) \u2014 the exact predicate find_signal_implementation_run enforces for leg 2. Leg 2 (tasks.py:191-199) needs the reverse lookup only because a webhook carries no task context; leg 1 already holds the originating TaskRun. The suggested in-task lookup would reverse-resolve to that same TaskRun, confirming data read off the same row (and offers no defense against tainted TaskRun output either, since the lookup matches on the same output fields). Blast radius is bounded regardless: team-scoped synced+enabled repo config required (tasks.py:1140-1147); webhook-path bot/draft refusals untouched (tasks.py:218-234).",+ "notes": "The finding is explicitly hypothetical \u2014 it guards against \"a receiver bug, a future refactor that loosens the trigger\", i.e. a future defect in a currently-correct sole caller. No reachable defect in the code as written; the proposed fix is a redundant self-confirmation. At most a design-taste note about where the identification lives (caller vs task body), which the docstrings and AGENTS.md already document deliberately."+ },+ {+ "id": "V4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "medium",+ "evidence": "Premise accurate: facade/api.py:504-513 has no task.deleted check and webhooks.py:41-57/68-76 (pr_url and non-wizard branch legs of find_task_run) omit task__deleted=False (only the wizard leg at :89 filters it); Task inherits DeletedMetaFields (models.py:112). But the carve-out (stamphog/backend/tasks/tasks.py:145-215) enforces team scope twice (api.py:507, tasks.py:201), requires a bot-authored repo-native head, an enabled synced repo config, and the acting reviewer's live opt-in toggle (tasks.py:204-210) \u2014 none altered by soft-deleting the task.",+ "notes": "No security boundary is crossed and no external actor gains anything: the \"bypassed\" gates (write permission, review mode, bot/draft pre-filters) exist to stop untrusted human PRs, while this path only fires on the team's own machine-authored self-driving PR whose reviewer is currently opted in. The function verifies provenance (\"did a self-driving run open this PR?\"), which stays true after deletion; filtering deleted tasks would reject genuine provenance. The only delta is a re-review the opted-in user already signed up for, on a rare confluence (deleted task + later head-changing webhook + still-open PR). The toggle, not task deletion, is the documented off-switch, and find_task_run's primary webhook consumer intentionally matches deleted-task PRs. Defense-in-depth hygiene at most; confidence medium because the facts are certain but the severity call is a judgment."+ },+ {+ "id": "V5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_local.py:321 uses bool(context.get(\"self_driving_review\")), but review_local.py:396 loads the context with json.loads, so JSON false -> Python False; the string \"false\" can never appear. The only producer (products/stamphog/backend/logic/reviewer.py:101,131,137) takes a bool-typed parameter and json.dumps it, and its caller (products/stamphog/backend/temporal/activities.py:451) explicitly coerces with bool(output.get(\"inbox_review\")). Absent key fails closed. No alternate writer of the context file exists in the tree.",+ "notes": "The claimed trigger (truthy non-boolean like \"false\" coercing to True) is unreachable given the sole trusted producer and JSON round-trip semantics; an attacker able to write the context file controls the sandbox and would write true anyway, so `is True` adds no real security. Pure defensive-coding/style suggestion with no reachable failure scenario \u2014 the finding's own Impact section reaches the same dismissal, which independent verification confirms."+ },+ {+ "id": "V6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1203-1224 \u2014 process_inbox_pr_review dedupes on (pull_request, head_sha) via select_for_update, excluding SUPERSEDED/FAILED, and returns early before _supersede_prior_runs/ReviewRun.create/workflow start when a run at that head exists (only restarting a stranded QUEUED run, whose start is idempotent). _start_review_workflow (tasks.py, ~line 1240+) derives the workflow id from review_run_id under ALLOW_DUPLICATE_FAILED_ONLY and swallows WorkflowAlreadyStartedError, so approval-producing work (Temporal workflow) cannot run twice per head. receivers.py:80-86 and tasks.py:1124-1129 document the same-head refire as a deliberate one-fetch early-exit design.",+ "notes": "The finding is a hedged \"confirm X / consider guarding the enqueue\" verification request, not a concrete defect. Verification shows the downstream head-keyed dedupe is robust, row-locked, and early-exits before any approval-producing work; duplicate GitHub approvals are unreachable. Residual cost of a repeat receiver fire is one Celery publish + one get_pr call on a low-volume opted-in path, which the code explicitly documents as intended. Adding receiver-side enqueue guarding would duplicate state for no correctness gain."+ },+ {+ "id": "V7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1155-1159 \u2014 the pre-dedupe get_pr is a documented deliberate tradeoff (\"the dedupe keys on the PR's current head, which only GitHub knows\"; retry-not-drop preserves lost-synchronize recovery, which the suggested TTL debounce would sacrifice). Refire volume is bounded: products/review_hog/backend/receivers.py:85-89 filters out every TaskRun save whose update_fields lacks \"output\", and the only two non-test output write sites are products/tasks/backend/facade/api.py:2154 (milestone-driven set_task_run_output) and products/tasks/backend/webhooks.py:276-299 (_record_run_output_field, idempotent \u2014 returns False without saving once pr_url is set). No polling or per-turn loop writes output, so the required \"bursts of output saves\" have no in-repo producer.",+ "notes": "The described mechanism (one GitHub fetch + one no-op transaction per refire, no pre-fetch cache guard unlike the webhook leg's delivery-id idempotency cache) is factually accurate. But the claimed harm \u2014 rate-limit/DB-write amplification degrading all of an installation's reviews \u2014 needs an implausible burst of pr_url-carrying output saves against a 5000+/hr installation budget, and the feature sits behind a default-off per-user toggle scoped to non-internal signal-report runs. A handful of redundant get_pr calls per PR lifetime against an explicitly comment-documented design tradeoff is an efficiency nit below the user-affecting-damage bar; the original should_fix rating overstates it."+ },+ {+ "id": "V8",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "medium",+ "evidence": "reviewer.py:692 gates the trusted \"author is a machine user\" block on cl[\"self_driving\"] alone; review_pr.py:590 relaxes the draft gate on the same flag; review_local.py:321-326 takes the flag verbatim from context JSON and skips the bot-author refusal, never cross-checking pr.author_is_bot. The bot-author invariant is NOT airtight upstream: process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1110-1240) stamps inbox_review without any author check (unlike the webhook re-review leg, which requires _is_bot_authored), and its pr_url comes from TaskRun.output.pr_url (products/review_hog/backend/receivers.py:93), which the tasks webhook backstop _record_run_pr_url (products/tasks/backend/webhooks.py, handle_pull_request_event) writes for ANY repo-native PR matched by branch+repo \u2014 no author check. A write-access human opening a PR from the agent's pushed work branch (when agent-side detection missed, the exact case the backstop exists for) yields self_driving=True on a human-authored PR.",+ "notes": "The finding framed the trigger as a hypothetical server mis-stamp, but a concrete instantiation exists: human opens PR from the task's work branch -> tasks webhook backstop binds it to the run by branch+repo -> review_hog receiver queues process_inbox_pr_review -> engine gets self_driving=True on a human PR, relaxing the draft gate on a branch-protection-counting approval and injecting a false trusted claim (\"author is a machine user, draft state is not a caution signal\"). Requires opted-in acting reviewer + missed agent PR detection + insider with write access, and the LLM still reviews the real diff, so damage is degraded review integrity rather than automatic approval -> should_fix, not must_fix. The suggested fix (gate both carve-outs on self_driving AND pr.author_is_bot) is a one-line engine-side re-assertion that preserves the intended flow. Note: this contradicts the prior dismissed verdict in setV.md, whose \"bot author by construction\" claim overlooked the branch-matched webhook backstop leg."+ },+ {+ "id": "V9",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "settings.py:73-82 get_stamphog_connected \u2192 has_reviewable_repo_config(team_id), which is team-level \"any synced+enabled repo exists\" (facade/api.py:112-125). The review itself is gated per-repo: tasks.py:1140-1153 filters StamphogRepoConfig on repository__iexact=<PR repo> and returns silently (info log stamphog_inbox_pr_repo_not_reviewable) when absent. Frontend (CodeReviewScene.tsx:1061-1069) gates toggle interactivity only on stamphog_connected. So connected-repo-A + Inbox-PR-in-repo-B \u2192 enabled toggle, silent no-op. Mismatch is factually real.",+ "notes": "Real coarseness mismatch, but low stakes: the silent no-op is intentional, documented fail-closed design (facade docstring api.py:141 \"silent no-op without one\"; task docstring tasks.py:1123-1124 \"self-scoping\"), and a review on an unconnected repo is impossible regardless (no App installation). The primary suggested fix (repo-aware signal in the settings serializer) is infeasible \u2014 no PR repo is knowable at settings-serialization time; the toggle is inherently project-level. Worst case is UX confusion (no verdict, no explanation) in the edge case where connected repos and Inbox PR target repos diverge. The help_text already documents the team-level condition, though not the finer per-repo gate. Valid observation worth a UI-copy/observability tweak at most, not a defect requiring a fix in this PR."+ },+ {+ "id": "V10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_local.py:299-303 confirms _attach_familiarity does not check self_driving, but both self_driving_review and author_pr_numbers are derived from the same run.output[\"inbox_review\"] field in products/stamphog/backend/temporal/activities.py (line 237-238: author_pr_numbers forced to [] when inbox_review truthy; line 451: self_driving_review=bool(output.get(\"inbox_review\"))). inbox_review truthy forces self_driving=True AND author_pr_numbers=[] in lockstep, so _attach_familiarity early-returns and the familiarity block never renders alongside the provenance block. The Action path (review_pr.py:196, 225, 523) never sets self_driving and refuses bot authors before familiarity, so it cannot contradict either.",+ "notes": "The finding's mechanical observation is technically true (the engine relies on the server upholding the invariant rather than enforcing it locally), but the contradictory-prompt scenario is unreachable with any caller in the tree \u2014 it requires a hypothetical server misconfiguration or hand-built context. The invariant is enforced at its single derivation site and documented there (activities.py:233-236 comment). The suggestion is defense-in-depth hardening of an invariant that holds by construction: speculative, not user-affecting."+ },+ {+ "id": "V11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:71-81 \u2014 get_stamphog_connected does run per serialization (GET at :143, PATCH response at :137), but it is one indexed exists() query (products/stamphog/backend/facade/api.py:112-125: for_team(...).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id=\"\").exists()) on a per-user, alpha-gated config endpoint (REVIEWHOG_TEAM_ID gate at settings.py:68-69). The availability coupling is already handled twice: the serializer's fail-soft try/except returning False (settings.py:77-81) and the product-DB fail-fast circuit breaker (posthog/settings/data_stores.py:172-175, posthog/db_circuit_breaker.py).",+ "notes": "The mechanical observation is accurate but no user-affecting damage follows: single cheap cross-DB existence check on a low-traffic endpoint, outage risk mitigated in the same PR by fail-soft handling plus the existing circuit breaker. The suggested TTL cache would introduce staleness exactly when the flag matters most (right after connecting the Stamphog App) to save a sub-ms query \u2014 a premature micro-optimization. Performance/reliability claim does not meet the real-damage bar."+ },+ {+ "id": "V12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:77-81 does catch Exception and call logger.exception before returning False, and the comment (lines 73-76) frames the failure as expected fail-soft degradation. But has_reviewable_repo_config (products/stamphog/backend/facade/api.py:112-125) is a single exists() query whose exception path only fires on real DB/circuit-breaker faults, and the endpoint is per-user and alpha-gated (viewset docstring, settings.py:90).",+ "notes": "Purely a log-level preference with zero behavioral or user-facing difference \u2014 the fail-soft return False is identical either way. The claimed harm (log volume burying real errors) requires a sustained stamphog-DB outage combined with meaningful traffic on a low-volume alpha settings endpoint, and during such an outage ERROR-level tracebacks are arguably desirable operator signal. One log line per failing request of an infra fault is standard practice; the dangerous pattern (swallowing the error silently) is what the code correctly avoids. Style/observability taste, not a defect."+ },+ {+ "id": "V13",+ "is_real": true,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: line 876 calls _inbox_rereview_carve_out, which for a bot-authored (L169), repo-native (L177), head-changing skipped PR resolves the config at L179; when the carve-out resolves empty (genuine dependabot/renovate), the retraction branch at L891 calls _resolve_repo_config(installation_id, repo) again. _resolve_repo_config (L298-304) is a writer-pinned primary-DB read. So the double lookup exists exactly as described.",+ "notes": "Factually correct but negligible: the duplicate is one constant, equality-filtered lookup on a small config table, on an async already-ACKed webhook task \u2014 sub-millisecond, not N+1/unbounded, zero correctness or user-visible impact. The find_task_run cost the finding cites is the carve-out's inherent identification cost, untouched by the proposed fix. The fix is also not behavior-identical as claimed: the carve-out short-circuits before resolving config for human PRs (L169) and hides the config when disabled (L180-186), while the retraction branch deliberately ignores .enabled (L892 comment), so reuse needs semantic care. Per-branch re-resolution is the file's deliberate existing pattern (L858, L891, L918). Micro-optimization below the actionable bar."+ },+ {+ "id": "V14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:874-881 (carve-out retry before retraction \u2014 code flow confirmed), :170 (human PRs short-circuit before the tasks lookup), :483-517 (_retract_stale_approvals_on_skip is a no-op without a prior PullRequest row / standing app approval), :227-231 (bot_author skip is pre-existing \u2014 dependabot/renovate never approved).",+ "notes": "The mechanical observation is correct: a persistent tasks-facade fault inside _inbox_rereview_carve_out exhausts retries and abandons the delivery before _retract_stale_approvals_on_skip runs. But the asserted damage cannot occur for the named victim class: non-self-driving bot PRs (dependabot/renovate) are refused as bot_author (pre-existing behavior) and never hold a stamphog APPROVE, so the skipped retraction strands nothing \u2014 no PullRequest row means early return, and no standing APPROVE means nothing to dismiss. Human PRs, the class that can hold approvals, never reach the tasks lookup (not-bot short-circuit), so their retraction path gained no new dependency. The only residual exposure is self-driving PRs \u2014 explicitly excluded by the finding \u2014 and even there it needs an isolated persistent tasks-DB outage across all 3 retries while stamphog's DB stays healthy, and self-heals on the next delivery/refire (workflow dismisses stale approvals first). The retry-before-retraction ordering is a documented deliberate trade-off; the finding's mistaken premise plus a contrived, self-healing residual edge puts this below the real-damage bar."+ },+ {+ "id": "V15",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:590-593 does relax the draft gate for self_driving and fall through to `if pr.mergeable_state == \"dirty\"`, and PRData (github.py:25) has no `mergeable` boolean \u2014 those mechanics check out. But the finding's load-bearing claim (GitHub reports mergeable_state \"draft\"/\"unknown\" for drafts, never \"dirty\", so the conflict gate can't fire) is empirically false: live GitHub REST API on posthog/posthog conflicted draft PRs returns {\"draft\":true,\"mergeable\":false,\"mergeable_state\":\"dirty\"} (PRs #73403, #73367; GraphQL mergeStateStatus DIRTY / mergeable CONFLICTING on #73403, #73367, #73359). \"dirty\" takes precedence over draft status.",+ "notes": "The conflict gate at review_pr.py:592 fires for conflicted self-driving drafts exactly as for non-draft PRs, so the claimed safety-gate removal does not exist. Residual sliver: mergeable_state can be transiently \"unknown\" right after PR open while GitHub computes the test merge, but that race applies equally to non-draft PRs and predates this change \u2014 not introduced by the draft-gate relaxation. Even under the finding's own (wrong) premise, harm was already bounded: GitHub blocks merging dirty PRs regardless of approvals, and the head-pinned approval is dismissed on the conflict-resolving push."+ },+ {+ "id": "V16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:590-592 skips the draft blocker for self-driving and :607 returns \"all clear\"; _render_review_body (:900-908) builds the gate table only from gate_results with no self_driving reference; bot-author refusal (:224-226) is an early return, not a GateResult. All facts confirmed. But the carve-out is intentional and documented in code (:200-207), provenance is recorded in to_dict() (:938, tested at test_review_local.py:315) and fed to the reviewer prompt (reviewer.py:506 self_driving_block), and the draft/bot-author state is directly visible on the PR page itself.",+ "notes": "The finding's facts are accurate but it describes a comment-wording/disclosure enhancement, not a defect: no gate is bypassed unintentionally, no value computed wrongly, and the self-driving provenance is captured in the machine-readable audit trail and available to the LLM reasoning that heads the comment. Adding a carve-out disclosure line to the rendered verdict comment is legitimate polish an author could take, but it is presentation/auditability taste with no user-affecting damage \u2014 the auditor sees the draft badge and bot author on the PR anyway. Classified not_an_issue for the keep bar; if the team wants belt-and-suspenders auditability the one-line suggestion is cheap to adopt."+ }+ ]+ },+ "clusters": {+ "clusters": [+ {+ "issue": "find_signal_implementation_run rejects internal=True tasks but production self-driving implementation tasks are always internal=True, so the webhook carve-out leg is dead",+ "members": ["Y5", "P12", "Q5", "T10"]+ },+ {+ "issue": "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "members": ["X20", "P10", "Q18", "R3", "T7", "U2", "V3"]+ },+ {+ "issue": "self_driving_review read from context JSON with truthy bool() coercion instead of a strict `is True` check",+ "members": ["X10", "Y12", "P3", "Q9", "R6", "T2", "U11", "V5"]+ },+ {+ "issue": "Engine does not gate familiarity computation/rendering on self_driving, relying on the server omitting author_pr_numbers",+ "members": ["X14", "Y17", "P5", "P14", "Q2", "R7", "T9", "U6", "V10"]+ },+ {+ "issue": "_format_self_driving renders TRUSTED provenance claims (machine author / verified-by-task-linkage) solely off the self_driving flag with no engine-side verification",+ "members": ["X3", "Y3"]+ },+ {+ "issue": "Draft/bot gate relaxations in Pipeline are keyed only on self_driving, not coupled to pr.author_is_bot",+ "members": ["X9", "P15", "T6", "U12", "V8"]+ },+ {+ "issue": "stamphog_connected SerializerMethodField does an uncached cross-product-DB read on every settings serialization (GET and PATCH)",+ "members": ["X15", "Y6", "P6", "Q13", "U7", "V11"]+ },+ {+ "issue": "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "members": ["X12", "Q10", "V9"]+ },+ {+ "issue": "process_inbox_pr_review performs a live GitHub get_pr on every receiver refire before any dedupe",+ "members": ["X16", "P19", "Q16", "U8", "U9", "V6", "V7"]+ },+ {+ "issue": "Carve-out path resolves the same StamphogRepoConfig twice (or thrice) per delivery",+ "members": ["Y14", "P7", "Q11", "U13", "V13"]+ },+ {+ "issue": "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "members": ["X11", "Q8", "T3"]+ },+ {+ "issue": "Webhook-leg toggle re-check repeats the multi-query reviewer-resolution chain on every synchronize/reopen push (performance)",+ "members": ["P18", "Q17"]+ },+ {+ "issue": "_parse_pr_url regex is not host-anchored, so lookalike domains/embedded github.com substrings parse as valid GitHub PR URLs",+ "members": ["Y10", "P1"]+ },+ {+ "issue": "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "members": ["Y2", "P2"]+ },+ {+ "issue": "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "members": ["X4", "P23"]+ },+ {+ "issue": "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "members": ["X13", "Q3"]+ },+ {+ "issue": "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "members": ["X1"]+ },+ {+ "issue": "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "members": ["X2", "U3", "V1"]+ },+ {+ "issue": "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "members": ["X5"]+ },+ {+ "issue": "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "members": ["X6"]+ },+ {+ "issue": "find_signal_implementation_run still matches cancelled/failed runs and soft-deleted tasks, extending the carve-out past the automation's lifetime",+ "members": ["X7", "V4"]+ },+ {+ "issue": "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "members": ["X8"]+ },+ {+ "issue": "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "members": ["X17"]+ },+ {+ "issue": "Relaxed gates leave no trace in logs/gate messages/posted review comment that the self-driving carve-out fired",+ "members": ["X18", "V16"]+ },+ {+ "issue": "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "members": ["X19", "T4"]+ },+ {+ "issue": "stamphog_review_inbox_prs is PATCH-writable without a server-side stamphog_connected precondition validator",+ "members": ["Y1", "U1"]+ },+ {+ "issue": "Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled-state copy in the UI",+ "members": ["Y4"]+ },+ {+ "issue": "Second synchronous Celery broker publish on the on_commit path with no bounded publish timeout against a hung broker",+ "members": ["Y7"]+ },+ {+ "issue": "Carve-out exception retry path can block the stale-approval safety dismissal for head-changing bot PRs",+ "members": ["Y8", "U14", "V14"]+ },+ {+ "issue": "AGENTS.md carve-out section conflicts with the file's 'every invariant earned through a real review finding' preamble framing",+ "members": ["Y9"]+ },+ {+ "issue": "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "members": ["Y11"]+ },+ {+ "issue": "Claimed stranding of QUEUED runs because on_commit workflow restart supposedly runs after the Celery task returns (disproven Django semantics)",+ "members": ["Y13"]+ },+ {+ "issue": "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "members": ["Y15"]+ },+ {+ "issue": "Alleged \\s character-class typo in _parse_pr_url making repos containing 's' unparseable (fabricated/misquoted regex)",+ "members": ["Y16"]+ },+ {+ "issue": "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "members": ["P4"]+ },+ {+ "issue": "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "members": ["P8"]+ },+ {+ "issue": "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "members": ["P9"]+ },+ {+ "issue": "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "members": ["P11"]+ },+ {+ "issue": "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "members": ["P13", "R4", "T8", "U4"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer has no try/except guard despite being invoked from another product's webhook path",+ "members": ["P16", "U10", "V2"]+ },+ {+ "issue": "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "members": ["P17"]+ },+ {+ "issue": "Alleged check-then-act race in process_inbox_pr_review's dedupe allowing duplicate runs under concurrent refires (serialized by PR row lock)",+ "members": ["P20"]+ },+ {+ "issue": "repository__iexact lookup cannot use StamphogRepoConfig's case-sensitive indexes",+ "members": ["P21"]+ },+ {+ "issue": "stamphog_inbox_pr_create_run_failed log omits the error=str(e) structured field its siblings include",+ "members": ["P22"]+ },+ {+ "issue": "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy",+ "members": ["P24"]+ },+ {+ "issue": "Claim that max_migration.txt was not bumped to the new 0019 migration (false against PR head)",+ "members": ["Q1", "R2"]+ },+ {+ "issue": "Engine's stamphog_review_completed analytics event lacks a self-driving marker property",+ "members": ["Q4", "R1"]+ },+ {+ "issue": "AGENTS.md provenance key name (inbox_review vs trigger/stamphog_self_driving_review) suspected of not matching the implementation",+ "members": ["Q6"]+ },+ {+ "issue": "AGENTS.md carve-out section placement splits the egress-to-trust-boundaries document flow",+ "members": ["Q7"]+ },+ {+ "issue": "Opt-out dismissal copy/log mismatch on a base-retarget delivery (retarget message posted while log says inbox_opt_out)",+ "members": ["Q12"]+ },+ {+ "issue": "Broad except in get_stamphog_connected collapses transient circuit-breaker failures and real bugs into one error-level log",+ "members": ["Q14", "T5", "V12"]+ },+ {+ "issue": "Carve-out pays repo-config and tasks-DB lookups before the cheap resolver-is-None short-circuit",+ "members": ["Q15"]+ },+ {+ "issue": "Opt-out dismissal message claims 'New commits were pushed' on a reopened PR where no commits were pushed",+ "members": ["Q19"]+ },+ {+ "issue": "queue_inbox_pr_review facade does not guard the Celery .delay publish, so broker/serialization errors can raise into the caller's save path",+ "members": ["R5"]+ },+ {+ "issue": "Claim that tach.toml does not declare the new review_hog -> stamphog dependency (false against PR head, which adds it)",+ "members": ["T1"]+ },+ {+ "issue": "Relaxing the draft gate leaves mergeable_state == \"dirty\" as the only conflict check, which GitHub never reports for drafts, so the merge-conflict gate is inert for self-driving draft PRs",+ "members": ["U5", "V15"]+ }+ ]+ },+ "judges": [+ {+ "ranking": ["M2", "M1", "M3", "M4"],+ "margins": "M2 > M1: narrow and contested \u2014 M1 wins raw recall (14 confirmed real, 6 high-impact, best precision at 31.8%) but M2 wins the heaviest-weighted axis (3 confirmed must_fix vs 1, and the only must_fix caught reliably in BOTH runs). M1 > M3: clear \u2014 M1 delivers 6-8 confirmed real findings in every run, while M3's aggregate (2 must_fix) hangs entirely on one run. M3 > M4: moderate \u2014 M3 covered both must_fix issues while M4 confirmed zero must_fix in either run, but M3's 0/7 dead run (R) and M4's steadier 2-real-per-run floor narrow the gap.",+ "rationale": "Scored on adversarially verified verdicts only, aggregating both runs per model, weighting confirmed must_fix/should_fix heaviest and cross-run repeatability as the reliability signal.\n\nM2 (Y+Q) ranks first because it dominates exactly where the lens puts the weight. It produced 3 of the 4 confirmed must_fix findings in the entire experiment: Y5 and Q5 (the dead internal=True carve-out \u2014 the PR's core deliverable being inert in production) and Q18 (the receiver-leg re-attestation gap enabling unearned Stamphog approvals). Critically, Y5+Q5 is the ONLY issue any model caught in both of its runs at must_fix severity \u2014 a single M2 run is near-guaranteed to surface the top defect, whereas every other model's must_fix coverage is a coin flip. Its verified framings were also sharper: on the receiver-leg issue, M2's Q18 verified as must_fix while M1's P10 and both M4 attempts (U2, V3) were dismissed as hypothetical. Cost: only 7/36 real (19.4% precision, 29 noise findings) and thin below must_fix (one should_fix Y8, three considers Y4/Q12/Q19) \u2014 it misses much of the should_fix tier M1 finds.\n\nM1 (X+P) is a very close second and would win under a pure breadth-of-recall lens: 14 confirmed real findings (most of any model), 6 high-impact (P12 must_fix; X3, X7, X9, X20, P8 should_fix), best precision (31.8%), and several confirmed catches no other model landed (X3 trusted provenance rendering, X7 cancelled/failed-run matching, P8 same-head double-review, X17, X19). It touched both must_fix clusters (P12; X20 verified should_fix). What demotes it under THIS lens is reliability: not one issue was confirmed in both runs \u2014 the confirmed-real sets of X and P are completely disjoint. The top must_fix (internal=True) was caught only in P and missed outright in X; the gate-relaxation issue verified in X (X9) but its P twin (P15) was dismissed; X20 verified but P10 dismissed. Each individual M1 run is strong (7 real findings per run \u2014 the best per-run floor), but which high-impact issues you get is luck-dependent, and it only surfaces the single most important defect 50% of the time versus M2's 100%.\n\nM3 (R+T) ranks third on the strength of one outstanding run: T alone confirmed BOTH must_fix issues (T7 receiver-leg re-attestation \u2014 the sharpest, most concretely argued version of that finding \u2014 and T10 dead carve-out) plus T6 (consider), with modest noise (7 dismissed). But run R was a total zero: 0/7 real, pure noise. Aggregate must_fix recall beats M4 decisively, but reliability is the worst possible profile \u2014 a 50% chance any given run contributes nothing at all, and zero cross-run repetition. Small output volume (17 findings) keeps its noise burden lowest in absolute terms.\n\nM4 (U+V) ranks last. It confirmed zero must_fix across both runs: it missed the dead-carve-out issue entirely, and though it raised the receiver-leg issue in both runs (U2, V3), both framings hedged into hypotheticals and verified as not_an_issue \u2014 surfacing the right area but failing to make the real case, which is worthless to an author. Its confirmed yield is 2 should_fix (U14 stale-approval dismissal gating \u2014 its best catch; V8 self_driving/bot-author coupling, medium confidence) plus 2 considers (U13, V13/V9-tier), each in one run only (V14, the twin of U14, was dismissed on a mistaken premise). Worst precision (4/30, 13.3%) and 26 noise findings mean its rare real catches are the most buried. Consistent per-run output, but consistently low-impact."+ },+ {+ "ranking": ["M1", "M2", "M3", "M4"],+ "margins": "M1 > M2: decisive \u2014 31.8% vs 19.4% precision, 2.1 vs 4.1 noise findings per real catch, and M1's precision is stable across both runs (X 35%, P 29%). M2 > M3: moderate \u2014 headline rates are nearly tied (19.4% vs 17.6%) but M2's reliability is far better: 3 confirmed must_fix with the biggest bug caught in both runs (Y5+Q5), versus M3 concentrating all value in one run while its other run (R) was 100% noise. M3 > M4: narrow-to-moderate \u2014 M3 wins on rate (82% vs 87% noise), impact weight (2 must_fix vs 0), and absolute attention tax (14 vs 26 noise findings), but M4's only edge is that each of its runs contained at least one real finding, whereas M3's run R contained zero.",+ "rationale": "Under the precision lens, value = real confirmed findings surfaced per unit of reviewer attention burned, weighted by severity and run-to-run reliability.\n\nM1 (sets X+P) is the clear winner. It has the best precision by a wide margin: 14 of 44 findings confirmed real (31.8%), including 1 must_fix (P12, the internal=True dead-carve-out bug) and 5 should_fix (X3, X7, X9, X20, P8), against 30 not_an_issue. Its noise cost per real catch (2.1) is half the next-best model's. It is also the only model whose confirmed catches span all three high-impact clusters: the receiver-leg trust asymmetry (X20 confirmed should_fix), the internal=True dead code (P12 must_fix), and the self_driving gate-relaxation trust issue (X3, X9). Precision was consistent across runs (65% and 71% noise), so a single run of M1 is dependably useful. Weakness: it raised the internal=True must_fix in only one run, and it produces the highest absolute finding volume, but per-finding it wastes the least attention.\n\nM2 (sets Y+Q) is second. Raw precision is mediocre (7/36 real, 19.4%; 29 noise findings, 4.1 noise per real catch), but it is the severity-weighted heavyweight: 3 confirmed must_fix (Y5, Q5, Q18) \u2014 more than any other model \u2014 and critically it caught the single most consequential bug of the PR (find_signal_implementation_run rejecting internal=True tasks, making the webhook carve-out dead against production data) in BOTH runs (Y5 and Q5). That is the only both-run must_fix catch by any model, which is exactly the reliability the lens rewards. Q18 also independently confirmed the receiver-leg re-attestation gap as must_fix. Both runs delivered real value (Y: 3 real incl. must_fix; Q: 4 real incl. 2 must_fix), so M2 never produced an empty run. It sits below M1 because it buries those catches under an 81% noise rate \u2014 nearly every non-flagship finding (Y1-Y3, Y6-Y7, Y9-Y17, Q1-Q4, Q6-Q11, Q13-Q17) was dismissed, including a fabricated regex claim (Y16) and disproven Django semantics (Y13).\n\nM3 (sets R+T) is third. Aggregate precision (3/17, 17.6%) is statistically indistinguishable from M2's, and when it hit, it hit hard: T7 (receiver-leg approval-bypass, the security must_fix, with the most exploit-precise framing of any model \u2014 contrast R3/U2/V3, which raised the same surface defensively and were dismissed) and T10 (internal=True dead carve-out, must_fix, with the historical root-cause commit identified). But the lens explicitly penalizes luck-dependence, and M3 is the poster child: run R produced 7 findings and 0 real (100% noise \u2014 R1-R7 all dismissed, including two premise-false claims R1 and R2 about things the PR diff itself already contains), while run T produced everything. The same model reviewing the same PR either finds 2 must_fix or finds nothing; a coin-flip reviewer cannot be relied on. Its low output volume (17 findings) does mean the least total wasted attention of any model, which keeps it above M4.\n\nM4 (sets U+V) is last on every axis. Worst precision (4/30, 13.3%; 26 noise findings, 6.5 noise per real), zero confirmed must_fix \u2014 its best catches are U14 and V8 (should_fix) plus U13/V9 (consider) \u2014 and it whiffed on both flagship bugs: it never raised the internal=True dead-carve-out issue at all, and both of its framings of the receiver-leg trust gap (U2, V3) were dismissed as hypothetical defensive hardening rather than identifying the reachable exploit that T7/Q18 nailed. Its noise has a characteristic signature the verifiers repeatedly called out: self-confessed speculation (\"no reachable vulnerability exists today\" in U12, hedged verification requests in V6), defensive-coding preferences (U11, V5), micro-optimizations (U7, V11, V13), and a premise-false safety claim (V15, refuted by live GitHub API evidence). Consistency is its only redeeming trait \u2014 both runs found something real and it raised the stale-approval-dismissal issue in both runs (U14 confirmed, V14's framing dismissed) \u2014 but consistently drowning 2 should_fix in 26 dismissed findings is the profile that wastes the most reviewer attention per unit of value."+ },+ {+ "ranking": ["M2", "M1", "M3", "M4"],+ "margins": "M2 > M1: narrow, genuinely contested \u2014 on weighted heavy-severity count they are nearly tied (M1: 1 must_fix + 5 should_fix; M2: 3 must_fix + 1 should_fix) and M1 has better precision (32% vs 19% real), but M2 is the only model that caught the top must_fix in BOTH runs, which is the decisive reliability signal. M1 > M3: decisive \u2014 M1 produced multiple confirmed heavy findings in every run with the field's best precision, while M3's run R was a total blank (0/7 real). M3 > M4: moderate \u2014 M3's T run caught both experiment-defining must_fixes (M4 caught neither in 30 findings and twice argued the security hole was benign), but M4's run-to-run consistency (one confirmed should_fix per run) keeps the gap from being decisive.",+ "rationale": "Verified tallies: M1 (X+P) = 44 findings, 14 confirmed real (P12 must_fix; X3/X7/X9/X20/P8 should_fix; X12/X17/X19/P4/P7/P13/P17/P19 consider), 30 noise, 32% precision \u2014 best of the field. M2 (Y+Q) = 36 findings, 7 real (Y5/Q5/Q18 must_fix; Y8 should_fix; Y4/Q12/Q19 consider), 19% precision, but owns 3 of the experiment's 4 must_fix verdicts. M3 (R+T) = 17 findings, 3 real, all in run T (T7/T10 must_fix, T6 consider); run R was 0/7 real including a wrongly-rated security must_fix (R6). M4 (U+V) = 30 findings, ~4 real (U14/V8 should_fix, U13/V9 consider, V13 negligible), zero must_fix.\n\nThe ranking turns on the two killer issues. (1) Dead feature \u2014 find_signal_implementation_run rejects internal=True but every production self-driving task is internal, so the PR's core webhook carve-out is inert (cluster Y5/P12/Q5/T10): M2 caught it at must_fix strength in BOTH runs (Y5, Q5 \u2014 verifier corroborated every claim against the PR tree and git history, tracing the stale assumption to #68752); M1 caught it once (P12; set X missed it \u2014 X8 grazed the identification predicate and concluded it deliberate); M3 once (T10); M4 never. (2) Receiver-leg approval bypass \u2014 process_inbox_pr_review stamps inbox_review from caller-controlled pr_url with no re-attestation, letting a prompt-injected agent obtain an unearned head-pinned GitHub APPROVE (cluster X20/P10/Q18/R3/T7/U2/V3): M1 surfaced it both runs but only X20 survived (should_fix; P10's narrow framing dismissed); M2 confirmed once (Q18 must_fix); M3 confirmed once (T7 must_fix, with the best concrete fix \u2014 mirror the webhook leg's re-attestation) but R3's tautological framing was dismissed; M4 raised it both runs (U2, V3) and reasoned itself into dismissing the real vulnerability both times.\n\nM2 first, narrowly: it is the only model whose highest-impact catch is reliable rather than luck-dependent (both-run must_fix on the dead feature), each of its runs contained at least one must_fix, and its run sizes (17-19 findings) impose less noise burden than M1's (20-24). Its demerits are real \u2014 Q1 falsely claimed max_migration.txt wasn't bumped (missed hunk) and Y16 fabricated a regex misquote \u2014 but they don't offset 3/4 of all must_fix verdicts. M1 second, close behind: broadest confirmed coverage (unique should_fixes X3 trusted-provenance rendering, X7 cancelled/deleted-run matching, X9 draft/bot gate coupling, P8 duplicate-review race) and the best signal-to-noise ratio, but its must_fix was one-run-only and its second-run framings of both killer issues (P10, P15) fell below the keep bar \u2014 the model finds the right code shapes consistently but argues them to confirmed strength inconsistently. M3 third: run T alone rivals the leaders (both killer must_fixes plus T6 consider), but a model that returns pure noise half the time \u2014 including an unwarranted must_fix security rating (R6) \u2014 cannot be trusted as the pipeline's reviewer; expected per-run value still edges M4 because must_fix catches dominate. M4 last: most consistent noise profile but the lowest ceiling \u2014 zero must_fix across 30 findings, the dead feature invisible in both runs, and the genuine security hole explicitly argued away twice (U2, V3); its best work (U14 stale-approval dismissal gap, V8 human-PR-as-self-driving via the branch-matched webhook backstop) is solid should_fix material but was itself run-inconsistent (V14 and U12, the sibling framings, were both dismissed)."+ }+ ],+ "_meta": {+ "round": "fourway-extension-2026-07-24",+ "blinding": "judges saw four anonymous models M1=X+P (sonnet-5), M2=Y+Q (glm-5.2), M3=R+T (gpt-5.5), M4=U+V (opus-4-8); set files blinded via blind_prep.py",+ "verified_against": "PR 72680 worktree @ 1341596e + full diff; one adversarial refutation-first verifier per R/T/U/V finding (effort high)",+ "note": "clusters = incremental extension of judge-final.json 53 clusters over all 8 sets; X/Y/P/Q verdicts NOT re-run (see judge-round1.json, judge-setP.json, judge-final.json). Set R is the degraded C1 run (perspective coverage of chunks 1-2 lost to model refusals)."+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round1.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round1.jsonnew file mode 100644index 000000000000..c44f69872999--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round1.json@@ -0,0 +1,362 @@+{+ "xVerdicts": [+ {+ "id": "X1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/facade/api.py:128-155 (facade forwards verbatim, as claimed); products/review_hog/backend/receivers.py:111,202-207,210-236 (sole caller derives acting_user_id via team-scoped org-member resolution for the same team_id); products/stamphog/backend/tasks/tasks.py:1176-1180,1229 (acting_user_id stamped as write-only provenance); products/stamphog/backend/temporal/activities.py:123,175,237,451 (credential minted under repo_config.connected_by_user_id; carve-out keyed on bool(output.get(\"inbox_review\")), never on acting_user_id); products/stamphog/backend/tasks/tasks.py:199-205 (webhook \"belt and braces\" check guards run.team_id vs repo_config.team_id facade boundary, not reviewer membership \u2014 webhook leg trusts its resolver identically)",+ "notes": "The finding accurately describes the code (no membership check on acting_user_id) but the risk is unreachable and inconsequential: the only caller is an in-process receiver that resolves acting_user_id to an org member of the same team_id it forwards, the field is non-authorizing provenance that drives no credential, approval, or carve-out decision, and the cited webhook-leg precedent guards a different boundary (cross-product facade team scope), not reviewer identity \u2014 so the claimed asymmetry does not exist. Adding the suggested check would be redundant defense against a hypothetical future caller bug; speculative/defensive-paranoia, below the bar."+ },+ {+ "id": "X2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/facade/api.py:112-125 (has_reviewable_repo_config lacks provider filter \u2014 premise accurate); products/stamphog/backend/facade/api.py:107-109 (get_repo_config also omits provider, refuting \"every other lookup\" claim); products/stamphog/backend/models.py:26-29 (provider CharField default \"github\", no choices, GitHub only implemented provider); products/stamphog/backend/tasks/tasks.py:666-674 (only path stamping non-blank installation_id + connected_by_user_id creates rows with provider=\"github\")",+ "notes": "Code premise is correct but the failure scenario is unreachable: the predicate (enabled + synced installation_id + connecting user) can only be satisfied by rows created via the GitHub App sync flow, which hardcodes provider=\"github\". A non-github row satisfying it would require an unimplemented second SCM provider. The claimed divergence from \"every other repo-config lookup\" is also inaccurate \u2014 get_repo_config in the same file omits the provider filter too. Adding provider=\"github\" would be harmless consistency polish, not a fix for any real behavior today."+ },+ {+ "confidence": "medium",+ "evidence": "reviewer.py:692-703 renders the TRUSTED machine-user block off cl.get(\"self_driving\") alone. Webhook leg is bot-gated (products/stamphog/backend/tasks/tasks.py:171-175), but the receiver leg is not: process_inbox_pr_review (tasks.py:1110-1229) stamps inbox_review with no author check, and its pr_url can be bound by the tasks-webhook backstop via branch+repo match only (products/tasks/backend/webhooks.py:176-185, _record_run_pr_url) \u2014 a human opening a PR from the agent's work branch when agent-side detection missed reaches self_driving=True with author_is_bot=False (review_local.py:321-324 passes it through).",+ "id": "X3",+ "is_real": true,+ "notes": "The rebuttal embedded in the finding file (\"no reachable path to self_driving=True + non-bot author\") is wrong: only the webhook re-review leg checks _is_bot_authored; the receiver leg trusts TaskRun.output.pr_url, which the tasks-webhook backstop binds by branch+repo with no author check \u2014 exactly the path used when the agent fails to open the PR itself and a human opens it from the agent's branch. In that reachable scenario reviewer.py asserts a false trusted fact (\"author is a machine user\", \"draft state is not a caution signal\") on a path that mints real GitHub approvals. Bounded impact: the diff is still agent-produced at that head, the reviewer still judges the diff and can refuse/escalate, later pushes re-review through the normal gated path, and the suppressed signals cut both ways. Cheap fix: cross-check pr.author_is_bot (already on PRData) before rendering, or surface the mismatch. should_fix, not must_fix.",+ "severity": "should_fix"+ },+ {+ "confidence": "high",+ "evidence": "products/db_routing.yaml (tasks app absent \u2014 TaskRun is main-DB); posthog/dbrouter.py:22-31 (ReplicaRouter.db_for_read returns \"default\"/writer unless model opted in via READ_REPLICA_OPT_IN, empty default per posthog/settings/data_stores.py:271-272); posthog/product_db_router.py:27-34 (only stamphog/visual_review/warehouse_sources_queue/agent_platform get _db_reader routing); products/tasks/backend/webhooks.py:40 (the unpinned TaskRun read \u2014 pre-existing, unchanged); products/stamphog/backend/tasks/tasks.py:300,396 (stamphog-DB reads in the PR are pinned); products/stamphog/backend/tasks/tasks.py:882-894 (head-changing skip path retracts stale approvals unconditionally, so a lagged false-negative is fail-closed)",+ "id": "X4",+ "is_real": false,+ "notes": "The finding's raw facts check out (unpinned find_task_run read; pinned stamphog reads; no AGENTS.md cross-reference), but the conclusion misapplies the Reader-lag invariant: that invariant governs the stamphog product DB, whose ProductDBRouter sends unpinned reads to a real replica. TaskRun lives in the main DB under ReplicaRouter, where reads go to the writer by default \u2014 pinning via .using(router.db_for_write(TaskRun)) would be a no-op, and every read of the DB the invariant covers IS pinned in this PR. Even under a hypothetical replica config the failure is fail-closed: carve-out resolves empty, the bot PR stays refused, and the skip path still dismisses stale approvals; the carve-out only fires on synchronize/reopen/retarget, long after the linkage row committed, and signal linkage is never revoked post-creation. A must_fix demanding documentation plus a no-op pin on pre-existing, unchanged code is not a defect.",+ "severity": "not_an_issue"+ },+ {+ "id": "X5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/AGENTS.md:129-135 (Engine parity section, unchanged by PR \u2014 0 diff matches for \"Engine parity\"/\"wherever both apply\" in pr72680.diff) vs AGENTS.md:80-114 (new carve-out section); lines 93-95 already state the flag \"defaults closed and the Action never sets it, so Action behavior is unchanged by construction\".",+ "notes": "Premise is textually accurate but there is no defect: the parity rule is scoped to \"wherever both apply\", and the Action never sets self_driving_review, so the carve-out is outside that rule by its own wording. The new section documents the divergence completely in the same file. The suggestion is a one-line cross-reference in a section this PR does not touch \u2014 pure documentation taste with no behavioral, correctness, or contract consequence."+ },+ {+ "id": "X6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/receivers.py:159 (`signal_report_id: Any` in _resolve_assigned_reviewer), :111 (caller passes UUID `task.signal_report_id`), :152 (resolve_stamphog_acting_reviewer passes str), :180-187 (filter on report_id); pr72680_tree/products/signals/backend/models.py:184 (SignalReport is UUIDModel), :746 (SignalReportArtefact.report FK); pr72680_tree/products/tasks/backend/models.py:191 (Task.signal_report FK)",+ "notes": "The loose `Any` annotation exists as described, but Django's UUIDField coerces str and UUID identically in query prep, so both call sites (UUID from the signal receiver, str from stamphog's hook) match the same rows \u2014 no runtime mismatch is possible. Any hypothetical mismatch fails closed (resolver returns None, no review starts), so there is no security or correctness consequence. The finding is a type-annotation hygiene suggestion with zero behavior change; style-level, not a defect."+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/tasks/backend/facade/api.py:505-513 (only team_id/signal_report_id/internal checks); pr72680_tree/products/tasks/backend/webhooks.py:46-57 (pr_url leg falls back to terminal runs via order_by(\"terminal_rank\",\"-created_at\").first()), :64-78 (branch leg has no task__deleted or status filter; only wizard leg :85-95 excludes both); pr72680_tree/products/stamphog/backend/tasks/tasks.py:191-201 (carve-out checks only run is None / team_id), :946 and :967-969 (carve-out bypasses review-mode and write-permission gates); pr72680_tree/products/tasks/backend/facade/cancellation.py (no GitHub calls, PR left open); pr72680_tree/products/tasks/backend/models.py:445-452 (soft_delete flips DB flags only)",+ "id": "X7",+ "is_real": true,+ "notes": "Confirmed: the new find_signal_implementation_run facade matches CANCELLED/FAILED runs (terminal fallback in find_task_run's pr_url leg) and deleted tasks (no task__deleted filter on the pr_url or plain-branch legs), and the stamphog carve-out adds no status check, so a later push to the still-open bot PR of a cancelled/deleted self-driving task re-applies the full gate bypass (bot-author, draft, review-mode, write-permission) and can post a real approval for automation the team explicitly stopped. Severity bounded to should_fix: not forgeable or cross-tenant (genuine same-team signal-run linkage required, fork-rejected before lookup), pusher needs repo write access anyway, acting reviewer must be opted in, approval only if the engine judges content approvable, and a human still merges \u2014 a within-tenant authorization-window scoping fix, not a merge-blocking vulnerability. Suggested fix (exclude CANCELLED/FAILED runs and deleted tasks in the facade, keep COMPLETED matchable) is correct and minimal.",+ "severity": "should_fix"+ },+ {+ "id": "X8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/tasks/backend/facade/api.py:508 mirrors the documented discriminator at pr72680_tree/products/review_hog/backend/receivers.py:98-105 (\"internal plumbing tasks also carry signal_report_id\"); field still load-bearing (37 non-test refs, deprecated note at models.py:190 is aspirational); caller pr72680_tree/products/stamphog/backend/tasks/tasks.py:191-201 returns empty _InboxCarveOut() on None, so retirement of the field fails closed (bot PR refused), never a bypass",+ "notes": "The check deliberately matches the review_hog trigger that produces these runs \u2014 signal_report_id + not internal is the codebase's actual precedent for identifying the self-driving implementation task; origin_product pairing at api.py:~3796 is creation-time bookkeeping and both fields are set together, so adding it changes no outcome. The finding's security framing collapses on its own admission that failure is fail-closed; what remains is speculative future-proofing against a field retirement not in scope, with no misbehaving input today."+ },+ {+ "id": "X9",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "medium",+ "evidence": "tools/pr-approval-agent/review_pr.py:225 (bot refusal relaxed by flag), review_pr.py:590 (draft gate relaxed by flag alone, not conditioned on author_is_bot); products/stamphog/backend/tasks/tasks.py:169-172 (webhook leg enforces _is_bot_authored) vs tasks.py:1110-1232 (receiver leg process_inbox_pr_review stamps inbox_review with NO author check on the fetched PR \u2014 bot authorship is docstring-only at tasks.py:1117); products/tasks/backend/webhooks.py:159,185,203-212 (backstop stamps output.pr_url by branch match with no author check, so a human-opened PR from the agent's repo-native branch can become the run's pr_url); products/stamphog/backend/temporal/activities.py:451 \u2192 tools/pr-approval-agent/review_local.py:321 (flag flows to the engine); tasks.py:225-229 (_review_skip_reason docstring: \"The engine keeps the same bot/draft refusals as defense in depth\" \u2014 the invariant the PR's carve-out no longer guarantees).",+ "notes": "The finding's code claim is correct and the common refutation (\"no caller can set self_driving=True for a non-bot PR\") does not hold: the receiver leg (process_inbox_pr_review) never verifies the fetched PR's author, and the tasks webhook backstop stamps pr_url purely on a head-branch match, so on the public repo a human-authored PR opened from the agent's work branch can reach the engine with self_driving=True. In that state the draft gate silently disappears and the reviewer prompt carries trusted task provenance for a PR whose title/body/base are human-controlled. The one-line fail-closed guard (disable self_driving when pr.author_is_bot is False after fetch) matches the codebase's explicit belt-and-braces doctrine and closes the gap at the layer upstream code documents as defense in depth. must_fix is overblown though: the bad path needs an opted-in acting reviewer, an unstamped pr_url race, and still passes every other gate plus the LLM verdict over agent-pushed diff content \u2014 real but limited, hence should_fix."+ },+ {+ "id": "X10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/tools/pr-approval-agent/review_local.py:321 consumes bool(context.get(\"self_driving_review\")); pr72680_tree/products/stamphog/backend/logic/reviewer.py:101 (typed `self_driving_review: bool = False`), :131 (placed in context dict), :137 (json.dumps serialization); pr72680_tree/products/stamphog/backend/temporal/activities.py:451 (sole caller passes bool(output.get(\"inbox_review\")))",+ "notes": "The value is a genuine Python bool at the only producer, serialized via json.dumps (emits JSON true/false, round-trips to Python bool). Absent key yields None -> bool(None) = False, so bool() is fail-closed for every reachable value. The string-\"false\" scenario requires a hypothetical future serialization regression that has no basis in the PR code; the flag is server-stamped from inbox provenance, not author-controlled input. Speculative defensive-coding suggestion, not a real gap."+ },+ {+ "id": "X11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/receivers.py:162-164 (assignment explicitly defined as the report's latest artefact \u2014 dynamic by design), receivers.py:111 (leg 1 also re-derives on every save, so no pinned identity exists), receivers.py:148-149 (live re-check on later pushes is the stated purpose); pr72680_tree/products/stamphog/backend/facade/inbox_hooks.py:20-21 (contract: \"toggle is currently on\"); pr72680_tree/products/stamphog/backend/tasks/tasks.py:207,888-910 (opted_out path still dismisses stale approvals and logs reason=\"inbox_opt_out\"), tasks.py:211-216 (provenance records acting_user_id per run)",+ "notes": "The re-derivation the finding describes exists, but it is the documented follow-current-assignment semantics shared by both legs, not a missing identity pin: the resolver docstring, the hook contract, and the append-only latest-artefact model all specify current-state resolution, and leg 1 itself re-resolves on every TaskRun save. Drift only changes whether a later push gets re-reviewed (fail-closed: stale-approval dismissal runs unconditionally on the opt-out skip path), so no wrong approvals or security impact. The suggested pin-at-leg-1 fix would regress the intended behavior of following live reassignment."+ },+ {+ "id": "X12",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/api/settings.py:72-81 (get_stamphog_connected \u2192 has_reviewable_repo_config(team_id)); pr72680_tree/products/stamphog/backend/facade/api.py:112-126 (project-wide .exists() over any synced+enabled repo config); pr72680_tree/products/stamphog/backend/tasks/tasks.py:1141-1155 (per-repo gate in process_inbox_pr_review: logger.info + silent return when the PR's repo has no config)",+ "notes": "The described behavior exists: stamphog_connected is a project-wide \"at least one repo\" signal while the actual inbox-review gate is per-repository and silently no-ops (logged only) for uncovered repos, so a multi-repo team with partial Stamphog coverage can see the toggle enabled yet get no reviews for PRs in unconnected repos. But it is low-stakes and largely by design: the help_text at settings.py:50-54 already states the \"at least one synced, enabled Stamphog repository\" semantics (the finding's fallback fix is effectively done), the settings endpoint has no repository in context so per-repo scoping is ill-defined for a project-wide per-user toggle, and the failure mode is fail-closed (skipped review, no wrong output). Valid observation, UX-copy-level at most \u2014 not must/should fix."+ },+ {+ "id": "X13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/receivers.py:222 (deferred import before try at :225, inside on_commit lambda at :131) \u2014 shape confirmed; but receivers.py:254-261 shows the identical merged convention in _start_review, and pr72680_tree/products/review_hog/backend/api/settings.py:16 imports the same facade at module level, so an import-time failure fails deterministically at settings-API import / CI, never as an on-commit surprise.",+ "notes": "Code-shape claim is accurate but the failure scenario is defensive paranoia: the stamphog facade is module-level-imported elsewhere in the same PR (settings.py:16) and cached in sys.modules, so the deferred import in the on_commit callback cannot realistically raise in a deployed app; a broken facade would fail CI/startup loudly. Pattern exactly mirrors the pre-existing _start_review convention, so the PR introduces no new gap. Even in the hypothetical, on_commit runs post-commit \u2014 no rollback or data loss, only a logged exception in the committing path."+ },+ {+ "confidence": "high",+ "evidence": "Engine gap exists as described: pr72680_tree/tools/pr-approval-agent/review_local.py:299-303 (_attach_familiarity bails only on empty author_pr_numbers, no self_driving guard). But the harm is closed upstream in the same PR: pr72680_tree/products/stamphog/backend/temporal/activities.py:233-238 sets author_pr_numbers=[] for inbox reviews with an explicit comment giving the exact machine-author-familiarity rationale, and both that skip (line 237) and the engine flag self_driving_review (line 451, \"keys off this and ONLY this\") derive from the same run.output[\"inbox_review\"] in the same file \u2014 both hunks are in pr72680.diff (lines 1215-1216, 1227), refuting the \"different, unreviewed chunk\" premise. Action-shaped contexts default self_driving closed (review_local.py:316-321), so no current path yields the contradictory prompt or machine-author familiarity in a posted comment.",+ "id": "X14",+ "is_real": false,+ "notes": "The described damage (dual contradictory TRUSTED prompt blocks; machine-author familiarity in the posted review body) cannot occur in the shipped code: the server-side context builder in this same PR deliberately returns an empty author_pr_numbers list for self-driving runs, and both the skip and the self_driving_review flag are coupled to the identical inbox_review provenance field in one file. The finding's trigger is explicitly hypothetical (\"if the server's context builder ever populates... future refactor\") \u2014 a redundant engine-side re-enforcement of a carve-out the caller already performs. The one-line defense-in-depth guard has design-consistency appeal (mirrors _refuse_bot_author's stated philosophy) but is a hardening preference, not a defect; must_fix is unsupported.",+ "severity": "not_an_issue"+ },+ {+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:73-82 (fail-soft SerializerMethodField calling has_reviewable_repo_config); products/stamphog/backend/facade/api.py:112-125 (single .exists() query, team_id-scoped); products/stamphog/backend/models.py:58 (unique_stamphog_repo_per_team (team_id, repository) constraint making the lookup index-backed); products/review_hog/backend/api/settings.py:139-143 (\"always-called\" = Code review tab GET, human-navigation frequency, which already runs seed_canonicals_tolerantly inline)",+ "id": "X15",+ "is_real": false,+ "notes": "The code reads as described, but the impact claim doesn't hold: one index-backed .exists() on a tiny per-team table, per human settings-tab load, with fail-soft try/except plus a fail-fast circuit breaker already covering the DB-down case. The residual \"up-but-slow before the breaker trips\" concern is speculative, and the suggested per-team TTL cache would leave the toggle stale-disabled immediately after a user connects a Stamphog repo \u2014 the exact flow the flag guides. Ordinary cost, correctly handled by design; not worth a change.",+ "severity": "not_an_issue"+ },+ {+ "id": "X16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:1155-1162 (fetch-before-dedupe with explicit rationale comment + GitHubRateLimitError retry countdown>=60); pr72680_tree/products/review_hog/backend/receivers.py:77-79 (docstring accepting \"a same-head re-trigger costs one fetch\"), receivers.py:81-142 (cheapest-first gating: created/update_fields/status/pr_url/internal/toggle checks bound refires); tasks.py:1159 is the file's only get_pr \u2014 the webhook path has the payload and makes no GitHub call, so the claimed asymmetry vs _is_duplicate_pr_event is a false parallel.",+ "notes": "The code shape described (GitHub get_pr before head-keyed dedupe) is factually present, but it is an intentional, documented tradeoff: dedupe must key on the PR's current head, which only GitHub knows, and the every-time fetch is what provides lost-synchronize recovery. Refire volume is bounded to a few saves per self-driving run by the receiver's gating, each redundant fire costs one lightweight GET, and rate-limit errors are already caught and retried with a >=60s countdown. The finding's central contrast with the webhook path is wrong (that path never fetches from GitHub), and the suggested (team_id, pr_url) debounce would undermine the recovery semantics the design deliberately buys. Speculative-scale inefficiency, already self-limiting \u2014 not user-affecting."+ },+ {+ "id": "X17",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/tasks/backend/facade/api.py:504 (find_task_run called with pr_url + branch); products/tasks/backend/webhooks.py:64-76 (branch-only leg: filter(branch=..., task__repository__iexact=..., state__wizard_head_branch__isnull=True)); products/tasks/backend/models.py:1081 (branch CharField, no db_index) and models.py:1147-1174 (Meta.indexes contain only output__pr_url, state__wizard_head_branch, created_at, task+created_at+id, team+stage+task \u2014 nothing serving branch or iexact repository); products/stamphog/backend/tasks/tasks.py:167-198 (carve-out gates: head-changing + bot-authored + repo-native + enabled config, then the facade call \u2014 dependabot/renovate synchronize passes all gates, misses the indexed pr_url leg, and always runs the never-matching unindexed branch leg); products/tasks/backend/webhooks.py:159 (pre-existing tasks-webhook caller of the same query)",+ "notes": "All factual claims verified: the branch-only fallback leg has no supporting index, and the new stamphog carve-out exercises it for every bot-authored head-changing PR delivery (dependabot/renovate synchronize) on stamphog-enabled repos, where it can never match \u2014 pure waste per delivery. Severity correctly capped at consider: (1) the query shape is pre-existing on the hotter tasks-webhook backstop path (webhooks.py:159), this PR only adds a narrower-gated second caller; (2) the \"sequential scan of posthog_task_run\" claim is slightly overstated \u2014 TaskRun.task is an FK with a default index, so the planner can seq-scan the much smaller posthog_task on the iexact predicate and nested-loop into task_run, keeping cost proportional to the tasks table rather than the runs table; (3) frequency is bounded by the bot-author/repo-config gate stack. The suggested mitigation (carve-out passes head_branch=None since self-driving PRs at synchronize/reopen time already have the indexed output.pr_url bound \u2014 self-recorded or via the opened-event backstop _record_run_pr_url) is cheap and safe. Valid observation, low stakes today, cost grows with table size."+ },+ {+ "id": "X18",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/tools/pr-approval-agent/review_pr.py:225 (bot-author skip), :590 (draft carve-out), :937-938 (\"Audit trail for the carve-out\" comment + \"self_driving\": self.self_driving in to_dict()), :477 (flag in classification dict), :585-589 (comment documenting intentional draft review); pr72680_tree/products/stamphog/backend/temporal/activities.py:176 (extra_properties[\"stamphog_self_driving_review\"] = True)",+ "notes": "The line-level observations are accurate (no print at the bot-author bypass; draft carve-out produces the generic \"all clear\" gate message, which also reaches the rendered review-body table). But the headline claim \"no observable trace\" is wrong: to_dict() emits classification.self_driving with an explicit audit-trail comment, and the hosted runtime stamps stamphog_self_driving_review=True on analytics. The relaxed behavior is deliberate and documented in code; gates evaluate correctly and \"all clear\" truthfully describes the gate outcome under the carve-out. The suggestion amounts to echoing an already-recorded boolean into human-readable strings plus an extra console print \u2014 observability/message-wording polish, not a correctness/security/reliability defect. Does not meet the should_fix bar; at most a cosmetic nicety."+ },+ {+ "id": "X19",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/receivers.py:116-125 and :131-139 \u2014 two sequential transaction.on_commit registrations, both default robust=False; :254-255 deferred imports in _start_review sit outside its try/except (:261-273), the only unguarded code besides trivial dict construction (:257-260); _start_stamphog_review's import at :222 likewise outside its try (:224-234). robust=True is repo convention elsewhere: pr72680_tree/products/alerts/backend/destinations.py:124, products/logs/backend/presentation/views/alerts_api.py:1224.",+ "notes": "The described mechanism checks out in the actual PR head: two independently-gated non-robust on_commit hooks share Django's FIFO commit-hook queue, and a raise from the first would both skip the Stamphog hook and propagate into the tasks save path (the receiver's line-140 try/except does not cover commit-time callbacks). However, the only raise path in the first callback is a failed deferred import of the review_hog temporal client package \u2014 everything else is wrapped or infallible. An import failure of that package is a loud, feature-wide ReviewHog outage, so there is no reachable state where ReviewHog is healthy yet the Stamphog leg is silently cancelled; the marginal harm is subsumed by the outage. Adding robust=True to both registrations is a correct, cheap, convention-matching hardening worth doing, but it defends against a practically unreachable trigger, so this is a low-stakes observation rather than a fix-worthy defect."+ },+ {+ "id": "X20",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:1140-1153 (receiver leg's only check = repo-config resolution; no _is_bot_authored, no find_signal_implementation_run, no fork check before stamping inbox_review at 1176-1230) vs tasks.py:169-207 (webhook leg requires bot author, same-repo head, facade linkage match, resolver opt-in); tasks.py:947 (inbox_review bypasses review_mode gate on webhook path); temporal/activities.py:449-451 (self_driving_review set purely from output.inbox_review, comment falsely claims both paths positively link the PR); products/review_hog/backend/receivers.py:93,126-139 (pr_url read straight from TaskRun.output, forwarded to stamphog); receivers.py:34-35 (TaskRun.branch seeded with BASE branch by auto-start); products/tasks/backend/webhooks.py:68-76,184-185,203-212 (branch-matched backstop writes a same-repo PR's URL onto the run when output.pr_url unset, saving with update_fields=[\"output\",\"updated_at\"] which re-fires the receiver)",+ "notes": "Verified end to end. The receiver leg posts a real head-pinned GitHub approval with self-driving provenance while applying none of the positive-identification checks the sibling webhook leg treats as load-bearing, and it also skips the review_mode/write-permission gates entirely. The trust chain bottoms out in TaskRun.output.pr_url, which the tasks webhook backstop can mis-bind: auto-start seeds TaskRun.branch with the BASE branch, so a same-repo human PR whose head ref equals that base (e.g. a main->release promotion PR) opened before the agent records its own PR gets bound to the signals run and then auto-approved with every human gate bypassed. Fork-safety and write-once upstream narrow but don't close this (the dangerous case is same-repo and pre-pr_url by construction). Reachability needs a multi-condition coincidence, so not must_fix; but the worst case satisfies branch protection with zero human review and the fix (drop out if not _is_bot_authored(pr) after the fetch, ideally re-verify linkage via find_signal_implementation_run) is a cheap mirror of the existing sibling guard, so should_fix rather than consider. The prior triage note's downgrade-to-consider underweights that the base-branch seeding makes the collision a real pattern (promotion PRs from main), not just an exotic name collision."+ }+ ],+ "yVerdicts": [+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/api/settings.py:27-33 (no validator, help_text documents \"Only takes effect when the project has a synced, enabled Stamphog repository\"); settings.py:80 (get_stamphog_connected calls has_reviewable_repo_config(instance.team_id)); pr72680_tree/products/stamphog/backend/facade/api.py:120-125 (has_reviewable_repo_config is team-scoped via for_team) and :136-142 (queue_inbox_pr_review docstring: repo-config gating in the Celery task, \"silent no-op without one\"); pr72680_tree/products/review_hog/backend/receivers.py:210-217 (_start_stamphog_review docstring repeats the silent no-op design)",+ "id": "Y1",+ "is_real": false,+ "notes": "The premise is factually accurate (the field is writable with no connected-precondition validator), but persist-then-gate is the deliberate, documented design: the field help_text states the toggle \"only takes effect\" when connected, and both downstream docstrings (queue_inbox_pr_review, _start_stamphog_review) document the silent no-op without a synced+enabled StamphogRepoConfig. Storing true while disconnected is a harmless preference that activates when a repo connects \u2014 no wrong result, no data corruption, no security exposure. The suggested cross-team-leak check is already satisfied (has_reviewable_repo_config uses for_team with instance.team_id). The finding itself concedes \"no code change is needed\" if the design is intentional, which the code confirms; UI-disabled-vs-API-writable is a benign UX choice, not a broken contract.",+ "severity": "not_an_issue"+ },+ {+ "confidence": "high",+ "evidence": "Read site with invariant comment: pr72680_tree/products/stamphog/backend/temporal/activities.py:448-451. Only two writers, both full 4-key provenance after positive linkage: pr72680_tree/products/stamphog/backend/tasks/tasks.py:1064 (webhook; provenance built at tasks.py:208-215 behind team-scope recheck at :199) and tasks.py:1176-1181/1229 (receiver leg). Non-carve-out runs get output={} (tasks.py:1064). Later run.output merges add only unrelated keys (activities.py:246-251, 485-489). Invariant also documented in products/stamphog/AGENTS.md:80-108. Empty dict would NOT enable the carve-out: bool({}) is False.",+ "id": "Y2",+ "is_real": false,+ "notes": "Speculative defensive-hardening finding about a hypothetical future writer. No current code path can stamp a truthy inbox_review on a human PR; both existing writers construct a full 4-key provenance dict only after positively linking the PR to a signals implementation run (team-scoped, resolver-gated). The finding's \"even an empty dict\" failure scenario is factually wrong (falsy). The suggested auditability fix (comment naming the permitted writers) already exists at the read site and in AGENTS.md. Shape validation would only guard against future code that ignores both, which is the speculative what-if category.",+ "severity": "not_an_issue"+ },+ {+ "id": "Y3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/tools/pr-approval-agent/reviewer.py:692-702 (block gated only on cl.get(\"self_driving\") \u2014 premise correct); pr72680_tree/tools/pr-approval-agent/review_local.py:316-321 (flag rides in from server-stamped context JSON, defaults closed); pr72680_tree/products/stamphog/backend/temporal/activities.py:448-451 (self_driving_review set exclusively from run.output[\"inbox_review\"]); pr72680_tree/products/stamphog/backend/tasks/tasks.py:144-215 (_inbox_rereview_carve_out performs actual task linkage via find_signal_implementation_run, fork-safe, team-scoped, fail-closed) and tasks.py:1176-1182 (inbox receiver path stamps provenance from the TaskRun linkage itself).",+ "notes": "The factual premise holds (the engine itself does no linkage check), but the prompt's claim is true for every input that can reach it: both server paths that stamp inbox_review perform genuine task-linkage verification before the flag exists, and untrusted PR content cannot set it. The harm scenario requires a hypothetical future regression in another component \u2014 speculative defensive documentation, and the remedy is a behavior-neutral prompt rewording. The provenance/contract is already documented at both ends (reviewer.py docstring, stamphog logic/reviewer.py:113-115, activities.py comment)."+ },+ {+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:72-81 in the PR tree \u2014 get_stamphog_connected catches all exceptions from has_reviewable_repo_config and returns False, with a comment marking this deliberate fail-soft; products/review_hog/frontend/CodeReviewScene.tsx:1064-1069 \u2014 that same False drives the disabled copy 'Connect a repository to Stamphog first. Stamphog is not set up for this project yet.', which misstates the reason when the read failed rather than the config being absent.",+ "id": "Y4",+ "is_real": true,+ "notes": "The premise is accurate: no-config and read-failure are collapsed into one boolean and the tooltip hard-asserts setup state. But the functional gating (disabling opt-in while the stamphog DB is unreachable) is correct and explicitly intentional, an already-enabled switch is never dead-ended, and the wrong copy only appears in a rare compound state (stamphog DB outage + not-yet-opted-in user + repo actually connected) and self-corrects on recovery. Valid but low-stakes; the cheap fix is softening the copy, not a new tri-state API field.",+ "severity": "consider"+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/tasks/backend/facade/api.py:508 has `if task.signal_report_id is None or task.internal: return None`, but pr72680_tree/products/signals/backend/auto_start.py:254,261 creates every production self-driving implementation task with signal_report_id set AND internal=True (on master since commit 0da0b8dcb7f / #68752, 2026-07-06; forwarded verbatim via facade create_and_run_task api.py:881,903). The carve-out at pr72680_tree/products/stamphog/backend/tasks/tasks.py:191-202 returns empty _InboxCarveOut() when the facade returns None, so Leg 2 never fires for real self-driving PRs. Tests mask it: test_webhooks.py:1245 defaults internal=False (a shape only the dev seed command seed_inbox_data.py:279 produces) and the \"internal_pipeline_task\" parameterized case (~line 1290) asserts the broken internal=True\u2192None behavior.",+ "id": "Y5",+ "is_real": true,+ "notes": "Every claim in the finding checks out against the PR tree and git history. Additional corroboration: the only non-test producer of a non-internal signal-report task is the dev seed command, explaining green local runs while production fails. One framing refinement: the identical stale predicate pre-exists on master in products/review_hog/backend/receivers.py (internal guard from #64651, merged Jul 14 after #68752 flipped the flag Jul 6), so Leg 1's receiver shares the latent bug outside this diff \u2014 but this PR bakes the same fatal predicate into a new facade contract, documents a data-model shape (\"non-internal task carrying a signal report\") that no production code produces, and adds tests that lock the broken behavior in. Fix must reconcile both legs: drop task.internal (signal_report_id already excludes review_hog spawns/loops) or use a precise discriminator (e.g. interaction_origin/ai_stage), plus a test creating the task the way auto_start does (internal=True) expecting a DTO.",+ "severity": "must_fix"+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/review_hog/backend/api/settings.py:73-83 (fail-soft try/except around has_reviewable_repo_config) and :135-140 (PATCH returns serializer.data); pr72680_tree/products/stamphog/backend/facade/api.py:120-125 (single indexed .exists()); pr72680_tree/products/review_hog/frontend/reviewHogSettingsLogic.ts:954-956 (settings loaded once per mount), :758-760 (10s poll drives loadRecentReviews, not settings), :810-812 (reload only on update failure)",+ "id": "Y6",+ "is_real": false,+ "notes": "The code facts are correct (cross-product DB read runs on GET and PATCH responses), but the endpoint is cold, not hot: settings are fetched once per scene mount and on rare user-initiated PATCHes; the 10s poll polls the reviews list, not settings. The added work is a single indexed .exists() already wrapped fail-soft (except -> False with logging) and behind the product DB's fail-fast circuit breaker, so latency/reliability coupling is bounded by design. Skipping the check on PATCH or adding a TTL cache would save one cheap query per rare request \u2014 a micro-optimization, not a real reliability or performance defect.",+ "severity": "not_an_issue"+ },+ {+ "id": "Y7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/facade/api.py:149-156 \u2014 queue_inbox_pr_review is just process_inbox_pr_review.delay(...), an ordinary Celery broker publish with all heavy work (PR fetch, run creation, workflow start) inside the queued task; pr72680_tree/products/review_hog/backend/receivers.py:224-234 \u2014 _start_stamphog_review wraps the publish in try/except Exception + logger.exception, so a down broker never raises into the save path; receivers.py:257-273 \u2014 the pre-existing _start_review has the identical on_commit + except-Exception shape (Temporal start), so the PR follows the established pattern.",+ "notes": "The only failure mode not covered is a broker that hangs (accepts connection, stalls on publish, no send timeout). That tail condition applies to every Celery .delay() in every Django request path in PostHog and is a global broker-config question, not a defect this receiver introduces. The finding concedes it is an incremental widening of a pre-existing shape, and its ask (\"confirm Celery has bounded connect/send timeouts\") is verify-the-framework-config, not a concrete reachable bug. Speculative/defensive-paranoia; drop."+ },+ {+ "id": "Y8",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "medium",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:809 (max_retries=3), :870-879 (carve-out computed first, exception -> whole-task retry), :881-903 (stale-approval dismissal only reachable after carve-out succeeds), :911 (_mark_pr_event_processed never called on failure), :189-205 (new tasks-facade DB read + review_hog resolver on this path); pr72680.diff hunk at old line 749 shows pre-PR skip path went straight to the dismissal.",+ "notes": "Mechanism confirmed: a persistent exception in _inbox_rereview_carve_out exhausts 3 Celery retries, the task fails permanently, and the head-changing stale-approval dismissal never runs, leaving an earlier-head approval satisfying required reviews over unreviewed commits. Coupling is genuinely new (tasks facade + review_hog hook were not on this path pre-PR) and contradicts the code's own \"safety is never preference-gated\" docstring (tasks.py:165). Narrowing holds though: Task/TaskRun live in the same main Postgres, so general DB outages already failed the dismissal block pre-PR (which retains identical retry-then-fail semantics at :899-903); the true new exposure is a bug in find_task_run/facade or the review_hog resolver, or a tasks-tables-only partial failure \u2014 and failures are logged, monitored, and healed by the next head-changing delivery (worst case: no further push, approval stands). Fix is low-risk: run the dismissal before/independent of the carve-out on the skip branch (dismissing ahead of a re-review is harmless), or retry only the carve-out resolution separately. Real but incident-scoped: should_fix, not must_fix."+ },+ {+ "id": "Y9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/AGENTS.md:3-5 (preamble claim), :80 (header self-labels \"carve-out ... the one exception\"), :84 (\"ONE deliberate exception\"), :87 (\"Rules that keep the exception narrow:\")",+ "notes": "The textual observation is accurate (the carve-out section is a sanctioned relaxation, not a finding-earned invariant), but the section explicitly self-identifies as an exception in its own header and body, so the claimed reader confusion is defused. Even if a reader treats the narrowing rules as strict invariants, that produces only conservative, correct behavior. Pure doc-wording taste with zero behavioral, correctness, security, or contract impact \u2014 below the surfacing bar."+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:113 (unanchored regex, .search() at :118 \u2014 premise true), :1130-1147 (parsed repo only matched against team-scoped StamphogRepoConfig via for_team + repository__iexact), :1159 (fetch uses repo_config.repository + installation_id, never the URL host), :1176-1181 and :1223-1230 (raw pr_url never persisted; run provenance and PR upsert come from the fetched GitHub payload)",+ "id": "Y10",+ "is_real": false,+ "notes": "Code fact is accurate: the regex accepts lookalike hosts like evil-github.com. But the host is discarded after parsing \u2014 downstream uses only owner/repo (matched against the team's own connected StamphogRepoConfig rows) and pr_number, and the GitHub fetch goes to real github.com via the trusted DB repository value and installation credentials. No SSRF, no cross-tenant access, no credential exposure; worst case a malformed URL triggers a review of the team's own real PR, which a canonical URL would trigger anyway. Input also originates internally (review_hog TaskRun output.pr_url). Host-anchoring is optional hardening, not a defect.",+ "severity": "not_an_issue"+ },+ {+ "id": "Y11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1110-1245 (process_inbox_pr_review has no toggle re-check \u2014 premise true) vs tasks.py:201-207 (webhook leg resolver check); tasks.py:160-165 docstring already documents the deliberate asymmetry and the mid-PR toggle-off skip/dismissal path; receivers.py:126 re-checks the toggle on every receiver fire; facade/api.py:149 + receivers.py:131 show the fire-and-forget on_commit dispatch making the queue\u2192execute gap seconds; tasks.py:1109/1162 cap retries at 3 (5s default, 60s+ rate-limit) \u2014 all paths under /private/tmp/claude-501/-Users-woutut-Documents-Code-posthog/6b02ce00-9d8e-46e2-88ba-281e0843a672/scratchpad/pr72680_tree",+ "notes": "Code asymmetry exists exactly as described, but it is intentional and already documented in the carve-out docstring (the finding's own doc suggestion is pre-satisfied). The uncovered window is only the seconds-to-minutes queue\u2192execute gap of a fire-and-forget Celery task; every receiver refire re-checks the toggle fresh. The toggle is a per-user preference, not a security boundary \u2014 team scoping and repo-config gates are enforced at execution, and a race-window verdict on a bot-authored draft is retracted by the next head-changing delivery's opted-out skip path. Speculative near-zero-probability race with benign, self-healing impact; does not meet the bar."+ },+ {+ "id": "Y12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/tools/pr-approval-agent/review_local.py:321 reads bool(context.get(\"self_driving_review\")); the only producer is pr72680_tree/products/stamphog/backend/temporal/activities.py:451 (self_driving_review=bool(output.get(\"inbox_review\")), a genuine Python bool) via the typed builder pr72680_tree/products/stamphog/backend/logic/reviewer.py:101 (self_driving_review: bool = False) which json.dumps-serializes at line 138 \u2014 JSON preserves bool type, so the engine only ever sees True/False/None. Tests pin the strict-bool contract: products/stamphog/backend/tests/test_integration.py:1413 (is True) and tools/pr-approval-agent/test_review_local.py:278,283.",+ "notes": "The fragility scenario (string \"false\", int, list) is unreachable: the flag is server-stamped from inbox provenance, coerced with bool(...) at the source, typed bool on the builder, and round-trips through JSON which preserves bool type. It is never derived from PR-controlled/untrusted content. Over the actual value domain {True, False, absent}, bool(x) and x is True are identical, so the suggested change has no behavioral effect. Purely speculative defensive hardening against an upstream contract change the PR's own types and tests exclude."+ },+ {+ "id": "Y13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1185 (outermost atomic in a Celery task), :1214 (on_commit registration in QUEUED branch), :1235-1237 (except Exception \u2192 retry wraps the with-block), :1232-1233 (author's comment documenting propagate-and-retry), :377-380 (_start_review_workflow swallows only WorkflowAlreadyStartedError); Django 5.2.14 BaseDatabaseWrapper.set_autocommit/run_and_clear_commit_hooks confirm non-robust on_commit hooks execute inside Atomic.__exit__ and raise through it.",+ "notes": "The finding assumes on_commit callbacks run after the task returns success and are therefore unretried. In fact the hook runs synchronously during Atomic.__exit__ (triggered by the `return` inside the with-block), so a Temporal start failure propagates into the task's except Exception and fires Celery retry; the row is already committed QUEUED, so the retry re-enters the select_for_update dedupe and restarts the run. The webhook leg's new-run path uses the identical on_commit pattern, so there is no reliability asymmetry; _resume_existing_delivery_run is synchronous only because it runs outside any transaction. The durable recovery the docstring describes works as written."+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:179 (_resolve_repo_config inside _inbox_rereview_carve_out), :876-880 (carve-out call, provenance kept), :918 (unconditional re-resolve on main path \u2014 duplication confirmed), :298-304 (single indexed filter/first query), :858 and :891 (module already re-resolves per retry-guarded block by design)",+ "id": "Y14",+ "is_real": false,+ "notes": "Premise is factually accurate: a carved-out delivery resolves StamphogRepoConfig twice (line 179 in the carve-out, line 918 on the main path). But it is one extra single-row indexed query in a Celery task on a rare path (bot-authored self-driving inbox re-reviews), with no correctness/security/contract dimension. The module intentionally re-resolves the config in each independently retry-guarded block (lines 858, 891, 918), so the \"duplication\" matches the file's deliberate freshness+retry pattern; threading the config through the frozen _InboxCarveOut would add coupling for negligible gain. Micro-optimization, not a real issue.",+ "severity": "not_an_issue"+ },+ {+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:199-205 \u2014 resolver is called only after `find_signal_implementation_run` returns a non-None team-matched run; lines 167-186 show four earlier exits (non-head-changing, human author, fork head, unconfigured repo). pr72680_tree/products/tasks/backend/webhooks.py:36-59 \u2014 pr_url leg queried first, branch leg is fallback only. tasks.py:891-898 \u2014 same skip path already performs GitHub API calls (_retract_stale_approvals_on_skip), dwarfing one DB lookup.",+ "id": "Y15",+ "is_real": false,+ "notes": "The finding's core claim \u2014 that the review_hog resolver hook runs on every bot-authored head-changing webhook \u2014 is refuted by the code: `if run is None or run.team_id != repo_config.team_id: return _InboxCarveOut()` sits before the resolver call, so dependabot/renovate/posthog-bot pushes (no linked TaskRun) never reach it. The finding even concedes this in its own suggestion (\"it already does\"). The only genuinely new per-event cost is a single find_task_run query, gated behind bot-authorship, head-changing action, repo-native head, and a synced+enabled config, with the indexed pr_url leg dominating. That is negligible next to the GitHub API calls the same skip path already makes. Remaining substance is a micro-optimization observation, not a defect.",+ "severity": "not_an_issue"+ },+ {+ "id": "Y16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/products/stamphog/backend/tasks/tasks.py:113 \u2014 od -c byte dump shows `_PR_URL_RE = re.compile(r\"github\\.com/([^/\\s]+/[^/\\s]+)/pull/(\\d+)\")` with a single backslash before `s` in BOTH character classes (bytes: `[ ^ / \\ s ]` twice). Executing this exact regex: 'https://github.com/posthog/posthog/pull/123' -> ('posthog/posthog', '123'); 'acme/widgets' and 'posthog/analytics' also match.",+ "notes": "The finding misquotes the source: it claims the second class is `[^/\\\\s]` (literal backslash + literal s), but the actual code has `[^/\\s]` in both halves \u2014 the whitespace shorthand, identical classes. The claimed failure (\"posthog/posthog returns None\") is empirically disproven with the real regex from the tree. Leg 1 does not no-op for repos containing the letter 's'; no fix is warranted. (Host anchoring is a separate, already-reported finding.)"+ },+ {+ "id": "Y17",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr72680_tree/tools/pr-approval-agent/review_local.py:301-303 (_attach_familiarity returns early when author_pr_numbers is empty); pr72680_tree/products/stamphog/backend/temporal/activities.py:237-238 (author_pr_numbers fetched only when `not is_inbox_review`, with a comment documenting the familiarity carve-out) and :451 (self_driving_review derived from the same run.output[\"inbox_review\"]); pr72680_tree/products/stamphog/backend/tests/test_integration.py:1413-1415 (e2e asserts self_driving_review is True AND author_pr_numbers == [] together)",+ "notes": "The factual observation is correct \u2014 the engine has no self_driving guard in _attach_familiarity \u2014 but the claimed contradiction/bias cannot occur in the shipped code. Both author_pr_numbers omission and the self_driving_review flag derive from the same run.output[\"inbox_review\"] value in the same server file (single producer via build_reviewer_invocation, sole caller activities.py:434), the intent is documented in a comment at the gate, and an existing integration test pins the invariant, so the hypothesized regression would fail CI. For self-driving runs familiarity is always None: no familiarity block in the prompt, no familiarity bullet in the public comment. This is a speculative defense-in-depth suggestion against a non-occurring, test-guarded condition, not a defect; should_fix overstates it."+ }+ ],+ "matches": {+ "pairs": [+ {+ "x": "X3",+ "y": "Y3",+ "issue": "reviewer.py _format_self_driving renders TRUSTED provenance claims solely off cl.get(\"self_driving\") with no engine-side verification, so the prompt asserts facts (machine-user author / task-linkage verification) the engine cannot back up if the upstream boundary desyncs"+ },+ {+ "x": "X10",+ "y": "Y12",+ "issue": "review_local.py:316-321 derives the self_driving flag via bool(context.get(\"self_driving_review\")) truthy coercion, which would treat a non-bool value like the string \"false\" as True and silently enable the carve-out; both suggest an explicit `is True` check"+ },+ {+ "x": "X14",+ "y": "Y17",+ "issue": "_attach_familiarity in review_local.py is not gated on self_driving \u2014 the engine relies on the server omitting author_pr_numbers for self-driving runs, so a server-side regression would inject the machine author's own familiarity into the prompt and posted comment, contradicting the _format_self_driving block"+ },+ {+ "x": "X15",+ "y": "Y6",+ "issue": "get_stamphog_connected in settings.py:71-82 adds an uncached synchronous cross-product Stamphog-DB read (has_reviewable_repo_config) to the always-called review_hog settings GET/PATCH path, coupling its latency to another product's DB health; both suggest caching or scoping the check"+ },+ {+ "x": "X17",+ "y": "Y15",+ "issue": "The webhook carve-out's find_signal_implementation_run lookup runs on every bot-authored head-changing delivery on stamphog-enabled repos and wastes DB work for bots that can never match (dependabot/renovate), with the unindexed branch-fallback leg of find_task_run as the costly part \u2014 X17 pins the missing-index seq scan mechanism, Y15 states the same per-event lookup cost diffusely"+ }+ ],+ "x_only": ["X1", "X2", "X4", "X5", "X6", "X7", "X8", "X9", "X11", "X12", "X13", "X16", "X18", "X19", "X20"],+ "y_only": ["Y1", "Y2", "Y4", "Y5", "Y7", "Y8", "Y9", "Y10", "Y11", "Y13", "Y14", "Y16"]+ },+ "judges": [+ {+ "winner": "X",+ "margin": "thin",+ "x_score": 6.5,+ "y_score": 5.5,+ "rationale": "X: 7 confirmed real findings (4 should_fix: X3, X7, X9, X20; 3 consider: X12, X17, X19) out of 20 (35% precision). Its unique confirmed catches include a coherent security cluster on the receiver leg's missing positive identification (real approvals mintable for a human-authored PR via the branch-matched pr_url backstop) and the distinct cancelled/deleted-task authorization-window gap (X7). X also won both contested overlaps: its versions of the trusted-block issue (X3 vs Y3) and the missing-index cost (X17 vs Y15) survived adversarial verification while Y's counterparts were refuted. Y: only 3 confirmed real of 17 (18% precision) \u2014 but its Y5 is the single most impactful finding in either set: the webhook carve-out leg is dead in production (task.internal predicate excludes every real self-driving task) with tests locking the broken behavior in; X not only missed it, X8 examined the exact predicate and blessed it. Y8 (safety-dismissal blocked by carve-out failure) is a second genuine unique should_fix. However, Y carries a fabricated must_fix (Y16, misquoted regex, empirically disproven) and lost both shared-issue matchups. Under the recall lens with unique confirmed catches weighted heaviest, X's 3-4 unique confirmed should_fix findings plus two contested wins narrowly outweigh Y's must_fix crown jewel plus one should_fix; better precision (fewer, less-toxic noise findings) breaks the near-tie toward X. Thin margin because Y5 alone is worth more than any single X finding, and a maintainer reading only X would ship a functionally broken feature."+ },+ {+ "winner": "X",+ "margin": "moderate",+ "x_score": 5.5,+ "y_score": 3.5,+ "rationale": "Precision lens. X: 7/20 verified real (35% precision, 65% noise) with 4 confirmed should_fix (X3, X7, X9, X20) and 3 confirmed consider (X12, X17, X19); most of its 13 misses are speculative/defensive-hardening noise, though it inflated two false must_fix labels (X4, X14). Y: 3/17 verified real (17.6% precision, 82.4% noise) with 1 must_fix (Y5), 1 should_fix (Y8), 1 consider (Y4); its 14 misses include the worst noise in either set \u2014 Y16, a must_fix built on a misquoted regex empirically disproven (fabricated bug), and Y13, a should_fix based on wrong Django on_commit semantics. X nearly doubles Y's hit rate, has better high-severity label accuracy (5/12 vs 2/6), more confirmed actionable findings (4 vs 2), and more unique confirmed findings (X7, X9, X20, X12, X17, X19 vs Y5, Y8, Y4); X's framing also won the paired X3/Y3 verification. Y's Y5 is the single most valuable finding across both sets (feature-breaking internal=True predicate with false-green tests) and X missed it entirely \u2014 that keeps the margin moderate rather than decisive \u2014 but under the precision lens an 82% noise rate with a fabricated must_fix loses to a 65% noise rate with a larger confirmed payload."+ },+ {+ "winner": "Y",+ "margin": "thin",+ "x_score": 5.5,+ "y_score": 6,+ "rationale": "Y wins on impact where it matters most: Y5 is the only confirmed must_fix in either set (the task.internal predicate kills the entire webhook re-review leg for every production self-driving PR, with the PR's own tests locking in the broken behavior), verified end to end with root cause, git history, and the exact fix plus test to add. Y8 adds a confirmed should_fix on a real safety-invariant weakening (carve-out failure blocks stale-approval dismissal). X has more confirmed payload by count (4 should_fix: X3, X7, X9, X20, plus 3 considers) and better precision (7/20 real vs 3/17), but X3/X9/X20 are three layers of one vulnerability (roughly two distinct fixes), all four of X's claimed must_fix failed verification at that level (two are outright non-issues), and X examined the exact predicate behind Y5 (X8) yet rationalized the broken check as intentional, actively steering a maintainer away from the merge-blocking bug. Y's noise is quieter (mostly consider-labeled) though it contains the worst single accuracy failure (Y16's fabricated regex typo at must_fix, self-debunked in triage). A maintainer with only Y avoids shipping a dead feature and gets correct severity on the one finding that blocks merge; a maintainer with only X gets real but edge-case-reachable hardening fixes plus false reassurance on the fatal bug. Thin margin because X's broader unique confirmed payload and more accurate average premises nearly offset Y's decisive single catch."+ }+ ],+ "_meta": {+ "round": 1,+ "blinding": "X = A-sonnet5-xhigh-1, Y = B-glm52-max-1",+ "verified_against": "PR head 1341596e via git worktree",+ "note": "independent adversarial verifiers, one per finding; 3-lens blind judge panel"+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round4.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round4.jsonnew file mode 100644index 000000000000..45e33ee114bf--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round4.json@@ -0,0 +1,804 @@+{+ "newVerdicts": [+ {+ "id": "M1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "medium",+ "evidence": "receivers.py:206 selects one acting reviewer (`acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])`) and receivers.py:126 / 151-156 gate stamphog on that one user's `stamphog_review_inbox_prs` \u2014 the described skip scenario is mechanically real. But the claimed any-assigned-reviewer contract exists nowhere in the tree or diff: receivers.py:17 (added by this PR) documents \"The same resolved acting reviewer carries a second, independent toggle\"; stamphog/AGENTS.md:86 says \"whose acting reviewer opted in\"; receivers.py:159-173 records the first-resolved-canonical rule as explicit maintainer decisions (2026-07-02/03); the pre-existing ReviewHog leg gates identically. Grep of the full diff for \"any assigned\"/\"at least one\" reviewer language returned only repo-config help text, no reviewer contract.",+ "notes": "The behavior is a deliberate, documented single-acting-reviewer design mirroring the existing ReviewHog gate, not a contract violation this PR introduces; the \"any assigned reviewer\" wording lives only in PR prose outside the repo. Residual nit: dismiss copy at tasks.py:70-74 (\"No reviewer currently has stamphog inbox reviews enabled\") is imprecise in the multi-reviewer edge \u2014 a wording tweak at most. Confidence medium only because the PR description itself is not part of the ground truth I could inspect.",+ "set": "M"+ },+ {+ "id": "M2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:113/118 \u2014 regex is unanchored (search, no host/path anchor), so the factual observation is true. But tasks.py:1140-1147 uses the parsed repository solely as a team-scoped lookup key (for_team(team_id), provider=\"github\", repository__iexact, enabled=True, connected_by_user_id set, installation_id non-blank); a miss returns at 1151-1153. tasks.py:1159 \u2014 the URL is never fetched; the GitHub call uses repo_config.repository (canonical) and repo_config.installation_id, so only pr_number (\\d+, int-safe) comes from the parsed string \u2014 no SSRF/redirect surface. team_id is an explicit task arg (1111), not URL-derived. Sole call site is process_inbox_pr_review (grep: only tasks.py:1130). A lookalike-host URL parses to the identical (owner/repo, N) a well-formed github.com URL would, so the proposed host/path anchoring prevents nothing an influencer of pr_url couldn't do with a valid URL; the residual arbitrary-pr_number concern is not closed by the suggested fix and is covered by finding M9.",+ "notes": "The regex laxity is real but consequence-free: downstream team-scoped config lookup and canonical-repo fetch neutralize both claimed vectors (lookalike domain, malformed path). Anchoring would be harmless tidiness, but the finding asserts a security defect that does not exist, so it fails adversarial verification.",+ "set": "M"+ },+ {+ "id": "M3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The flag's sole producer is products/stamphog/backend/temporal/activities.py:451 (`self_driving_review=bool(output.get(\"inbox_review\"))`), passed through the bool-typed parameter of build_reviewer_invocation (products/stamphog/backend/logic/reviewer.py:101) into the context dict (line 131) and serialized via json.dumps (line 137). The engine reads it back with json.loads (tools/pr-approval-agent/review_local.py:396), so context.get(\"self_driving_review\") at review_local.py:321 is always a genuine bool or None (Action-shaped contexts omit the key, and bool(None) is False \u2014 fail-closed). A truthy non-boolean string such as \"false\" cannot reach this key through any code path in the diff, so bool(...) and the suggested `is True` behave identically for every producible value.",+ "notes": "The context JSON is server-generated from task provenance inside the sandbox provisioning path, not attacker-controllable via PR content; anyone able to forge the context file would control the whole PR snapshot anyway, so strict boolean checking adds no security boundary. Pure defensive-coding speculation against an unreachable input.",+ "set": "M"+ },+ {+ "id": "M4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:984 \u2014 Action entrypoint constructs Pipeline without self_driving (defaults False, review_pr.py:196), so _maybe_compute_familiarity (review_pr.py:251) never runs in self-driving mode and bot authors are refused first (review_pr.py:225-226). review_local.py:321 is the sole self_driving=True site; its familiarity comes from _attach_familiarity (review_local.py:292-311) which early-returns on empty context[\"author_pr_numbers\"] (lines 301-303). products/stamphog/backend/temporal/activities.py:237-238 empties author_pr_numbers whenever run.output[\"inbox_review\"] is set \u2014 the same flag that drives self_driving_review=True (activities.py:451). With familiarity None, _format_familiarity returns \"\" (reviewer.py:644-646) and the review-body bullet is guarded by fam is not None (review_pr.py:871-872). Regression coverage exists: test_integration.py:1413-1415 asserts self_driving_review is True and author_pr_numbers == [] end to end.",+ "notes": "The no-machine-familiarity contract is enforced server-side (emptied author_pr_numbers coupled to the same inbox_review provenance as the self_driving flag), not in the review_pr.py path the finding inspected. The claimed scenario \u2014 a self-driving review computing and exposing bot-author familiarity \u2014 is unreachable on both entrypoints.",+ "set": "M"+ },+ {+ "id": "M5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:213 docstring declares fire-and-forget intent; lines 224-234 catch-log mirrors sibling _start_review (246, 261-273); recovery via re-fire on repeat saves (76-79) and stamphog webhook re-review (20-23, 144-156); dispatch is on_commit + single delay() publish (131-138; facade/api.py:149).",+ "notes": "Deliberate, documented, sibling-consistent fire-and-forget with real recovery paths; the proposed durable-outbox machinery is disproportionate for a best-effort initial review of a toggle-gated experimental feature. Worst case is a rare, recoverable missed pre-review, not data loss.",+ "set": "M"+ },+ {+ "id": "M6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1109 does set max_retries=3/delay=5, but every failure branch logs (logger.exception at 1149, 1164; logger.warning at 1161) and retry exhaustion raises MaxRetriesExceededError \u2014 loss is not silent. The docstring (tasks.py:1113-1128) documents this leg as the best-effort initial review with two recovery paths: the receiver re-fires on every TaskRun output save with head-keyed dedupe that \"still reviews the new commits\" after a lost head, and later pushes re-review via the webhook carve-out (confirmed in receivers.py:20-31). Worst case is a missed optional pre-review of a toggle-gated draft PR that never gets another push or output save during a >15s outage window; no approval posted, no safety invariant broken.",+ "notes": "The finding's factual kernel (bounded retries, no outbox row) is present, but the characterization (silent, permanent, unreconciled loss meriting must_fix outbox+reconciler machinery) is refuted by logging, documented recovery paths, and the deliberately best-effort design of this leg. At most a longer-backoff nicety, not a defect.",+ "set": "M"+ },+ {+ "id": "M7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "facade/api.py:120-125 indeed omits provider=\"github\", but the flagged state is unproducible: installation_id is read_only on the plain serializer (presentation/serializers.py:98-103) and connected_by_user_id is not a serializer field, while every path setting either hardcodes provider=\"github\" \u2014 sync get_or_create (views.py:307-308), _adopt_preexisting_config (views.py:88), connected-user restamp of synced rows (views.py:461-464), webhook _add_installation_repos (tasks/tasks.py:666-674). So no non-GitHub row can ever pass the enabled+connected_by_user+non-blank-installation filter. The helper also only drives the informational stamphog_connected UI flag (review_hog/backend/api/settings.py:72-81); the real review paths filter provider=\"github\" themselves (tasks/tasks.py:301, 1143) and no-op otherwise.",+ "notes": "Adding provider=\"github\" would be harmless consistency with the sibling queries, but it guards an unreachable state for a provider that has no sync path \u2014 speculative future-proofing, not a defect. Worst hypothetical impact is a cosmetic toggle mismatch.",+ "set": "M"+ },+ {+ "id": "M8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "At the PR head worktree, every symbol the finding calls \"not present in the checked-out code\" exists: queue_inbox_pr_review (products/stamphog/backend/facade/api.py:128; invoked in products/review_hog/backend/receivers.py:225), process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1110), ReviewRun.output[\"inbox_review\"] -> self_driving_review (products/stamphog/backend/temporal/activities.py:237,451), Pipeline(self_driving=bool(context.get(\"self_driving_review\"))) (tools/pr-approval-agent/review_local.py:321), and the bot refusal is conditional on self_driving (review_local.py:324), not unconditional. The webhook pre-filter has the carve-out too (_inbox_rereview_carve_out, tasks.py:144, applied at :876), and facade/inbox_hooks.py exists. The AGENTS.md carve-out section is present and matches the implementation.",+ "notes": "The finding is an artifact of validating the PR's documentation against the base tree instead of the PR head \u2014 the docs and code are consistent within the PR. The claimed alternative trigger_source=\"inbox\" flow is the separate ReviewHog temporal leg, which coexists with the documented Stamphog contracts.",+ "set": "M"+ },+ {+ "id": "M9",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "Verified in pr75215_tree: (1) webhook carve-out validates before granting provenance \u2014 _is_bot_authored at products/stamphog/backend/tasks/tasks.py:169, fork check :176-178, team-scoped find_signal_implementation_run match + team recheck :191-200; (2) initial leg process_inbox_pr_review (tasks.py:1110-1237) fetches the PR at :1159 and stamps output={\"inbox_review\": ...} at :1176-1229 with zero revalidation \u2014 no bot-author, fork, or task-match check on the fetched PR, and caller-supplied task_run_id/signal_report_id are never resolved or cross-checked; (3) the stamp becomes self_driving_review=True at products/stamphog/backend/temporal/activities.py:451, which relaxes the engine's bot-author refusal (review_local.py:324, review_pr.py:225) and draft gate (review_pr.py:590); the initial leg also never runs _review_skip_reason (draft/bot/author-association) or _author_lacks_write_permission, which exist only on the webhook path; (4) reviewer.py:694-696 asserts to the LLM the PR was \"verified by task linkage\", which the initial leg does not do; (5) stamphog posts a real GitHub approval (receivers.py:18-19). Reachability is narrow: output.pr_url writers are server-mediated (agent-server observation; fork-safe webhook backstop at products/tasks/backend/webhooks.py:178-185), and the feature needs a per-user toggle plus a synced+enabled repo config \u2014 no confirmed adversarial path to pr_url.",+ "notes": "Finding's mechanism and consequence fully verified (real defense-in-depth asymmetry between the two provenance-granting legs; worst case is an unattended APPROVE on a PR never positively identified as self-driving). must_fix overreaches because every current pr_url write path is server-mediated and fork-safe, so the exploit precondition is unconfirmed; cheap parity fix (reuse _is_bot_authored + fork check + facade match) makes this a should_fix before rollout.",+ "set": "M"+ },+ {+ "id": "M10",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "receivers.py:206 selects one canonical acting reviewer (next(user==task_created_by_id, resolved[0])); lines 114+126 gate stamphog dispatch on that single user's stamphog_review_inbox_prs; resolve_stamphog_acting_reviewer (144-156) mirrors it for the webhook path \u2014 so the described behavior (opted-in non-canonical reviewer ignored) does occur. However, the diff shows the pre-existing _resolve_acting_reviewer used the identical single-reviewer selection to gate review_inbox_prs; the docstring (160-173) documents 'the first resolved reviewer is canonical (maintainer decisions, 2026-07-02/03)' and lists both toggles as the acting reviewer's; the module docstring added by this PR states 'The same resolved acting reviewer carries a second, independent toggle'; all added tests use exactly one reviewer. No code, docstring, or test anywhere in the repo encodes an 'any assigned reviewer' contract.",+ "notes": "The single-acting-reviewer gating is a deliberate, pre-existing, consistently documented design that this PR extends faithfully \u2014 the 'any assigned reviewer' requirement lives only in PR prose, so this is an intent-vs-wording discrepancy for the author to reconcile, not a code defect. Not must_fix.",+ "set": "M"+ },+ {+ "id": "M11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "api.py:504-506 does check team_id after a global find_task_run call, but api.py:492-495 documents this as a deliberate fail-closed tenant guard. webhooks.py:41-43: the pr_url leg filters on output__pr_url (a globally unique GitHub html_url recorded on exactly one bound run) plus task__repository__iexact, so a cross-team run and a valid same-team run can never both match \u2014 no shadowing on the primary leg, which is always exercised because the caller (stamphog tasks.py:191-196) passes pr.html_url. The only unordered, team-unfiltered lookup is the branch fallback (webhooks.py:68-76), reachable only when the run never recorded its pr_url AND the same repo is connected to multiple teams AND a run's branch column (which stores the base/checkout branch, per the wizard-exclusion comment at webhooks.py:65-67) collides with the PR's agent-generated head ref \u2014 a compound state with no realistic construction. Worst case is the carve-out resolving empty (tasks.py:199-200), i.e. the default bot-PR refusal, a missed optional re-review.",+ "notes": "The code shape the finding describes exists, but the claimed failure (valid same-team run shadowed, reviews nondeterministically lost) is not reachable through the primary pr_url path and only via a practically unconstructible branch-fallback edge with trivial consequence. Filtering by team inside the lookup is at most a cosmetic consistency tweak.",+ "set": "M"+ },+ {+ "id": "M12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:75-79 docstring documents re-fires on unchanged targets as deliberate with bounded cost (\"a same-head re-trigger costs one fetch (early-exit)\"). The PR diff shows the resolver + ReviewUserSettings.load work at receivers.py:111-114 is pre-existing (old _resolve_acting_reviewer did the same artefact query, login resolution, and settings load per qualifying save); net-new work is one boolean check plus one opt-in-gated on_commit Celery enqueue (receivers.py:126-139). Guards at receivers.py:82-105 (created, update_fields without output, FAILED/CANCELLED, no target, no signal_report_id, task.internal) restrict the resolver to output saves of the one non-internal signal-report implementation task, not TaskRun saves at large. stamphog tasks.py:1155-1157 explains why dedup must follow the GitHub fetch (dedupe keys on the PR's current head, which only GitHub knows; the receiver holds only the URL), and tasks.py:1124-1128 documents that a PR-URL-keyed receiver watermark would defeat the intended lost-synchronize recovery; unchanged-head refires no-op at tasks.py:1198-1219 under select_for_update.",+ "notes": "The re-fire mechanism the finding describes exists, but it is a deliberate, documented tradeoff: the heavy resolver cost predates this PR, the added stamphog leg costs one opt-in-gated enqueue plus an async idempotent Celery task, and the suggested watermark is unworkable (URL-keyed suppresses the intended lost-synchronize backstop; head-keyed requires the fetch it would avoid). No hot-path, unbounded, or N+1 defect introduced.",+ "set": "M"+ },+ {+ "id": "M13",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "receivers.py (pr75215_tree): handle_task_run_saved registers _start_review then _start_stamphog_review via transaction.on_commit without robust=True; _start_review's deferred imports of products.review_hog.backend.temporal.client/.types are outside its try block (only start_review_pr_workflow is wrapped). Django 5.2 run_and_clear_commit_hooks (source verified): a non-robust callback that raises drops all remaining popped callbacks and propagates into the committer. So an import failure in _start_review would suppress the stamphog dispatch and raise into the tasks commit path.",+ "notes": "Mechanism is technically accurate, but the only propagating trigger is the product's own temporal package being unimportable \u2014 a process-wide systemic deploy breakage (monorepo single env, sys.modules-cached after first success), under which every ReviewHog inbox review is already dead; the incremental harm is only suppressing the stamphog leg for dual-toggle users. robust=True (or imports inside the try) is cheap, reasonable hardening, but this is defensive robustness against a practically unreachable edge, not a production defect this PR introduces.",+ "set": "M"+ },+ {+ "confidence": "medium",+ "evidence": "webhooks.py:68-77 branch leg has no terminal-status/deleted filter and no order_by (arbitrary .first() on collision); wizard leg (84-96) does exclude both, proving the omission is leg-specific. facade/api.py:501-510 (new in diff) reuses that leg as positive self-driving identification for the stamphog carve-out. Refutation's base-branch premise only covers auto_start.py:253 runs, which are internal=True (line 263) and rejected at api.py:508; the matchable non-internal shape stores the head branch in `branch` per the PR's own tests (_make_run(branch=\"posthog-code/sd-fix\") matched via head_branch). Carve-out gates (bot author, repo-native head, enabled config, team match, opted-in reviewer) bound impact to stale-provenance stamphog review within the same team/repo.",+ "id": "M14",+ "is_real": true,+ "notes": "The staleness hazard is real (branch leg can return a completed/deleted-task run, unordered), but exploitation needs a same-team same-repo bot PR whose head ref collides with an old run's stored head branch plus pr_url-binding failure; worst case is wrong-report attribution, not a security issue. The suggested fix (exclude terminal runs) would regress legitimate post-completion identification; prefer-non-terminal ordering is the right shape. Downgraded from should_fix to consider.",+ "severity": "consider",+ "set": "M"+ },+ {+ "id": "J1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr75215_tree/products/stamphog/README.md:14 does contain the added em dashes (\"facade \u2014 gated by ... settings \u2014\"), and the diff confirms this line is new in the PR. However, the cited em-dash rule lives in the repo's \"User-facing copy\" guidance, explicitly scoped to text a PostHog user reads (UI labels, tooltips, error states, notifications, docs, support replies) \u2014 not internal developer READMEs. The same README already uses em dashes in pre-existing lines 3, 9, 10, 12, and 26 (its established house style), so the new sentence is stylistically consistent with the file it edits.",+ "notes": "Pure style/taste finding with no behavioral difference; the guideline it invokes does not apply to internal product READMEs, and the file's existing style uses em dashes throughout. No trigger-to-consequence chain exists.",+ "set": "J"+ },+ {+ "confidence": "high",+ "evidence": "tasks.py:1109-1245 \u2014 process_inbox_pr_review has no bot/fork/run re-verification and stamps inbox_review (1176-1181, 1229), which bypasses gates (tasks.py:881, 944, 968; activities.py:451 self_driving_review). However: sole caller is review_hog's in-process receiver (receivers.py:225 via facade api.py:149) which already gates task.signal_report_id (receivers.py:98), not task.internal (:104), and an opted-in resolved reviewer (:111-126) \u2014 the queued values ARE the triggering run's own identity, unforgeable by any external caller. output.pr_url is written only by the trusted agent server or the fork-safe webhook backstop (webhooks.py:178-185: head repo must equal base repo, fills only an unset pr_url). process_inbox_pr_review additionally requires a team-scoped synced+enabled repo config (tasks.py:1140-1147). The claimed exploit needs a repo-write insider (who already passes the write gate) or compromised internal agent infrastructure \u2014 not reachable from any untrusted input this PR exposes.",+ "id": "J2",+ "is_real": false,+ "notes": "The finding's code observations are accurate but its threat model conflates the webhook leg (untrusted arbitrary PR events, hence positive identification in _inbox_rereview_carve_out) with the receiver leg (trusted in-process run save reusing the run's own recorded PR URL). Re-verifying the queued run/report IDs guards nothing. The only residual value is defense-in-depth: adding _is_bot_authored + head-repo==base checks on the fetched PR in process_inbox_pr_review would mirror the webhook carve-out cheaply \u2014 a consider-level hardening improvement, not a must_fix security defect.",+ "severity": "consider",+ "set": "J"+ },+ {+ "id": "J3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "activities.py:237-238 (fetch_review_context) sets author_pr_numbers=[] whenever run.output[\"inbox_review\"] is set; activities.py:451 sets self_driving_review from the same flag on the same run, so self-driving contexts always arrive with no author_pr_numbers. review_local.py:301-303 (_attach_familiarity) early-returns on empty author_pr_numbers, so classification[\"familiarity\"] is never set; reviewer.py:644-646 (_format_familiarity) then renders \"\" \u2014 the self-driving prompt at reviewer.py:568 contains only the provenance block, never a familiarity block. The Action path cannot produce the contradiction either: review_pr.py:974-979 exposes no self-driving flag and review_pr.py:225 refuses bot authors before _maybe_compute_familiarity (line 251) runs. test_integration.py:1415 pins author_pr_numbers==[] for inbox runs.",+ "notes": "The finding's core premise (\"familiarity still computed/rendered for self-driving\") is false in every reachable path: this PR enforces absence server-side by withholding author_pr_numbers for inbox runs, keyed off the exact same inbox_review flag that enables the carve-out. The engine-side gap (_attach_familiarity has no self_driving check) is only exploitable by a hypothetical future caller that sets self_driving_review while also injecting PR numbers \u2014 a defense-in-depth suggestion, not a defect introduced by this PR. The docstring \"familiarity is deliberately absent\" is accurate as shipped.",+ "set": "J"+ },+ {+ "id": "J4",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "receivers.py:206 picks one canonical reviewer (`next((u for u in resolved if u.id == task_created_by_id), resolved[0])`); receivers.py:114,126 gate the initial Stamphog dispatch on only that user's `stamphog_review_inbox_prs`; receivers.py:151-156 (`resolve_stamphog_acting_reviewer`, wired via `connect()` at :69) re-checks the same single user for webhook re-reviews. PR 75215 description (verified via gh) states the gate as \"at least one of the assigned users has `stamphog_review_inbox_prs` enabled\" / \"checks whether any assigned reviewer opted in\" / Case 3 \"everyone turns the toggle off ... nobody is opted in\"; dismiss copy at stamphog/backend/tasks/tasks.py:70-74 also asserts \"No reviewer currently has ... enabled\". With assignees [alice(first, opted out), bob(opted in)] and a bot-created task, acting=alice \u2192 no initial review and all re-reviews skipped, contradicting the stated spec.",+ "notes": "Genuine spec-vs-code gap, but fail-safe: the feature under-triggers silently, no unwanted approval is posted. The single-canonical-reviewer resolver is a pre-existing documented mechanism (needed for ReviewHog per-user options); the fix is contained \u2014 select an opted-in assignee for the Stamphog path. must_fix overstates it; should_fix is right.",+ "set": "J"+ },+ {+ "id": "J5",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree 0019_reviewusersettings_stamphog_review_inbox_prs.py:7-8 depends on 0018_backfill_urgency_threshold_to_consider; origin/master already has products/review_hog/backend/migrations/0019_reviewreport_author_login_and_more.py with the same 0018 parent (verified via git show), and master's max_migration.txt = 0019_reviewreport_author_login_and_more while the PR diff sets it to 0019_reviewusersettings_stamphog_review_inbox_prs. Two migrations parented on 0018 = conflicting leaves for the review_hog app on merge, failing Django's migration checks, plus a guaranteed max_migration.txt conflict.",+ "notes": "Deterministic CI/merge-queue blocker, not a runtime prod bug, but a hard correctness failure the PR introduces against current master. Fix: renumber to 0020 depending on 0019_reviewreport_author_login_and_more and update max_migration.txt.",+ "set": "J"+ },+ {+ "id": "J6",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "facade/api.py:504-506 does call unscoped find_task_run then fail-closed team check (deliberate, documented at api.py:492-495 \"team scoping is enforced here \u2014 a run belonging to any other team returns None\"). webhooks.py:36-59: pr_url leg runs first, filtered by output__pr_url + task__repository__iexact, and returns before the branch leg; a PR html_url is recorded on exactly one run at PR-open, so no cross-team run shares it. Sole caller stamphog tasks.py:191-196 is gated to synchronize/reopened/base-retarget (tasks.py:49,167), always passes the real pr.html_url, and by those deliveries output.pr_url is already saved (the save is what triggers the initial receiver leg), so the branch fallback never governs this path. Mismatch outcome is fail-closed (tasks.py:199-200): carve-out resolves empty, today's bot-PR skip behavior applies and stale approvals are still dismissed.",+ "notes": "The described failure needs either two teams' runs sharing one globally-unique PR URL (does not occur) or a pr_url miss plus two tenants on the same repo with identical non-wizard branch strings \u2014 an unreachable condition stack, and even then the effect is a silently skipped re-review, not an unsafe action. Adding team_id to the query would be valid cheap hardening, but no reachable defect is introduced by this PR.",+ "set": "J"+ },+ {+ "confidence": "high",+ "evidence": "review_pr.py:590 `if pr.draft and not self.self_driving` \u2014 bypass exists as described. But no reachable input sets self_driving on a human draft: (a) review_pr.py main() constructs Pipeline without self_driving (CLI args only), so the Action path never sets it; (b) the sole production setter is review_local.py:321 `self_driving=bool(context.get(\"self_driving_review\"))`, fed by activities.py:451 `self_driving_review=bool(output.get(\"inbox_review\"))`; (c) inbox_review provenance is stamped only at tasks.py:880 (webhook carve-out, which hard-gates `if not _is_bot_authored(pr): return _InboxCarveOut()` at tasks.py:169 plus repo-native head check at 176-178) and tasks.py:1176 (process_inbox_pr_review, whose pr_url is the triggering signal-report TaskRun's own output.pr_url \u2014 written only by the agent server for the bot-opened PR or by products/tasks/backend/webhooks.py:179-185, which requires head repo == base repo and only backfills when output.pr_url is unset). The failure scenario is explicitly conditioned on a hypothetical upstream \"construction bug\", not on any actual input.",+ "id": "K1",+ "is_real": false,+ "notes": "The suggested `self_driving and pr.author_is_bot` effective-flag is pure defense-in-depth over bot-author invariants the two provenance producers already enforce; for a hypothetically mis-flagged human PR the bot-refusal branch (review_pr.py:225) is already a no-op and a GitHub draft cannot merge while draft. Speculative what-if, not a production defect this PR introduces.",+ "severity": "not_an_issue",+ "set": "K"+ },+ {+ "id": "K2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:159-173 docstring documents the single canonical acting reviewer as a maintainer decision (2026-07-02/03) predating this PR; receivers.py:17-23 documents stamphog_review_inbox_prs as \"the same resolved acting reviewer['s]\" second toggle. test_inbox_trigger.py:229-238 (pre-existing test, untouched by the diff) asserts mock_start.assert_not_called() when the canonical reviewer is opted out and another assigned reviewer opted in \u2014 the exact scenario the finding calls a bug \u2014 with the comment \"a later reviewer's opt-in must not hijack whose options the review runs with\". Grep of the full pr75215.diff finds no statement of \"run Stamphog when at least one assigned reviewer opted in\"; the only \"at least one\" prose concerns synced repo configs. The webhook leg (stamphog/backend/tasks/tasks.py via resolve_stamphog_acting_reviewer, receivers.py:144-156) uses the same single-reviewer resolution.",+ "notes": "Mistaken-premise finding: the single-acting-reviewer gate is deliberate, documented, and test-pinned design; the suggested \"any opted-in assigned reviewer\" behavior would break the invariant that a review runs under one reviewer's identity and options.",+ "set": "K"+ },+ {+ "id": "K3",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "receivers.py:224-234 does catch and log queue_inbox_pr_review failures (mechanism confirmed), and the stamphog webhook carve-out is later-deliveries-only (tasks.py:168-171: \"the initial review is the receiver leg's job\"). But permanent loss is refuted: the receiver fires on every TaskRun save touching output (receivers.py:85-89; docstring 77-79 \"re-fire it deliberately\"), process_inbox_pr_review's contract depends on exactly these re-fires with head-keyed dedupe (tasks.py:1124-1128), and re-fire sources exist: set_task_run_output saves output wholesale preserving pr_url (products/tasks/backend/facade/api.py:2149-2154), pr_merged output writes (products/tasks/backend/webhooks.py:276-292), plus any later push hits the synchronize carve-out. The swallow is a documented module invariant (\"broker being down must never surface into the saver\", receivers.py:213), runs in transaction.on_commit (receivers.py:131) where raising is useless, and mirrors the pre-existing _start_review Temporal leg (receivers.py:246,272-273).",+ "notes": "Loss requires a compound rare scenario (broker down at the one dispatch + no later output save + no later head-changing delivery), and the consequence is one missed approve-first Stamphog review on an opt-in experimental flow still covered by ReviewHog and human review, with a full traceback logged. A durable outbox is a valid optional hardening, not a defect this PR must fix.",+ "set": "K"+ },+ {+ "id": "K4",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "facade/api.py:504-506 \u2014 new find_signal_implementation_run calls find_task_run(pr_url, branch, repository) with no team filter, then returns None on run.team_id != team_id, so cross-tenant binding is impossible by construction (docstring at api.py:492-495 documents this as the enforced boundary). webhooks.py:64-76 \u2014 branch leg filters branch + task__repository__iexact only, and TaskRun Meta ordering = [\"-created_at\"] (models.py:1146) makes .first() newest-first, so the finding's ordering premise is technically true. Reachability: only caller is stamphog tasks.py:191-196, fired solely on synchronize/reopen/base-retarget of bot-authored repo-native PRs (tasks.py:167-178), always passing the globally-unique pr_url (tasks.py:194), which the pr_url leg (webhooks.py:36-59) resolves first when output.pr_url is stamped; models.py:651-654 shows TaskRun.branch holds the provisioning checkout branch, not the agent's PR head, so a cross-team branch-leg collision on a signal run's head ref is practically unreachable. Worst case is a false negative (one skipped Stamphog re-review) \u2014 fail-closed, no data exposure. find_task_run itself is pre-existing and untouched by the diff.",+ "notes": "The structural claim (post-filter is not equivalent to scoped selection) is accurate, and threading team_id into find_task_run would be a valid hardening/cleanliness improvement consistent with the repo's tenant-scoping conventions. But the concrete failure scenario (correct run missed via a newer cross-team branch collision) requires a compound improbable state \u2014 lost pr_url stamping AND two teams on the same repo AND identical head-branch strings \u2014 and its consequence is a skipped optional re-review, not a security or correctness break. The performance angle fails the at-scale bar: indexed selective filters on an infrequent webhook path. Improvement, not a defect.",+ "set": "K"+ },+ {+ "id": "K5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:984 \u2014 main() builds Pipeline without self_driving, so Pipeline.run() with self_driving=True never occurs in production (Action path refuses bot authors at line 225 before _maybe_compute_familiarity at line 251). Self-driving inbox reviews run via review_local.run() (review_local.py:314-359), which calls _attach_familiarity (line 353), not _maybe_compute_familiarity; _attach_familiarity early-returns when author_pr_numbers is empty (review_local.py:301-303). activities.py:237-238 sets author_pr_numbers=[] whenever run.output.inbox_review is set, so inbox reviews do no familiarity git work; the sandbox's _familiarity_offline (review_local.py:245-256) makes zero gh calls, and the server-side gh fetch (get_author_merged_pr_numbers) is skipped for inbox reviews.",+ "notes": "The finding's claimed cost (gh request + git ops per inbox review) is unreachable: the production self-driving path never enters Pipeline.run(), and the sandbox path is already short-circuited by the empty author_pr_numbers list the PR itself introduces in activities.py. The suggestion duplicates existing behavior.",+ "set": "K"+ },+ {+ "id": "K6",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree: migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py depends on 0018_backfill_urgency_threshold_to_consider (file lines 7-9); worktree max_migration.txt = \"0019_reviewusersettings_stamphog_review_inbox_prs\"; both added by the diff (pr75215.diff lines 72, 101). origin/master: git ls-tree shows migrations/0019_reviewreport_author_login_and_more.py and max_migration.txt = \"0019_reviewreport_author_login_and_more\". Two 0019 migrations both rooted on 0018 = two leaf nodes in the review_hog graph, so Django's migration loader rejects it (\"Conflicting migrations detected\") and makemigrations --check / the max_migration.txt linear-migrations CI check fail after merge/rebase.",+ "notes": "Deterministic migration-number collision with current master, not speculative: master gained its own 0019 after this branch forked at 0018. Fix is mechanical (renumber to 0020, repoint dependency to 0019_reviewreport_author_login_and_more, update max_migration.txt) but required before the PR can merge and migrate.",+ "set": "K"+ },+ {+ "id": "K7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The claimed missing registration exists: products/review_hog/backend/receivers.py:69 calls register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer) (function defined at receivers.py:144) inside connect(), which is invoked from ReviewHogConfig.ready() (products/review_hog/backend/apps.py:13); ReviewHogConfig is in INSTALLED_APPS (posthog/settings/web.py:76), so the resolver is registered at django.setup() in every web/worker process. Thus get_inbox_acting_reviewer_resolver() (products/stamphog/backend/tasks/tasks.py:201) returns a real callable in production, and the fail-closed `resolver is None` branch (tasks.py:202-204) is only reachable when review_hog is not installed.",+ "notes": "The finding's core premise (\"repository contains no registration\") is refuted by direct grep of the PR worktree. The registration lives in review_hog (not stamphog) by design to avoid a stamphog\u2192review_hog dependency cycle, which the reviewer's search apparently missed. The secondary \"add an integration test\" suggestion cannot sustain a must_fix when the alleged bug does not exist.",+ "set": "K"+ },+ {+ "id": "K8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/models.py:294 declares `stamphog_review_inbox_prs = models.BooleanField(default=False, db_default=False)` (new in this PR, coexisting with the older `review_inbox_prs`); receivers.py:126 and :154 gate on `settings.stamphog_review_inbox_prs`; migration 0019_reviewusersettings_stamphog_review_inbox_prs.py creates the column; the serializer, generated types, and CodeReviewScene.tsx all expose it; test_inbox_trigger.py parameterizes the two toggles independently. products/stamphog/AGENTS.md:87 references exactly this existing field name.",+ "notes": "The finding claims the documented toggle name doesn't exist and only `review_inbox_prs` does \u2014 but this PR introduces `stamphog_review_inbox_prs` as a distinct field, and the AGENTS.md reference is accurate. The suggested \"fix\" would document the wrong gate and contradict code and tests.",+ "set": "K"+ },+ {+ "confidence": "high",+ "evidence": "queue_inbox_pr_review is defined in the PR worktree at products/stamphog/backend/facade/api.py:128 (keyword-only signature team_id/pr_url/acting_user_id/signal_report_id/task_run_id, delegates to process_inbox_pr_review.delay). products/review_hog/backend/receivers.py:222 imports it from products.stamphog.backend.facade.api and line 225 calls it. products/stamphog/README.md:14 references exactly this facade. The PR diff itself adds the definition (+def queue_inbox_pr_review at diff line 687), the receiver call (diff line 279), and the test patch target _STAMPHOG_QUEUE = \"products.stamphog.backend.facade.api.queue_inbox_pr_review\" (diff line 309).",+ "id": "K9",+ "is_real": false,+ "notes": "Finding claims the documented symbol doesn't exist; it is introduced by this PR and is imported and invoked by the inbox receiver. start_review_pr_workflow is the separate ReviewHog leg, not a replacement for the Stamphog facade. The reviewer likely searched a checkout lacking the PR's new files.",+ "severity": "not_an_issue",+ "set": "K"+ },+ {+ "id": "K10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:17-18 docstring documents that the one resolved acting reviewer carries the stamphog toggle; receivers.py:111-126 reads both toggles from that single user's ReviewUserSettings; receivers.py:144-156 makes the webhook recheck deliberately reuse the same single-user resolution; receivers.py:159-173 documents canonical-reviewer selection as maintainer decisions 2026-07-02/03. tests/test_inbox_trigger.py:229-238 (test_opted_out_canonical_reviewer_blocks_the_review) asserts no review runs when the canonical reviewer is opted out despite another assignee opting in \u2014 the exact scenario the finding calls a bug \u2014 with the comment \"a later reviewer's opt-in must not hijack whose options the review runs with\"; test_inbox_trigger.py:313-316 describes \"the two toggles on the one acting reviewer\". Grep of pr75215.diff finds no \"any assigned reviewer\" / \"at least one assigned user\" contract anywhere \u2014 all opt-in prose is singular (\"whose acting reviewer opted in\").",+ "notes": "Mistaken-premise finding: the claimed \"any assignee opts in\" contract exists nowhere in the code, docstrings, or diff prose; the single-canonical-acting-reviewer model is deliberate, documented, and explicitly test-pinned. Applying the suggestion would break the pinned invariant that a non-canonical reviewer's opt-in must not run a review under a different reviewer's configuration. Duplicate of K2 under a different perspective.",+ "set": "K"+ },+ {+ "id": "K11",+ "is_real": false,+ "severity": "consider",+ "confidence": "medium",+ "evidence": "tasks.py:1110-1245 (process_inbox_pr_review) indeed performs no bot-author/repo-native/linkage recheck, unlike the webhook carve-out at tasks.py:169-199. But its inputs come only from receivers.py:72-139, which passes the triggering TaskRun's own output.pr_url/id/report for non-internal signal-report runs; the only in-repo writer of output.pr_url is the webhook backstop at products/tasks/backend/webhooks.py:178-185, which is fork-gated (is_internal_branch: head.repo.full_name must equal base repo) and branch-matched, so a fork or arbitrary foreign PR cannot be recorded. Even a wrong URL is bounded to repos with the team's own enabled StamphogRepoConfig (tasks.py:1140-1153). No API serializer exposes TaskRun.output as writable (presentation/serializers.py pr_url is read-only). The \"arbitrary PR URL in task output\" precondition therefore has no demonstrated untrusted write path.",+ "notes": "Finding's code observation is accurate (no post-fetch checks) but the exploit is a speculative what-if conditioned on an upstream provenance bug. The other writer (the hosted agent server) lives outside this repo, so the \"bot-authored draft by construction\" invariant cannot be fully verified here \u2014 a cheap post-fetch _is_bot_authored + head-repo-native recheck would be consistent belt-and-braces hardening (the code already does this pattern at tasks.py:197-199), which is why this rates consider rather than not_an_issue. Not a confirmed must_fix security bug introduced by the PR.",+ "set": "K"+ },+ {+ "id": "K12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")) (Python bool); reviewer.py:101 types the param `bool = False` and reviewer.py:131/137 store it verbatim then json.dumps the context; review_local.py:396 json.loads the file and line 321 does bool(context.get(\"self_driving_review\")). JSON round-trip of a Python bool produces literal true/false, restored to Python True/False \u2014 the string \"false\" can never appear; possible values are True/False/None, for which bool(x) == (x is True). Context file is authored by the trusted server-side invocation builder, not the PR author.",+ "notes": "The failure scenario (truthy string \"false\" enabling the carve-out) is unreachable given the typed-bool producer and JSON round-trip. Suggestion `is True` is marginal defensive hardening against a hypothetical malformed producer, not a fix for a real defect.",+ "set": "K"+ },+ {+ "id": "K13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:127-139 does enqueue a Celery task per output-touching TaskRun save with pr_url, and tasks.py:1160-1167 fetches the PR before deduping \u2014 but tasks.py:1157-1159 documents why (dedupe keys on the PR's current head, which only GitHub knows; TaskRun.output has no SHA), and tasks.py:1200-1220 dedupes the expensive path: a head-keyed select_for_update lookup no-ops on a live/delivered run, so a same-head re-fire costs one get_pr + a few DB queries, never a duplicate review or workflow. Docstrings at receivers.py:78-83 and tasks.py:1125-1129 show the re-fire is the deliberate lost-synchronize recovery; the suggested per-PR idempotency key would suppress legitimate re-reviews of new commits on the same PR URL. Volume is bounded (pr_url written once, head_branch once per branch-changing turn; non-output saves early-return at receivers.py:88-91) on a double-opt-in, low-volume flow.",+ "notes": "Finding's facts are accurate but describe a documented, bounded design tradeoff, not a defect; the proposed coalesce is infeasible without the head SHA and would break the documented missed-synchronize recovery.",+ "set": "K"+ },+ {+ "id": "K14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Concurrent fires are serialized before the ReviewRun dedupe by _upsert_pull_request, which runs inside the same transaction (tasks.py:1185-1186). For an existing PR row, the conditional refresh UPDATE (tasks.py:349-353, WHERE payload_updated_at IS NULL OR <= incoming) matches for equal/newer snapshots and takes a PullRequest row lock held to commit \u2014 the second task blocks there until the first task's transaction (including ReviewRun.create at tasks.py:1223) commits, then its select_for_update (tasks.py:1202-1210, fresh READ COMMITTED statement snapshot) sees the committed run and takes the no-op/restart branch (tasks.py:1211-1221, idempotent via WorkflowAlreadyStartedError, tasks.py:375-380). For a first-ever fire, UniqueConstraint(team_id, repo_config, pr_number) on PullRequest (models.py:118-123) blocks the losing INSERT until the winner commits; get_or_create retries the get and the loser then hits the same dedupe. A strictly older snapshot matches 0 rows in the UPDATE, refresh_from_db (tasks.py:362) reloads the newer clock, and the locked stale-snapshot recheck (tasks.py:1190-1197) bails before create. The mechanism is explicitly documented in the mirrored webhook path's comment (tasks.py:1037-1044: \"conditional refresh UPDATE takes the PR row lock ... serializing deliveries\"). The only unserialized path requires incoming_updated_at=None for both tasks, but the inbox leg fetches the PR via GitHub REST (tasks.py:1159), which always returns updated_at.",+ "notes": "The finding correctly observes that the ReviewRun select_for_update and _supersede_prior_runs lock nothing when no run row exists, and that delivery_id=None defeats the unique column \u2014 but it misreads _upsert_pull_request as \"get_or_create with no row lock\", missing the locking conditional UPDATE at tasks.py:349-353 and the PullRequest unique constraint, which together close the claimed race in every realistically reachable path.",+ "set": "K"+ },+ {+ "id": "L1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:159-173 (_resolve_assigned_reviewer docstring) documents the single-canonical-acting-reviewer model explicitly, citing \"maintainer decisions, 2026-07-02/03\": the acting reviewer is the task creator when among assignees, else the FIRST resolved assignee, and \"their `review_inbox_prs` / `stamphog_review_inbox_prs` toggles gate the respective reviews\". receivers.py:144-156 (resolve_stamphog_acting_reviewer) says \"Same acting-reviewer resolution as this module's own trigger\". The pre-existing test test_inbox_trigger.py:229 (test_opted_out_canonical_reviewer_blocks_the_review \u2014 absent from pr75215.diff, so it predates the PR) asserts the exact scenario the finding calls a bug: reviewers [\"bob\",\"alice\"], canonical bob opted out, alice opted in \u2192 no review, with the comment \"a later reviewer's opt-in must not hijack whose options the review runs with.\" The acting reviewer's identity is load-bearing: queue_inbox_pr_review(acting_user_id=...) (receivers.py:225-231) runs the review under that user, so selecting \"any opted-in assignee\" would change whose identity/options govern \u2014 the hijack the tested contract forbids. The \"at least one assigned reviewer opted in\" contract the finding relies on appears nowhere in the code or diff; the diff's \"at least one\" phrases (pr75215.diff:36,672) all concern synced repo configs, not reviewers.",+ "notes": "Mistaken-premise finding. The single-gate-on-the-canonical-acting-reviewer behavior is a deliberate, pre-existing, test-enforced design that the PR's stamphog toggle intentionally mirrors (\"the two toggles on the one acting reviewer gate their reviews independently\"). The suggested fix would break the tested ReviewHog selection semantics.",+ "set": "L"+ },+ {+ "confidence": "high",+ "evidence": "review_pr.py:251 does call _maybe_compute_familiarity() unconditionally in Pipeline.run(), but run() is only reached from the Action CLI (review_pr.py:984) which never sets self_driving (defaults False, review_pr.py:196, 202-208) and refuses bot authors at review_pr.py:225. The only path with self_driving=True is the hosted runtime: review_local.py:321 builds the Pipeline and review_local.run() drives steps itself without calling Pipeline.run(); familiarity there comes solely from _attach_familiarity (review_local.py:292-311, called at :353), which no-ops when context[\"author_pr_numbers\"] is empty. The server sets author_pr_numbers=[] for inbox/self-driving runs (products/stamphog/backend/temporal/activities.py:233-238), so classification[\"familiarity\"] stays None and _format_familiarity renders \"\" (reviewer.py:644-646). The provenance block is the only author context on the self-driving path \u2014 the contradiction the finding describes cannot occur on any reachable path.",+ "id": "L2",+ "is_real": false,+ "notes": "The finding traced the wrong entry point: it assumed self-driving reviews flow through Pipeline.run(), but they flow through review_local.run(), which attaches familiarity only from server-provided author_pr_numbers, and the server explicitly blanks that list for inbox reviews (with a comment and test covering exactly this). A defensive self_driving guard inside _maybe_compute_familiarity would be harmless future-proofing for hypothetical callers, but no such caller exists, so no defect ships.",+ "severity": "not_an_issue",+ "set": "L"+ },+ {+ "id": "L3",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree: migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py lines 7-9 depend on \"0018_backfill_urgency_threshold_to_consider\"; PR max_migration.txt = \"0019_reviewusersettings_stamphog_review_inbox_prs\". origin/master: migrations/0019_reviewreport_author_login_and_more.py also depends on the same 0018 (verified via git show), and master's max_migration.txt = \"0019_reviewreport_author_login_and_more\". Two migrations share parent 0018 \u2192 two leaf nodes on merge; Django's graph check fails (\"Conflicting migrations detected\") and max_migration.txt is both a git conflict and a linear-migrations guard failure.",+ "notes": "Merge-blocking migration numbering conflict, not a runtime bug on the branch alone \u2014 but it deterministically breaks migrate/makemigrations --check once combined with current master, so it must be fixed (renumber to 0020, depend on master's 0019, update max_migration.txt) before merge.",+ "set": "L"+ },+ {+ "id": "L4",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "receivers.py:126-139 dispatches only pr_url+ids to queue_inbox_pr_review (no task.repository, no linkage check). tasks.py:1110-1245 process_inbox_pr_review stamps inbox_review after only URL-parse, team repo-config resolution, and an open-PR fetch \u2014 no _is_bot_authored, no head.repo.full_name==repo fork check, no find_signal_implementation_run, and _review_skip_reason never runs on this leg. activities.py:451 sets self_driving_review from that provenance, and its comment (448-450) falsely asserts both trigger paths positively link the PR; the engine bypasses its bot-author refusal (review_pr.py:225, review_local.py:324) and draft gate (review_pr.py:590) on the flag and can post a real GitHub APPROVE. The contrast leg _inbox_rereview_carve_out (tasks.py:144-218) performs exactly the missing checks. Critically, output.pr_url is NOT upstream-guaranteed: the set_output API (presentation/views/api.py:1092-1121, task:write) and facade set_task_run_output (facade/api.py:2139-2153) persist caller-supplied pr_url with zero repo-native/authorship validation (_apply_caller_output guards only webhook-attested keys); the fork check at products/tasks/backend/webhooks.py:178-186 covers only the backstop write path.",+ "notes": "The finding's failure scenario is concretely reachable: on a qualifying run (non-internal signal-report task, opted-in reviewer, synced Stamphog config), an attacker-influenced output.pr_url (unvalidated set_output API, or a prompt-injected agent \u2014 the codebase's own modeled threat, per the fork-safety comments defending the same vector elsewhere) aims an approval-capable, gate-bypassing review at any open PR in a team-configured repo, including untrusted fork PRs; the resulting APPROVE can satisfy required reviews. Blast radius is within-tenant, but it defeats security-motivated trust gates on an approval-posting path this PR introduces, and the suggested fix (pass repository, verify bot-authored + repo-native + run linkage, mirroring _inbox_rereview_carve_out) is correct. Overlaps L6 (same defect anchored in tasks.py); the earlier dismissal rested on a false invariant about pr_url writers.",+ "set": "L"+ },+ {+ "id": "L5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Verified in the frozen PR worktree: queue_inbox_pr_review is defined at products/stamphog/backend/facade/api.py:128; products/stamphog/backend/facade/inbox_hooks.py exists; review_hog's receiver calls the facade (products/review_hog/backend/receivers.py:222-225); the webhook carve-out _inbox_rereview_carve_out exists (products/stamphog/backend/tasks/tasks.py:144, applied at :876 with inbox_review overriding gates at :968); the stamphog_review_inbox_prs toggle exists (products/review_hog/backend/models.py:294) with migration 0019_reviewusersettings_stamphog_review_inbox_prs.py. Every element the README (products/stamphog/README.md:14) documents is implemented in this same PR.",+ "notes": "The finding's core premise (\"neither that facade nor facade/inbox_hooks.py exists in this checkout\") is factually wrong against the PR head \u2014 it reproduces only against a stale/incomplete checkout that lacks the PR's changes. The documentation matches the implemented API names and entry points exactly.",+ "set": "L"+ },+ {+ "id": "L6",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "Verified in the frozen worktree (all paths under .../pr75215_tree):\n\n1. The new receiver leg does zero positive identification of the PR. products/stamphog/backend/tasks/tasks.py:1109-1245 (`process_inbox_pr_review`): parses the URL (L1130), resolves any enabled StamphogRepoConfig for that repo in the team (L1140-1147), fetches the PR (L1159), checks only `state == \"open\"` (L1166) and a non-empty head sha (L1170), then stamps `output={\"inbox_review\": {...}}` and creates a QUEUED ReviewRun (L1176-1230). There is no `_is_bot_authored(pr)` call, no `head.repo.full_name == repo_config.repository` fork check, and no `find_signal_implementation_run` PR\u2192run linkage check anywhere in the function.\n\n2. That provenance is the sole unlock for the engine carve-out. products/stamphog/backend/temporal/activities.py:448-451 passes `self_driving_review=bool(output.get(\"inbox_review\"))`, with the comment \"it is set exclusively from the run's inbox provenance, which both trigger paths stamp only after positively linking the PR to a signals implementation run\" \u2014 false for this leg. products/stamphog/AGENTS.md:96-98 repeats the claim (\"only the two linkage-verified trigger paths stamp\"), and AGENTS.md:110-113 documents that carved-out runs deliberately \"bypass the review-mode and author-write-permission gates\".\n\n3. The webhook leg does perform exactly the checks the receiver leg omits: tasks.py:169 `_is_bot_authored`, L176-178 head-repo == repo fork check, L189-200 `find_signal_implementation_run` + team recheck; and tasks.py:944 / L966-968 skip `_review_mode_skip_reason` and `_author_lacks_write_permission` when `inbox_review is not None`. So the two legs of the same carve-out are asymmetric, and the receiver leg's run never passes any of those gates (they live in `process_pull_request_event`, not the workflow).\n\n4. `output.pr_url` is caller-writable and unvalidated. products/tasks/backend/facade/api.py:2139-2154 (`set_task_run_output`) writes caller output wholesale through `_apply_caller_output`, which constrains only `_WEBHOOK_ATTESTED_RUN_OUTPUT_KEYS = {\"pr_merged\"}` (api.py:1770-1788); pr_url is not attested. The PATCH path api.py:2038-2044 carries the same comment (\"this PATCH surface is caller-controlled too\"). Serializer does no URL validation (presentation/serializers.py:671-674). The endpoint is `runs/<id>/set_output/` with `required_scopes=[\"task:write\"]` (presentation/views/api.py:1101-1121). Only the GitHub backstop writer is fork-safe (products/tasks/backend/webhooks.py:178-185), not the API writers.\n\n5. Reachability by a low-privilege actor: the qualifying task is a signals implementation task, and products/tasks/backend/visibility.py:22-46 puts `Task.OriginProduct.SIGNAL_REPORT` in `TEAM_VISIBLE_ORIGIN_PRODUCTS`, so `task_control_q` grants **any team member** control of it. Writing `output.pr_url` re-fires the receiver (products/review_hog/backend/receivers.py:85-139 only requires update_fields containing \"output\", non-internal task with signal_report_id, and an opted-in assigned reviewer) \u2192 `queue_inbox_pr_review` with the attacker-chosen URL.\n\n6. Consequence: nothing downstream re-gates. activities.py:723-753 posts a real `post_approve_review` once the engine returns APPROVED; the engine itself has no author-association/fork gate (grep of tools/pr-approval-agent/*.py shows author_association used only for comment filtering) and `self_driving=True` relaxes the bot-author refusal (review_pr.py:222-223) and the draft prerequisite. The reviewed head is also cloned into the sandbox that holds the installation token (activities.py:431-473) \u2014 the exact fork hazard tasks.py:222-224 says fork PRs are \"dropped here for security, not just cost\".",+ "notes": "Finding's code claims hold; only its line citations for the tasks facade are off (set_task_run_output is api.py:2139-2160, not 2203-2226/5768) and its framing of task_run_id/signal_report_id as attacker-supplied is wrong (it self-corrects). The real defect \u2014 missing bot-author + repo-native + PR\u2192run linkage verification before stamping `inbox_review` \u2014 is confirmed, contradicts the code's and AGENTS.md's own stated invariant, and is reachable by any team member with task:write because signals tasks are team-controllable. Fix is two cheap checks on the already-fetched `pr` dict plus a `find_signal_implementation_run` match, mirroring `_inbox_rereview_carve_out`. Blast radius stays within the tenant (repo config is `for_team`-scoped) and an approval still requires the engine to judge the diff approvable, but the fork-code-into-sandbox exposure and the write-permission/branch-protection bypass occur regardless.",+ "set": "L"+ },+ {+ "id": "L7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Factual core confirmed but framing wrong; see notes.",+ "notes": "The narrow observation (no re-check in the task) is accurate, but the finding's failure scenario \u2014 an unauthorized review after revocation \u2014 mischaracterizes a preference toggle as an authorization boundary. The design comment at tasks.py:165 shows the mid-PR opt-out case was explicitly considered and handled via approval retraction on the next head change. Re-resolving the toggle at task start would be a marginal hardening (consider-grade at best), not a fix for a defect.",+ "set": "L"+ },+ {+ "id": "L8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1185-1186 \u2014 both racing tasks call _upsert_pull_request inside the same transaction.atomic before the existing-run query. tasks.py:339-343 + models.py:119-123 \u2014 new-PR races serialize on the unique_stamphog_pull_request INSERT (loser blocks, then get_or_create's savepoint recovers the committed row). tasks.py:349-354 \u2014 existing-PR races serialize on the clock-gated UPDATE's PullRequest row lock, held to commit (mechanism explicitly documented for the webhook leg at tasks.py:1036-1044). After the winner commits, the loser's READ COMMITTED existing-run query (tasks.py:1202-1210) sees the committed run and dedupes at tasks.py:1211-1221 (idempotent QUEUED restart only). Finding's narrow facts are right \u2014 no (pull_request, head_sha) uniqueness (models.py:140-145, delivery_id=None at tasks.py:1227) and the select_for_update locks nothing on first fire \u2014 but the duplicate-run scenario cannot occur because serialization happens upstream in the same transaction.",+ "notes": "Only unserialized residual: pre-existing PR row with unparseable GitHub updated_at (tasks.py:346-348 skips the UPDATE lock) \u2014 not reachable for real PRs from the REST API. The comment at tasks.py:1198 attributing serialization to \"the row lock\" of the ReviewRun query is slightly imprecise wording, but the suggested PullRequest lock/uniqueness would duplicate protection already in place. Agrees with the prior dismissal.",+ "set": "L"+ },+ {+ "id": "L9",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "tasks.py:1109 confirms max_retries=3, default_retry_delay=5 (~15s window for generic failures) on a leg with no webhook redelivery (comment at tasks.py:1155-1157 admits the loss risk). But: identical policy on shipped webhook legs (tasks.py:721, 809); rate-limit retry sleeps the full window via countdown=max(retry_after, 60) (tasks.py:1162), defusing the \"particularly likely for rate limits\" claim; recovery paths exist \u2014 receiver re-fires on any later output-carrying TaskRun save (receivers.py:77-79, 85-96), QUEUED-run restart on refire (tasks.py:1211-1214), and later pushes re-review via the webhook carve-out (receivers.py:20-22). Permanent loss requires a sustained outage AND no subsequent output save AND no later push \u2014 reachable but narrow, and the miss is a draft-time pre-review on an opt-in feature with no correctness/approval exposure.",+ "notes": "Mechanism confirmed but impact overstated; valid durability improvement (longer backoff or resumable pending record), not a defect meeting the should_fix bar given the mirrored accepted pattern and graceful degradation.",+ "set": "L"+ },+ {+ "id": "L10",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "pr75215_tree/products/stamphog/backend/tasks/tasks.py:1155-1162 \u2014 fetch precedes dedupe by design (dedupe keys on current head \"which only GitHub knows\"); rate-limit path retries with adaptive countdown. tasks.py:1202-1221 \u2014 head-keyed dedupe early-exits after one GET. products/review_hog/backend/receivers.py:82-96 \u2014 receiver drops created saves and non-output declared-field saves; dispatch gated on non-internal signal-report task + resolved opted-in reviewer. receivers.py:76-79 \u2014 docstring documents the deliberate refire tradeoff (\"a same-head re-trigger costs one fetch (early-exit)\"). products/tasks/backend/facade/api.py:2154,2163-2172 \u2014 output saves are a bounded handful per run (set_task_run_output, webhook backstop); log appends go to S3 without touching output, so they never fire the receiver.",+ "notes": "The finding's mechanical facts are right (no coalescing cache, GET before dedupe) but its failure scenario is not: dispatches are bounded per run, not an \"unbounded stream\"; each redundant fire costs one read-only GET; the refire is a documented deliberate recovery mechanism for lost webhooks; rate-limit hits are absorbed by adaptive retry. A coalescing window is at most a low-value micro-optimization, not a defect.",+ "set": "L"+ }+ ],+ "clusters": [+ {+ "issue": "find_signal_implementation_run rejects internal=True tasks but production self-driving implementation tasks are always internal=True, so the webhook carve-out leg is dead",+ "members": ["Y5", "P12", "Q5", "T10"]+ },+ {+ "issue": "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "members": ["X20", "P10", "Q18", "R3", "T7", "U2", "V3", "M9", "J2", "K11", "L4", "L6"]+ },+ {+ "issue": "self_driving_review read from context JSON with truthy bool() coercion instead of a strict `is True` check",+ "members": ["X10", "Y12", "P3", "Q9", "R6", "T2", "U11", "V5", "M3", "K12"]+ },+ {+ "issue": "Engine does not gate familiarity computation/rendering on self_driving, relying on the server omitting author_pr_numbers",+ "members": ["X14", "Y17", "P5", "P14", "Q2", "R7", "T9", "U6", "V10", "M4", "J3", "K5", "L2"]+ },+ {+ "issue": "_format_self_driving renders TRUSTED provenance claims (machine author / verified-by-task-linkage) solely off the self_driving flag with no engine-side verification",+ "members": ["X3", "Y3"]+ },+ {+ "issue": "Draft/bot gate relaxations in Pipeline are keyed only on self_driving, not coupled to pr.author_is_bot",+ "members": ["X9", "P15", "T6", "U12", "V8", "K1"]+ },+ {+ "issue": "stamphog_connected SerializerMethodField does an uncached cross-product-DB read on every settings serialization (GET and PATCH)",+ "members": ["X15", "Y6", "P6", "Q13", "U7", "V11"]+ },+ {+ "issue": "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "members": ["X12", "Q10", "V9"]+ },+ {+ "issue": "process_inbox_pr_review performs a live GitHub get_pr on every receiver refire before any dedupe",+ "members": ["X16", "P19", "Q16", "U8", "U9", "V6", "V7", "M12", "K13", "L10"]+ },+ {+ "issue": "Carve-out path resolves the same StamphogRepoConfig twice (or thrice) per delivery",+ "members": ["Y14", "P7", "Q11", "U13", "V13"]+ },+ {+ "issue": "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "members": ["X11", "Q8", "T3"]+ },+ {+ "issue": "Webhook-leg toggle re-check repeats the multi-query reviewer-resolution chain on every synchronize/reopen push (performance)",+ "members": ["P18", "Q17"]+ },+ {+ "issue": "_parse_pr_url regex is not host-anchored, so lookalike domains/embedded github.com substrings parse as valid GitHub PR URLs",+ "members": ["Y10", "P1", "M2"]+ },+ {+ "issue": "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "members": ["Y2", "P2"]+ },+ {+ "issue": "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "members": ["X4", "P23"]+ },+ {+ "issue": "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "members": ["X13", "Q3"]+ },+ {+ "issue": "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "members": ["X1"]+ },+ {+ "issue": "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "members": ["X2", "U3", "V1", "M7"]+ },+ {+ "issue": "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "members": ["X5"]+ },+ {+ "issue": "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "members": ["X6"]+ },+ {+ "issue": "find_signal_implementation_run still matches cancelled/failed runs and soft-deleted tasks, extending the carve-out past the automation's lifetime",+ "members": ["X7", "V4", "M14"]+ },+ {+ "issue": "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "members": ["X8"]+ },+ {+ "issue": "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "members": ["X17"]+ },+ {+ "issue": "Relaxed gates leave no trace in logs/gate messages/posted review comment that the self-driving carve-out fired",+ "members": ["X18", "V16"]+ },+ {+ "issue": "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "members": ["X19", "T4", "M13"]+ },+ {+ "issue": "stamphog_review_inbox_prs is PATCH-writable without a server-side stamphog_connected precondition validator",+ "members": ["Y1", "U1"]+ },+ {+ "issue": "Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled-state copy in the UI",+ "members": ["Y4"]+ },+ {+ "issue": "Second synchronous Celery broker publish on the on_commit path with no bounded publish timeout against a hung broker",+ "members": ["Y7"]+ },+ {+ "issue": "Carve-out exception retry path can block the stale-approval safety dismissal for head-changing bot PRs",+ "members": ["Y8", "U14", "V14"]+ },+ {+ "issue": "AGENTS.md carve-out section conflicts with the file's 'every invariant earned through a real review finding' preamble framing",+ "members": ["Y9"]+ },+ {+ "issue": "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "members": ["Y11", "L7"]+ },+ {+ "issue": "Claimed stranding of QUEUED runs because on_commit workflow restart supposedly runs after the Celery task returns (disproven Django semantics)",+ "members": ["Y13"]+ },+ {+ "issue": "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "members": ["Y15"]+ },+ {+ "issue": "Alleged \\s character-class typo in _parse_pr_url making repos containing 's' unparseable (fabricated/misquoted regex)",+ "members": ["Y16"]+ },+ {+ "issue": "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "members": ["P4"]+ },+ {+ "issue": "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "members": ["P8"]+ },+ {+ "issue": "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "members": ["P9"]+ },+ {+ "issue": "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "members": ["P11"]+ },+ {+ "issue": "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "members": ["P13", "R4", "T8", "U4", "M11", "J6", "K4"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer has no try/except guard despite being invoked from another product's webhook path",+ "members": ["P16", "U10", "V2"]+ },+ {+ "issue": "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "members": ["P17"]+ },+ {+ "issue": "Alleged check-then-act race in process_inbox_pr_review's dedupe allowing duplicate runs under concurrent refires (serialized by PR row lock)",+ "members": ["P20", "K14", "L8"]+ },+ {+ "issue": "repository__iexact lookup cannot use StamphogRepoConfig's case-sensitive indexes",+ "members": ["P21"]+ },+ {+ "issue": "stamphog_inbox_pr_create_run_failed log omits the error=str(e) structured field its siblings include",+ "members": ["P22"]+ },+ {+ "issue": "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy",+ "members": ["P24"]+ },+ {+ "issue": "Claim that max_migration.txt was not bumped to the new 0019 migration (false against PR head)",+ "members": ["Q1", "R2"]+ },+ {+ "issue": "Engine's stamphog_review_completed analytics event lacks a self-driving marker property",+ "members": ["Q4", "R1"]+ },+ {+ "issue": "AGENTS.md provenance key name (inbox_review vs trigger/stamphog_self_driving_review) suspected of not matching the implementation",+ "members": ["Q6", "K8"]+ },+ {+ "issue": "AGENTS.md carve-out section placement splits the egress-to-trust-boundaries document flow",+ "members": ["Q7"]+ },+ {+ "issue": "Opt-out dismissal copy/log mismatch on a base-retarget delivery (retarget message posted while log says inbox_opt_out)",+ "members": ["Q12"]+ },+ {+ "issue": "Broad except in get_stamphog_connected collapses transient circuit-breaker failures and real bugs into one error-level log",+ "members": ["Q14", "T5", "V12"]+ },+ {+ "issue": "Carve-out pays repo-config and tasks-DB lookups before the cheap resolver-is-None short-circuit",+ "members": ["Q15"]+ },+ {+ "issue": "Opt-out dismissal message claims 'New commits were pushed' on a reopened PR where no commits were pushed",+ "members": ["Q19"]+ },+ {+ "issue": "queue_inbox_pr_review facade does not guard the Celery .delay publish, so broker/serialization errors can raise into the caller's save path",+ "members": ["R5"]+ },+ {+ "issue": "Claim that tach.toml does not declare the new review_hog -> stamphog dependency (false against PR head, which adds it)",+ "members": ["T1"]+ },+ {+ "issue": "Relaxing the draft gate leaves mergeable_state == \"dirty\" as the only conflict check, which GitHub never reports for drafts, so the merge-conflict gate is inert for self-driving draft PRs",+ "members": ["U5", "V15"]+ },+ {+ "issue": "Stamphog gate keys on a single canonical acting reviewer's toggle, so an opted-in non-canonical assigned reviewer is ignored, contradicting the PR's 'any assigned reviewer opted in' contract",+ "members": ["M1", "M10", "J4", "K2", "K10", "L1"]+ },+ {+ "issue": "Initial inbox review dispatch is fire-and-forget with no durable pending record or reconciliation, so a broker enqueue failure or exhaustion of the task's three retries silently drops the review",+ "members": ["M5", "M6", "K3", "L9"]+ },+ {+ "issue": "Claim that the documented carve-out contracts (queue_inbox_pr_review facade, inbox_hooks resolver, engine flag) do not exist in the code \u2014 stale-checkout false positive validating PR docs against a tree without the PR's changes",+ "members": ["M8", "K9", "L5"]+ },+ {+ "issue": "Em dash in the new README copy violates the repository's documentation writing style guidance",+ "members": ["J1"]+ },+ {+ "issue": "New review_hog migration numbered 0019 conflicts with master's existing 0019_reviewreport_author_login_and_more leaf (both depend on 0018), producing two migration leaves and a max_migration.txt conflict that break migration checks on merge",+ "members": ["J5", "K6", "L3"]+ },+ {+ "issue": "Claim that no inbox acting-reviewer resolver is ever registered so the webhook carve-out always fails closed (false \u2014 receivers.connect() registers resolve_stamphog_acting_reviewer at app ready)",+ "members": ["K7"]+ }+ ],+ "stats": {+ "M1": {+ "sets": ["X", "P"],+ "total": 44,+ "real": 14,+ "must_fix": 1,+ "should_fix": 5,+ "consider": 8,+ "real_ids": [+ "X3(should_fix)",+ "X7(should_fix)",+ "X9(should_fix)",+ "X12(consider)",+ "X17(consider)",+ "X19(consider)",+ "X20(should_fix)",+ "P4(consider)",+ "P7(consider)",+ "P8(should_fix)",+ "P12(must_fix)",+ "P13(consider)",+ "P17(consider)",+ "P19(consider)"+ ]+ },+ "M2": {+ "sets": ["Y", "Q"],+ "total": 36,+ "real": 7,+ "must_fix": 3,+ "should_fix": 1,+ "consider": 3,+ "real_ids": [+ "Y4(consider)",+ "Y5(must_fix)",+ "Y8(should_fix)",+ "Q5(must_fix)",+ "Q12(consider)",+ "Q18(must_fix)",+ "Q19(consider)"+ ]+ },+ "M3": {+ "sets": ["R", "T"],+ "total": 17,+ "real": 3,+ "must_fix": 2,+ "should_fix": 0,+ "consider": 1,+ "real_ids": ["T6(consider)", "T7(must_fix)", "T10(must_fix)"]+ },+ "M4": {+ "sets": ["U", "V"],+ "total": 30,+ "real": 4,+ "must_fix": 0,+ "should_fix": 2,+ "consider": 2,+ "real_ids": ["U13(consider)", "U14(should_fix)", "V8(should_fix)", "V9(consider)"]+ },+ "M5": {+ "sets": ["M", "K"],+ "total": 28,+ "real": 4,+ "must_fix": 1,+ "should_fix": 1,+ "consider": 2,+ "real_ids": ["M9(should_fix)", "M13(consider)", "M14(consider)", "K6(must_fix)"]+ },+ "M6": {+ "sets": ["J", "L"],+ "total": 16,+ "real": 6,+ "must_fix": 4,+ "should_fix": 1,+ "consider": 1,+ "real_ids": [+ "J4(should_fix)",+ "J5(must_fix)",+ "L3(must_fix)",+ "L4(must_fix)",+ "L6(must_fix)",+ "L9(consider)"+ ]+ }+ },+ "clusterCoverage": {+ "M1": 36,+ "M2": 31,+ "M3": 13,+ "M4": 17,+ "M5": 17,+ "M6": 11+ },+ "judges": [+ {+ "lens": "recall",+ "ranking": ["M1", "M2", "M6", "M5", "M4", "M3"],+ "scores": {+ "M1": 9,+ "M2": 5,+ "M6": 3.5,+ "M5": 3,+ "M4": 3,+ "M3": 2+ },+ "rationale": "M1 dominates recall: 14 verified-real findings mapping to 14 distinct clusters (~67% of the ~21 real clusters the whole panel surfaced), including 5 solo-covered real issues no other model verified (X3 trusted-provenance rendering, X17 unindexed TaskRun.branch scan, P4 stale draft-on-purpose copy, P8 missing cross-leg head dedupe, P17 FAILED-run retry loop) plus sole real coverage of the unscoped find_task_run tenant check (P13). M2 is a clear second: 7 reals collapsing to 6 clusters (Y5/Q5 duplicate the dead internal=True carve-out), with 3 solo clusters (Y4 fail-soft ambiguity, Q12 retarget copy mismatch, Q19 false 'commits pushed' claim). M6 takes third on a tiebreak: its 6 reals cover only 4 clusters (J5/L3 and L4/L6 are intra-model dupes), the same cluster count as M4 and M5, but it has 2 solo-covered real clusters (J4 canonical-reviewer gate contradiction, L9 fire-and-forget dispatch) and more raw real findings. M5 and M4 are effectively tied at 4 reals / 4 clusters / 0 solo clusters each; M5 is ordered ahead marginally for covering the merge-blocking migration-0019 conflict (K6), but their scores are equal. M3 is last: only 3 reals (T6, T7, T10), every one redundantly covered by multiple other models, contributing zero unique real-issue coverage. Noise (e.g., M1's 30 non-real findings) was ignored per the lens definition."+ },+ {+ "lens": "precision",+ "ranking": ["M6", "M1", "M2", "M3", "M5", "M4"],+ "scores": {+ "M6": 7,+ "M1": 6,+ "M2": 4,+ "M3": 3.5,+ "M5": 3,+ "M4": 2.7+ },+ "rationale": "M6 leads on precision: 6/16 = 37.5% verified-real, and its hits are dense in value (4 must_fix: J5, L3, L4, L6, plus J4, L9) \u2014 a reviewer reads 16 findings and gets 6 real ones, the best signal-to-noise on the panel, though its junk still includes the stale-checkout fabrication L5. M1 is second at 14/44 = 31.8%; the rate is respectable and includes must_fix P12, but the sheer volume (30 junk findings, including the self-undermining meta-finding P24 and low-value noise like P11/P22) taxes the reader more in absolute terms than any other model. M2 drops to 7/36 = 19.4% and its false positives are the worst kind \u2014 outright fabrications (Y16 misquoted regex, Y13 disproven Django on_commit semantics, Y15) and a false stale-tree claim (Q1) \u2014 which erode reviewer trust beyond what the raw rate shows. M3 is 3/17 = 17.6%; low volume did not buy accuracy \u2014 its entire R set produced zero verified reals, and it emitted the false tach.toml claim T1 and false max_migration claim R2. M5 (4/28 = 14.3%) and M4 (4/30 = 13.3%) sit at the bottom: M5's junk includes three stale-checkout/false-registration claims (M8, K9, K7), and M4 pairs the worst rate with zero must_fix among its 4 reals (U13, U14, V8, V9), meaning 26 of 30 findings were wasted reviewer time with no high-severity payoff. M5 edges M4 on both rate and having a must_fix hit (K6)."+ },+ {+ "lens": "impact",+ "ranking": ["M6", "M2", "M1", "M3", "M5", "M4"],+ "scores": {+ "M6": 9,+ "M2": 8,+ "M1": 6.5,+ "M3": 5.5,+ "M5": 5,+ "M4": 2+ },+ "rationale": "M6 wins on heavy-catch density: 4 verified must_fix from only 16 findings, covering the receiver-leg approval-redirect hole from both sides (L4 dispatch, L6 worker) and the semi-exclusive migration-leaf CI blocker in both runs (J5, L3 \u2014 shared only with M5's K6; four models missed a deterministic merge-queue failure). It also owns the only verified-real finding in two more clusters (J4 canonical-reviewer contract contradiction, L9 fire-and-forget dispatch loss). Its sole heavy miss is the dead internal=True carve-out leg. M2 is the only model with must_fix hits on both top security clusters \u2014 the dead carve-out leg in both runs (Y5, Q5) and the receiver-linkage hole (Q18, the single most thorough writeup of the approval-redirect blast radius) \u2014 plus should_fix Y8 (stale-approval dismissal blocking); but all three of its must_fix land in clusters 3-4 other models also hit, so it has no exclusivity premium. M1 has just 1 must_fix (P12, dead leg) and under-called the receiver hole as should_fix (X20), but its should_fix portfolio adds real unique impact: X3 (trusted provenance rendered solely off the flag) and P8 (webhook/receiver double-review gap) are verified-real nowhere else, plus unique-real P13/P17/P19. M3's tiny output (3 real) hits both top clusters at must_fix (T7, T10) but contributes nothing M2 didn't already cover and nothing unique. M5 gets credit for the rare migration catch (K6) and receiver cluster at should_fix (M9), but that's the whole impact story. M4 is last: 0 must_fix, no heavy cluster at heavy severity, and its receiver-cluster attempts failed verification \u2014 it missed everything that mattered most."+ }+ ],+ "missingClusterIds": [],+ "_meta": {+ "round": 4,+ "blinding": {+ "M": "G1 luna",+ "K": "G2 luna",+ "J": "H1 terra",+ "L": "H2 terra",+ "panel": {+ "M1": "sonnet-5",+ "M2": "glm-5.2",+ "M3": "gpt-5.5",+ "M4": "opus-4-8",+ "M5": "gpt-5.6-luna",+ "M6": "gpt-5.6-terra"+ }+ },+ "verified_against": "worktree @ 1341596e (PR 75215)"+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round5.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round5.jsonnew file mode 100644index 000000000000..8474f1b733bf--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round5.json@@ -0,0 +1,1296 @@+{+ "newVerdicts": [+ {+ "id": "N1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The flagged code exists as described: review_local.py:321 `pipeline = Pipeline(0, context.get(\"repo\") or \"\", self_driving=bool(context.get(\"self_driving_review\")))`, gating the bot-author refusal at L324 and (via Pipeline) the draft prerequisite. But the claimed failure scenario \u2014 a stringified `\"false\"` reaching this coercion \u2014 is unreachable on the only production path. The sole producer is `build_reviewer_invocation` (products/stamphog/backend/logic/reviewer.py:101), whose parameter is typed `self_driving_review: bool = False`, placed verbatim in the context dict (L131) and serialized with `json.dumps` (L137); its only caller passes `self_driving_review=bool(output.get(\"inbox_review\"))` (products/stamphog/backend/temporal/activities.py:451), a genuine Python bool. The engine reads it back with a pure JSON round-trip: `context = json.loads(Path(args.context).read_text())` (review_local.py:396) \u2014 no env-var interpolation, shell templating, or jq step exists between producer and consumer. The integration test asserts the round-tripped value is a real boolean: `assert context[\"self_driving_review\"] is True` (products/stamphog/backend/tests/test_integration.py:1413), which would fail on the string \"true\". An absent key fails closed (`bool(None) == False`), matching the documented default-closed contract (reviewer.py:113-117, review_local.py:316-320).",+ "notes": "The hypothesized bypass requires a stringifying serializer that no code on this path uses and that a test explicitly rules out. `context.get(\"self_driving_review\") is True` would be a harmless one-token hardening, but it guards nothing reachable \u2014 speculative defensive coding, below the defect bar.",+ "set": "N"+ },+ {+ "id": "N2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "api.py:484-516 \u2014 facade takes no head_repo param, docstring (496-498) explicitly assigns fork safety to the caller, and enforces team scoping itself (505: `run.team_id != team_id \u2192 None`), closing the cross-tenant hazard internally. tasks.py:176-178 \u2014 the sole caller `_inbox_rereview_carve_out` performs the fork check (`head_repo.strip().lower() != repo.strip().lower() \u2192 return`) before calling, plus team recheck at 199. webhooks.py:29-69 + 175-186 \u2014 pre-existing `find_task_run` follows the identical convention (branch match without fork enforcement, caller applies `is_internal_branch` guard), so the split is the established pattern, now better documented than before.",+ "notes": "The finding's facts are accurate but it concedes the only caller is safe; the hazard exists only for a hypothetical future caller ignoring an explicitly documented precondition. Mandatory head_repo enforcement in the facade would also be wrong for the pr_url-exact-match leg where fork safety is irrelevant. Speculative future-proofing, not a defect introduced by this PR.",+ "set": "N"+ },+ {+ "id": "N3",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "reviewer.py:692-702 (worktree): _format_self_driving returns the block whenever cl.get(\"self_driving\") is truthy, with no draft-state check; the text asserts present-tense \"It is a draft on purpose ... draft state is not a caution signal for this PR.\" The non-draft re-review scenario is reachable: products/stamphog/backend/tasks/tasks.py:218-234 _review_skip_reason returns \"bot_author\" for a ready (non-draft) bot PR, so tasks.py:870-880 invokes _inbox_rereview_carve_out on synchronize/reopen/base-retarget; the carve-out (tasks.py:144-215) never inspects pr[\"draft\"] \u2014 its docstring (tasks.py:160-163) explicitly contemplates a ready_for_review flip followed by later head-changing deliveries, and it stamps inbox_review provenance for an opted-in, task-linked, repo-native bot PR regardless of draft state. That provenance drives self_driving=True into the engine (review_pr.py:938 to_dict \"self_driving\"; reviewer.py:506 consumes it), so a self-driving PR flipped to ready that receives a new commit gets a re-review whose prompt falsely states it is currently a draft.",+ "notes": "Premise confirmed and reachable, but it is a one-clause factual staleness in a trusted LLM prompt, not a logic bug: when the PR is ready there is no draft-ness to suppress caution about, so the operative instruction is moot, and believing a ready PR is a draft drifts toward more caution, never toward wrongly approving. Valid polish (gate the sentence on live pr.draft), not a defect \u2014 consider, not should_fix/must_fix.",+ "set": "N"+ },+ {+ "id": "N4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "settings.py:71-81 get_stamphog_connected does re-run has_reviewable_repo_config on every GET/PATCH serialization (lines 137, 143), and stamphog is a separate product DB \u2014 the premise is accurate. But facade/api.py:112-125 shows it is a single team_id-indexed .exists(); the endpoint is a human-rate settings route already doing get_or_create + seed_canonicals_tolerantly (settings.py:102, 142); and the \"slow DB latency/pool pressure\" scenario is bounded by the product-DB fail-fast circuit breaker (posthog/db_circuit_breaker.py:145, posthog/db_backends/failopen/base.py:19-35) plus the fail-soft try/except returning False. No realistic production impact.",+ "notes": "The cross-DB read is the feature's purpose (fresh stamphog_connected drives the toggle's enabled state); a TTL cache with cross-product invalidation is disproportionate and would introduce staleness for negligible savings. Perf/reliability concern already mitigated twice at infrastructure and code level.",+ "set": "N"+ },+ {+ "id": "N5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr75215_tree/products/stamphog/backend/facade/api.py:149 \u2014 queue_inbox_pr_review does call process_inbox_pr_review.delay(...) directly, as the finding says. But pr75215_tree/products/review_hog/backend/receivers.py:131-139 \u2014 the sole production caller wraps _start_stamphog_review(...) (which calls queue_inbox_pr_review at receivers.py:225) in transaction.on_commit(lambda: ...), inside handle_task_run_saved. The task therefore publishes only after the TaskRun-save transaction durably commits; a rollback discards the callback and no task fires. receivers.py:116-125 shows the identical on_commit wrap on the sibling _start_review leg, confirming the convention of guarding at the transaction-owning receiver rather than inside the facade.",+ "notes": "The phantom-task premise is refuted at the only call site. Pushing on_commit into the facade would be redundant here (double-deferral) and adds nothing for callers outside a transaction (autocommit runs on_commit immediately). The residual ask \u2014 a docstring note about the commit invariant for hypothetical future callers \u2014 is speculative future-proofing, and the facade docstring already frames caller responsibilities explicitly.",+ "set": "N"+ },+ {+ "id": "N6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr75215_tree/products/review_hog/frontend/CodeReviewScene.tsx:1066 gates the switch on settings.stamphog_connected as claimed. But reviewHogSettingsLogic.ts refutes \"never revalidated\": updateSettings (L447-452) returns the full serialized settings including stamphog_connected (generated/api.schemas.ts:465), so any settings write refreshes it; updateSettingsFailure (L809-812) reloads; afterMount (L954-956) re-runs loadAll on every remount, so in-app navigation away and back refetches. The only stale path is a still-mounted tab while connecting Stamphog in another tab, recoverable by renavigating or toggling anything \u2014 not only a full reload.",+ "notes": "Core claims (\"never re-fetched\", \"stuck until manual reload\", \"scene navigation doesn't remount\") are factually wrong. The narrow residual cross-tab staleness is standard SPA behavior with trivial recovery on an internal-gated surface; the focus/visibility-revalidation suggestion is optional polish, not a defect this PR introduces.",+ "set": "N"+ },+ {+ "id": "N7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Every symbol the finding claims does not exist is present in the PR-head worktree: tools/pr-approval-agent/review_pr.py:196 defines `Pipeline.__init__(..., self_driving: bool = False)`, with the bot-author gate at :225 (`if self.pr.author_is_bot and not self.self_driving`) and the draft gate at :590; products/stamphog/backend/facade/inbox_hooks.py exists (1.7K, alongside api.py/contracts.py/etc.); `queue_inbox_pr_review` is defined at products/stamphog/backend/facade/api.py:128; `process_inbox_pr_review` at products/stamphog/backend/tasks/tasks.py:1110, stamping the `inbox_review` provenance dict at tasks.py:1176; `stamphog_review_inbox_prs` is a BooleanField at products/review_hog/backend/models.py:294 with migration 0019_reviewusersettings_stamphog_review_inbox_prs.py; review_local.py:321 threads `self_driving=bool(context.get(\"self_driving_review\"))` into Pipeline; and `register_inbox_acting_reviewer_resolver` is referenced from both products/stamphog/backend/facade/inbox_hooks.py and products/review_hog/backend/receivers.py, confirming the cross-product hook coupling the finding says is absent.",+ "notes": "The finding was evidently generated against a checkout containing the AGENTS.md doc change but not the implementation files. AGENTS.md documents code the PR actually ships; nothing is fabricated.",+ "set": "N"+ },+ {+ "id": "N8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "The finding claims `queue_inbox_pr_review`, `stamphog_review_inbox_prs`, and `facade/inbox_hooks.py` \"do not exist anywhere in the repository\". All three exist in the PR worktree: `queue_inbox_pr_review` is defined at products/stamphog/backend/facade/api.py:128 and called by review_hog's inbox receiver at products/review_hog/backend/receivers.py:225 (import of the stamphog facade referenced in the module docstring at lines 18-20); `stamphog_review_inbox_prs` is a real BooleanField at products/review_hog/backend/models.py:294 (plus migration 0019_reviewusersettings_stamphog_review_inbox_prs.py and gating in receivers.py); products/stamphog/backend/facade/inbox_hooks.py exists (1.7K) and defines `register_inbox_acting_reviewer_resolver` at line 27, which receivers.py imports at line 53. The README paragraph (products/stamphog/README.md, \"There is one non-webhook entry\" section) accurately describes this shipped wiring.",+ "notes": "The reviewer's grep evidently ran against a checkout without the PR's implementation files. Against the authoritative frozen head, every symbol the README names is real and wired exactly as documented, so the \"fabricated docs\" premise collapses entirely.",+ "set": "N"+ },+ {+ "confidence": "high",+ "evidence": "PR worktree products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9 declares dependencies on 0018_backfill_urgency_threshold_to_consider, and the PR sets max_migration.txt to that 0019 (diff lines 72-99). origin/master (commit 3acab590390, 2026-07-30) ships 0019_reviewreport_author_login_and_more.py with the identical dependency on 0018, and master's max_migration.txt = 0019_reviewreport_author_login_and_more. Two migrations numbered 0019 both off 0018 = Django \"multiple leaf nodes\" conflict + max_migration.txt merge conflict; the PR must be rebased and the migration regenerated as 0020.",+ "id": "N9",+ "is_real": true,+ "notes": "Core collision confirmed. One embellishment is wrong: the finding claims master has migrations 0020-0024 with max_migration.txt = 0024_reviewreport_published_head_shas; master's actual head is 0019_reviewreport_author_login_and_more. This doesn't change the verdict \u2014 the sibling-0019 conflict alone blocks migrate/makemigrations and the migration-linearity CI gate.",+ "severity": "must_fix",+ "set": "N"+ },+ {+ "confidence": "high",+ "evidence": "tasks.py:1130-1174 \u2014 process_inbox_pr_review checks only repo-config enabled, PR open, head_sha present; no _is_bot_authored, no fork (head.repo == repo) check, no find_signal_implementation_run linkage; L1176-1181/1229 stamp caller-supplied ids verbatim into output[\"inbox_review\"]. Contrast tasks.py:169-200 (_inbox_rereview_carve_out) which does all three before stamping identical provenance. activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")); its comment (L448-450, \"both trigger paths stamp only after positively linking\") is false for the receiver leg. tasks.py:968 skips _author_lacks_write_permission when inbox_review is set; grep over temporal/activities.py+workflow.py shows zero author_association/permission gates, and the engine (review_pr.py:225, 590, 794-795) relaxes bot/draft gates and can post APPROVE with no fork/association check. Input path: set_task_run_output (tasks facade api.py:2139-2154) persists agent-supplied output.pr_url with no PR validation (only webhook-attested keys guarded; _apply_caller_output docstring L1778-1780 explicitly contemplates a caller repointing pr_url); review_hog receivers.py:93,126-139 forward output.get(\"pr_url\") unverified into queue_inbox_pr_review. tasks.py:84-87 (TRUSTED_AUTHOR_ASSOCIATIONS comment) states fork/external PRs must never be auto-reviewed because an auto-approval satisfies required reviews with zero human in the loop.",+ "id": "N10",+ "is_real": true,+ "notes": "Every factual claim in the finding reproduces in the worktree. The receiver leg is the only path that stamps self-driving provenance without positively re-deriving the PR\u2194run linkage, bot authorship, and non-fork status \u2014 checks its sibling webhook path performs explicitly for the same feature. Exploitation requires a prompt-injected or misbehaving sandboxed inbox agent repointing output.pr_url, but agent-influenced content is this codebase's own modeled threat (policy-file injection defenses, credential scrubbing), and pr_url is only shape-checked elsewhere, never here. Result: an external fork PR (human-authored, non-draft \u2014 so even the engine's relaxed gates never fire) can receive an unattended GitHub APPROVE, contradicting both the TRUSTED_AUTHOR_ASSOCIATIONS invariant and the activities.py comment claiming positive linkage on both trigger paths. Fix is what the finding suggests: re-verify linkage (find_signal_implementation_run keyed on the pr_url/task_run_id), bot authorship, and fork-safety inside process_inbox_pr_review before stamping inbox_review, failing closed on mismatch.",+ "severity": "must_fix",+ "set": "N"+ },+ {+ "id": "N11",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "tasks.py:1110-1245 \u2014 process_inbox_pr_review checks only repo config (1140-1147), PR open (1166), head_sha (1170); no toggle/resolver re-check before ReviewRun creation (1223) and workflow start (1234). receivers.py:126 \u2014 toggle checked once at dispatch. tasks.py:201-207 \u2014 webhook carve-out re-checks resolver per delivery. tasks.py:1109,1162 \u2014 max_retries=3, rate-limit countdown >=60s (seconds-to-minutes window). tasks.py:160-165 \u2014 docstring documents the split as deliberate (\"Scope is deliberately later deliveries only... the initial review is the receiver leg's job\") and the safety property (\"A toggle switched off mid-PR lands in the caller's skip path, whose head-changing retraction still dismisses the stale approval \u2014 safety is never preference-gated\").",+ "notes": "Code facts confirmed, but the TOCTOU is a deliberate, documented design: toggle honored at dispatch for the one-shot initial review, re-checked per delivery only on the webhook leg where the opt-out window is real. The race requires the opted-in acting reviewer to flip off within seconds/minutes of their own run's dispatch; the outcome is one authorized review of the team's own bot draft PR, with head-pinned approvals retracted on the next head change. Toggle is a preference, not an authorization boundary \u2014 no security dimension. Re-checking the resolver in the task is a cheap consistency improvement at most, not a defect; should_fix is unsupported.",+ "set": "N"+ },+ {+ "id": "N12",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "medium",+ "evidence": "review_pr.py:225 (`if self.pr.author_is_bot and not self.self_driving`) and :590 (`if pr.draft and not self.self_driving`) relax both gates on one flag; review_local.py:321 sets it verbatim from `context.get(\"self_driving_review\")` with no cross-check against `_build_pr_data`'s `author_is_bot`. The mis-set-flag precondition is reachable, not hypothetical: tasks facade api.py:1773-1788 lets a task:write caller repoint `output.pr_url` (shape-only validation, api.py:1940); review_hog receivers.py:93,126-139,225 forwards it unverified; stamphog tasks.py:1110-1234 (`process_inbox_pr_review`) checks only repo-config-enabled + PR open + head_sha \u2014 no `_is_bot_authored`, no fork check, no pr_url\u2194task_run linkage verification \u2014 and stamps `inbox_review` (line 1229); activities.py:451 turns that into `self_driving_review=True` in the sandbox context. A prompt-injected sandbox agent can therefore point the run at a human-authored draft PR in the connected repo and have the engine waive the draft prerequisite en route to a real APPROVE. The proposed engine guard (`self_driving and pr.author_is_bot`) would block that specific chain because the context's author data comes from a live GitHub fetch of the actual PR (activities.py:434-451).",+ "notes": "Real defense-in-depth gap on a concretely reachable attack path, but must_fix overstates it: the root defect is the receiver leg's missing verification (same chain as finding N10), whose fix closes this scenario; the bot-author-refusal half of the relaxation is inert for non-bot authors (only the draft waiver is behaviorally live); and the suggested guard is partial (PRData has no head-repo field, so bot-authored fork PRs still pass). The webhook re-review path already validates bot/fork/linkage \u2014 only the initial receiver leg lacks it.",+ "set": "N"+ },+ {+ "id": "N13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:822 \u2014 _capture_review_completed spreads **analytics_extra_properties() into the stamphog_review_completed properties; gateway.py:25-32 \u2014 that function parses the STAMPHOG_EXTRA_PROPERTIES env JSON; products/stamphog/backend/temporal/activities.py:175-177 \u2014 the hosted server stamps stamphog_self_driving_review=True into that env whenever run.output[\"inbox_review\"] is set, with a comment stating the purpose is analytics segmentation; products/stamphog/backend/tests/test_integration.py:1419 asserts the stamp. So the analytics event DOES carry a self-driving audit marker, refuting the finding's core claim. The human-comment half is accurate as a fact (review_pr.py:590 waives the draft issue silently; _render_review_body at 859-912 adds no carve-out note) but the carve-out remains visible via the draft bot-authored PR itself in GitHub, to_dict()'s classification.self_driving (review_pr.py:937-938), and the analytics marker.",+ "notes": "The finding searched only for a literal stamphog_self_driving key in review_pr.py and missed the deliberate env-based analytics_extra_properties mechanism. The residual suggestion (mention the draft-check waiver in the posted comment body) is a minor copy nicety at best, not a should_fix defect.",+ "set": "N"+ },+ {+ "id": "N14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:206 `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` \u2014 single acting reviewer, verified; toggle checked only for that user at receivers.py:126 and :154. But the PR diff shows master's removed `_resolve_acting_reviewer` gated `review_inbox_prs` on the identical single-acting resolution (`if not ReviewUserSettings.load(team_id, acting.id).review_inbox_prs`), and the docstring (receivers.py:167-168) records it as deliberate (\"the **first** resolved reviewer is canonical (maintainer decisions, 2026-07-02/03)\"). All in-repo docs describe single-acting semantics correctly: stamphog/README.md:14 \"gated by the acting reviewer's per-user stamphog_review_inbox_prs toggle\", stamphog/AGENTS.md:86 \"whose acting reviewer opted in\", receivers.py:17 \"The same resolved acting reviewer carries a second, independent toggle\". The phrase \"at least one of the assigned users\" appears nowhere in the tree \u2014 every diff occurrence of \"at least one\" refers to synced repo configs, not user toggles.",+ "notes": "The code matches its documented, pre-existing, intentional design; the only discrepancy is with loose wording in the PR description prose (not repo content). The finding's own primary remedy is \"correct the PR description\" \u2014 a prose tweak, not a code defect. Not a keepable finding.",+ "set": "N"+ },+ {+ "id": "N15",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:144-156 resolver re-runs _resolve_assigned_reviewer + ReviewUserSettings.load uncached (premise literally true). Cost verified bounded: receivers.py:180-188 one indexed SignalReportArtefact query; resolve_reviewers.py:304-332 one Team query + ~3 bulk user_id__in candidate queries + one User query with prefetches \u2014 ~7-9 indexed queries, no N+1. Reachability verified narrow: tasks.py:201-205 calls the resolver only inside _inbox_rereview_carve_out, which runs in Celery task process_pull_request_event (tasks.py:810, @shared_task \u2014 async, not the webhook view) and only after head-changing action + bot-authored + non-fork + enabled repo config + positive find_signal_implementation_run match (tasks.py:167-199), i.e. only for genuine self-driving PRs at human push rate; each pass then launches a full sandbox LLM review that dwarfs the queries. Freshness is deliberate: receivers.py:147-149 and tasks.py:158-165 document that a toggle switched off mid-PR must stop new runs per delivery \u2014 the proposed per-signal_report_id TTL cache would serve a stale opt-in and break that documented behavior.",+ "notes": "Factual premise (uncached per-push resolution) confirmed, but it's ~8 bounded indexed queries on a low-frequency async Celery path gating far costlier work \u2014 not performance that bites at real scale. The fresh per-delivery read is intentional (opt-out must take effect immediately); caching would introduce a real semantics bug. Reviewer's should_fix is unsupported.",+ "set": "N"+ },+ {+ "id": "N16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/facade/inbox_hooks.py:24-33 \u2014 the registry is a single module-level variable (`_inbox_acting_reviewer_resolver`); `register_inbox_acting_reviewer_resolver` overwrites it (`global ...; _inbox_acting_reviewer_resolver = fn`), it does not append to a list. `get_inbox_acting_reviewer_resolver` (line 32-33) returns the one callable, and the sole caller (products/stamphog/backend/tasks/tasks.py:201) invokes it once per event. Repeated `connect()` runs (products/review_hog/backend/receivers.py:69) merely re-assign the same function, so the \"resolver invoked multiple times per event / multiplied DB load\" scenario cannot occur.",+ "notes": "The finding is self-conditional (\"if ... appends to a list rather than overwriting a single slot\"); inspection shows the safe overwrite branch is the actual code, so registration is already idempotent and no dispatch_uid-style guard is needed.",+ "set": "N"+ },+ {+ "id": "N17",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:876 calls _inbox_rereview_carve_out only when skip_reason is set; tasks.py:170-185 shows the flow exits after one indexed _resolve_repo_config read unless the repo has an enabled+connected Stamphog config, so the cross-product lookup never runs for arbitrary bot PRs on unconfigured repos. find_task_run (products/tasks/backend/webhooks.py:29-90) is a bounded 2-3 indexed reads: the output__pr_url leg is served by the partial functional index task_run_output_pr_url_idx (products/tasks/backend/models.py:1147-1156), the branch leg keys on branch equality, and the wizard leg is prefix-gated off for non-wizard branches. All of it runs inside the async Celery task process_pull_request_event (tasks.py:810), not a request path. The cited caching precedent _author_lacks_write_permission (tasks.py:100-110) guards a rate-limited external GitHub API call, not local DB reads \u2014 the analogy doesn't transfer.",+ "notes": "The described code path exists, but the \"defect\" is a few millisecond-scale indexed local reads per bot-PR push on an async worker, gated to Stamphog-enabled repos. That's not a performance problem at realistic scale, and the proposed (repo, pr_number)-keyed negative cache would introduce a real hazard: a cached miss could mask a self-driving run created between deliveries and suppress a legitimate re-review. Premature optimization, not a defect.",+ "set": "N"+ },+ {+ "id": "N18",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "tasks.py:179 \u2014 _inbox_rereview_carve_out calls _resolve_repo_config after bot-author (line 169) and same-repo (line 177) guards; tasks.py:891 \u2014 on the same skipped delivery (skip_reason set, no carve-out provenance, head-changing action) process_pull_request_event calls _resolve_repo_config again for approval retraction; tasks.py:289-305 \u2014 _resolve_repo_config is a single indexed .filter(provider, installation_id, repository).first() on the writer DB with no .enabled filter, so both calls return the identical row. The double query is real but costs one extra cheap indexed SELECT on an async Celery webhook path, only for bot-authored head-changing PRs on configured repos.",+ "notes": "Factually accurate redundancy; reusing the config via _InboxCarveOut would be a behavior-preserving DRY cleanup. No correctness, N+1, or scale impact, so it is an improvement suggestion rather than a defect \u2014 should_fix is overstated.",+ "set": "N"+ },+ {+ "id": "N19",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1155-1165 does fetch the PR before the dedupe, as claimed, and the docstring (1121-1128) documents that ordering as deliberate (dedupe keys on the PR's current head, which only GitHub knows). But the finding's amplifier \u2014 frequent output saves from streaming progress \u2014 is false: progress is a `_posthog/progress` notification going to S3 log + Redis stream (models.py:1635-1679, facade/api.py:2163-2172), never an `output` save; the receiver drops non-output declared-field saves (receivers.py:85-89); `output` is written only at discrete milestones (webhooks.py:292 one-time pr_url record, facade/api.py:2154 set_task_run_output at session end, facade/api.py:2043 PATCH output merge). No bare TaskRun.save() on hot paths. Receiver docstring (receivers.py:77-79) already bounds a same-head refire to one fetch + early-exit.",+ "notes": "Realistic redundant volume is ~1 extra get_pr per self-driving run on an async Celery path \u2014 nowhere near a rate-limit-relevant burst. The proposed last-head TTL cache/debounce would risk skipping a genuinely changed head (the lost-synchronize recovery the design explicitly serves) to save a single cheap API call. Premise-driven severity does not hold; the code is working as designed.",+ "set": "N"+ },+ {+ "confidence": "high",+ "evidence": "tasks.py:1140-1147 filters StamphogRepoConfig.objects.for_team(team_id) with repository__iexact; models.py:58 has UniqueConstraint on (team_id, repository), so the team_id equality prefix index-seeks and the iexact predicate is applied over only that team's rows (bounded to one row per repo by the same constraint \u2014 a handful of rows, not a scan of the table). The comment at tasks.py:1136-1137 documents iexact as required: tasks stores repository slugs lowercased while configs keep GitHub's casing, so an exact match would silently fail to resolve the config. The query runs in process_inbox_pr_review, an async Celery task (line 1109) fired ~1-2 times per self-driving PR, followed immediately by a live GitHub API fetch (line 1159) that dominates cost.",+ "id": "N20",+ "is_real": false,+ "notes": "Code fact is technically true (btree can't seek case-insensitively on repository), but the query is team-scoped so the (team_id, repository) index bounds it to a team's few config rows on a low-frequency background path \u2014 no production performance effect. The iexact is deliberate and correctness-required per the in-code comment; write-time normalization / functional index would be overengineering for this cardinality.",+ "severity": "not_an_issue",+ "set": "N"+ },+ {+ "confidence": "high",+ "evidence": "tasks.py:1236 \u2014 logger.exception(\"stamphog_inbox_pr_create_run_failed\", repository=repository, pr_number=pr_number) omits error=str(e); siblings in the same function include it (tasks.py:1149 stamphog_inbox_pr_config_resolution_failed with error=str(e); tasks.py:1164 stamphog_inbox_pr_fetch_failed with error=str(e)), as do the process_pull_request_event failure paths (e.g. lines 826, 878). Line 1237 re-raises via retry(exc=e), and logger.exception captures the full traceback, so no information is lost \u2014 only the structured error field for log filtering.",+ "id": "N21",+ "is_real": true,+ "notes": "Factually accurate but purely a logging-convention consistency nit: the exception message/traceback is already auto-captured by logger.exception and the failure is retried, so nothing is hidden. Adding error=str(e) is a valid one-line improvement for structured-log filterability, not a defect.",+ "severity": "consider",+ "set": "N"+ },+ {+ "id": "N22",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:809 \u2014 process_pull_request_event is @shared_task (Celery, webhook already ACKed), not a sync webhook handler, so no 500/redelivery storm is possible. tasks.py:875-879 \u2014 the sole production call path to the resolver (_inbox_rereview_carve_out \u2192 get_inbox_acting_reviewer_resolver, tasks.py:201) is wrapped in try/except Exception that logs and retries, added in this same PR; the finding's claim that the PR \"does not control or guarantee\" the wrapping is factually wrong. tasks.py:873-874 comment documents deliberate retry-don't-drop semantics: an internal swallow-and-return-None in resolve_stamphog_acting_reviewer (receivers.py:144-156) would make a transient DB blip resolve as an empty carve-out \u2192 skip path retracts the standing approval and silently drops a legitimate re-review \u2014 the exact failure the caller's design prevents. Carve-out resolution runs before the retraction block (tasks.py:881), and the task is idempotent via delivery-id dedup, so retry never resumes mid-retraction.",+ "notes": "Wrong premise (sync webhook 500) and wrong claim about missing caller guard; the suggested fix would worsen intended fail-with-retry behavior by silently dropping re-reviews on transient errors.",+ "set": "N"+ },+ {+ "id": "N23",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "Verified: review_local.py run() (lines 314-359) never assigns pipeline.provenance \u2014 no pr_provenance import/call anywhere in the file; it stays at Pipeline.__init__'s None default (review_pr.py:212). review_pr.py:385 sets provenance only on the Action _fetch path. to_dict() emits \"provenance\": provenance_evidence(self.provenance) (review_pr.py:940, github.py:546-556 returns None for None) and analytics fields stamphog_agent_authored/agent_commit_count degrade to None (review_pr.py:814,843-844). self_driving=True is only reachable via review_local.py:321 (comment at review_pr.py:202-205 confirms the Action never sets it), so every self-driving review has null provenance. However: the verdict/prompt are unaffected \u2014 _format_self_driving (reviewer.py:683-702) keys only on cl[\"self_driving\"], and the backend parses only gates/classification/policy from engine output (products/stamphog/backend/logic/reviewer.py:172-182), never the provenance field. The carve-out's audit trail exists elsewhere: run.output[\"inbox_review\"] (signal_report_id/task_run_id/acting_user_id) plus the stamphog_self_driving_review analytics marker via STAMPHOG_EXTRA_PROPERTIES (activities.py + integration test). The PR's review_local.py diff hunk only adds the self_driving flag \u2014 the offline path's missing provenance is pre-existing behavior, not introduced by this PR.",+ "notes": "The factual claim is fully reproducible (offline/self-driving reviews always emit null provenance and empty agent-authorship analytics), so it is not a false finding \u2014 but it is telemetry/observability completeness with zero verdict, security-gate, or server-side consumer impact, and the gap predates the PR. The \"use provenance as a second factor for the carve-out\" idea is a forward-looking hardening suggestion, not a present defect. should_fix overstates it; consider is the right bucket.",+ "set": "N"+ },+ {+ "id": "O1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:113-121: _parse_pr_url returns only (owner/repo, pr_number); the URL host is discarded. tasks.py:1140-1147: parsed repository is used solely as a positive-match lookup key against a team-scoped, enabled StamphogRepoConfig with non-empty installation_id; no match is a silent no-op. tasks.py:1159: the PR fetch uses repo_config.repository via the team's own App installation client \u2014 never the URL \u2014 so a lookalike host (e.g. evilgithub.com/owner/repo/pull/1) yields extraction identical to a canonical github.com URL and cannot redirect the fetch or select an unconfigured repo. Sole caller is review_hog receivers.py:225 via queue_inbox_pr_review.",+ "notes": "The unanchored-regex observation is factually correct, but host anchoring closes no reachable path: every value the regex can extract must still positively match an already-configured team repo, and all GitHub access goes through the config's canonical repo name on the App installation. Pure defensive-parsing hygiene, no failure scenario.",+ "set": "O"+ },+ {+ "id": "O2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_local.py:321 does use bool(context.get(\"self_driving_review\")), but the flag's sole producer is type-constrained end to end: activities.py:451 passes self_driving_review=bool(output.get(\"inbox_review\")) (explicit bool coercion), reviewer.py:101 types the build_reviewer_invocation parameter as bool with default False, and reviewer.py:131+137 writes it into the context dict serialized via json.dumps \u2014 a Python bool round-trips as JSON true/false, never a string. The consumer thus only ever receives True, False, or key-absent (None for Action-shaped contexts, per the comment at review_local.py:316-320), and bool(x) is identical to (x is True) for all three reachable values.",+ "notes": "The claimed trigger (a truthy non-boolean like \"false\" or \"0\" arriving in the context JSON) has no reachable production path \u2014 the context is server-stamped, not attacker-influenced. The suggested `is True` check is belt-and-suspenders hardening against an input the producer's types already rule out; a speculative what-if, not a defect.",+ "set": "O"+ },+ {+ "id": "O3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "settings.py:73-82 does call has_reviewable_repo_config per serialization, but facade/api.py:112-125 shows it is a single fail-soft .exists() query. reviewHogSettingsLogic.ts:954 (afterMount \u2192 loadAll) and the setInterval at ~758 (polls loadRecentReviews only) show settings is fetched once per tab mount, not polled. settings.py:142 shows the same GET already runs seed_canonicals_tolerantly + a get_or_create, dwarfing the one existence query.",+ "notes": "Factually accurate code description, but no failure scenario: O(1) indexed existence check, fail-soft (try/except returning False), on a once-per-mount endpoint. Suggested TTL cache would leave the toggle stale/disabled right after connecting Stamphog \u2014 worse than the cost it saves.",+ "set": "O"+ },+ {+ "id": "O4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr75215_tree/products/stamphog/backend/facade/api.py:149 calls process_inbox_pr_review.delay() directly, but its only production caller is products/review_hog/backend/receivers.py:225 inside _start_stamphog_review, which is invoked exclusively via transaction.on_commit(...) at receivers.py:131-139 in the handle_task_run_saved post_save receiver. Repo-wide grep confirms no other call site (tasks.py:1115 and inbox_hooks.py:4 are docstring mentions; test file mocks the facade). The dispatch therefore already fires only after the triggering save's transaction commits.",+ "notes": "Wrong premise: the on_commit deferral exists one level up at the receiver, which is the layer that knows the transaction context. Wrapping the facade's .delay() in on_commit as well would be speculative double-deferral for a caller that doesn't exist.",+ "set": "O"+ },+ {+ "id": "O5",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "facade/api.py:504-509 (new in this PR): gate is `if task.signal_report_id is None or task.internal` \u2014 no deleted check. webhooks.py:41 (pr_url leg) and :68-76 (branch leg) lack `task__deleted=False`; only the wizard leg (:89) has it. models.py:445-455: Task.delete() raises, soft_delete() sets deleted=True; no custom Task manager (only line 999, a different model), and select_related(\"task\") fetches the deleted row. stamphog tasks.py:144-215: carve-out fires on every synchronize/reopen/base-retarget and a positive match + opted-in resolver bypasses bot-author/draft/association/write-permission gates. review_hog receivers.py:144-156: resolver checks artefact + toggle only \u2014 no deletion awareness anywhere in the chain.",+ "notes": "Concretely reachable: soft-deleting a signals-implementation task neither closes its PR nor cancels its run, so later head-changing deliveries keep positively identifying the PR as self-driving and can post real bot-identity APPROVEs, with the task gone from the Inbox UI. Violates the feature's stated \"positive identification only\" invariant; fix is a one-line mirror of the wizard leg's existing filter. Not must_fix: no cross-tenant exposure \u2014 confined to the team's own bot-authored PR with an opted-in reviewer.",+ "set": "O"+ },+ {+ "id": "O6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/receivers.py ~100-104: trigger skips internal tasks (`if task.internal: return`); comment states plumbing tasks (report research, repo selection, custom agents) are all internal=True and \"the auto-start implementation task is the only non-internal signal-report task\". products/tasks/backend/facade/api.py:491,508: matcher docstring says \"a non-internal task carrying a signal report\" and code early-returns on `if task.signal_report_id is None or task.internal:`. The AGENTS.md phrase (line ~85) therefore matches the implementation exactly.",+ "notes": "Finding's premise is inverted: the reviewed self-driving implementation task is internal=False; the internal=True tasks cited (repo_selection/agent.py) are precisely the plumbing tasks the gate excludes. The suggested edit would introduce, not fix, an inconsistency in a security-relevant doc.",+ "set": "O"+ },+ {+ "id": "O7",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree (pr75215_tree/products/review_hog/backend/migrations/): new file 0019_reviewusersettings_stamphog_review_inbox_prs.py declares dependencies = [(\"review_hog\", \"0018_backfill_urgency_threshold_to_consider\")] (lines 7-9), and the PR sets max_migration.txt to 0019_reviewusersettings_stamphog_review_inbox_prs (diff hunk at pr75215.diff lines 95-101 shows pre-image 0018 \u2192 0019_stamphog, i.e. the branch predates master's 0019-0024). Live master (verified via gh api at 2026-07-31): max_migration.txt = 0024_reviewreport_published_head_shas, and 0019_reviewreport_author_login_and_more.py already exists with the identical parent dependencies = [(\"review_hog\", \"0018_backfill_urgency_threshold_to_consider\")]. django-linear-migrations~=2.17.0 is installed (pyproject.toml:219, posthog/settings/web.py:207 appends \"django_linear_migrations\" to INSTALLED_APPS). Result on merge: two sibling migrations both numbered 0019 branching off 0018 \u2014 Django reports conflicting leaf nodes for the review_hog app and the linear-migrations single-leaf check fails, plus max_migration.txt has a textual merge conflict (master changed 0018\u2192\u2026\u21920024 while the PR changes 0018\u21920019_stamphog).",+ "notes": "The finding is accurate in every particular. This is a merge/CI/deploy blocker rather than a runtime data bug: as merged, migrate would refuse to run (conflicting migrations, multiple leaf nodes) and CI's linear-migrations check fails deterministically. Fix is mechanical: rebase onto current master, regenerate the migration as 0025_* depending on 0024_reviewreport_published_head_shas, and update max_migration.txt (per the repo's own feedback rule, via makemigrations, not hand-editing).",+ "set": "O"+ },+ {+ "id": "O8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:201-205 \u2014 the resolver's only call site passes repo_config.team_id (derived from the webhook's installation_id+repo at tasks.py:289-304) and run.signal_report_id from find_signal_implementation_run, which matches the run to this exact PR (pr_url/head_branch) and enforces run.team_id != team_id \u2192 None (facade/api.py:504-506); tasks.py:199 re-asserts run.team_id != repo_config.team_id, with fork safety at 176-178 and _is_bot_authored at 169. Inside the resolver (receivers.py:151-207) every query is scoped to the single team_id argument: SignalReportArtefact.filter(team_id=..., report_id=...) at 180-188, resolve_org_github_login_to_users(team_id, ...) at 202, ReviewUserSettings.load(team_id, ...) at 154 \u2014 a mismatched (team, report) pair finds no artefact and returns None, fail-closed. The precondition is already documented at tasks.py:153-158 and facade/api.py:492-498.",+ "notes": "The claimed scenario (hook silently acting on a different team's reviewer settings) is unreachable: identifiers are positively derived from the PR under review with double team-scope checks, and the resolver's internal queries are single-team-consistent so even a caller bug fails closed rather than crossing tenants. The suggested documentation already exists in both docstrings. Speculative defense-in-depth with no demonstrable failure path.",+ "set": "O"+ },+ {+ "id": "O9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "medium",+ "evidence": "tasks.py:1110-1245 confirms process_inbox_pr_review omits find_signal_implementation_run/_is_bot_authored/fork checks and stamps caller args verbatim, but the finding's core impact claim is refuted: _inbox_rereview_carve_out (tasks.py:144-215) never consults stored inbox_review provenance \u2014 it independently re-checks bot authorship (line 169), fork safety (176-178), team-scoped task linkage with a run.team_id recheck (191-200), and the opt-in toggle (201-207) on every later delivery, so stored provenance only sets the initial run's own self_driving flag (activities.py:175,237,451). The sole caller (receivers.py:126-139 \u2192 _start_stamphog_review \u2192 facade/api.py:128-155) fires only for a non-internal signals-implementation TaskRun and passes the run's own output.pr_url, which is written either by the agent server for the PR the run opened or by the signature-verified, fork-safe webhook backstop (products/tasks/backend/webhooks.py:171-185). A forged pr_url can only reach a PR in the team's own Stamphog-connected repo via the team's own installation (tasks.py:1140-1159).",+ "notes": "The finding's factual observations about the function are correct, but its must_fix framing rests on a false premise (stored provenance skipping webhook gates on later deliveries) plus speculative triggers (caller bug, hypothetical future caller, compromised agent). Positive identification is enforced at the only caller and re-derived on every subsequent delivery. Mirroring _is_bot_authored/fork checks on the initial leg would be optional defense-in-depth hardening, not a reachable defect.",+ "set": "O"+ },+ {+ "confidence": "high",+ "evidence": "review_pr.py:225 and :590 match the finding's description (draft/bot gates keyed on self.self_driving alone). But the flag reaches the engine only via bool(output.get(\"inbox_review\")) (products/stamphog/backend/temporal/activities.py:451, review_local.py:321), and both stamping paths enforce bot authorship: the webhook carve-out checks _is_bot_authored(pr) (products/stamphog/backend/tasks/tasks.py:169), fork safety (:176-178), team-scoped run match + recheck (:191-200), and toggle (:205-207) on every head-changing delivery; the initial leg (process_inbox_pr_review, tasks.py:1109-1133) fires only for the signals run's own bot-opened PR. The finding's concrete trigger (human pushes to the bot's branch) keeps author_is_bot=True (PR author = opener), so the suggested guard `author_is_bot and self_driving` behaves identically in that scenario \u2014 the fix doesn't address its own example. Replays are guarded by the payload_updated_at stale-snapshot recheck (tasks.py:1190-1197) and select_for_update dedupe (:1202-1207). The draft gate is a policy gate (tasks.py:227 \"reviewing one now is wasted\"), not the security boundary.",+ "id": "O10",+ "is_real": false,+ "notes": "No reachable path produces self_driving=True with author_is_bot=False absent an upstream bug; remaining triggers are speculative. The suggested combined guard is legitimate cheap defense-in-depth at the server-to-sandbox context boundary, but hardening, not a defect this PR introduces. (Closest residual edge: tasks/webhooks.py:184-185 backstop could bind a same-repo human-opened PR to a run pre-detection \u2014 internal write-access actor only, not the finding's scenario.)",+ "severity": "consider",+ "set": "O"+ },+ {+ "id": "O11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "reviewer.py:692 does gate only on cl.get(\"self_driving\") with no author_is_bot check, and the block (lines 694-702) does assert machine authorship and downplay draft state in the TRUSTED section (line 568) \u2014 the code description is accurate. But the precondition (self_driving=True for a non-bot PR) has no reachable trigger: review_pr.py:477 copies self.self_driving verbatim; it is only True via review_local.py:321 \u2190 activities.py:451 bool(output.get(\"inbox_review\")); inbox_review provenance is stamped only by _inbox_rereview_carve_out (products/stamphog/backend/tasks/tasks.py:169-172 returns empty unless _is_bot_authored(pr), plus fork-safety at 176-178 and team-scoped task linkage at 191-200) or by process_inbox_pr_review for a signals run's own bot-opened draft PR. The Action CLI never sets self_driving (review_pr.py:202-205 comment, default False). Deterministic gates (bot-author refusal review_pr.py:225, draft gate) are unaffected by prompt wording, and the block itself instructs strict diff scrutiny and treats the PR body as untrusted.",+ "notes": "Speculative hardening suggestion layered on an unreachable precondition (would require a bug in the stamping paths, which both verify or construct bot authorship). The prompt block is a soft nudge, not a control; only one sentence is scrutiny-reducing and only under the same impossible precondition. Fails the concrete-failure-scenario bar.",+ "set": "O"+ },+ {+ "id": "O12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:200 `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` \u2014 single acting reviewer; docstring at receivers.py:181-196 documents this as deliberate (\"the **first** resolved reviewer is canonical (maintainer decisions, 2026-07-02/03)... Their `review_inbox_prs` / `stamphog_review_inbox_prs` toggles gate the respective reviews\"). Both call sites check only that one user's toggle, as the finding says \u2014 but no code, docstring, or user-facing copy promises OR-across-reviewers; every \"at least one\" string in the diff refers to Stamphog repositories. Only the ephemeral PR-description prose conflicts.",+ "notes": "Single-acting-reviewer gating is intentional, documented, tested, and matches the pre-existing review_inbox_prs precedent. The mismatch is confined to PR-description wording; the actionable fix is rewording the blurb, which is below the defect bar.",+ "set": "O"+ },+ {+ "id": "O13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1125-1128 docstring states dedupe keys on the PR's current head for repeat receiver fires; tasks.py:1202-1221 implements it \u2014 select_for_update() filter on (pull_request, head_sha) excluding SUPERSEDED/FAILED inside transaction.atomic(), returning early (\"stamphog_inbox_pr_already_reviewed\") when a run exists at that head, only idempotently restarting a stranded QUEUED run's workflow; tasks.py:1190-1197 adds a stale-snapshot guard so an old refire can't supersede a newer webhook-delivered run. Repeat TaskRun saves with the same pr_url resolve to the same head_sha and no-op \u2014 no duplicate reviews are posted.",+ "notes": "The finding is phrased as \"verify a dedup exists; add one if not.\" Verification shows the dedup exists exactly as the suggestion prescribes (head-keyed, row-locked, mirroring the ReviewHog leg's USE_EXISTING semantics), so the premise of a missing idempotency guard is refuted.",+ "set": "O"+ },+ {+ "id": "O14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "medium",+ "evidence": "tasks.py:1176-1181,1223-1229 \u2014 process_inbox_pr_review stamps the enqueue-time acting_user_id and creates the ReviewRun with no toggle re-resolution (fact confirmed). tasks.py:1109,1162 \u2014 retries (3x, rate-limit countdown >=60s) make a delayed run reachable (fact confirmed). But tasks.py:160-165 (carve-out docstring) documents the design: a head-pinned approval granted on the draft stands until the next head change regardless of a mid-PR opt-out, and \"safety is never preference-gated\"; tasks.py:887-898 + 70-74 show the opted-out skip path dismisses the standing approval with _INBOX_OPT_OUT_DISMISS_MESSAGE on every subsequent head-changing delivery. The race therefore produces an end state identical to the legal ordering where the review finishes just before the opt-out: an approval over an actually-reviewed head that stands until the next push and is then dismissed. No invariant (positive identification, stale-approval retraction, tenant scoping) is violated.",+ "notes": "The finding's facts are accurate but its conclusion is not a defect: the toggle is a preference checked at a valid decision point (enqueue, seconds after the user's own opted-in run saved its PR link), and the design explicitly handles mid-PR opt-out on the safety axis via preference-independent approval retraction. The missing re-check only narrows a seconds-to-minutes window whose outcome is race-equivalent to an accepted legal ordering; adding it would require threading task_created_by_id through queue_inbox_pr_review/process_inbox_pr_review for negligible behavioral gain. Marked medium confidence only because one could defensibly rate the mirror-the-carve-out re-check as a \"consider\" nicety; it is not a correctness or security defect.",+ "set": "O"+ },+ {+ "id": "O15",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "Verified in pr75215_tree: (1) ReviewRun has no unique constraint on (pull_request, head_sha) \u2014 only delivery_id is unique (products/stamphog/backend/models.py:145), and process_inbox_pr_review creates with delivery_id=None (tasks.py:1227), so no DB backstop exists (nullable unique allows multiple NULLs). (2) The dedupe's select_for_update (tasks.py:1205) locks only pre-existing rows; the comment \"the row lock serializes racing fires\" (tasks.py:1198) actually relies on _upsert_pull_request's conditional UPDATE (tasks.py:349-353) taking the PullRequest row lock. (3) That lock is skipped by the explicit early return when incoming_updated_at is None (tasks.py:346-348). Mechanism confirmed exactly as claimed. However the trigger is not reachable in practice: pr is a successful GitHub REST get_pr response (tasks.py:1159) whose updated_at is always a non-null ISO-8601 string that Django's parse_datetime accepts (same parse works on the production webhook leg, tasks.py:329/1015); duplicate creation additionally requires two truly concurrent Celery executions for the same PR in that window.",+ "notes": "The code analysis is accurate \u2014 no misreading \u2014 but the claimed duplicate-run/duplicate-review failure requires a GitHub payload without a parseable updated_at, which real API responses never produce. Not a production defect; valid hardening/maintainability suggestion (explicit lock on the PullRequest row or a (pull_request, head_sha) uniqueness backstop) matching the finding's own \"consider\" rating.",+ "set": "O"+ },+ {+ "id": "O16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_pr.py:225 refuses bot authors before _maybe_compute_familiarity (line 251) on the Action path, and the Action CLI (line 984) never sets self_driving. The self-driving entrypoint is review_local.py:run() (line 314), which uses _attach_familiarity (line 353); that function early-returns on empty author_pr_numbers (review_local.py:301-303). The server sets author_pr_numbers=[] for inbox reviews (products/stamphog/backend/temporal/activities.py:237-238, with an explicit comment and an integration test asserting the empty list). Consumers guard None: reviewer.py:644-646 (_format_familiarity returns \"\" when fam is None) and review_pr.py:871-872 (_render_review_body familiarity bullet requires fam is not None).",+ "notes": "The finding's premise \u2014 familiarity machinery still runs for self-driving bot-authored PRs \u2014 is wrong: familiarity is zeroed at the server (empty author_pr_numbers), skipped at the sandbox attach step, and both consumers no-op on None. The suggested guard is redundant with the existing early return.",+ "set": "O"+ },+ {+ "id": "O17",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "resolve_reviewers.py:304-332 + 355-384: resolution is fully batched \u2014 1 Team lookup, 3 subquery-scoped candidate queries, 1 User query with prefetch; with the SignalReportArtefact .first() (receivers.py:182-191) and ReviewUserSettings.load (receivers.py:156) that's ~6-8 indexed queries, no N+1. tasks.py:144-217: the resolver runs only after head-changing action + bot author + non-fork head + enabled repo config + tasks-facade self-driving match \u2014 a narrow async webhook path, not a hot path. receivers.py:145-151 and tasks.py:159-165: per-push re-resolution is the intended mechanism for mid-PR opt-out (\"switching the toggle off mid-PR stops new stamphog runs\"), so the suggested (team_id, signal_report_id)-keyed cache would cache the toggle decision and defeat opt-out.",+ "notes": "Not a performance defect: a few batched indexed queries per push on a low-frequency, positively-identified self-driving-PR path. The pre-existing TaskRun-save receiver already ran the identical chain. The proposed caching fix would regress the mid-PR opt-out feature invariant.",+ "set": "O"+ },+ {+ "id": "O18",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:126-139 dispatches only toggle-gated (verified); facade/api.py:145-155 queue_inbox_pr_review calls .delay() with no repo-config check (verified). But receivers.py:213-217 explicitly documents the deferral as deliberate (\"Repo-config gating ... happens inside the queued task ... this stays a plain toggle-gated dispatch\") and facade docstring states the goal: \"the caller's save path never blocks on GitHub or the product DB.\" The suggested has_reviewable_repo_config pre-check is a cross-product-DB query behind a fail-fast circuit breaker (settings.py:72-81 wraps it in try/except for exactly that reason) and would run synchronously in the post_save on_commit path for every dispatch, including the common connected case. Waste in the edge state (toggle on, no synced repo) is one broker publish plus one indexed .exists() no-op, only on inbox PR creation (low frequency), and the UI already disables the toggle when stamphog_connected is false (settings.py:50-54).",+ "notes": "Factually accurate description of intentional, documented behavior. The proposed \"improvement\" would add blocking cross-DB latency to a hot-model save receiver to skip a trivially cheap async no-op in a rare edge state \u2014 it contradicts the stated light-save-path design rather than improving it.",+ "set": "O"+ },+ {+ "id": "O19",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "tasks.py:872-876 runs _inbox_rereview_carve_out whenever skip_reason is not None on the webhook Celery task; tasks.py:169-196 shows bot-authored, same-repo-head PRs proceed to _resolve_repo_config (:179) and, on enabled+synced config, find_signal_implementation_run (:191), which calls find_task_run (facade/api.py:504). webhooks.py:68-76 branch leg filters branch= with task__repository__iexact; TaskRun.Meta.indexes (models.py:1147-1174) index output__pr_url, state__wizard_head_branch, created_at, [task,-created_at,-id], [team,stage,task] \u2014 no branch index, and TaskRun.branch is a plain CharField. No negative-result cache exists on this path. However, the finding's premise \"zero DB access before this PR\" is wrong: the pre-existing head-changing skip path (tasks.py:887-898, unchanged context in pr75215.diff) already ran _resolve_repo_config + _retract_stale_approvals_on_skip for bot PRs on synchronize/reopened. process_pull_request_event is an async @shared_task (tasks.py:809), and the branch-leg query is scoped by the repository join, so it is bounded, not a guaranteed full-table scan.",+ "notes": "Core claim verified: newly-introduced, uncached per-delivery DB work (one extra repo-config lookup + an unindexed branch-leg TaskRun query) for bot-PR head-changing events on Stamphog-enabled repos. But the \"zero DB access before\" premise is overstated (repo-config + approval-retraction queries already ran pre-PR on this exact path), the work runs on an async Celery worker with bounded frequency, and the pr_url leg short-circuits cheaply via its partial index. A legitimate minor inefficiency worth a negative cache and/or branch index, not a fix-now defect \u2014 down-rank should_fix \u2192 consider.",+ "set": "O"+ },+ {+ "id": "O20",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1155-1157 documents the pre-dedupe fetch as deliberate (dedupe keys on the PR's CURRENT head, \"which only GitHub knows\") and that a transient failure \"must not silently lose\" the review since no webhook redelivery backs this leg. tasks.py:1160-1162 already backs off on GitHubRateLimitError with countdown=max(retry_after, 60). receivers.py:82-105 bounds re-fires: created saves, non-output update_fields saves, FAILED/CANCELLED runs, internal tasks, and non-opted-in reviewers all return before enqueueing \u2014 only output-touching saves of the one implementation run fire, each costing one GET that early-exits on the head-sha dedupe (tasks.py:1202-1221).",+ "notes": "The \"no debounce\" observation is factually true but the consequence (rate-limit pressure) is speculative and already mitigated by bounded fire volume plus explicit rate-limit backoff. The suggested pre-fetch cooldown would risk silently dropping a legitimate review of a fresh head landing just after a progress save \u2014 the lost-synchronize case this leg exists to cover. The label-toggle cooldown precedent guards adversarial human spam, a different shape.",+ "set": "O"+ },+ {+ "confidence": "high",+ "evidence": "tasks.py:179 \u2014 _inbox_rereview_carve_out calls _resolve_repo_config for bot-authored fork-safe PRs on head-changing deliveries. tasks.py:876-881 \u2014 when the carve-out sets provenance, the skip return is bypassed and tasks.py:918 calls _resolve_repo_config again on the main path; when opted_out, tasks.py:891 re-calls it as skip_repo_config. tasks.py:289-305 \u2014 _resolve_repo_config is a single writer-pinned point lookup (.filter(...).order_by(...).first()) on StamphogRepoConfig, which is unique per (team, repository), so the duplicate query is a constant sub-ms read on a low-frequency async webhook path.",+ "id": "O21",+ "is_real": true,+ "notes": "The redundant re-query genuinely exists as described, but it is a tiny constant-cost point read on a rare path \u2014 a DRY micro-optimization, not a defect. Threading the config out of _InboxCarveOut is a valid minor cleanup; nothing breaks or degrades measurably without it.",+ "severity": "consider",+ "set": "O"+ },+ {+ "id": "O22",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Verified in worktree: products/stamphog/backend/tasks/tasks.py:1236 is `logger.exception(\"stamphog_inbox_pr_create_run_failed\", repository=repository, pr_number=pr_number)` with no `error=str(e)`, while siblings at :1149 (`stamphog_inbox_pr_config_resolution_failed`) and :1164 (`stamphog_inbox_pr_fetch_failed`) include it. But `logger.exception` records exc_info (full exception message + traceback) automatically, so no error detail is dropped \u2014 the title's claim is inaccurate. Line 1237 also re-raises via Celery retry, so the failure is fully surfaced. The :1161 `logger.warning` rate-limit path likewise omits `error=`, so the field isn't even a uniform in-function convention.",+ "notes": "The field omission exists as described, but the claimed consequence (lost error detail) is false \u2014 logger.exception captures everything via traceback. Adding `error=str(e)` would be a one-word cosmetic consistency tweak for structured-field filtering, purely stylistic, below the defect bar.",+ "set": "O"+ },+ {+ "id": "O23",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": ".stamphog/review-guidance.md:23 lists \"Bot author (dependabot, renovate) \u2014 always needs human review\" under \"Showstoppers (REFUSE or ESCALATE)\"; the PR diff's file list touches neither guidance file. reviewer.py:271 composes REVIEWER_SYSTEM from that file, and the scaffold tail's verdict contract is \"APPROVE: no showstoppers found\". The new _format_self_driving (reviewer.py:683-703) injects \"The author is a machine user ... judge the diff strictly on its own merits\" into TRUSTED CONTEXT without referencing or waiving the showstopper, while the prompt shows the bot author login (reviewer.py:577). The run reaches the LLM only because review_pr.py:225-226 carves the deterministic bot-author refusal out for self_driving, leaving the un-carved LLM showstopper as the sole bot-author instruction. No test exercises real LLM arbitration: test_review_local.py stubs Pipeline._llm_review, e2e fakes emit canned approved output, test_reviewer.py only asserts prompt strings.",+ "notes": "The contradiction is real and unreconciled on the feature's core path, but must_fix overstates it: the \"every run REFUSEs\" outcome is LLM-arbitration speculation, the failure direction is safe (spurious escalate, never wrong approval), and the judge's line-66 meta-rule argument over-generalizes \u2014 that rule is scoped to author familiarity, not all trusted blocks. Real robustness gap with a cheap fix (carve out the showstopper in guidance or have the block explicitly supersede it) \u2192 should_fix.",+ "set": "O"+ },+ {+ "id": "O24",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "reviewer.py:692-702 \u2014 block gated only on cl[\"self_driving\"], hardcodes \"It is a draft on purpose... draft state is not a caution signal\", never reads pr.draft. tasks.py:167-215 \u2014 _inbox_rereview_carve_out fires on _HEAD_CHANGING_ACTIONS for bot-authored self-driving PRs with no pr.draft check; tasks.py:870-881 \u2014 carve-out bypasses the skip, so a synchronize on a now-ready self-driving PR re-reviews with self_driving=True, pr.draft=False. review_pr.py:590 \u2014 draft prerequisite skipped when self_driving, so nothing corrects the false claim; trusted prompt (reviewer.py:552-568) carries no draft/ready field.",+ "notes": "Mechanism and trigger are real and reachable in production, but no concrete harmful consequence: draft state is enforced only by the deterministic gate, not the LLM prompt, so the stale sentence changes no verdict or gate outcome. Prompt-accuracy improvement (condition the sentence on pr.draft), not a defect.",+ "set": "O"+ },+ {+ "id": "O25",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "AGENTS.md's \"exactly two\" sentence is explicitly scoped: \"The engine flag (`self_driving_review`... \u2192 `Pipeline(self_driving=...)`)... It relaxes exactly two gates\" \u2014 the subject is the engine flag, and the code confirms that flag only reaches the engine (reviewer.py:101,131; activities.py:451 sets it from inbox_review provenance). The review-mode/write-permission bypass is a separate webhook-task-layer mechanism: tasks.py:867-869 states \"the toggle is its gate and the review-mode/write-permission gates below don't apply either\", keyed on carve_out.provenance (tasks.py:880), not the Pipeline flag; _author_lacks_write_permission (tasks.py:237) and _review_mode_skip_reason (tasks.py:264) exist only in that layer. The final AGENTS.md bullet (\"These runs bypass the review-mode and author-write-permission gates\") has a different subject (\"these runs\") and sits in the same visible bullet list, which enumerates all four bypasses \u2014 so a reader cannot undercount and there is no contradiction.",+ "notes": "Doc-wording taste nit at most; the finding's own hedge concedes the \"exactly two\" scoping is technically correct, and both statements accurately reflect two distinct code layers with distinct trigger conditions.",+ "set": "O"+ },+ {+ "id": "O26",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1140-1153 \u2014 process_inbox_pr_review filters StamphogRepoConfig with enabled=True, connected_by_user_id__isnull=False, excludes blank installation_id, and returns (silent no-op) if none; docstring at 1123-1124 documents \"Silent no-op without a synced+enabled config\". tasks.py:179-186 \u2014 _inbox_rereview_carve_out returns an empty carve-out unless repo_config exists, is enabled, has installation_id, and connected_by_user_id. AGENTS.md:87-112 \u2014 the \"Rules that keep the exception narrow\" list names only the gates the carve-out relaxes; enabled is not among them, and bullet 3 points to queue_inbox_pr_review whose docstring covers repo-config gating.",+ "notes": "The enabled/installation gate is fully enforced on both the receiver and webhook legs and documented in the same PR's docstrings. The doc never implies the gate is bypassed; the finding reduces to a wish that a non-relaxed gate be restated in the AGENTS.md list \u2014 doc-taste, not a defect.",+ "set": "O"+ },+ {+ "id": "S1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_local.py:321 does use bool(context.get(\"self_driving_review\")), but the only producer is trusted server code: build_reviewer_invocation (products/stamphog/backend/logic/reviewer.py:101,131) takes a typed bool and json.dumps-serializes it, and its sole production caller (products/stamphog/backend/temporal/activities.py:451) passes bool(output.get(\"inbox_review\")). The context field can therefore only be JSON true/false or absent; absent/false both evaluate falsy, so the gate is default-closed. The context JSON is assembled by the token-holding server (review_local.py:16-21 docstring), and PR-author content only appears under nested keys (pr, files, discussion), never as top-level context keys \u2014 no attacker path can inject a truthy non-boolean. The same bool() coercion is the file's convention for the other security gate field (draft=bool(pr.get(\"draft\"))).",+ "notes": "The claimed bypass (truthy string like \"false\") requires the trusted server to malform its own boolean serialization, which the producer's bool() coercion plus json.dumps makes impossible. \"is True\" strictness would be optional hardening, not a fix for a reachable defect.",+ "set": "S"+ },+ {+ "id": "S2",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9 declares dependency on 0018_backfill_urgency_threshold_to_consider; origin/master already has migrations/0019_reviewreport_author_login_and_more.py with the identical 0018 dependency and max_migration.txt = 0019_reviewreport_author_login_and_more; the PR diff rewrites max_migration.txt from 0018_... to 0019_reviewusersettings_stamphog_review_inbox_prs. Two sibling migrations off 0018 = two leaf nodes, failing Django's conflicting-migrations check and the django-linear-migrations single-leaf gate.",+ "notes": "Core conflict verified directly against origin/master. The finding's claim that master extends through 0024_reviewreport_published_head_shas could not be confirmed (local origin/master ends at 0019; fetch blocked by SSH auth), but the 0019-vs-0019 sibling conflict alone is sufficient. Fix is mechanical (rebase_migration review_hog + regenerate max_migration.txt), yet the PR is unmergeable until done.",+ "set": "S"+ },+ {+ "id": "S3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "activities.py:237-238 sets author_pr_numbers=[] when run.output[\"inbox_review\"] is truthy; activities.py:451 derives self_driving_review from the same output key, so self-driving implies empty author_pr_numbers. review_local.py:301-303 early-returns on empty list (familiarity stays None); reviewer.py:644-646 renders \"\" for None familiarity, so the {familiarity_block} at reviewer.py:568 is empty for every self-driving run. _maybe_compute_familiarity (review_pr.py:251) runs only on the Action path, which never receives self_driving_review and refuses bot authors. test_integration.py:1415 pins author_pr_numbers == [] for the inbox e2e.",+ "notes": "The finding's trigger (\"a T1 bot PR with any author_pr_numbers\") cannot occur: the server hard-codes the list to empty for inbox/self-driving runs before the sandbox is provisioned, and both flags key off the same run.output[\"inbox_review\"] so they cannot diverge. The suggested suppression is already implemented one layer up, with a regression test.",+ "set": "S"+ },+ {+ "id": "S4",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:96-140 \u2014 pr_url/task_run_id/signal_report_id all derive from the saved TaskRun inside a trusted post_save receiver (gates: signal_report_id set, task.internal False, resolved acting reviewer + toggle); no external caller supplies them. tasks.py:1178-1183/~1230 \u2014 the provenance ids are only stamped into output={\"inbox_review\": ...}; they drive no fetch, and team scoping is enforced via StamphogRepoConfig.objects.for_team(team_id) (enabled+connected, tasks.py:~1141-1148) and ReviewRun.objects.for_team(team_id). webhooks.py:179-186/203 \u2014 the only in-repo writer of output.pr_url (_record_run_pr_url) requires head.repo.full_name == repository.full_name (fork PRs excluded) and matches only the run's own branch+repo, so the pr_url is constrained to the run's repo-native bot PR. tasks.py:144-178 \u2014 _inbox_rereview_carve_out's bot-author/repo-native checks exist because its input is an arbitrary GitHub webhook; the initial leg's input is not.",+ "notes": "The claimed attack (forged/fork/unrelated human PR entering the self-driving path) has no reachable trigger: every write path of output.pr_url binds it to the run's own repo-native bot PR, and the celery args come from a trusted internal receiver, not a caller. \"Verify stored PR URL matches this PR\" is circular since the passed pr_url is the stored output.pr_url. Residual scenario requires an authenticated same-team insider editing TaskRun.output via the tasks API \u2014 within-tenant, pre-existing surface, not introduced by this PR. Suggestion is defensive belt-and-braces only.",+ "set": "S"+ },+ {+ "id": "S5",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "api.py:504-506 does call unscoped find_task_run then post-filter `run.team_id != team_id -> None`, but the cross-team match is discarded before any field reaches the caller, so the tenant boundary IS enforced and the docstring (api.py:494-496) promises exactly this None behavior \u2014 not \"scoping at the query boundary\". webhooks.py:41-56 pr_url leg keys on globally-unique output__pr_url + repository, so it cannot be shadowed cross-tenant; only the branch fallback (webhooks.py:63-77, .first() under TaskRun Meta ordering -created_at) could let a newer cross-team run win, and that requires pr_url-leg miss plus two teams sharing the same repo and a colliding head branch. Sole caller tasks.py:191 (_inbox_rereview_carve_out) treats None as \"unidentified\" and falls to the normal skip path with head-changing approval retraction \u2014 a missed re-review, fail-safe, never a wrong or cross-tenant approval.",+ "notes": "The security framing is wrong (scoping enforced, no leak) and the \"hidden valid run\" scenario is a contrived multi-tenant shared-repo colliding-branch edge with fail-safe outcome. Adding team_id to the query is valid hygiene, hence consider, but not a defect this PR must fix.",+ "set": "S"+ },+ {+ "id": "S6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Worktree receivers.py:206-207 \u2014 `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` selects one canonical reviewer; receivers.py:159-173 docstring documents this as deliberate (\"Otherwise the **first** resolved reviewer is canonical (maintainer decisions, 2026-07-02/03)\"). The PR diff (pr75215.diff, receivers.py hunk) shows the removed `_resolve_acting_reviewer` already gated `review_inbox_prs` on the same single acting reviewer \u2014 the single-reviewer model predates this PR; the new `stamphog_review_inbox_prs` check (receivers.py:126) and `resolve_stamphog_acting_reviewer` (receivers.py:144-156) intentionally mirror it. New test `test_the_two_toggles_gate_their_reviews_independently` codifies the one-acting-reviewer contract.",+ "notes": "The scenario (opted-out canonical reviewer + opted-in secondary assignee \u2192 no review) does occur, but it is the documented, tested, pre-existing design shared with the sibling review_inbox_prs toggle \u2014 not a regression this PR introduces. The suggested all-assignee scan is a semantics change, not a correctness fix.",+ "set": "S"+ },+ {+ "id": "S7",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "receivers.py:116 and :131 register two on_commit callbacks (ReviewHog first, Stamphog second), both default robust=False; Django halts later non-robust callbacks when an earlier one raises. _start_review's deferred imports at receivers.py:254-255 are outside its try (starts :261), and the outer except at :140 cannot catch post-commit callbacks, so an import failure would both skip the Stamphog dispatch and escape into tasks' save path. However the only pre-try raiser is the module import \u2014 cached after first success, failing only on systemic misconfiguration (e.g. the SANDBOX_PROVIDER env rejection noted in test_inbox_trigger.py) that already breaks every ReviewHog inbox review; the realistic runtime failure (Temporal down) is inside the try at :262 and is swallowed at :272-273.",+ "notes": "Mechanism verified real and the fix (robust=True, imports inside try) matches the module's own fire-and-forget contract, but the trigger is a practically-unreachable systemic import failure with no transient scenario \u2014 a hardening improvement, not a production defect this PR introduces.",+ "set": "S"+ },+ {+ "id": "S8",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1185-1186 \u2014 _upsert_pull_request is the first statement inside the same transaction.atomic block, before the ReviewRun select_for_update at 1202-1210. models.py:119-121 \u2014 unique_stamphog_pull_request on (team_id, repo_config, pr_number) makes concurrent get_or_create serialize: the loser's INSERT blocks on the unique index until the winner's whole transaction (including its ReviewRun create) commits. tasks.py:349-353 + 1037-1044 \u2014 when the PR row exists, the conditional refresh UPDATE takes the PR row lock held to commit (mechanism explicitly documented on the webhook path). tasks.py:1190-1197 \u2014 a strictly newer committed snapshot triggers the stale-snapshot bail before any create. After unblocking, READ COMMITTED lets the loser's filter(pull_request, head_sha) see the winner's committed run (1211), returning without a second create; QUEUED restart is idempotent via WorkflowAlreadyStartedError (375-380). The only lock-free path requires GitHub's GET-PR response to omit updated_at (346-348), which does not happen.",+ "notes": "The finding's premises (no (pull_request, head_sha) unique constraint; select_for_update over an absent row locks nothing) are correct, but its conclusion is wrong: both concurrent fires must first pass through _upsert_pull_request in the same transaction, which serializes them on the PullRequest row (unique-index INSERT wait or UPDATE row lock), so the loser always observes the winner's committed ReviewRun and no-ops. A DB-level idempotency constraint would be defense in depth at most, not a fix for a reachable defect.",+ "set": "S"+ },+ {+ "id": "S9",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "TaskRun.branch (products/tasks/backend/models.py:1081) has no index and is absent from Meta.indexes (models.py:1147-1174, which cover output.pr_url, state.wizard_head_branch, created_at, task+created_at, team+stage+task only). find_task_run's branch leg (products/tasks/backend/webhooks.py:68-78) filters branch + task__repository__iexact (join, iexact defeats btree) + state__wizard_head_branch__isnull=True with no supporting index. The PR's new find_signal_implementation_run (products/tasks/backend/facade/api.py:504) forwards both pr_url and head_branch from the stamphog carve-out (products/stamphog/backend/tasks/tasks.py:191-196), so an unmatched bot PR (e.g. dependabot: bot-authored, repo-native head, stamphog-enabled repo, head-changing action) misses the indexed pr_url leg and executes the unindexed scan. However: it runs inside Celery task process_pull_request_event (tasks.py:809-810), not the webhook request path, and the identical branch-leg query is already invoked pre-PR by the tasks webhook on every opened/closed PR (webhooks.py:159).",+ "notes": "Mechanism verified real, but not a defect this PR introduces: the scan-shaped query is a pre-existing, production-exercised path (tasks webhook backstop); the new caller adds a bounded subset of traffic (head-changing bot PRs on opt-in experimental stamphog repos), executed async in Celery. Valid improvement (index or skip branch fallback when pr_url supplied), not should_fix.",+ "set": "S"+ },+ {+ "id": "S10",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "webhooks.py:68-76 \u2014 non-wizard branch leg filters only on branch + repository + wizard_head_branch__isnull, no output.pr_url consistency check, no terminal-status exclusion; wizard leg at :84-96 does exclude terminal statuses (\"so a reopened branch can't fire events on a dead run\"). models.py:1146 \u2014 TaskRun Meta ordering [\"-created_at\"], so .first() = newest branch match. facade/api.py:504-509 (new in this PR per diff hunk at pr75215.diff:1686) \u2014 find_signal_implementation_run checks only team_id/signal_report_id/internal, never compares the run's recorded output.pr_url to the supplied pr_url. stamphog tasks.py:191-215 \u2014 DTO + opted-in resolver \u2192 provenance that bypasses the bot/draft pre-filters and authorizes a self-driving re-review attributed to the mis-bound run. Reachability gates verified at tasks.py:167-186: only bot-authored, repo-native (head_repo == repo), enabled/connected repo config PRs reach the lookup, and the pr_url-indexed leg wins whenever the incoming PR's URL is recorded \u2014 so mis-binding needs branch reuse across PRs in the team's own repo.",+ "notes": "The code gap is real and introduced by this PR, but the failure needs an abnormal state (second bot PR reusing a prior signals run's head branch, its URL absent from every run's output) and the blast radius is bounded to the team's own bot-authored repo-native PR getting a review with wrong signal-report attribution \u2014 an attacker would already need repo write access. Not must_fix as claimed; a cheap hardening (reject branch match when the run's recorded pr_url differs) is worth doing.",+ "set": "S"+ },+ {+ "id": "S11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Verified in pr75215_tree: process_inbox_pr_review (products/stamphog/backend/tasks/tasks.py:1109-1237) indeed re-checks nothing about opt-in \u2014 gates are only enabled repo config (1140-1147) and PR open/head-sha (1166-1174); acting_user_id is provenance-only (1176-1180). However dispatch is transaction.on_commit immediately after the receiver read settings.stamphog_review_inbox_prs (products/review_hog/backend/receivers.py:126-139), so the checked value is fresh at enqueue; the race window is broker latency + max 3 retries (@shared_task max_retries=3, default_retry_delay=5, tasks.py:1109). The trust contract is explicit and intentional: task docstring \"the receiver resolved the acting reviewer and confirmed their stamphog_review_inbox_prs toggle\" (tasks.py:1115-1116), facade docstring same (facade/api.py:138-139), and _inbox_rereview_carve_out docstring scopes re-checking to \"later deliveries only... the initial review is the receiver leg's job\" and \"safety is never preference-gated\" (tasks.py:160-165). Worst-case harm: one preference-stale review of the team's own bot-authored draft PR; a standing approval is dismissed on the next head-changing event via the opted_out skip path (_INBOX_OPT_OUT_DISMISS_MESSAGE, tasks.py:70-74).",+ "notes": "The finding accurately describes the code but not a defect: the initial-leg/webhook-leg asymmetry is a documented, intentional design (fresh check at dispatch vs re-check on temporally decoupled events). The failure needs a toggle flip inside a seconds-to-minutes window after the agent autonomously opens its own PR, and the outcome self-corrects. Defensive re-checking of an already-fresh value guarding a preference, not safety \u2014 below the defect bar.",+ "set": "S"+ },+ {+ "id": "W1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py handle_task_run_saved schedules dispatch exclusively via transaction.on_commit(lambda: _start_stamphog_review(...)) (products/review_hog/backend/receivers.py, stamphog PR-leg block ~L125-138), so no pre-commit dispatch or rollback race is possible. _start_stamphog_review (receivers.py:210-234) wraps queue_inbox_pr_review in try/except Exception with logger.exception, and the whole receiver body is itself in try/except (L79, L139-140), so a broker outage cannot raise into the TaskRun save. The facade docstring (products/stamphog/backend/facade/api.py, queue_inbox_pr_review) confirms all heavy work runs inside the Celery task; the post-commit .delay() publish is the standard on_commit+Celery pattern CLAUDE.md endorses.",+ "notes": "Both remediations the finding suggests (on_commit scheduling + best-effort error handling/logging) are already implemented at the sole call site; the facade-level synchronous .delay() claim is true but not a defect given the wrapping.",+ "set": "W"+ },+ {+ "id": "W2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_local.py:301-303 \u2014 _attach_familiarity returns immediately when context[\"author_pr_numbers\"] is empty, before _ensure_diff_path/_familiarity_offline (the git analysis). activities.py:237-238 \u2014 server sets author_pr_numbers=[] whenever run.output has inbox_review (explicit comment documenting the skip); activities.py:451 \u2014 self_driving_review=bool(output.get(\"inbox_review\")) reads the same output key; tasks.py:1064/1229 \u2014 inbox_review is stamped at ReviewRun creation, before the fetch activity, and the fetch preserves it (activities.py:246-247). So self_driving=True implies author_pr_numbers=[] by construction, making _attach_familiarity a guaranteed no-op. test_integration.py:1415 asserts context[\"author_pr_numbers\"] == [] for the self-driving path. With familiarity never computed, _format_familiarity renders \"\" (reviewer.py), so no familiarity text appears beside the no-signal provenance block.",+ "notes": "The finding's \"consider also avoiding the upstream merged-PR lookup\" suggestion is already implemented server-side (activities.py:233-238), and both claimed harms (wasted git analysis, contradictory prompt text) are unreachable for self-driving runs. Suggested guard would be dead code.",+ "set": "W"+ },+ {+ "id": "W3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Verified in pr75215_tree: (1) receivers.py:224-234 does swallow-and-log publish failures post-commit (the finding's one true sub-claim), per the documented invariant at line 213 (\"the broker being down must never surface into the saver\") on tasks' hot TaskRun save path. (2) The central claim that \"later webhook handling depends on the initial review having recorded the PR as Inbox-originated\" is false: products/stamphog/backend/tasks/tasks.py:144-215 (_inbox_rereview_carve_out) re-derives self-driving identity per delivery from the payload (bot author line 169, fork check lines 176-178), repo config (179), the tasks facade find_signal_implementation_run (191), and the registered resolver (205) \u2014 nothing persisted by the initial review is read. (3) \"Permanently drop\" is false: the receiver re-fires on every output-touching TaskRun save (receivers.py:76-79) re-attempting the publish, and tasks.py:1124-1128 explicitly designs the head-keyed dedupe around those refires; any later push/reopen re-reviews via the webhook carve-out; once published, process_inbox_pr_review has max_retries=3 with explicit .retry() on config/fetch/rate-limit failures (tasks.py:1109, 1150, 1162, 1165).",+ "notes": "Residual exposure is a broker blip at the exact on-commit instant with no subsequent output save and no further push \u2014 one draft PR's initial review skipped until the next commit, fail-safe and self-healing. The finding's failure scenario (permanent silent loss breaking webhook recognition) does not occur; the suggested outbox/retry machinery would reverse a deliberate, documented tradeoff on a hot save path for an opt-in experiment-gated feature.",+ "set": "W"+ },+ {+ "id": "W4",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree pr75215_tree/products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9 declares dependencies=[(\"review_hog\",\"0018_backfill_urgency_threshold_to_consider\")], and the diff (lines 95-101) sets max_migration.txt to that name. Live master (verified via gh api contents?ref=master) already contains 0019_reviewreport_author_login_and_more.py \u2014 which also depends on 0018 (its lines 7-9) \u2014 plus 0020 through 0024_reviewreport_published_head_shas, with max_migration.txt = \"0024_reviewreport_published_head_shas\". Merging therefore yields two migrations depending on 0018 \u2192 two leaf nodes in the review_hog graph, which Django rejects (\"Conflicting migrations detected; multiple leaf nodes\") and which fails the django-linear-migrations max_migration.txt check. gh pr view 75215 reports mergeStateStatus: DIRTY, confirming the max_migration.txt collision at the git level.",+ "notes": "The PR branched before the 0019-0024 chain landed on master. The suggested fix is correct: renumber to 0025, depend on 0024_reviewreport_published_head_shas, update max_migration.txt. The migration content itself (AddField stamphog_review_inbox_prs, BooleanField db_default=False) is fine \u2014 only the graph position is broken. Cannot deploy as-is, so must_fix stands.",+ "set": "W"+ },+ {+ "id": "W5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "review_local.py:321 does bool(context.get(\"self_driving_review\")) over context loaded at line 396 from a server-written JSON file. The only writer is build_reviewer_invocation (products/stamphog/backend/logic/reviewer.py:101,131), whose parameter is typed bool and whose sole production caller passes self_driving_review=bool(output.get(\"inbox_review\")) (products/stamphog/backend/temporal/activities.py:451) \u2014 a real Python bool that JSON round-trips to True/False. Action-shaped contexts omit the key (review_local.py:316-320 docstring; test_review_local.py:283), yielding None \u2192 False. test_integration.py:1413 asserts the hosted value is literally True. No code path can place a string like \"false\" or \"0\" in this key; the only way is an attacker already controlling the sandbox filesystem, who could write literal true anyway.",+ "notes": "The claimed malformed-truthy-string scenario is unreachable: value is bool-typed end to end and the flag defaults closed when absent. Switching to `is True` changes behavior for no reachable input; at most a defensive-style preference, not a defect.",+ "set": "W"+ },+ {+ "id": "W6",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "All load-bearing claims verified in the frozen worktree.\n\n1) The new initial leg does no linkage/fork/author validation. `products/stamphog/backend/tasks/tasks.py:1109-1245` (`process_inbox_pr_review`, added by this PR \u2014 diff line 1041): it parses `pr_url` (`_parse_pr_url`, L1130), resolves a StamphogRepoConfig by the repository extracted *from that URL* (`for_team(team_id) ... repository__iexact=repository`, L1140-1147), fetches the PR (L1159), checks only `state == \"open\"` (L1166) and non-empty `head_sha` (L1170), then creates a ReviewRun stamped `output={\"inbox_review\": {...signal_report_id, task_run_id, acting_user_id...}}` (L1176-1230). There is no head-repo/fork check, no bot-author check, no `find_signal_implementation_run` call, no `author_association` check, and no `_author_lacks_write_permission` call anywhere in this function. `signal_report_id`/`task_run_id` are copied into provenance, never verified.\n\n2) The sibling webhook leg deliberately does all of it. `tasks.py:144-215` (`_inbox_rereview_carve_out`): `_is_bot_authored(pr)` (L169), an explicit fork check `head_repo != repo \u2192 empty` with the comment \"on a fork PR head.ref is attacker-controlled ... a branch-keyed task match could bind an unrelated fork PR to a run\" (L173-178), and a tasks-facade linkage lookup `find_signal_implementation_run(team_id=repo_config.team_id, repository=repo, pr_url=..., head_branch=...)` plus a `run.team_id` recheck (L189-200). The webhook path additionally runs `_review_skip_reason` (draft/bot/`author_association`, L218-234) and `_author_lacks_write_permission` (L237-257) \u2014 none of which the initial leg executes.\n\n3) The provenance stamp is what turns on the privileged carve-out. `products/stamphog/backend/temporal/activities.py:451` sets `self_driving_review=bool(output.get(\"inbox_review\"))`; in the engine, `tools/pr-approval-agent/review_local.py:321-324` (`if pipeline.pr.author_is_bot and not pipeline.self_driving`) and `review_pr.py:225` / `review_pr.py:590` (`if pr.draft and not self.self_driving`) confirm it relaxes the bot-author and draft refusals. The engine carries no fork/author-association/write-permission gate of its own (grep for fork/head_repo/author_association in `activities.py` returns only comments), so those checks exist *only* in the webhook pre-filter this leg skips. The path ends in a real GitHub approval \u2014 `products/stamphog/backend/tests/test_integration.py:1385 test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end`.\n\n4) The trigger field is attacker-writable through a normal team-scoped API. `products/tasks/backend/presentation/views/api.py:1101-1121` exposes `PATCH .../set_output` with `required_scopes=[\"task:write\"]`; `validate_set_output` (`products/tasks/backend/facade/api.py:2123-2136`) only validates against `task.json_schema` (unset for these tasks), and `set_task_run_output` (L2139-2154) stores any `pr_url` and saves with `update_fields=[\"output\", ...]`. `partial_update` (views/api.py:1082-1090) is a second write path. `TaskWriteSerializer` (`products/tasks/backend/presentation/serializers.py:435-461, 611-614`) lets an API caller set `signal_report` (any report in their own team) and `internal` freely, so a caller can construct a task that satisfies the receiver's `task.signal_report_id is not None` + `not task.internal` guards (`products/review_hog/backend/receivers.py:98-105`) and then point `output.pr_url` at any open PR in a Stamphog-connected repo of that team. The receiver then queues `process_inbox_pr_review` with that URL whenever the resolved acting reviewer has `stamphog_review_inbox_prs` on (receivers.py:111-139).",+ "notes": "Confirmed as described. The initial leg trusts a mutable, API-writable `output.pr_url` to select which PR receives the privileged self-driving treatment, while the sibling webhook leg enforces fork-safety, bot-authorship, and a team-scoped tasks-facade linkage for the same decision \u2014 the asymmetry is real and introduced by this PR. Preconditions limit blast radius (an insider with `task:write` plus a victim reviewer who has the new toggle enabled), and severity could be argued down to should_fix on that basis; I keep must_fix because the outcome is a bot APPROVE on an untrusted/fork PR in an approval-granting path whose own comments call the fork/author gates security-critical, and the minimal remediation (head_repo == base repo, expected bot author) is cheap. The finding's own caveat is correct: `pr_url`-keyed linkage alone would not fix it, since the attacker controls that key.",+ "set": "W"+ },+ {+ "id": "W7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:111-126 resolves one acting reviewer then checks that user's toggles; receivers.py:159-173 docstring documents creator-when-assigned-else-first-resolved as \"maintainer decisions, 2026-07-02/03\" with both toggles gating off that one reviewer; receivers.py:17-23 frames stamphog as \"a second, independent toggle\" on \"the same resolved acting reviewer\"; test_inbox_trigger.py:228-238 test_opted_out_canonical_reviewer_blocks_the_review asserts the finding's exact scenario (canonical opted out, later assignee opted in) must produce NO review (\"a later reviewer's opt-in must not hijack whose options the review runs with\"); test_inbox_trigger.py:255-267 and 324-343 lock in the same single-acting-reviewer model; the diff's own wording (line 873) says \"the acting reviewer currently opted in\", not \"any assignee\".",+ "notes": "The described behavior exists but is the deliberate, documented, test-enforced design; the suggested fix would reverse a tested maintainer decision and split stamphog's eligibility from ReviewHog's shared resolver. Any gap is PR-description wording, not a code defect.",+ "set": "W"+ },+ {+ "id": "W8",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/tasks/backend/facade/api.py:504-505 \u2014 new facade calls unscoped webhooks.find_task_run then post-filters `run.team_id != team_id \u2192 None`. products/tasks/backend/webhooks.py:29-89 \u2014 find_task_run filters by repository only (no team); pr_url leg orders by terminal_rank/-created_at, both branch legs use .first() with no order_by (nondeterministic). So a cross-team row on the same repo can shadow the requesting team's valid run, returning None (false negative). Fail-safe confirmed: stamphog/backend/tasks/tasks.py:191-200 returns an empty carve-out and the skip path still calls _retract_stale_approvals_on_skip (diff ~L967-985), so no stale approval survives \u2014 worst case is one silently missed self-driving re-review. Post-filter never returns another team's run, so tenant isolation holds (no IDOR).",+ "notes": "Mechanism is real and introduced by this PR's new facade wrapper, but the trigger needs the same repo connected to two teams plus a branch-leg collision (pr_url is globally unique and normally resolves first), and the outcome fails safe. Real, cheaply fixable (team_id filter inside the query + deterministic ordering on branch legs), but below the should_fix bar the finding claims.",+ "set": "W"+ },+ {+ "id": "W9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "activities.py:237-238 sets author_pr_numbers=[] when run.output.inbox_review is truthy (is_inbox_review gate, explicit comment); activities.py:402+451 read author_pr_numbers and self_driving_review from the SAME run.output, so self_driving=True implies author_pr_numbers=[]. inbox_review is written only at ReviewRun creation (tasks.py:1064, tasks.py:1229), before the fetch activity, and the output merge at activities.py:246-257 preserves it \u2014 no path yields a self-driving run with populated PR numbers. review_local.py:301-303 short-circuits _attach_familiarity on empty raw_prs, leaving classification[\"familiarity\"] unset, and reviewer.py:644-646 renders \"\" for None \u2014 so familiarity_block at reviewer.py:568 is always empty when self_driving_block is non-empty. reviewer.py:683-690 docstring documents familiarity as \"deliberately absent\" for the carve-out.",+ "notes": "The claimed contradiction (non-empty familiarity block next to the \"no signal\" provenance block) is unreachable: the server couples both signals to one provenance marker per run. A self_driving-keyed familiarity suppression guard would be dead code guarding a state the pipeline already rules out.",+ "set": "W"+ },+ {+ "confidence": "high",+ "evidence": "products/db_routing.yaml routes only stamphog/visual_review/warehouse_sources_queue/agent_platform to product DBs \u2014 tasks/TaskRun is main-DB. posthog/dbrouter.py:22-31 sends reads to \"default\" unless the model is in READ_REPLICA_OPT_IN (posthog/settings/data_stores.py:271, env-driven, empty default), so find_task_run reads the writer by default. Carve-out fires only on synchronize/reopened/base-retarget (products/stamphog/backend/tasks/tasks.py:49,167), never `opened`; TaskRun.branch is set at run creation and output.pr_url at PR-open, both long before any later push, so the <100ms lag window (dbrouter.py docstring) cannot coincide. find_signal_implementation_run (products/tasks/backend/facade/api.py:504) passes both pr_url and head_branch; webhooks.py:64-78 branch leg covers a lagged pr_url write. A miss keeps the skip path, which dismisses stale approvals (tasks.py:876-953, dismiss_stale_approvals_for_head at :509) and re-runs on the next delivery \u2014 not permanent, fails safe.",+ "id": "W10",+ "is_real": false,+ "notes": "The writer-pinned precedent the finding cites applies to stamphog's product-DB models (ReviewRun etc.), which do replica-read by default; TaskRun does not. Three independent refutations: no replica routing established, no plausible lag window on the deliveries that reach this code, and fail-safe + self-healing outcome even if forced.",+ "severity": "not_an_issue",+ "set": "W"+ },+ {+ "id": "W11",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "auto_start.py:244-265 creates the draft-PR-opening implementation task with internal=True (added 2026-07-06, commit 0da0b8dcb7f); receivers.py:104 `if task.internal: return` precedes both the ReviewHog dispatch (115-125) and this PR's new Stamphog dispatch (126-139), and its comment (100-103, \"the auto-start implementation task is the only non-internal signal-report task\") is factually wrong \u2014 the guard landed 2026-07-14 in #64651, after auto-start became internal. The PR's new facade find_signal_implementation_run (products/tasks/backend/facade/api.py:508) also rejects `task.internal`, so for auto-start PRs the webhook re-review leg is dead too: neither toggle can ever produce a review. BUT the finding overstates scope: the Inbox \"Create PR\" click path (frontend/src/scenes/inbox/inboxTaskKickoffLogic.ts:80-96) creates a non-internal task (internal not exposed on TaskWriteSerializer, defaults False) with signal_report set and a bot-authored run (run_source=SignalReport), which passes the guard \u2014 the feature works for click-initiated self-driving PRs.",+ "notes": "Real reachability bug: the autonomous auto-start branch \u2014 the feature's flagship \"self-driving\" scenario, explicitly contemplated by the receiver docstring (\"the auto-start assignee\") \u2014 silently gets neither the initial Stamphog review nor any webhook re-review. Downgraded from must_fix: the claim of total unreachability is wrong (the user-clicked Create PR path works end-to-end), the failure is a fail-safe silent no-op of an opt-in feature (nothing incorrect is posted), and the `task.internal` guard predates this PR (ReviewHog's leg has the same dead path on master); the new Stamphog code inherits it. Suggested fix direction is sound \u2014 record_implementation_task (auto_start.py:271) already provides a positive identifier to replace the internal heuristic.",+ "set": "W"+ },+ {+ "id": "W12",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Verified: tasks.py:1109-1245 (process_inbox_pr_review) indeed does not re-check the toggle and stamps the queued acting_user_id (lines 1176-1181, 1229). But receivers.py:126 checks stamphog_review_inbox_prs immediately before the on_commit dispatch (receivers.py:131-138), so the stale window is only Celery latency plus bounded retries (default_retry_delay=5, max_retries=3, rate-limit countdown >=60s \u2014 tasks.py:1109/1162). The split is deliberate and documented: tasks.py:160-165 states the initial review is the receiver leg's job and that a toggle switched off mid-PR is handled by the skip path's head-changing retraction (\"safety is never preference-gated\"); the webhook leg re-resolves per delivery (tasks.py:201-207) because it spans the PR's lifetime. If the reviewer opts out, the next head-changing delivery resolves opted_out (tasks.py:206-207) and dismisses stale approvals (tasks.py:500-515). The stamped acting_user_id is provenance/attribution only \u2014 it grants no privilege, and any approval is pinned to the head actually reviewed.",+ "notes": "The race is real only in a seconds-to-minutes window on a user preference the reviewer had just affirmatively enabled, with self-correcting retraction on the next push and no security or correctness invariant violated. A defensive re-check inside the task would be a minor nicety at best; the must_fix \"potentially approve the PR\" framing overstates a speculative preference race.",+ "set": "W"+ },+ {+ "id": "W13",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "self_driving=True is only set on the hosted path (review_local.py:321); the Action entrypoint (review_pr.py:984) never passes it. The hosted path runs _run_gates_offline (review_local.py:330), which deliberately omits _summarize_ownership (docstring review_local.py:227-230) and sets ownership_summary via _ownership_summary (review_local.py:242) \u2014 plain \"touches <owners>\" text with no membership claim. author_on_owning_team is set only in _summarize_ownership (review_pr.py:650), so on self-driving runs the key is absent; _format_ownership defaults it to True (reviewer.py:711) and the \"NOTE: Author is NOT on the owning team\" line requires `teams and not on_team` (reviewer.py:718-719), so it can never render in a self-driving prompt.",+ "notes": "The claimed contradictory text (\"Author is NOT on the owning team\" before the provenance block) is structurally unreachable for self-driving runs, because membership summarization only happens on the Action path where self_driving is always False. Even taken at face value, the residual concern is a speculative LLM-weighting worry already addressed by the provenance block's explicit \"org membership carries no signal\" directive (reviewer.py:694-702).",+ "set": "W"+ }+ ],+ "clusters": [+ {+ "issue": "find_signal_implementation_run rejects internal=True tasks but production self-driving implementation tasks are always internal=True, so the webhook carve-out leg is dead",+ "members": ["Y5", "P12", "Q5", "T10", "O6", "W11"]+ },+ {+ "issue": "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "members": [+ "X20",+ "P10",+ "Q18",+ "R3",+ "T7",+ "U2",+ "V3",+ "M9",+ "J2",+ "K11",+ "L4",+ "L6",+ "N10",+ "O9",+ "S4",+ "W6"+ ]+ },+ {+ "issue": "self_driving_review read from context JSON with truthy bool() coercion instead of a strict `is True` check",+ "members": ["X10", "Y12", "P3", "Q9", "R6", "T2", "U11", "V5", "M3", "K12", "N1", "O2", "S1", "W5"]+ },+ {+ "issue": "Engine does not gate familiarity computation/rendering on self_driving, relying on the server omitting author_pr_numbers",+ "members": [+ "X14",+ "Y17",+ "P5",+ "P14",+ "Q2",+ "R7",+ "T9",+ "U6",+ "V10",+ "M4",+ "J3",+ "K5",+ "L2",+ "O16",+ "S3",+ "W2",+ "W9"+ ]+ },+ {+ "issue": "_format_self_driving renders TRUSTED provenance claims (machine author / verified-by-task-linkage) solely off the self_driving flag with no engine-side verification",+ "members": ["X3", "Y3", "O11"]+ },+ {+ "issue": "Draft/bot gate relaxations in Pipeline are keyed only on self_driving, not coupled to pr.author_is_bot",+ "members": ["X9", "P15", "T6", "U12", "V8", "K1", "N12", "O10"]+ },+ {+ "issue": "stamphog_connected SerializerMethodField does an uncached cross-product-DB read on every settings serialization (GET and PATCH)",+ "members": ["X15", "Y6", "P6", "Q13", "U7", "V11", "N4", "O3"]+ },+ {+ "issue": "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "members": ["X12", "Q10", "V9"]+ },+ {+ "issue": "process_inbox_pr_review performs a live GitHub get_pr on every receiver refire before any dedupe",+ "members": ["X16", "P19", "Q16", "U8", "U9", "V6", "V7", "M12", "K13", "L10", "N19", "O20"]+ },+ {+ "issue": "Carve-out path resolves the same StamphogRepoConfig twice (or thrice) per delivery",+ "members": ["Y14", "P7", "Q11", "U13", "V13", "N18", "O21"]+ },+ {+ "issue": "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "members": ["X11", "Q8", "T3"]+ },+ {+ "issue": "Webhook-leg toggle re-check repeats the multi-query reviewer-resolution chain on every synchronize/reopen push (performance)",+ "members": ["P18", "Q17", "N15", "O17"]+ },+ {+ "issue": "_parse_pr_url regex is not host-anchored, so lookalike domains/embedded github.com substrings parse as valid GitHub PR URLs",+ "members": ["Y10", "P1", "M2", "O1"]+ },+ {+ "issue": "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "members": ["Y2", "P2"]+ },+ {+ "issue": "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "members": ["X4", "P23", "W10"]+ },+ {+ "issue": "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "members": ["X13", "Q3"]+ },+ {+ "issue": "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "members": ["X1"]+ },+ {+ "issue": "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "members": ["X2", "U3", "V1", "M7"]+ },+ {+ "issue": "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "members": ["X5"]+ },+ {+ "issue": "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "members": ["X6"]+ },+ {+ "issue": "find_signal_implementation_run still matches cancelled/failed runs and soft-deleted tasks, extending the carve-out past the automation's lifetime",+ "members": ["X7", "V4", "M14", "O5"]+ },+ {+ "issue": "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "members": ["X8"]+ },+ {+ "issue": "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "members": ["X17", "S9"]+ },+ {+ "issue": "Relaxed gates leave no trace in logs/gate messages/posted review comment that the self-driving carve-out fired",+ "members": ["X18", "V16", "N13"]+ },+ {+ "issue": "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "members": ["X19", "T4", "M13", "S7"]+ },+ {+ "issue": "stamphog_review_inbox_prs is PATCH-writable without a server-side stamphog_connected precondition validator",+ "members": ["Y1", "U1"]+ },+ {+ "issue": "Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled-state copy in the UI",+ "members": ["Y4"]+ },+ {+ "issue": "Second synchronous Celery broker publish on the on_commit path with no bounded publish timeout against a hung broker",+ "members": ["Y7"]+ },+ {+ "issue": "Carve-out exception retry path can block the stale-approval safety dismissal for head-changing bot PRs",+ "members": ["Y8", "U14", "V14"]+ },+ {+ "issue": "AGENTS.md carve-out section conflicts with the file's 'every invariant earned through a real review finding' preamble framing",+ "members": ["Y9"]+ },+ {+ "issue": "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "members": ["Y11", "L7", "N11", "O14", "S11", "W12"]+ },+ {+ "issue": "Claimed stranding of QUEUED runs because on_commit workflow restart supposedly runs after the Celery task returns (disproven Django semantics)",+ "members": ["Y13"]+ },+ {+ "issue": "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "members": ["Y15", "N17", "O19"]+ },+ {+ "issue": "Alleged \\s character-class typo in _parse_pr_url making repos containing 's' unparseable (fabricated/misquoted regex)",+ "members": ["Y16"]+ },+ {+ "issue": "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "members": ["P4", "N3", "O24"]+ },+ {+ "issue": "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "members": ["P8"]+ },+ {+ "issue": "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "members": ["P9"]+ },+ {+ "issue": "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "members": ["P11"]+ },+ {+ "issue": "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "members": ["P13", "R4", "T8", "U4", "M11", "J6", "K4", "S5", "W8"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer has no try/except guard despite being invoked from another product's webhook path",+ "members": ["P16", "U10", "V2", "N22"]+ },+ {+ "issue": "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "members": ["P17"]+ },+ {+ "issue": "Alleged check-then-act race in process_inbox_pr_review's dedupe allowing duplicate runs under concurrent refires (serialized by PR row lock)",+ "members": ["P20", "K14", "L8", "O13", "O15", "S8"]+ },+ {+ "issue": "repository__iexact lookup cannot use StamphogRepoConfig's case-sensitive indexes",+ "members": ["P21", "N20"]+ },+ {+ "issue": "stamphog_inbox_pr_create_run_failed log omits the error=str(e) structured field its siblings include",+ "members": ["P22", "N21", "O22"]+ },+ {+ "issue": "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy",+ "members": ["P24"]+ },+ {+ "issue": "Claim that max_migration.txt was not bumped to the new 0019 migration (false against PR head)",+ "members": ["Q1", "R2"]+ },+ {+ "issue": "Engine's stamphog_review_completed analytics event lacks a self-driving marker property",+ "members": ["Q4", "R1"]+ },+ {+ "issue": "AGENTS.md provenance key name (inbox_review vs trigger/stamphog_self_driving_review) suspected of not matching the implementation",+ "members": ["Q6", "K8"]+ },+ {+ "issue": "AGENTS.md carve-out section placement splits the egress-to-trust-boundaries document flow",+ "members": ["Q7"]+ },+ {+ "issue": "Opt-out dismissal copy/log mismatch on a base-retarget delivery (retarget message posted while log says inbox_opt_out)",+ "members": ["Q12"]+ },+ {+ "issue": "Broad except in get_stamphog_connected collapses transient circuit-breaker failures and real bugs into one error-level log",+ "members": ["Q14", "T5", "V12"]+ },+ {+ "issue": "Carve-out pays repo-config and tasks-DB lookups before the cheap resolver-is-None short-circuit",+ "members": ["Q15"]+ },+ {+ "issue": "Opt-out dismissal message claims 'New commits were pushed' on a reopened PR where no commits were pushed",+ "members": ["Q19"]+ },+ {+ "issue": "queue_inbox_pr_review facade does not guard the Celery .delay publish, so broker/serialization errors can raise into the caller's save path",+ "members": ["R5", "W1"]+ },+ {+ "issue": "Claim that tach.toml does not declare the new review_hog -> stamphog dependency (false against PR head, which adds it)",+ "members": ["T1"]+ },+ {+ "issue": "Relaxing the draft gate leaves mergeable_state == \"dirty\" as the only conflict check, which GitHub never reports for drafts, so the merge-conflict gate is inert for self-driving draft PRs",+ "members": ["U5", "V15"]+ },+ {+ "issue": "Stamphog gate keys on a single canonical acting reviewer's toggle, so an opted-in non-canonical assigned reviewer is ignored, contradicting the PR's 'any assigned reviewer opted in' contract",+ "members": ["M1", "M10", "J4", "K2", "K10", "L1", "N14", "O12", "S6", "W7"]+ },+ {+ "issue": "Initial inbox review dispatch is fire-and-forget with no durable pending record or reconciliation, so a broker enqueue failure or exhaustion of the task's three retries silently drops the review",+ "members": ["M5", "M6", "K3", "L9", "W3"]+ },+ {+ "issue": "Claim that the documented carve-out contracts (queue_inbox_pr_review facade, inbox_hooks resolver, engine flag) do not exist in the code \u2014 stale-checkout false positive validating PR docs against a tree without the PR's changes",+ "members": ["M8", "K9", "L5", "N7", "N8"]+ },+ {+ "issue": "Em dash in the new README copy violates the repository's documentation writing style guidance",+ "members": ["J1"]+ },+ {+ "issue": "New review_hog migration numbered 0019 conflicts with master's existing 0019_reviewreport_author_login_and_more leaf (both depend on 0018), producing two migration leaves and a max_migration.txt conflict that break migration checks on merge",+ "members": ["J5", "K6", "L3", "N9", "O7", "S2", "W4"]+ },+ {+ "issue": "Claim that no inbox acting-reviewer resolver is ever registered so the webhook carve-out always fails closed (false \u2014 receivers.connect() registers resolve_stamphog_acting_reviewer at app ready)",+ "members": ["K7"]+ },+ {+ "issue": "find_signal_implementation_run facade leaves fork-safety (head-repo == base-repo) as a documentation-only caller precondition instead of enforcing it inside the facade",+ "members": ["N2"]+ },+ {+ "issue": "queue_inbox_pr_review dispatches its Celery task immediately instead of via transaction.on_commit, risking a phantom task if the caller's transaction rolls back",+ "members": ["N5", "O4"]+ },+ {+ "issue": "Frontend loads stamphog_connected once on mount and never revalidates, so connecting Stamphog elsewhere leaves the switch stuck showing not-connected until reload",+ "members": ["N6"]+ },+ {+ "issue": "Inbox-hook resolver registration in connect() has no duplicate-registration guard equivalent to the sibling post_save dispatch_uid",+ "members": ["N16"]+ },+ {+ "issue": "review_local.py never populates pipeline.provenance, so the self-driving path's commit-trailer audit/analytics fields are always empty",+ "members": ["N23"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer hook trusts caller-supplied team_id/signal_report_id with no verification tying them to the PR being re-reviewed",+ "members": ["O8"]+ },+ {+ "issue": "Receiver dispatches the Stamphog Celery task unconditionally even for teams with no Stamphog installation, paying a guaranteed no-op broker round trip",+ "members": ["O18"]+ },+ {+ "issue": "Self-driving TRUSTED prompt block contradicts the review-guidance.md system prompt's categorical 'bot author always needs human review' showstopper, which the PR never carves out",+ "members": ["O23"]+ },+ {+ "issue": "AGENTS.md's 'relaxes exactly two gates' claim reads as contradicted by the review-mode and author-write-permission bypasses documented two bullets later",+ "members": ["O25"]+ },+ {+ "issue": "AGENTS.md carve-out section never states whether StamphogRepoConfig.enabled (per-repo opt-in) still gates self-driving inbox reviews",+ "members": ["O26"]+ },+ {+ "issue": "find_task_run's branch fallback can bind an unrelated or stale run (whose output.pr_url names a different PR) to the incoming PR, authorizing it as self-driving",+ "members": ["S10"]+ },+ {+ "issue": "Ownership block still renders 'Author is NOT on the owning team' for self-driving machine authors, contradicting the adjacent provenance block's no-signal directive",+ "members": ["W13"]+ }+ ],+ "stats": {+ "M1": {+ "sets": ["X", "P"],+ "total": 44,+ "real": 14,+ "must_fix": 1,+ "should_fix": 5,+ "consider": 8,+ "real_ids": [+ "X3(should_fix)",+ "X7(should_fix)",+ "X9(should_fix)",+ "X12(consider)",+ "X17(consider)",+ "X19(consider)",+ "X20(should_fix)",+ "P4(consider)",+ "P7(consider)",+ "P8(should_fix)",+ "P12(must_fix)",+ "P13(consider)",+ "P17(consider)",+ "P19(consider)"+ ]+ },+ "M2": {+ "sets": ["Y", "Q"],+ "total": 36,+ "real": 7,+ "must_fix": 3,+ "should_fix": 1,+ "consider": 3,+ "real_ids": [+ "Y4(consider)",+ "Y5(must_fix)",+ "Y8(should_fix)",+ "Q5(must_fix)",+ "Q12(consider)",+ "Q18(must_fix)",+ "Q19(consider)"+ ]+ },+ "M3": {+ "sets": ["R", "T"],+ "total": 17,+ "real": 3,+ "must_fix": 2,+ "should_fix": 0,+ "consider": 1,+ "real_ids": ["T6(consider)", "T7(must_fix)", "T10(must_fix)"]+ },+ "M4": {+ "sets": ["U", "V"],+ "total": 30,+ "real": 4,+ "must_fix": 0,+ "should_fix": 2,+ "consider": 2,+ "real_ids": ["U13(consider)", "U14(should_fix)", "V8(should_fix)", "V9(consider)"]+ },+ "M5": {+ "sets": ["M", "K"],+ "total": 28,+ "real": 4,+ "must_fix": 1,+ "should_fix": 1,+ "consider": 2,+ "real_ids": ["M9(should_fix)", "M13(consider)", "M14(consider)", "K6(must_fix)"]+ },+ "M6": {+ "sets": ["J", "L"],+ "total": 16,+ "real": 6,+ "must_fix": 4,+ "should_fix": 1,+ "consider": 1,+ "real_ids": [+ "J4(should_fix)",+ "J5(must_fix)",+ "L3(must_fix)",+ "L4(must_fix)",+ "L6(must_fix)",+ "L9(consider)"+ ]+ },+ "M7": {+ "sets": ["S", "W"],+ "total": 24,+ "real": 8,+ "must_fix": 3,+ "should_fix": 1,+ "consider": 4,+ "real_ids": [+ "S2(must_fix)",+ "S7(consider)",+ "S9(consider)",+ "S10(consider)",+ "W4(must_fix)",+ "W6(must_fix)",+ "W8(consider)",+ "W11(should_fix)"+ ]+ }+ },+ "clusterCoverage": {+ "M1": 36,+ "M2": 31,+ "M3": 13,+ "M4": 17,+ "M5": 17,+ "M6": 11,+ "M7": 16+ },+ "judges": [+ {+ "lens": "recall",+ "ranking": ["M1", "M7", "M2", "M6", "M4", "M5", "M3"],+ "scores": {+ "M1": 9,+ "M7": 5.5,+ "M2": 5,+ "M6": 3.8,+ "M4": 3.2,+ "M5": 3,+ "M3": 2+ },+ "rationale": "I recomputed cluster coverage using only verified-real findings (raw clusterCoverage counts false-positive touches, which don't count as surfaced real issues). M1 is the runaway winner: 14 real findings mapping to 14 distinct clusters \u2014 double the runner-up \u2014 including 5 issues no other model surfaced as real (X3 trusted-provenance rendering, P4 stale draft copy, P8 missing head-dedupe, P17 FAILED-run retry loop, P19 pre-dedupe get_pr). M7 is second with 8 real findings across 7 clusters (S2/W4 migration conflict, W6 receiver-linkage gap, W11 internal=True dead leg, plus unique S10 branch-fallback misbinding). M2 is third: 7 real across 6 clusters, with 3 uniques (Y4, Q12, Q19) and strong hits on the two biggest issues (Y5/Q5, Q18). M6, M4, and M5 all cover exactly 4 distinct real clusters; M6 ranks ahead because 2 of its 4 are unique to it (J4 canonical-reviewer contract contradiction, L9 fire-and-forget drop) and it landed 6 real findings, while M4 (U13, U14, V8, V9) and M5 (M9, M13, M14, K6) surfaced nothing exclusive; M4 edges M5 because its clusters were rarer catches (each found-real by only 2-3 models vs M5's mostly widely-found issues). M3 is last: 3 real findings, 3 clusters (T6, T7, T10), all also found by others."+ },+ {+ "lens": "precision",+ "ranking": ["M6", "M7", "M1", "M2", "M3", "M5", "M4"],+ "scores": {+ "M6": 9,+ "M7": 8,+ "M1": 7,+ "M2": 4.5,+ "M3": 4,+ "M5": 3,+ "M4": 2.5+ },+ "rationale": "Verified-real rates: M6 6/16 (37.5%), M7 8/24 (33.3%), M1 14/44 (31.8%), M2 7/36 (19.4%), M3 3/17 (17.6%), M5 4/28 (14.3%), M4 4/30 (13.3%). M6 wins cleanly: highest rate AND the densest signal per emission \u2014 4 of its 6 reals are must_fix (J5, L3, L4, L6 \u2014 migration-leaf conflict and receiver-leg linkage gaps), so a reviewer reading M6's output wades through the least junk per real bug. M7 is close behind (S2, W4, W6 must_fix) with only 16 junk findings total. M1's rate is respectable and includes the dead-carve-out must_fix P12, but it bought its 14 reals with 30 junk emissions \u2014 the largest absolute wade-through burden on the panel \u2014 and its reals skew consider-grade (8/14), capping it at third. The bottom four all sit under 20%, and their junk includes outright fabrications, which is the worst kind: M2 misquoted a regex into a nonexistent \\s typo (Y16) and asserted disproven Django on_commit semantics (Y13); M3's tiny 17-finding output still contained two claims false against the PR head (T1 tach.toml, R2 max_migration); M5 emitted stale-checkout hallucinations declaring the PR's own facades nonexistent (M8, K9) plus the false resolver-registration claim K7. M4 avoided fabrications but has the worst rate (13.3%), zero must_fix reals, and duplicated its own noise (U8/U9, V6/V7 in the same cluster), earning last place."+ },+ {+ "lens": "impact",+ "ranking": ["M7", "M6", "M2", "M1", "M3", "M5", "M4"],+ "scores": {+ "M7": 9,+ "M6": 8.2,+ "M2": 7.5,+ "M1": 6.3,+ "M3": 4.5,+ "M5": 4.2,+ "M4": 2+ },+ "rationale": "No model owns an exclusive must_fix \u2014 every must_fix falls into three heavy clusters: A dead carve-out leg (internal=True), B receiver-leg provenance spoofing (no PR-to-run linkage), C migration-0019 leaf conflict. M7 is #1 as the only model touching all three with verified findings (S2+W4 must_fix on C in both runs, W6 must_fix on B, W11 should_fix on A) plus the unique security-adjacent S10 (branch fallback authorizing an unrelated run as self-driving). M6 is #2 with the densest heavy output \u2014 4 must_fix (J5/L3 on C both runs, L4/L6 on B) at 6/16 precision plus the uniquely-verified should_fix J4 (canonical-reviewer gate contradicts the any-assigned-reviewer contract) \u2014 but it is fully blind to A. M2 is #3: must_fix on A in both runs (Y5, Q5) and on B (Q18), plus should_fix Y8 (retry path blocking stale-approval dismissal), but it missed the CI-breaking C, and its unique catches (Y4, Q12, Q19) are low-impact copy/UX considers. M1 is #4: only one must_fix (P12 on A) and B only at should_fix (X20), but the strongest should_fix layer \u2014 5 total including two exclusives, X3 (TRUSTED provenance block rendered with zero engine-side verification) and P8 (webhook-leg double-review of the same head) \u2014 and the widest cluster coverage (36/74). M3 is #5: it nailed the two heaviest runtime clusters as must_fix (T10 on A, T7 on B) but delivered only 3 real findings total and missed C. M5 is #6: K6 must_fix on C and M9 should_fix on B, but missed A and added only two shared considers. M4 is #7 by a wide margin: zero must_fix, all four real findings (U14, V8, U13, V9) are shared mid-tier clusters, and it missed A, B, and C entirely."+ }+ ],+ "missingClusterIds": [],+ "stability": {+ "N": {+ "total": 23,+ "real": [+ {+ "id": "N3",+ "severity": "consider"+ },+ {+ "id": "N9",+ "severity": "must_fix"+ },+ {+ "id": "N10",+ "severity": "must_fix"+ },+ {+ "id": "N12",+ "severity": "should_fix"+ },+ {+ "id": "N18",+ "severity": "consider"+ },+ {+ "id": "N21",+ "severity": "consider"+ },+ {+ "id": "N23",+ "severity": "consider"+ }+ ]+ },+ "O": {+ "total": 26,+ "real": [+ {+ "id": "O5",+ "severity": "should_fix"+ },+ {+ "id": "O7",+ "severity": "must_fix"+ },+ {+ "id": "O15",+ "severity": "consider"+ },+ {+ "id": "O19",+ "severity": "consider"+ },+ {+ "id": "O21",+ "severity": "consider"+ },+ {+ "id": "O23",+ "severity": "should_fix"+ },+ {+ "id": "O24",+ "severity": "consider"+ }+ ]+ },+ "realNO": [+ "N3(consider)",+ "N9(must_fix)",+ "N10(must_fix)",+ "N12(should_fix)",+ "N18(consider)",+ "N21(consider)",+ "N23(consider)",+ "O5(should_fix)",+ "O7(must_fix)",+ "O15(consider)",+ "O19(consider)",+ "O21(consider)",+ "O23(should_fix)",+ "O24(consider)"+ ],+ "clustersXP": 36,+ "clustersNO": 33,+ "shared": 18,+ "onlyXP": [+ "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy"+ ],+ "onlyNO": [+ "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "Stamphog gate keys on a single canonical acting reviewer's toggle, so an opted-in non-canonical assigned reviewer is ignored, contradicting the PR's 'any assigned reviewer opted in' contract",+ "Claim that the documented carve-out contracts (queue_inbox_pr_review facade, inbox_hooks resolver, engine flag) do not exist in the code \u2014 stale-checkout false positive validating PR docs against a tree without the PR's changes",+ "New review_hog migration numbered 0019 conflicts with master's existing 0019_reviewreport_author_login_and_more leaf (both depend on 0018), producing two migration leaves and a max_migration.txt conflict that break migration checks on merge",+ "find_signal_implementation_run facade leaves fork-safety (head-repo == base-repo) as a documentation-only caller precondition instead of enforcing it inside the facade",+ "queue_inbox_pr_review dispatches its Celery task immediately instead of via transaction.on_commit, risking a phantom task if the caller's transaction rolls back",+ "Frontend loads stamphog_connected once on mount and never revalidates, so connecting Stamphog elsewhere leaves the switch stuck showing not-connected until reload",+ "Inbox-hook resolver registration in connect() has no duplicate-registration guard equivalent to the sibling post_save dispatch_uid",+ "review_local.py never populates pipeline.provenance, so the self-driving path's commit-trailer audit/analytics fields are always empty",+ "resolve_stamphog_acting_reviewer hook trusts caller-supplied team_id/signal_report_id with no verification tying them to the PR being re-reviewed",+ "Receiver dispatches the Stamphog Celery task unconditionally even for teams with no Stamphog installation, paying a guaranteed no-op broker round trip",+ "Self-driving TRUSTED prompt block contradicts the review-guidance.md system prompt's categorical 'bot author always needs human review' showstopper, which the PR never carves out",+ "AGENTS.md's 'relaxes exactly two gates' claim reads as contradicted by the review-mode and author-write-permission bypasses documented two bullets later",+ "AGENTS.md carve-out section never states whether StamphogRepoConfig.enabled (per-repo opt-in) still gates self-driving inbox reviews"+ ]+ },+ "_meta": {+ "round": 5,+ "date": "2026-07-31",+ "blinding": {+ "N": "A3-sonnet5-stability",+ "O": "A4-sonnet5-stability",+ "S": "I1-gpt56sol",+ "W": "I2-gpt56sol"+ },+ "panel": {+ "M1": "sonnet5(X,P)",+ "M2": "glm52(Y,Q)",+ "M3": "gpt55(R,T)",+ "M4": "opus48(U,V)",+ "M5": "luna(M,K)",+ "M6": "terra(J,L)",+ "M7": "sol(S,W)"+ },+ "note": "N/O verified+clustered for the Sonnet stability annex, excluded from the panel; M1..M6 basis unchanged from round 4."+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round6.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round6.jsonnew file mode 100644index 000000000000..349cb4dfd0cf--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-round6.json@@ -0,0 +1,503 @@+{+ "newVerdicts": [+ {+ "id": "Z1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:113,118 \u2014 regex is unanchored (`.search()` on `github\\.com/([^/\\s]+/[^/\\s]+)/pull/(\\d+)`), so the observation is factually true. But tasks.py:1130-1159 shows the parsed (owner/repo, number) is used only for a team-scoped lookup (`StamphogRepoConfig.objects.for_team(team_id)...filter(repository__iexact=..., enabled=True, connected_by_user_id__isnull=False).exclude(installation_id=\"\")`) and the GitHub fetch uses `repo_config.repository` + `repo_config.installation_id` from the DB \u2014 the URL's scheme/host is never used for any request. receivers.py:126-139 shows pr_url originates from the team's own TaskRun output; an actor who controls it can supply a clean github.com URL, so hostname anchoring blocks nothing. Target space is bounded to the team's own enabled Stamphog repos; no SSRF, no cross-tenant reach, no correctness bug for legitimate GitHub html_urls.",+ "notes": "The claimed attack (spoofed-host URL redirecting the review target) produces the exact same downstream behavior as a well-formed URL from the same actor, so the proposed strict parsing is a security no-op. The genuine gap on this receiver leg (no bot-author/repo-native check on the fetched PR) is finding Z8's territory, not fixable by URL anchoring. Stricter urlparse validation would be harmless polish at most (consider-level style), but as stated the finding's defect and threat are wrong-premise.",+ "set": "Z"+ },+ {+ "id": "Z2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "pr75215_tree/tools/pr-approval-agent/review_local.py:321 does use bool(context.get(\"self_driving_review\")), but the flag's only producer is products/stamphog/backend/temporal/activities.py:451 (self_driving_review=bool(output.get(\"inbox_review\")) \u2014 a real Python bool) feeding products/stamphog/backend/logic/reviewer.py:101,131,137 (parameter typed bool = False, placed in the context dict, serialized via json.dumps), so the context file always contains JSON true/false or omits the key (Action path never sets it, reviewer.py:113-117). bool(True/False/None) is behaviorally identical to `is True` for every reachable input; no path can deliver a truthy string/number/object.",+ "notes": "Speculative defensive-hardening finding: the \"malformed context\" premise is unreachable given the single typed producer, and the context is a server-written sandbox artifact \u2014 anyone able to tamper with it could just write the boolean true, so strict parsing adds no security. The must_fix framing is unjustified.",+ "set": "Z"+ },+ {+ "id": "Z3",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "receivers.py:206 selects one acting reviewer (`next((u for u in resolved if u.id == task_created_by_id), resolved[0])`); lines 114+126 gate the stamphog dispatch on only that user's `stamphog_review_inbox_prs`; lines 151-156 (`resolve_stamphog_acting_reviewer`, registered as stamphog's webhook re-check hook at line 69) return None when that single user's toggle is off. No code path scans the resolved assignee set for any opted-in user. PR 75215 body (fetched) states the gate as any-opted-in three times: \"at least one of the assigned users has stamphog_review_inbox_prs enabled\", \"checks whether any assigned reviewer opted in\", \"nobody is opted in, so no review runs\". Docstring lines 12-15 confirm auto-start tasks are created by the GitHub-integration user (not in the resolved set), so resolved[0] alone gates \u2014 an opted-out first assignee suppresses the review despite a later opted-in assignee, and their mid-PR opt-out halts webhook re-reviews.",+ "notes": "Implementation diverges from the PR's own thrice-stated any-opted-in requirement. Not must_fix: failure mode is fail-safe (skipped review, never a wrong approval), and the module docstring deliberately documents single-acting-reviewer gating for both toggles, giving a defensible intentional-design reading \u2014 but the PR body is the spec and contradicts it.",+ "set": "Z"+ },+ {+ "id": "Z4",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "facade/api.py:504-509 does apply team_id/signal_report_id/internal filters after find_task_run selects one run, and webhooks.py:29-57 selects globally without a team filter \u2014 the structural observation is correct. But the claimed failure (a qualifying self-driving run masked by a non-qualifying one) requires two TaskRuns sharing the same output__pr_url (webhooks.py:41), and a GitHub PR URL belongs to exactly one PR opened by one run lineage; the documented multi-run case (resume, webhooks.py:37-40) is same-team/same-task, so both pass the post-filters and the terminal_rank/-created_at ordering picks the live run. Internal tasks never populate pr_url or a PR head branch, so task.internal has no colliding candidate. If masking did occur, the path fails closed: carve-out stays empty (tasks.py:191-200), the skip path still retracts stale approvals on head-changing deliveries (tasks.py:881-898), so the worst residual is a missed re-review, never a wrong approval or cross-tenant bind (double team check at api.py:505 and tasks.py:199). The unordered branch-leg .first() (webhooks.py:68-76) is pre-existing code untouched by this diff, and the carve-out always passes pr.html_url so the ordered pr_url leg is the resolving path.",+ "notes": "Valid design-robustness suggestion (push predicates into the selection queryset), but the concrete defect scenario needs a duplicate agent-reported pr_url with no legitimate producer, and every failure mode is fail-closed with the stale-approval retraction intact. Improvement, not a defect.",+ "set": "Z"+ },+ {+ "id": "Z5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "activities.py:237-238 skips get_author_merged_pr_numbers when is_inbox_review (from run.output[\"inbox_review\"]), yielding author_pr_numbers=[]. review_local.py:301-303 _attach_familiarity early-returns on empty author_pr_numbers, leaving cl[\"familiarity\"] unset. reviewer.py:644-646 _format_familiarity returns \"\" when familiarity is None, so familiarity_block is empty at reviewer.py:568 whenever self_driving_block renders. Both self_driving_review (activities.py:451) and the fetch gate (activities.py:237) derive from the same run.output[\"inbox_review\"], stamped at trigger time, so they cannot diverge.",+ "notes": "The finding's premise (\"the server fetches merged PR numbers for the bot author\") is directly contradicted by the PR's own companion change in activities.py, which gates the fetch on not is_inbox_review with a comment explaining exactly this design. The bot-familiarity-plus-provenance prompt is unreachable; the suggested guard would be dead code.",+ "set": "Z"+ },+ {+ "id": "Z6",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "reviewer.py:692-702 \u2014 _format_self_driving gates only on cl[\"self_driving\"] and hardcodes \"It is a draft on purpose ... draft state is not a caution signal for this PR\"; pr.draft never consulted. review_local.py:321 \u2014 flag set from context provenance only. products/stamphog/backend/tasks/tasks.py:144-215 \u2014 _inbox_rereview_carve_out has no draft check (gates: head-changing action, bot author, repo-native head, config, facade run, toggle); tasks.py:226-231 \u2014 non-draft bot PR yields skip_reason \"bot_author\"; tasks.py:880-881 \u2014 carve-out provenance overrides the skip, so a ready-for-review self-driving PR receiving synchronize is re-reviewed with the false draft assertion. tasks.py:160-165 docstring explicitly keeps re-reviewing after the ready flip; review_pr.py:587-591 waives the draft prerequisite for self-driving, so nothing downstream blocks the non-draft path.",+ "notes": "Reachable (draft flipped ready + later push) and factually confirmed, but purely a prompt-accuracy inaccuracy: the false sentence's actionable part (\"draft state is not a caution signal\") is inert on a non-draft PR and \"judge the diff strictly on its own merits\" governs \u2014 no concrete wrong-verdict mechanism. Cheap conditional fix worth making; not a production defect.",+ "set": "Z"+ },+ {+ "id": "Z7",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "receivers.py:224-234 \u2014 catch is `except Exception: logger.exception(\"review_hog_stamphog_inbox_review_queue_failed\")`, running in a transaction.on_commit callback (line 131) where raising would propagate into the tasks save path the module contract (lines 75-77, docstring line 213) explicitly forbids; identical to the pre-existing accepted `_start_review` leg (lines 261-273, context in diff). facade/api.py:128-155 \u2014 the dispatch is a single Celery `.delay()` broker publish. receivers.py:77-79 \u2014 repeat output-saves deliberately re-fire the receiver and re-dispatch; receivers.py:144-156 \u2014 later pushes re-review via stamphog's webhook path with a fresh toggle check. Loss requires broker-down at the exact on-commit instant with no later save and no later push; consequence is a missed best-effort review, never a wrong approval.",+ "notes": "Mechanics accurately described but the \"permanently drops\" defect claim is refuted by the documented re-fire and webhook recovery paths; swallow-and-log is a deliberate, structurally required convention for this on_commit save-path callback. The proposed durable outbox is disproportionate for a fail-safe best-effort dispatch and would equally apply to the long-standing sibling leg.",+ "set": "Z"+ },+ {+ "id": "Z8",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "tasks.py:1166-1181 \u2014 process_inbox_pr_review checks only pr.state==\"open\" and non-empty head_sha before stamping inbox_review provenance from Celery args; no _is_bot_authored, no head.repo-vs-base-repo (fork) check, no find_signal_implementation_run binding. Contrast tasks.py:169-200 where the webhook carve-out requires all three before granting the same provenance. Downstream: activities.py:451 sets self_driving_review from that provenance; review_pr.py:225 (bot-author refusal) and :590 (draft prereq) are bypassed when self_driving is true, and grep confirms the engine has no fork/author-association gate; _author_lacks_write_permission and _review_skip_reason run only in process_pull_request_event, never on the initial leg. Source of pr_url: receivers.py:93,126-139 reads TaskRun.output[\"pr_url\"], writable via set_output (task:write, presentation/views/api.py:1107-1121) with validate_set_output (facade/api.py:2123) checking only task.json_schema \u2014 no PR-to-run binding. tasks.py:84-108 documents the invariant this bypasses (fork/under-privileged authors must never get an auto-approval satisfying required reviews). process_inbox_pr_review is new in this diff (pr75215.diff +1040).",+ "notes": "Real security gate gap introduced by this PR: the receiver leg is the only route into self-driving review mode with fork-safety, bot-authorship, and run-linkage enforced nowhere, and pr_url is agent/API-reported data. Bounded to the team's own enabled Stamphog repos and gated on the acting reviewer's toggle, but a redirected URL (agent mistake, prompt injection, or any task:write caller) gets a fork or human PR privileged-reviewed and potentially approved, with retraction only on a later push. The finding's suggestion overstates two points (Celery args aren't externally injectable; webhook re-reviews do verify provenance) \u2014 the fix that matters is bot-author + repo-native + facade run-binding checks on the fetched PR in process_inbox_pr_review.",+ "set": "Z"+ },+ {+ "id": "Z9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:1185-1186 \u2014 _upsert_pull_request runs first inside the same transaction.atomic as the dedupe/create. tasks.py:349-354 \u2014 its conditional UPDATE on the PR row takes a write lock held to commit; for identical concurrent snapshots (equal updated_at, lte matches) the second fire blocks here until the first commits its ReviewRun, then its existing-run SELECT (tasks.py:1202-1210, READ COMMITTED) sees the committed QUEUED run and no-ops or idempotently restarts (tasks.py:1211-1221; _start_review_workflow swallows WorkflowAlreadyStartedError, tasks.py:366-380). First-ever fire: get_or_create INSERTs contend on UniqueConstraint(team_id, repo_config, pr_number) \"unique_stamphog_pull_request\" (models.py:120-122), so the loser waits for the winner's commit, IntegrityError-retries the get, and again sees the committed run. Stale-loser path covered by refresh_from_db (tasks.py:360-362) + locked recheck (tasks.py:1191-1197). Only unserialized branch is incoming_updated_at is None (tasks.py:346-348), unreachable for GitHub PR payloads which always carry updated_at. Webhook path documents this exact PR-row-lock serialization design (tasks.py:1037-1044).",+ "notes": "The finding assumes dedup relies solely on select_for_update over matching ReviewRun rows; it overlooks that _upsert_pull_request's conditional UPDATE (or the PullRequest unique-constraint insert wait) serializes the whole check-and-create before the existing-run SELECT. Racing fires with different heads legitimately create a new run with supersession \u2014 intended re-review, not duplication. Suggested PullRequest-row locking is effectively already what the code does.",+ "set": "Z"+ },+ {+ "id": "Z10",+ "is_real": false,+ "severity": "consider",+ "confidence": "high",+ "evidence": "receivers.py:126-139 checks stamphog_review_inbox_prs immediately before on_commit dispatch; tasks.py:1109-1245 (process_inbox_pr_review) confirmed to never re-resolve the toggle (max_retries=3, default_retry_delay=5, rate-limit retry max(retry_after,60) \u2014 window is seconds to ~minutes); tasks.py:159-165 docstring states initial-leg scope and \"safety is never preference-gated\" as deliberate design; tasks.py:887-898 dismisses any standing approval with _INBOX_OPT_OUT_DISMISS_MESSAGE on the next head-changing delivery when carve_out.opted_out; carve-out (tasks.py:144-215) + resolve_stamphog_acting_reviewer (receivers.py:144-157) confirm only the webhook leg rechecks.",+ "notes": "Code asymmetry is factually accurate, but it is a documented deliberate design with a tiny race window, a benign target (the user's own linked self-driving draft PR they were opted into seconds earlier), and a safety backstop that retracts any post-opt-out approval on the next head change. Re-checking inside the task wouldn't fully close the race either. Not a must_fix defect; at most a cheap consistency hardening.",+ "set": "Z"+ },+ {+ "id": "E1",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "tasks.py:124-127 `_is_bot_authored` = `user.type==\"Bot\"` OR `\"[bot]\" in login`; tasks.py:169-172 carve-out gates only on that plus a comment asserting unenforced App-machine-user authorship; webhooks.py:64-77 branch leg matches branch+repo with NO terminal-run exclusion (wizard leg below does exclude) and no author identity; facade/api.py:510-516 SignalImplementationRunDTO carries no PR-author/bot identity; tasks.py:881/944/967-968 provenance bypasses pre-filter, review-mode, and write-permission gates; tasks.py:1062-1064 provenance keys the engine's self-driving behavior, so engine-side bot/draft refusals are bypassed too; github_client.py:53-69 + AGENTS.md:33-34 document that approval-adjacent decisions must use exact `<slug>[bot]` (allow_any_bot=False), which this path violates.",+ "notes": "Verified exploit chain: any other installed bot with repo write access can reuse a signal-run branch name (terminal runs match forever), open a repo-native PR, push a synchronize, and inherit the full draft/bot/review-mode/write-permission bypass \u2014 StampHog then reviews and can mint a standing approval satisfying branch protection on a non-self-driving PR. Preconditions (compromised/malicious bot with write access, opted-in acting reviewer, branch collision) are within the product's own threat model; the fix (require expected_app_bot_login() on pr.user and fail closed) matches the existing allow_any_bot=False pattern. Minor citation slip in the finding: invariant text lives in AGENTS.md, not CLAUDE.md.",+ "set": "E"+ },+ {+ "id": "E2",+ "is_real": true,+ "severity": "must_fix",+ "confidence": "high",+ "evidence": "PR worktree pr75215_tree/products/review_hog/backend/migrations/ contains 0019_reviewusersettings_stamphog_review_inbox_prs.py (generated 2026-07-21) depending on (\"review_hog\", \"0018_backfill_urgency_threshold_to_consider\"), and its max_migration.txt reads \"0019_reviewusersettings_stamphog_review_inbox_prs\". origin/master already has 0019_reviewreport_author_login_and_more.py (generated 2026-07-22) which also depends on 0018, plus a chain through 0024_reviewreport_published_head_shas, with master's max_migration.txt = \"0024_reviewreport_published_head_shas\". So 0018 gains two children on merge, producing two leaf nodes (0024 and the new 0019) \u2014 Django's migration loader raises \"Conflicting migrations detected\" on migrate/makemigrations. django_linear_migrations is installed (posthog/settings/web.py:207 in the current repo), so the single-leaf/max_migration.txt consistency check also fails in CI, and max_migration.txt itself is a guaranteed textual merge conflict (PR says new 0019, master says 0024).",+ "notes": "All three \"Found\" bullets verified against ground truth. The PR branch predates master's 0019\u20130024 chain; the fix (rebase_migration to 0025 + update max_migration.txt) is standard and correct. must_fix: the migration cannot apply once merged with master and CI blocks on it.",+ "set": "E"+ },+ {+ "id": "E3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "models.py:309-313 load() has no .using(); products/db_routing.yaml omits review_hog so ProductDBRouter.db_for_read returns None (product_db_router.py:27-35); ReplicaRouter.db_for_read (posthog/dbrouter.py:22-31) returns \"default\" unless the model name is in READ_REPLICA_OPT_IN, which is env-driven and empty by default (posthog/settings/data_stores.py:271-272) with no opt-in for ReviewUserSettings \u2014 reads already hit the primary.",+ "notes": "The stale-replica scenario is unreachable: ReviewUserSettings is a main-DB model whose reads route to \"default\" (the writer). The suggested .using(db_for_write(...)) resolves to \"default\" too \u2014 a no-op. Stamphog's writer-pinning convention applies only to its registered product DB with a lagged reader alias and was misapplied here.",+ "set": "E"+ },+ {+ "id": "E4",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "tasks.py:1206-1207 \u2014 inbox dedup filters on (pull_request, head_sha) and excludes FAILED, so a FAILED run at the same head never satisfies `existing` and a new ReviewRun is created each fire; no attempt cap or cooldown exists. receivers.py:85-96,126-139 \u2014 receiver fires on every TaskRun save touching `output` with pr_url, gated only by the TaskRun's status; docstrings (receivers.py:5-7,77-79; tasks.py:1124-1128) confirm repeat saves with an unchanged head are expected and rely on the head-keyed dedupe to no-op, which FAILED runs escape. temporal/client.py:43 \u2014 workflow id `stamphog-review-{review_run_id}` is per-row, so each new row launches a fresh full sandbox+LLM+GitHub workflow. activities.py:820-847 \u2014 mark_review_failed runs after an unrecoverable (post-retry) workflow error, so deterministic failures recur on every relaunch. test_tasks.py:979 \u2014 `(FAILED, \"sha-1\", \"new\", 2)` codifies retry-after-FAILED as intended, but with no transient/deterministic distinction or budget.",+ "notes": "Mechanism fully verified in this PR's new code. Mitigating nuance: relaunches are bounded by TaskRun output-save frequency (per agent turn), toggle- and assignee-gated, and transient failures self-heal \u2014 so it's uncapped resource amplification under a deterministic-failure precondition, not an infinite loop. The retry-after-FAILED is deliberately tested design for transient recovery; the missing piece is a per-(PR, head) attempt cap or cooldown. should_fix is the right severity.",+ "set": "E"+ }+ ],+ "clusters": [+ {+ "issue": "find_signal_implementation_run rejects internal=True tasks but production self-driving implementation tasks are always internal=True, so the webhook carve-out leg is dead",+ "members": ["Y5", "P12", "Q5", "T10", "O6", "W11"]+ },+ {+ "issue": "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "members": [+ "X20",+ "P10",+ "Q18",+ "R3",+ "T7",+ "U2",+ "V3",+ "M9",+ "J2",+ "K11",+ "L4",+ "L6",+ "N10",+ "O9",+ "S4",+ "W6",+ "Z8"+ ]+ },+ {+ "issue": "self_driving_review read from context JSON with truthy bool() coercion instead of a strict `is True` check",+ "members": ["X10", "Y12", "P3", "Q9", "R6", "T2", "U11", "V5", "M3", "K12", "N1", "O2", "S1", "W5", "Z2"]+ },+ {+ "issue": "Engine does not gate familiarity computation/rendering on self_driving, relying on the server omitting author_pr_numbers",+ "members": [+ "X14",+ "Y17",+ "P5",+ "P14",+ "Q2",+ "R7",+ "T9",+ "U6",+ "V10",+ "M4",+ "J3",+ "K5",+ "L2",+ "O16",+ "S3",+ "W2",+ "W9",+ "Z5"+ ]+ },+ {+ "issue": "_format_self_driving renders TRUSTED provenance claims (machine author / verified-by-task-linkage) solely off the self_driving flag with no engine-side verification",+ "members": ["X3", "Y3", "O11"]+ },+ {+ "issue": "Draft/bot gate relaxations in Pipeline are keyed only on self_driving, not coupled to pr.author_is_bot",+ "members": ["X9", "P15", "T6", "U12", "V8", "K1", "N12", "O10"]+ },+ {+ "issue": "stamphog_connected SerializerMethodField does an uncached cross-product-DB read on every settings serialization (GET and PATCH)",+ "members": ["X15", "Y6", "P6", "Q13", "U7", "V11", "N4", "O3"]+ },+ {+ "issue": "stamphog_connected is a project-wide any-repo check, so the toggle can appear active for inbox PRs whose specific repo has no Stamphog config",+ "members": ["X12", "Q10", "V9"]+ },+ {+ "issue": "process_inbox_pr_review performs a live GitHub get_pr on every receiver refire before any dedupe",+ "members": ["X16", "P19", "Q16", "U8", "U9", "V6", "V7", "M12", "K13", "L10", "N19", "O20"]+ },+ {+ "issue": "Carve-out path resolves the same StamphogRepoConfig twice (or thrice) per delivery",+ "members": ["Y14", "P7", "Q11", "U13", "V13", "N18", "O21"]+ },+ {+ "issue": "Webhook-leg resolver re-runs the full acting-reviewer resolution (latest suggested_reviewers artefact + org-login mapping) on every push, so the gating identity can drift from the leg-1 reviewer",+ "members": ["X11", "Q8", "T3"]+ },+ {+ "issue": "Webhook-leg toggle re-check repeats the multi-query reviewer-resolution chain on every synchronize/reopen push (performance)",+ "members": ["P18", "Q17", "N15", "O17"]+ },+ {+ "issue": "_parse_pr_url regex is not host-anchored, so lookalike domains/embedded github.com substrings parse as valid GitHub PR URLs",+ "members": ["Y10", "P1", "M2", "O1", "Z1"]+ },+ {+ "issue": "inbox_review provenance is an implicit, untyped ad-hoc dict contract (bare truthiness read, hand-built shape duplicated across both trigger legs)",+ "members": ["Y2", "P2"]+ },+ {+ "issue": "find_signal_implementation_run's underlying find_task_run read is not pinned to the writer DB despite gating the carve-out side effect",+ "members": ["X4", "P23", "W10"]+ },+ {+ "issue": "Exception-safety of _start_stamphog_review's deferred facade import relative to its try/except (import-failure handling of the stamphog on_commit leg)",+ "members": ["X13", "Q3"]+ },+ {+ "issue": "queue_inbox_pr_review facade trusts caller-supplied acting_user_id with no team-membership ownership check",+ "members": ["X1"]+ },+ {+ "issue": "has_reviewable_repo_config omits the provider=\"github\" filter used by sibling repo-config lookups",+ "members": ["X2", "U3", "V1", "M7"]+ },+ {+ "issue": "AGENTS.md Engine parity section lacks a cross-reference to the new self_driving runtime divergence",+ "members": ["X5"]+ },+ {+ "issue": "signal_report_id typed loosely (str vs Any/UUID) across the cross-product resolver hook boundary",+ "members": ["X6"]+ },+ {+ "issue": "find_signal_implementation_run still matches cancelled/failed runs and soft-deleted tasks, extending the carve-out past the automation's lifetime",+ "members": ["X7", "V4", "M14", "O5"]+ },+ {+ "issue": "Self-driving identification relies solely on the deprecated Task.signal_report field without origin_product corroboration",+ "members": ["X8"]+ },+ {+ "issue": "Unindexed TaskRun.branch fallback leg causes sequential scans for non-matching bot PR webhooks",+ "members": ["X17", "S9"]+ },+ {+ "issue": "Relaxed gates leave no trace in logs/gate messages/posted review comment that the self-driving carve-out fired",+ "members": ["X18", "V16", "N13"]+ },+ {+ "issue": "Two on_commit hooks registered with robust=False, so an exception in the first silently cancels the stamphog hook",+ "members": ["X19", "T4", "M13", "S7"]+ },+ {+ "issue": "stamphog_review_inbox_prs is PATCH-writable without a server-side stamphog_connected precondition validator",+ "members": ["Y1", "U1"]+ },+ {+ "issue": "Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled-state copy in the UI",+ "members": ["Y4"]+ },+ {+ "issue": "Second synchronous Celery broker publish on the on_commit path with no bounded publish timeout against a hung broker",+ "members": ["Y7"]+ },+ {+ "issue": "Carve-out exception retry path can block the stale-approval safety dismissal for head-changing bot PRs",+ "members": ["Y8", "U14", "V14"]+ },+ {+ "issue": "AGENTS.md carve-out section conflicts with the file's 'every invariant earned through a real review finding' preamble framing",+ "members": ["Y9"]+ },+ {+ "issue": "Receiver leg does not re-validate the acting reviewer's toggle at task execution time (queue-time trust)",+ "members": ["Y11", "L7", "N11", "O14", "S11", "W12", "Z10"]+ },+ {+ "issue": "Claimed stranding of QUEUED runs because on_commit workflow restart supposedly runs after the Celery task returns (disproven Django semantics)",+ "members": ["Y13"]+ },+ {+ "issue": "Claimed per-event cost of running the tasks-facade lookup plus review_hog resolver on every bot-authored head-changing webhook",+ "members": ["Y15", "N17", "O19"]+ },+ {+ "issue": "Alleged \\s character-class typo in _parse_pr_url making repos containing 's' unparseable (fabricated/misquoted regex)",+ "members": ["Y16"]+ },+ {+ "issue": "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "members": ["P4", "N3", "O24", "Z6"]+ },+ {+ "issue": "Webhook leg's supersede+create path has no head-based dedupe against receiver-leg runs, double-reviewing the same head",+ "members": ["P8"]+ },+ {+ "issue": "AGENTS.md carve-out bypass enumeration omits the untrusted_author_association branch of _review_skip_reason",+ "members": ["P9"]+ },+ {+ "issue": "Redundant stamphog_pr_url local alias before the on_commit lambda",+ "members": ["P11"]+ },+ {+ "issue": "find_task_run queries TaskRun unscoped and enforces the tenant boundary only via post-hoc run.team_id recheck",+ "members": ["P13", "R4", "T8", "U4", "M11", "J6", "K4", "S5", "W8", "Z4"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer has no try/except guard despite being invoked from another product's webhook path",+ "members": ["P16", "U10", "V2", "N22"]+ },+ {+ "issue": "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "members": ["P17", "E4"]+ },+ {+ "issue": "Alleged check-then-act race in process_inbox_pr_review's dedupe allowing duplicate runs under concurrent refires (serialized by PR row lock)",+ "members": ["P20", "K14", "L8", "O13", "O15", "S8", "Z9"]+ },+ {+ "issue": "repository__iexact lookup cannot use StamphogRepoConfig's case-sensitive indexes",+ "members": ["P21", "N20"]+ },+ {+ "issue": "stamphog_inbox_pr_create_run_failed log omits the error=str(e) structured field its siblings include",+ "members": ["P22", "N21", "O22"]+ },+ {+ "issue": "Meta-finding: PR diff absent from the checked-out tree, declaring the review context untrustworthy",+ "members": ["P24"]+ },+ {+ "issue": "Claim that max_migration.txt was not bumped to the new 0019 migration (false against PR head)",+ "members": ["Q1", "R2"]+ },+ {+ "issue": "Engine's stamphog_review_completed analytics event lacks a self-driving marker property",+ "members": ["Q4", "R1"]+ },+ {+ "issue": "AGENTS.md provenance key name (inbox_review vs trigger/stamphog_self_driving_review) suspected of not matching the implementation",+ "members": ["Q6", "K8"]+ },+ {+ "issue": "AGENTS.md carve-out section placement splits the egress-to-trust-boundaries document flow",+ "members": ["Q7"]+ },+ {+ "issue": "Opt-out dismissal copy/log mismatch on a base-retarget delivery (retarget message posted while log says inbox_opt_out)",+ "members": ["Q12"]+ },+ {+ "issue": "Broad except in get_stamphog_connected collapses transient circuit-breaker failures and real bugs into one error-level log",+ "members": ["Q14", "T5", "V12"]+ },+ {+ "issue": "Carve-out pays repo-config and tasks-DB lookups before the cheap resolver-is-None short-circuit",+ "members": ["Q15"]+ },+ {+ "issue": "Opt-out dismissal message claims 'New commits were pushed' on a reopened PR where no commits were pushed",+ "members": ["Q19"]+ },+ {+ "issue": "queue_inbox_pr_review facade does not guard the Celery .delay publish, so broker/serialization errors can raise into the caller's save path",+ "members": ["R5", "W1"]+ },+ {+ "issue": "Claim that tach.toml does not declare the new review_hog -> stamphog dependency (false against PR head, which adds it)",+ "members": ["T1"]+ },+ {+ "issue": "Relaxing the draft gate leaves mergeable_state == \"dirty\" as the only conflict check, which GitHub never reports for drafts, so the merge-conflict gate is inert for self-driving draft PRs",+ "members": ["U5", "V15"]+ },+ {+ "issue": "Stamphog gate keys on a single canonical acting reviewer's toggle, so an opted-in non-canonical assigned reviewer is ignored, contradicting the PR's 'any assigned reviewer opted in' contract",+ "members": ["M1", "M10", "J4", "K2", "K10", "L1", "N14", "O12", "S6", "W7", "Z3"]+ },+ {+ "issue": "Initial inbox review dispatch is fire-and-forget with no durable pending record or reconciliation, so a broker enqueue failure or exhaustion of the task's three retries silently drops the review",+ "members": ["M5", "M6", "K3", "L9", "W3", "Z7"]+ },+ {+ "issue": "Claim that the documented carve-out contracts (queue_inbox_pr_review facade, inbox_hooks resolver, engine flag) do not exist in the code \u2014 stale-checkout false positive validating PR docs against a tree without the PR's changes",+ "members": ["M8", "K9", "L5", "N7", "N8"]+ },+ {+ "issue": "Em dash in the new README copy violates the repository's documentation writing style guidance",+ "members": ["J1"]+ },+ {+ "issue": "New review_hog migration numbered 0019 conflicts with master's existing 0019_reviewreport_author_login_and_more leaf (both depend on 0018), producing two migration leaves and a max_migration.txt conflict that break migration checks on merge",+ "members": ["J5", "K6", "L3", "N9", "O7", "S2", "W4", "E2"]+ },+ {+ "issue": "Claim that no inbox acting-reviewer resolver is ever registered so the webhook carve-out always fails closed (false \u2014 receivers.connect() registers resolve_stamphog_acting_reviewer at app ready)",+ "members": ["K7"]+ },+ {+ "issue": "find_signal_implementation_run facade leaves fork-safety (head-repo == base-repo) as a documentation-only caller precondition instead of enforcing it inside the facade",+ "members": ["N2"]+ },+ {+ "issue": "queue_inbox_pr_review dispatches its Celery task immediately instead of via transaction.on_commit, risking a phantom task if the caller's transaction rolls back",+ "members": ["N5", "O4"]+ },+ {+ "issue": "Frontend loads stamphog_connected once on mount and never revalidates, so connecting Stamphog elsewhere leaves the switch stuck showing not-connected until reload",+ "members": ["N6"]+ },+ {+ "issue": "Inbox-hook resolver registration in connect() has no duplicate-registration guard equivalent to the sibling post_save dispatch_uid",+ "members": ["N16"]+ },+ {+ "issue": "review_local.py never populates pipeline.provenance, so the self-driving path's commit-trailer audit/analytics fields are always empty",+ "members": ["N23"]+ },+ {+ "issue": "resolve_stamphog_acting_reviewer hook trusts caller-supplied team_id/signal_report_id with no verification tying them to the PR being re-reviewed",+ "members": ["O8"]+ },+ {+ "issue": "Receiver dispatches the Stamphog Celery task unconditionally even for teams with no Stamphog installation, paying a guaranteed no-op broker round trip",+ "members": ["O18"]+ },+ {+ "issue": "Self-driving TRUSTED prompt block contradicts the review-guidance.md system prompt's categorical 'bot author always needs human review' showstopper, which the PR never carves out",+ "members": ["O23"]+ },+ {+ "issue": "AGENTS.md's 'relaxes exactly two gates' claim reads as contradicted by the review-mode and author-write-permission bypasses documented two bullets later",+ "members": ["O25"]+ },+ {+ "issue": "AGENTS.md carve-out section never states whether StamphogRepoConfig.enabled (per-repo opt-in) still gates self-driving inbox reviews",+ "members": ["O26"]+ },+ {+ "issue": "find_task_run's branch fallback can bind an unrelated or stale run (whose output.pr_url names a different PR) to the incoming PR, authorizing it as self-driving",+ "members": ["S10"]+ },+ {+ "issue": "Ownership block still renders 'Author is NOT on the owning team' for self-driving machine authors, contradicting the adjacent provenance block's no-signal directive",+ "members": ["W13"]+ },+ {+ "issue": "Webhook carve-out accepts any GitHub bot as the self-driving author (_is_bot_authored any-Bot floor) instead of requiring the expected PostHog Code App bot login, so another installed bot with write access can inherit the gate bypass",+ "members": ["E1"]+ },+ {+ "issue": "Claim that ReviewUserSettings toggle gates read from a lagging replica and need writer-DB pinning (false \u2014 the model is main-DB and load() already reads the primary)",+ "members": ["E3"]+ }+ ],+ "metrics": {+ "Z": {+ "total": 10,+ "real": ["Z3(should_fix)", "Z6(consider)", "Z8(must_fix)"]+ },+ "E": {+ "total": 4,+ "real": ["E1(must_fix)", "E2(must_fix)", "E4(should_fix)"]+ },+ "emissionDupZE": [],+ "unionRealClusters": [+ "Receiver leg (process_inbox_pr_review) stamps inbox_review/self_driving with no positive PR-to-run linkage or bot-author verification, unlike the webhook leg",+ "Hard-coded 'It is a draft on purpose' provenance sentence renders even when the self-driving PR is no longer a draft",+ "Receiver-leg dedupe excludes FAILED runs, so a persistently failing head is retried on every refire with no cooldown",+ "Stamphog gate keys on a single canonical acting reviewer's toggle, so an opted-in non-canonical assigned reviewer is ignored, contradicting the PR's 'any assigned reviewer opted in' contract",+ "New review_hog migration numbered 0019 conflicts with master's existing 0019_reviewreport_author_login_and_more leaf (both depend on 0018), producing two migration leaves and a max_migration.txt conflict that break migration checks on merge",+ "Webhook carve-out accepts any GitHub bot as the self-driving author (_is_bot_authored any-Bot floor) instead of requiring the expected PostHog Code App bot login, so another installed bot with write access can inherit the gate bypass"+ ],+ "totalClusters": 76+ },+ "missingClusterIds": [],+ "_meta": {+ "round": 6,+ "date": "2026-07-31",+ "blinding": {+ "Z": "J1-gpt56sol-seq-1 (blind turn)",+ "E": "J2-gpt56sol-seq-2 (turn 2 with native prior-findings injection, run_index=2 findings only)"+ },+ "note": "Arm J sequential Sol: J1 blind, empty commit a7fb363 (head bump, identical tree), J2 with <already_covered_findings_for_chunk> injection."+ }+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-setP.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-setP.jsonnew file mode 100644index 000000000000..6bdb95817553--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/judge-setP.json@@ -0,0 +1,199 @@+{+ "_meta": {+ "set": "P = A-sonnet5-xhigh-2"+ },+ "pVerdicts": [+ {+ "id": "P1",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:113-121 \u2014 the unanchored `.search()` parse exists exactly as described. However: (a) the sole caller is process_inbox_pr_review (tasks.py:1130), whose pr_url is a Celery argument sourced from TaskRun.output[\"pr_url\"] via review_hog's receiver (products/review_hog/backend/receivers.py:93, 225-231) \u2014 internal platform-written data, no HTTP/webhook path; (b) the parsed repository is only a filter term in a team-scoped config lookup that no-ops on no match (tasks.py:1140-1153), and the GitHub fetch uses repo_config.repository, not the parsed string (tasks.py:1159), so only pr_number carries through and it targets a repo the team's own App installation already authorizes.",+ "notes": "The code observation is factually accurate, but there is no reachable consequence: a decoy github.com substring can neither redirect a request (fetch host/repo come from the matched team-scoped config) nor bypass any auth boundary. The finding's own harm framing is future-speculative (\"easy to reuse later against a less-trusted source\"), i.e. it depends on a hypothetical call site that doesn't exist. Anchoring the regex would be harmless hygiene but fixes nothing user-affecting today."+ },+ {+ "id": "P2",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Build sites: products/stamphog/backend/tasks/tasks.py:209-214 (webhook leg) and tasks.py:1176-1181 (receiver leg) duplicate the 4-key dict as described. But every consumer keys on presence only, never an inner key: temporal/activities.py:175 (`if (run.output or {}).get(\"inbox_review\")`), activities.py:237 (`is_inbox_review = bool(...)`), activities.py:451 (`self_driving_review=bool(output.get(\"inbox_review\"))`), and tasks.py:881/944/968/1064 (`inbox_review is None` gates). A grep across the PR tree for any getitem/.get on trigger/task_run_id/signal_report_id/acting_user_id out of inbox_review finds zero readers \u2014 the inner keys are a write-only provenance record.",+ "notes": "The finding's stated consequence (a one-sided inner-key rename \"would silently break the flag/attribution\") is mechanically false: renaming an inner key leaves the dict non-empty, so bool()/presence checks \u2014 including the security-relevant self_driving_review flag and the analytics stamp \u2014 are unchanged. Both dicts are always 4-key/non-empty when stamped, so presence implies truthy. What survives is a DRY/style suggestion (shared TypedDict for two literals in the same file) guarding a hypothetical future refactor \u2014 speculative future-proofing with no reachable correctness, security, contract, or attribution impact today."+ },+ {+ "id": "P3",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Read site confirmed: tools/pr-approval-agent/review_local.py:321 uses bool(context.get(\"self_driving_review\")). But the sole producer chain is fully typed-bool: products/stamphog/backend/temporal/activities.py:451 sets self_driving_review=bool(output.get(\"inbox_review\")) (a Python bool), products/stamphog/backend/logic/reviewer.py:101 declares the param as `self_driving_review: bool = False` and line 131 writes it into the context dict, serialized via json.dumps (line 137) as JSON true/false. JSON round-trip yields Python True/False/absent(None) at the read site \u2014 for every producible value, bool(x) and (x is True) are behaviorally identical. Integration test products/stamphog/backend/tests/test_integration.py:1413 asserts context[\"self_driving_review\"] is True on the real decoded payload. The Action runtime never sets the key (defaults closed, per reviewer.py:113-117 docstring), so the missing-key case is also covered.",+ "notes": "The finding's trigger is explicitly \"a future bug in the server's context-assembly\" producing a truthy string like \"false\" or \"0\" \u2014 a value the typed pipeline (bool coercion at activities.py:451 + typed bool param + json.dumps) cannot produce today. Speculative defensive hardening, not a reachable defect. The trust-boundary framing also fails: the context JSON is server-produced trusted input written into the sandbox; any party able to forge that file could just write the literal true, so `is True` defends against nothing reachable. Suggested change (`is True`) is harmless hygiene but there is no user-affecting failure mode with the current code."+ },+ {+ "id": "P4",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "reviewer.py:692-702 renders \"It is a draft on purpose ... draft state is not a caution signal for this PR\" unconditionally when cl[\"self_driving\"] is truthy, with no draft-state check. The stale scenario is reachable as designed: tasks.py:162 documents that a ready_for_review flip keeps the draft-time verdict (no re-review), while synchronize/reopened (tasks.py:49 _HEAD_CHANGING_ACTIONS) do re-review \u2014 so a later push after a draft\u2192ready flip runs the engine with self_driving=True and pr.draft=False, and the trusted prompt block asserts a false present-tense draft status. However, pr.draft feeds nothing else in the prompt (its only other uses are the analytics property \"stamphog_draft\" at reviewer.py:363 and the draft gate at review_pr.py:590, which self-driving bypasses anyway), so the stale clause is inert: it only relaxes a caution that no longer applies, contradicts no other prompt fact, and cannot change a verdict or any posted output.",+ "notes": "The finding's mechanical premise survives scrutiny \u2014 the sentence can render present-tense-false on a re-review of a ready-flipped self-driving PR. But its should_fix rating overstates the stakes: the consequence is one inert clause in an LLM prompt with no behavioral, security, or user-visible effect. Worth the trivial reword the finding suggests (condition on actual draft state or soften to \"If this PR is still a draft...\"), so it's a valid low-stakes observation, not a defect. Note also that under the currently-shipped code the re-review legs are gated by the P12 internal-task bug, which further narrows present-day reachability, though that is a separate defect slated for fixing."+ },+ {+ "id": "P5",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "reviewer.py:505-506 does render familiarity and self-driving blocks independently, and _attach_familiarity (review_local.py:292-311) has no self_driving guard. But the only caller that sets self_driving=True is stamphog: activities.py:237-238 forces author_pr_numbers=[] whenever inbox_review is set (with an explicit comment stating why), and activities.py:451 sets self_driving_review from that same inbox_review flag. Empty author_pr_numbers \u2192 _attach_familiarity early-returns \u2192 familiarity=None \u2192 _format_familiarity returns \"\" (reviewer.py:645-646). The Action path (review_pr.py:200-207) never sets self_driving. So a populated familiarity block and the self-driving provenance block cannot co-occur.",+ "notes": "The finding is factually accurate about the engine code but its failure scenario is conditional on an input no call site can produce; the single-flag derivation at the caller is deliberate and documented. This is a defense-in-depth suggestion (redundant engine-side enforcement of a caller-guaranteed invariant), not a reachable correctness defect. Reasonable people could keep it as a hardening 'consider', but under precision-over-recall criteria it should be dropped."+ },+ {+ "id": "P6",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/api/settings.py:73-82 (get_stamphog_connected calls has_reviewable_repo_config in fail-soft try/except); same file, user_settings PATCH branch does serializer.save() then Response(serializer.data), re-rendering the field; products/stamphog/backend/facade/api.py:112-124 (the check is one team-scoped indexed .exists()).",+ "notes": "Factual premise is accurate \u2014 PATCH does pay one extra cross-product-DB .exists() per write \u2014 but the cost is a single lightweight indexed query on a human-driven, low-frequency per-user settings endpoint, wrapped in fail-soft error handling. Returning serializer.data after save is the standard DRF pattern. Suggested remedies (PATCH/GET schema asymmetry or cross-DB caching with invalidation) add more complexity than the query costs. Micro-optimization with no user-affecting impact; drop."+ },+ {+ "id": "P7",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:179 (`repo_config = _resolve_repo_config(installation_id, repo)` inside `_inbox_rereview_carve_out`) and tasks.py:918 (identical call in `process_pull_request_event` main path). For a qualifying inbox re-review, `skip_reason` is always set (self-driving PRs are bot-authored drafts, per comment at ~line 869), so the carve-out runs and resolves the config; when it returns a non-None provenance the function proceeds to line 918 and re-runs the exact same writer-pinned query. A base retarget adds a third call at line 858. `_resolve_repo_config` (def at ~line 289 region) is a single `.filter(provider, installation_id, repository).order_by(\"created_at\",\"id\").first()` point lookup on the small StamphogRepoConfig table.",+ "notes": "The redundant read exists exactly as described, so it is not speculative. But impact is negligible: one extra indexed point-lookup on a tiny table, on a cold path (only bot-authored self-driving inbox PRs receiving synchronize/reopen/retarget webhooks), not N+1 or hot-loop. The handler deliberately re-resolves config in each branch inside its own retry-wrapped try/except (lines 858, 891, 918), so threading the carve-out's config through would couple the helper's return to the main path for a sub-millisecond saving. Valid low-stakes observation; the original should_fix severity overstates it \u2014 consider is right."+ },+ {+ "id": "P8",+ "is_real": true,+ "severity": "should_fix",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py: carve-out bypasses gates (~L945 mode gate `if inbox_review is None`, ~L968 permission gate) and reaches the shared supersede+create block (~L1054-1065) which calls _supersede_prior_runs (L415-432, head-agnostic: supersedes ALL non-terminal runs) then unconditionally creates a run \u2014 no head_sha dedup. Leg 1, process_inbox_pr_review (L1110+), has exactly that guard: select_for_update on (pull_request, head_sha) excluding SUPERSEDED/FAILED (~L1204-1213), no-op/restart on match; its docstring admits it re-fires per TaskRun output save and backstops heads \"the webhook leg never delivered\". Stale-payload checks (~L1017-1030, ~L1041-1052) compare PR-level updated_at, equal for one push on both legs, so they don't block; delivery-id resume can't match leg-1 runs (delivery_id=None, L1227). Carve-out fires on _HEAD_CHANGING_ACTIONS/base retarget (L168-169), i.e., the events following self-driving pushes.",+ "notes": "Confirmed asymmetry: when the receiver leg wins the race for a push, the subsequent synchronize webhook supersedes its in-flight run and starts a duplicate full sandbox+LLM review of the identical head. Not a correctness/security issue \u2014 the superseded-status guard prevents double-approval \u2014 so this is bounded, race-gated compute waste on an opt-in feature. The reviewer's \"must_fix / routine on every push\" claim overstates frequency (output saves usually land after the push, letting the webhook win and leg 1 no-op), but the defect is real and the fix is a small mirror of leg 1's existing head-keyed dedup in the inbox_review branch. Note: finding cites pr_tasks.py, but both legs live in tasks.py \u2014 location details otherwise accurate."+ },+ {+ "id": "P9",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tasks.py:218-234 \u2014 _review_skip_reason short-circuits draft \u2192 bot_author before the association check; tasks.py:~172 \u2014 _inbox_rereview_carve_out requires _is_bot_authored(pr), so the association branch is unreachable for carved-out PRs, refuting \"that third gate would refuse the PR\". tasks.py:870-881 \u2014 bypass is wholesale (`skip_reason is not None and inbox_review is None`), not gate-by-gate, so no per-gate enumeration is missing. AGENTS.md:94-96 \u2014 the \"exactly two gates\" claim is scoped to the engine flag (Pipeline(self_driving=...)), not _review_skip_reason; AGENTS.md:81-84 already frames the carve-out as the exception to the whole pre-filter. _inbox_rereview_carve_out docstring lists all five gates including author association. test_tasks.py:761-795 \u2014 carve-out test drives author_association \"NONE\" and asserts a run queues (\"Any one gate accidentally re-applied breaks this\"), precluding the claimed silent break.",+ "notes": "Documentation-precision nit whose technical premise is mistaken: the untrusted_author_association branch never fires for bot-authored carved-out PRs, the webhook-leg bypass relaxes all three pre-filter reasons together by mechanism, the exhaustive gate list already exists in the carve-out docstring, and the feared re-applied-gate regression is covered by CI. No correctness, security, or contract defect."+ },+ {+ "id": "P10",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1110-1245 (team-scoped repo_config at 1140-1147, for_team ReviewRun at 1204/1223); products/review_hog/backend/receivers.py:92-141 (sole caller derives pr_url/task_run_id/signal_report_id/team_id from the TaskRun itself after signal_report_id-not-None and not-internal checks); products/tasks/backend/facade/api.py:484-517 + products/tasks/backend/webhooks.py:41 (find_signal_implementation_run matches via output__pr_url \u2014 the same field the receiver read, so the suggested recheck is circular); products/stamphog/backend/temporal/activities.py:448-451.",+ "notes": "The factual observation (no find_signal_implementation_run call inside process_inbox_pr_review) is accurate, but the conclusion is wrong. Verification of the PR-to-run linkage happens at the trigger: the only caller is review_hog's TaskRun receiver, which derives every argument from the identified non-internal, signal-report-linked run it fires on. The suggested fix would re-resolve the run via output__pr_url \u2014 the exact field the trigger read \u2014 so it detects none of the hypothesized failures (buggy receiver, stale output.pr_url, races). Blast radius is bounded to the team's own synced+enabled repo (for_team + connected_by_user check), not \"an arbitrary PR\". Skipping the bot/draft gates is the deliberate purpose of the inbox leg. All offered failure triggers are speculative future-caller/defense-in-depth scenarios, which map to the drop categories."+ },+ {+ "id": "P11",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/receivers.py:93 (`pr_url = output.get(\"pr_url\") or None`, sole assignment), :116-125 (`_start_review` lambda closes over `pr_url` directly), :130-139 (`stamphog_pr_url = pr_url` alias passed as `pr_url=stamphog_pr_url`). No loop exists in the function and `pr_url` is never reassigned after line 93, so both closures capture the same immutable value.",+ "notes": "The factual observation is accurate \u2014 the alias is redundant \u2014 but it has no behavioral difference whatsoever; both with and without the alias the lambdas resolve to the same value at commit time. This is a pure style/readability nit, which the criteria explicitly exclude (not correctness, security, reliability, contract, or performance). No user-affecting damage possible."+ },+ {+ "confidence": "high",+ "evidence": "facade/api.py:507-509 (new in PR, diff line 1718) returns None when task.internal; but the only production creator of the PR-opening signal-report implementation task sets internal=True (products/signals/backend/auto_start.py:261, made deliberate by master commit 0da0b8dcb7f / #68752). Other signal-report tasks (research.py:717, custom_agent/base.py:629) are also internal=True; only the dev seed command seed_inbox_data.py:279 uses internal=False. So for every real self-driving PR the function returns None, and _inbox_rereview_carve_out (stamphog/backend/tasks/tasks.py:191-215) always returns an empty carve-out before calling the resolver \u2014 the webhook re-review leg and the opted_out branch are unreachable. Tests only pass because _make_run defaults internal=False (test_webhooks.py:1245) and the internal=True case (line 1290) asserts None, codifying the falsified assumption.",+ "id": "P12",+ "is_real": true,+ "notes": "Every factual claim in the finding verified against the PR head tree and repo git history. The internal-exclusion should likely be inverted or dropped (find_task_run's pr_url/branch match already excludes plumbing tasks, which never carry a pr_url). The same stale assumption also sits on the pre-existing receiver leg (review_hog/backend/receivers.py:100-105 'if task.internal: return'), so the defect is broader than this PR alone. A fix should include a test using the real production shape (origin_product=SIGNAL_REPORT, internal=True, run.output.pr_url set).",+ "severity": "must_fix"+ },+ {+ "id": "P13",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "Unscoped query confirmed: products/tasks/backend/webhooks.py:41 (`TaskRun.objects.filter(output__pr_url=pr_url)`, plain manager, no team filter; branch leg lines 63-95 likewise). Post-hoc tenancy enforcement confirmed: products/tasks/backend/facade/api.py:505 (`if run is None or run.team_id != team_id: return None`), DTO built from run.team_id at api.py:513. Sole caller products/stamphog/backend/tasks/tasks.py:191-201 rechecks `run.team_id != repo_config.team_id` and falls back to the strict `_InboxCarveOut()` path \u2014 fail-closed twice over.",+ "notes": "The described code pattern exists exactly as claimed, but there is no current cross-tenant data exposure: the boundary is enforced in the facade and independently rechecked by the only caller, and every mismatch path fails closed to the stricter no-carve-out behavior. The unscoped-then-scope idiom is pre-existing and necessary for the webhook backstop, where the team is unknown until the run is found. The only concrete effect of not scoping at SQL level is a safe false-negative (a foreign-team run sharing pr_url+repository could shadow the correct team's run, making the carve-out silently not apply). Named harm is a hypothetical future refactor dropping the recheck \u2014 speculative. Pushing team_id into the query when supplied would be a small genuine improvement (fixes the shadow edge and hardens the boundary at the data layer), so this is a valid low-stakes hardening suggestion, not a must/should fix."+ },+ {+ "id": "P14",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_pr.py:984-985 \u2014 the only caller of Pipeline.run() is main(), which constructs Pipeline(args.pr_number, args.repo, dry_run=..., verbose=...) with no self_driving argument, and argparse (review_pr.py:974-980) exposes no --self-driving flag; so Pipeline(self_driving=True).run() has zero call sites. The self-driving runtime is review_local.py:314-321, which sets self_driving=True but never calls Pipeline.run() or _compute_familiarity(); it drives steps manually and attaches familiarity via _attach_familiarity (review_local.py:293-311), which is fully offline (_familiarity_offline over context-injected author_pr_numbers) and no-ops when the server omits author_pr_numbers. The live gh fetch in _compute_familiarity (review_pr.py:536-550) is reachable only from _maybe_compute_familiarity at review_pr.py:251, i.e. only via the non-self-driving Action CLI path.",+ "notes": "The finding's own trigger condition \u2014 \"if Pipeline(..., self_driving=True).run() is ever exercised\" \u2014 cannot occur in the reviewed code: the flag exists on Pipeline to share the relaxed-gate checks (author_is_bot and not self_driving at review_pr.py:225; pr.draft and not self_driving at review_pr.py:590) with review_local.py, not to route self-driving reviews through the network runtime. The claimed contradiction (bot history feeding the reviewer prompt while _format_self_driving says familiarity carries no signal) requires a caller that doesn't exist. Gating _compute_familiarity on self.self_driving would be pure defense-in-depth for a hypothetical future caller, and wiring self_driving into the network runtime would itself be a reviewable change. Speculative what-if guarding an unreachable path; the invariant is already enforced by both existing callers."+ },+ {+ "id": "P15",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "tools/pr-approval-agent/review_pr.py:590 (`if pr.draft and not self.self_driving:`) and :225 (`if self.pr.author_is_bot and not self.self_driving:`) \u2014 each gate tests its own subject; self_driving relaxes both. No caller can set self_driving=True on a non-bot PR: review_pr.py:973-984 main() never passes the flag (no --self-driving CLI arg), and the sole producer chain is review_local.py:321 `self_driving=bool(context.get(\"self_driving_review\"))` \u2190 products/stamphog/backend/temporal/activities.py:451 `self_driving_review=bool(output.get(\"inbox_review\"))`, stamped only on runs positively linked to signals implementation tasks, which open bot-authored draft PRs by construction (Pipeline.__init__ docstring, review_pr.py:202-209).",+ "notes": "The finding's trigger is explicitly \"a caller-side bug that sets self_driving=True without author_is_bot also being true\" \u2014 a hypothetical the current call sites rule out. Even if it fired, the bypass only skips the draft caution prerequisite in _check_prerequisites (review_pr.py:584-607); deny-list, size, tier gates and the LLM review still run and can REFUSE/ESCALATE, so it is not an approval-forcing gate. The suggested compound condition is redundant defensive coupling of two independent gates. Classic defensive-paranoia / speculative what-if; drop."+ },+ {+ "id": "P16",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "Sole production caller is _inbox_rereview_carve_out (products/stamphog/backend/tasks/tasks.py:201-205), invoked at tasks.py:876 inside try/except Exception that logs and retries the Celery task (tasks.py:875-879), with a comment explaining the webhook is already ACKed and a transient failure must retry rather than drop. Grep of the whole tree shows no other production invocation of the hook (only the registry in stamphog/backend/facade/inbox_hooks.py and a test patch target).",+ "notes": "The finding's premise \u2014 that the exception propagates into an unguarded webhook path \u2014 is factually wrong: the caller wraps the call and this runs in a Celery task, not the HTTP handler. Worse, the suggested swallow-and-return-None fix would regress: tasks.py:206-207 treats None as _InboxCarveOut(opted_out=True), routing a transient DB blip into the skip-dismiss branch that dismisses the standing approval with the opt-out message (tasks.py:894-898) and silently drops the legitimate re-review \u2014 exactly what the caller's retry design prevents. Propagating to the guarded caller is the correct contract for this hook."+ },+ {+ "id": "P17",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "Dedupe confirmed at products/stamphog/backend/tasks/tasks.py:1202-1207 (tree): `.exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))`, so a FAILED run at the current head_sha is not treated as handled; execution then falls through to `_supersede_prior_runs` + `ReviewRun.objects...create(...)` + `_start_review_workflow` (tasks.py:1222-1234) \u2014 a fresh full review. No cooldown exists on this leg: `STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS` (tasks.py:78) is applied only on the label webhook path (tasks.py:1095). The trigger is genuinely repeated: review_hog's `handle_task_run_saved` fires on every TaskRun save touching `output` with a `pr_url` (products/review_hog/backend/receivers.py:86-96, 126-139), and its docstring assumes a same-head refire \"costs one fetch (early-exit)\" \u2014 which stops being true once the run at that head is FAILED.",+ "notes": "Real code behavior, exactly as described, but the claimed impact (\"retried on every refire\", \"unbounded sandbox/LLM budget\") is materially overstated. Mitigations visible in the tree: (1) refires arriving while a run at the head is QUEUED/GATED/REVIEWING/COMPLETED early-exit (tasks.py:1211-1221) \u2014 QUEUED/GATED/COMPLETED are the non-excluded statuses per facade/enums.py:19-26 \u2014 so a new attempt can only start after the prior run terminally FAILs via the workflow's `mark_review_failed` (temporal/activities.py:820), i.e. cadence is throttled to roughly one attempt per failed-review duration, not per output save; (2) total spend is bounded by the self-driving task's finite lifetime and save frequency; (3) sandbox cost per retry is only incurred if the deterministic failure happens after provisioning \u2014 an early fetch_context failure retries cheaply. Excluding FAILED is also a deliberate transient-recovery design (GitHub blips, sandbox hiccups should get another shot); the genuine gap is only the missing backoff/cap for the rarer deterministic-failure + continuous-refire combination. Valid low-priority hardening note (mirror the label-path cooldown per (pull_request, head_sha)), not a should_fix."+ },+ {+ "id": "P18",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/review_hog/backend/receivers.py:146-158 \u2014 resolve_stamphog_acting_reviewer does re-run _resolve_assigned_reviewer + ReviewUserSettings.load per webhook-leg call, but the chain is a fixed-cardinality ~7-9 indexed queries (logins capped at MAX_SUGGESTED_REVIEWERS). Caller products/stamphog/backend/tasks/tasks.py:167-215 gates it behind head-changing action, bot-authored, non-fork, enabled-config, and signal-run-match checks in a background Celery webhook task; a proceeding event triggers a full sandbox+LLM review that dwarfs the query cost. Freshness is deliberate: _resolve_assigned_reviewer's docstring mandates the report's *latest* suggested_reviewers artefact, and resolve_stamphog_acting_reviewer's docstring states the hook exists so \"switching the toggle off mid-PR stops new stamphog runs\" \u2014 the suggested caching would apply a stale reviewer's toggle/settings.",+ "notes": "The factual description of the code is accurate, but the performance impact does not clear any realistic bar: bounded constant query count, low-frequency opt-in background path, cost dwarfed by the LLM review it gates. The remediation (memoize resolved reviewer per PR) would break the deliberate freshness contract for both the reviewer set and the mid-PR toggle-off behavior, making it a correctness regression rather than an optimization."+ },+ {+ "id": "P19",+ "is_real": true,+ "severity": "consider",+ "confidence": "high",+ "evidence": "tasks.py:1158-1159 \u2014 get_pr runs before the head-keyed dedupe (tasks.py:1202-1210), and github_client.py caches only the installation token, so every output-save refire is one live REST read. But the fetch is required for correctness: the dedupe keys on the PR's current head SHA, which only GitHub knows (comment at tasks.py:1155-1157); the receiver only carries pr_url/head_branch, never the SHA (receivers.py:93-94). The cost is documented as accepted (receivers.py:78-79 \"a same-head re-trigger costs one fetch (early-exit)\"), all expensive stages are gated behind the dedupe, and GitHubRateLimitError already gets warn+retry with backoff (tasks.py:1160-1162).",+ "notes": "The factual observation is accurate, but this is a deliberate, commented design, not an oversight. The suggested \"pass the head the receiver knows\" is unworkable (receiver knows branch name, not SHA), and a short-TTL pr_url cache would silently break the lost-synchronize recovery the leg exists for (docstring tasks.py:1125-1128) to save single cheap REST reads. Rate-limit exhaustion is speculative for an opt-in, low-frequency path with per-installation budgets in the thousands/hour and graceful backoff on 429. Valid low-stakes efficiency note at most; not should_fix."+ },+ {+ "id": "P20",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1185-1186 \u2014 the dedupe runs inside transaction.atomic() AFTER _upsert_pull_request; tasks.py:349-355 \u2014 _upsert_pull_request's conditional UPDATE on the PullRequest row acquires a Postgres row lock held to commit, serializing concurrent invocations for the same PR before either reaches the dedupe check (the webhook path documents this exact mechanism at tasks.py:1036-1039 and this task reuses the same helper in the same transaction shape); products/stamphog/backend/models.py:118-122 \u2014 unique_stamphog_pull_request on (team_id, repo_config, pr_number) closes the brand-new-PR corner: the losing get_or_create INSERT blocks on the winner's uncommitted INSERT until the winner's full transaction (including its ReviewRun.create) commits, then IntegrityError \u2192 retry-get \u2192 the loser's dedupe SELECT (tasks.py:1204-1221, fresh read-committed snapshot) sees the committed run and no-ops.",+ "notes": "The finding's core premise (\"nothing to lock on the first review of a given head\") is mistaken: it treats the ReviewRun select_for_update as the only guard and overlooks that every path first serializes on the PullRequest row via _upsert_pull_request's UPDATE lock (existing PR) or the unique constraint on INSERT (new PR), both inside the same transaction as the dedupe and create. The finding's own \"common cases\" (new head after push, after supersede) all involve an existing PR row, so the UPDATE-lock path applies. The delivery_id point is a non-sequitur \u2014 in the webhook path, same-head races are serialized by the same _upsert lock, not by the delivery_id constraint. Only theoretical hole: incoming_updated_at=None skips the UPDATE (tasks.py:346), but GitHub's REST get_pr always returns updated_at, so unrealistic and not what the finding claims. The suggested PullRequest select_for_update would duplicate existing serialization."+ },+ {+ "id": "P21",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1138-1147 filters StamphogRepoConfig.objects.for_team(team_id)...repository__iexact=repository once per task; products/stamphog/backend/models.py:56-72 has only case-sensitive unique indexes on (team_id, repository) and (provider, installation_id, repository), no functional upper()/lower() index \u2014 so the iexact predicate itself is unindexed, as claimed.",+ "notes": "Factually correct but no real impact: the team_id equality uses the leading column of the (team_id, repository) unique index, bounding the scan to one team's repo configs (realistically tens of rows at most), evaluated once per inbox review task. The iexact is a documented correctness necessity (tasks lowercases repo slugs, configs keep GitHub casing). Adding a functional index/migration for this is speculative micro-optimization; the finding's own text concedes today's impact is small."+ },+ {+ "id": "P22",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/stamphog/backend/tasks/tasks.py:1236 \u2014 `logger.exception(\"stamphog_inbox_pr_create_run_failed\", repository=repository, pr_number=pr_number)` indeed lacks `error=str(e)`, unlike siblings at :1149 (`stamphog_inbox_pr_config_resolution_failed`, has `error=str(e)`) and :1164 (`stamphog_inbox_pr_fetch_failed`, has `error=str(e)`). However all three use `logger.exception`, which logs the exception message and full traceback via exc_info, and the handler re-raises via `.retry(exc=e)` at :1237 identically to the siblings.",+ "notes": "The narrow inconsistency exists, but the claimed problem (\"drops the exception detail\") does not: logger.exception captures the message and traceback, so nothing is lost \u2014 only a redundant structured `error` kwarg differs. No behavioral difference, failure is still logged and retried. Pure structured-logging style/consistency; below the review bar."+ },+ {+ "id": "P23",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "products/tasks/backend/webhooks.py:41 does use unpinned TaskRun.objects.filter(...), but the cited invariant (products/stamphog/AGENTS.md:59-64) applies to stamphog's replicated product DB routed via ProductDBRouter (posthog/product_db_router.py:27-35). The tasks app is absent from products/db_routing.yaml, so TaskRun lives on the main default DB where ReplicaRouter (posthog/dbrouter.py:22-32) sends reads to the writer unless the model is explicitly in the READ_REPLICA_OPT_IN env list \u2014 the unpinned read hits the writer by default, so the lagged-replica miss mechanism doesn't exist as described. Additionally the carve-out (products/stamphog/backend/tasks/tasks.py:160-196) fires only on synchronize/reopened/base-retarget, long after output.pr_url was written at PR-open, and find_task_run has a branch+repo fallback.",+ "notes": "The finding concedes the path is fail-closed and self-healing (a miss skips one delivery's re-review, recovers on next push). It's a cross-product consistency suggestion: applying stamphog's writer-pin convention to a tasks-DB read that tasks' own primary caller (webhooks.py:159) also leaves unpinned. No realistic user-affecting failure; speculative defensive hardening at best."+ },+ {+ "id": "P24",+ "is_real": false,+ "severity": "not_an_issue",+ "confidence": "high",+ "evidence": "All changes the finding claims are absent are present in the PR head tree: pr72680_tree/tools/pr-approval-agent/review_pr.py:196 (self_driving kwarg), :209 (attr), :225 (bot gate), :477/:938 (provenance stamps), :590 (draft gate); review_local.py:321; reviewer.py:683 (_format_self_driving); version.py:12 (STAMPHOG_VERSION = \"2.0.0b4\", not \"2.0.0b3\" as claimed). The unified diff pr72680.diff carries the same hunks (lines 1955, 1968, 2020, 2093).",+ "notes": "The finding is a meta-note about the reviewing harness, not about the PR. Its premise (described diff not in checked-out tree) came from a base-branch checkout in the original review environment \u2014 it even cites a different base commit (1438ae30) than the PR head. It names no code defect, is marked not directly related to the changes, and gives the author nothing actionable. must_fix severity unwarranted; drop."+ }+ ]+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/night-notes-2026-07-24.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/night-notes-2026-07-24.mdnew file mode 100644index 000000000000..0782f6484ca5--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/night-notes-2026-07-24.md@@ -0,0 +1,71 @@+# Overnight 4-way extension — working notes (2026-07-24)++Working notes for the C/D arms; folded into FINAL_REPORT.md at the end of the night. Timestamps UTC.++## Run C1 (`C-gpt55-xhigh-1`, report `019f9122-…8cf5`, 22:39–23:54, 4548s) — HARD FAIL #1++Dump: `runs/C-gpt55-xhigh-1.md` (funnel 4 chunks / 7 units / 10 raw / 7 dedup / 0 valid). Run "finished" green but is not a valid arm-C data point: perspective coverage of chunks 1 and 2 was lost entirely — only chunk 3 (`tools/pr-approval-agent`) got perspective reviews.++**Root cause — deterministic model refusals.** Every failed perspective attempt (14 of 17) ended with ACP `stopReason: "refusal"` ~90–130s into the turn (from S3 turn logs, `_posthog/turn_complete`):++| chunk | perspective attempts | refused | completed |+| -------------------------------------- | -------------------- | ------- | --------- |+| c1 (review_hog backend + generated TS) | 4 | 4 | 0 |+| c2 (stamphog backend/facade) | 4 | 4 | 0 |+| c3 (pr-approval-agent tools) | 6 | 3 | 3 |+| c4 (docs) | 0 (selector pruned) | — | — |+| blind-spots c1–c4 | 4 | 0 | 4 |++gpt-5.5's provider-side safety layer declines the perspective-review turn on the security-heavy chunks (the PR's provenance/spoofing/token-gating code), with or without the perspective skill loaded. Blind-spot prompts (audit the wave's findings for gaps) never refused. Validation (opus-4-8, Claude adapter) unaffected.++**Secondary findings (ops/product bugs, independent of verdict):**++1. **Refusal → 30-min hang:** `poll_for_turn` (products/tasks `custom_prompt_internals.py`, `MAX_POLL_SECONDS=1800`) does not treat a completed-with-refusal turn as terminal; each refused unit burned the full 1800s window, then Temporal retried once (final attempt skips). A ~90s refusal cost ~62 min of wall-clock per unit. Fix: treat `stopReason: refusal` as a terminal turn failure.+2. **Codex MCP flakiness:** 9 of 21 Codex sessions never got the `posthog` MCP tools (`posthog/exec` absent; agent: "MCP skill reader is not exposed in this session") and fell back to local `.agents/skills` (incl. `security-audit`). Not correlated with refusal (refusals happened with MCP present too), but those sessions review without the perspective skill → invalid arm data even absent refusals.+3. **Codex telemetry gap:** agent-side usage shows OpenAI cached reads (e.g. 65,920 of 71,483 input) but `$ai_generation` reports `cache_read=0` for all gpt-5.5 gens → gateway prices the full input as fresh; gw$ for Codex runs is overstated, and `dump_result.py`'s `true $` can't price gpt-5.5 at all (unpriced model).+4. Both turn logs end with `Direct artifact upload failed … fetch failed` + `Discarding handoff checkpoint … packBytes:120193428` — 120MB handoff pack upload fails in Modal sandboxes (pre-existing? noise? worth a look).++**Decision:** per the agreed failure policy (hard-fail → retry once; two hard fails → skip to D), C run #2 launched 00:09:52 UTC as the policy retry (`C-gpt55-xhigh-2`, start epoch 1784851792). Expected outcome: same refusals (content-deterministic); if so, arm C closes as DNF and arm D starts.++## Run C2 (`C-gpt55-xhigh-2`, report `019f9175-…ce0c`, 00:09–01:35, 5143s) — VALID (with caveats)++Dump: `runs/C-gpt55-xhigh-2.md` (4 chunks / 12 units / 14 raw / 10 dedup / 2 valid, 0 model switches, review stage 69m01s, gens 379, gw $36.10 — overstated by the Codex cache-telemetry gap; true cost unpriceable from `$ai_generation`).++The retry ladder went to a **third attempt** this run, and refusals proved attempt-stochastic rather than absolute: attempt 1 refused 8/8 (~2.5 min in), attempt 2 refused 6/8 (p2-c3, p1-c3 completed), attempt 3 completed 6/6 (01:13–01:15, resumed sessions). Full perspective coverage of chunks 1–3 resulted (8 selected pairs; the selector picked 8 this run vs 9 in C1).++**Caveats to carry into judging/report:**++- 4 of 8 perspective units (p1-c2, p2-c2, p3-c2, p1-c3) completed in sessions that never had MCP → reviewed WITHOUT their perspective skill (local `.agents/skills` fallback).+- Reviews were assembled across refusal-interrupted resumed sessions (cumulative ~20–30 gens/unit); depth is thin vs Sonnet/GLM units (raw 1–2 issues/unit).+- Refusal tally across both C runs: 22 of 25 first/second perspective attempts refused; 17/17 on first attempts.++Arm C status: C1 = hard fail, C2 = valid-with-caveats. **C3 top-up skipped** (decided 02:30 UTC): C2's caveats (skill-less units, resume-assembled reviews) would dominate any stability comparison, the refusal behavior is already characterized across 25 attempts, and the failure policy's spirit is "don't burn the night".++## Run D1 (`D-opus48-xhigh-1`, report `019f91c6-…f556`, 01:39–02:24, 2724s) — VALID, clean++Dump: `runs/D-opus48-xhigh-1.md` (4 chunks / 13 units / 14 raw / 14 dedup / 1 valid, 0 switches). Fastest run of the experiment: 45.4 min wall, review stage 26m22s. Zero unit loss, zero retries. Opus is selective (~1 raw issue/unit) and expensive: true $57.52 (gens 388). Purity probe: all review + blind gens on `claude-opus-4-8` (fallback indistinguishable by construction — noted).++## Run D2 (`D-opus48-xhigh-2`, report `019f91f1-…28d4`, 02:25–03:09, 2645s) — VALID, clean++Dump: `runs/D-opus48-xhigh-2.md` (4 chunks / 12 units / 16 raw / 16 dedup / 1 valid, 0 switches,+review stage 24m16s, 44.1 min wall, true $52.26). Same profile as D1: zero retries, purity clean.++## Judging prep (done during C2)++- PR worktree: `<scratchpad>/pr72680_tree` @ `1341596e` (HTTPS fetch).+- Diff: `<scratchpad>/pr72680.diff` (2222 lines, via `rtk proxy gh pr diff`).+- Blind sets regenerated: X=A1 (20), Y=B1 (17), P=A2 (24), Q=B2 (19) in `<scratchpad>/judge/`; new+ R=C1 (7), T=C2 (10), U=D1 (14), V=D2 (16).++## Judging (03:4x–04:1x UTC)++Workflow `wf_606fa251-156`: 47 adversarial verifiers (R/T/U/V, effort high, against the worktree) ++incremental clusterer (56 clusters over all 8 sets, every id covered exactly once) + 3-lens blind+panel over M1=X+P / M2=Y+Q / M3=R+T / M4=U+V. Evidence: `judge-fourway.json`. First invocation+silently spawned ZERO verifiers — the Workflow `args` arrived JSON-stringified, `setCounts[s]`+became undefined, and the judges ranked on unverified sets; caught via `agent_count=4`, fixed with a+defensive parse + count assertion, resumed (clusterer cache-replayed, judges re-ran). Lesson recorded+in memory.++Results and verdict: see FINAL_REPORT.md § 4-way extension. Experiment hacks reverted 03:20 UTC+(backend tree byte-identical to master); DB wiped after every dump; nothing committed.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/pinned_chunks.json b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/pinned_chunks.jsonnew file mode 100644index 000000000000..1ef059a2ee4a--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/pinned_chunks.json@@ -0,0 +1,121 @@+{+ "chunks": [+ {+ "chunk_id": 1,+ "files": [+ {+ "filename": "products/review_hog/backend/models.py"+ },+ {+ "filename": "products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py"+ },+ {+ "filename": "products/review_hog/backend/api/settings.py"+ },+ {+ "filename": "products/review_hog/backend/receivers.py"+ },+ {+ "filename": "products/review_hog/frontend/CodeReviewScene.tsx"+ },+ {+ "filename": "products/review_hog/frontend/generated/api.schemas.ts"+ },+ {+ "filename": "products/review_hog/frontend/generated/api.zod.ts"+ },+ {+ "filename": "services/mcp/src/api/generated.ts"+ }+ ],+ "chunk_type": "feature",+ "key_changes": [+ "Adds stamphog_review_inbox_prs boolean field to ReviewUserSettings (migration 0019), default off, alongside the existing review_inbox_prs toggle",+ "Serializer exposes the new field plus a computed stamphog_connected flag that fails soft (returns False) if the cross-product Stamphog DB check errors",+ "TaskRun receiver now resolves the acting reviewer once (_resolve_assigned_reviewer) and independently checks both toggles, dispatching review_hog's own review and/or stamphog's queue_inbox_pr_review facade on commit",+ "Registers resolve_stamphog_acting_reviewer with stamphog's inbox hook registry at app-ready so the webhook leg can re-check the toggle without a circular import",+ "New 'Let Stamphog review your Inbox PRs' switch in CodeReviewScene, disabled with a reason when Stamphog isn't connected but always interactive to opt out",+ "Generated API schema/zod/mcp client types regenerated for the new fields (mechanical, attached for context)"+ ]+ },+ {+ "chunk_id": 2,+ "files": [+ {+ "filename": "products/stamphog/backend/facade/api.py"+ },+ {+ "filename": "products/stamphog/backend/facade/inbox_hooks.py"+ },+ {+ "filename": "products/stamphog/backend/tasks/tasks.py"+ },+ {+ "filename": "products/stamphog/backend/temporal/activities.py"+ },+ {+ "filename": "products/stamphog/backend/logic/reviewer.py"+ },+ {+ "filename": "products/tasks/backend/facade/api.py"+ },+ {+ "filename": "products/tasks/backend/facade/contracts.py"+ },+ {+ "filename": "tach.toml"+ }+ ],+ "chunk_type": "business_logic",+ "key_changes": [+ "New facade/inbox_hooks.py: import-light inversion-hook registry so stamphog can call back into review_hog's toggle resolver without a dependency cycle",+ "facade/api.py: has_reviewable_repo_config (drives the UI's stamphog_connected flag) and queue_inbox_pr_review (fire-and-forget Celery dispatch for the receiver/inbox leg)",+ "tasks.py: _inbox_rereview_carve_out positively identifies self-driving PRs on the webhook path (repo-native head, synced+enabled repo config, tasks-facade match, re-checked toggle) and bypasses bot-author/draft/review-mode/write-permission gates only for that carve-out; new process_inbox_pr_review Celery task implements the initial receiver-leg review with head-keyed dedupe and inbox provenance; dedicated dismissal copy for opted-out reviewers",+ "temporal/activities.py: derives self_driving_review from the run's stamped provenance for the engine context, skips the author merged-PR fetch on inbox runs, and stamps analytics with stamphog_self_driving_review",+ "logic/reviewer.py: threads the new self_driving_review flag into the sandboxed engine invocation context",+ "products/tasks facade: new find_signal_implementation_run + SignalImplementationRunDTO, mirroring the webhook backstop's PR lookup and enforcing team scoping to positively identify self-driving runs",+ "tach.toml: registers stamphog as a facade-only dependency for the modules now calling into it"+ ]+ },+ {+ "chunk_id": 3,+ "files": [+ {+ "filename": "tools/pr-approval-agent/review_pr.py"+ },+ {+ "filename": "tools/pr-approval-agent/review_local.py"+ },+ {+ "filename": "tools/pr-approval-agent/reviewer.py"+ },+ {+ "filename": "tools/pr-approval-agent/version.py"+ }+ ],+ "chunk_type": "feature",+ "key_changes": [+ "Pipeline gains an additive, default-off self_driving flag that relaxes exactly two gates: the bot-author refusal and the draft prerequisite",+ "review_local.py sets the flag from the hosted context JSON's self_driving_review key, defaulting closed so Action-shaped contexts are unaffected",+ "reviewer.py renders a TRUSTED provenance block in the LLM prompt only when the flag is set, replacing human-author trust signals; empty string otherwise keeps every other prompt byte-identical",+ "Engine version bumped to 2.0.0b4"+ ]+ },+ {+ "chunk_id": 4,+ "files": [+ {+ "filename": "products/stamphog/AGENTS.md"+ },+ {+ "filename": "products/stamphog/README.md"+ }+ ],+ "chunk_type": "documentation",+ "key_changes": [+ "New 'self-driving inbox carve-out' invariant section in AGENTS.md documenting the narrow, positively-identified exception to the bot-author refusal and the gates it does/doesn't bypass",+ "README.md documents the non-webhook entry point via the inbox receiver's queue_inbox_pr_review facade call"+ ]+ }+ ]+}diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1-tainted.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1-tainted.mdnew file mode 100644index 000000000000..ed4bb8c0357b--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1-tainted.md@@ -0,0 +1,431 @@+# Reviewer-quality run — `A-sonnet5-xhigh-1`++> ⚠️ **TAINTED RUN** — the temporal worker restarted twice mid-run (nodemon, one restart caused by an+> eval-script edit during the run). Every wave unit double-executed (16 task-runs / 8 results, zombie+> sandboxes), 2 units fell back to Opus mid-session, validation-c2 re-ran. Findings are usable; cost+> (~2× on the wave) and stage timings are NOT comparable. Superseded by the clean re-run.++- **Dumped:** 2026-07-23T15:05:10+00:00+- **Report id:** `019f8f24-984c-7c8a-ac44-51f5c95bedb0` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 6152s (102.5 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-sonnet-5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 29 | 25 | 1 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 187 | 129,271 | 1,001,312 | 21,820,014 | 219,816 | 6 | $23.31 | $23.31 |+| claude-sonnet-5 | review | 263 | 418,552 | 3,052,075 | 34,086,041 | 383,136 | 40 | $19.12 | $19.12 |+| claude-sonnet-5 | blind-spot | 106 | 127,157 | 1,089,163 | 12,501,937 | 174,313 | 0 | $7.22 | $7.22 |+| claude-opus-4-8 | review | 6 | 12 | 378,228 | 248,727 | 620 | 0 | $2.50 | $2.50 |+| claude-sonnet-5 | chunking | 1 | 49,852 | 0 | 0 | 15,579 | 0 | $0.26 | $0.26 |+| claude-sonnet-5 | dedup | 1 | 20,645 | 0 | 0 | 5,427 | 0 | $0.10 | $0.10 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,511 | 0 | $0.03 | $0.03 |+| **total** | | **565** | **754,518** | **5,520,778** | **68,656,719** | **800,402** | **46** | **$52.53** | **$52.53** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- naive method (all prompt tokens at input price): $231.91 — 4.4× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $41.2241 over 565 gen(s) (true $41.2241, Δ -0.0%)+ - · of which cache read: $20.3520 over 548 gen(s) (true $20.3520, Δ +0.0%)+ - · of which cache write: $18.9752 over 562 gen(s) (true $18.9752, Δ +0.0%)+ - · of which fresh (derived): $1.8969 over 565 gen(s) (true $1.8969, Δ -0.0%)+ - output: $11.3106 over 565 gen(s) (true $11.3106, Δ +0.0%)+- 46 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------------------------------- |+| …d7a9c22b | issues-review-p2-c1 | 13:32:38 | 0 | 70,808 | claude-sonnet-5 |+| …97bef48c | issues-review-p3-c1 | 13:32:46 | 22,746 | 48,059 | claude-sonnet-5 |+| …cd15c778 | issues-review-p1-c3 | 13:32:47 | 22,746 | 36,247 | claude-sonnet-5 |+| …e57ffad2 | issues-review-p1-c2 | 13:32:48 | 22,746 | 50,327 | claude-sonnet-5 |+| …5103d1b8 | issues-review-p1-c1 | 13:34:32 | 22,746 | 48,062 | claude-sonnet-5 |+| …6e10b127 | issues-review-p1-c2 | 13:34:32 | 22,746 | 50,328 | claude-sonnet-5 |+| …e03fb88c | issues-review-p1-c3 | 13:34:33 | 22,746 | 36,246 | claude-sonnet-5 |+| …11dc622a | issues-review-p3-c1 | 13:34:34 | 22,746 | 48,054 | claude-sonnet-5 |+| …ab3671fe | issues-review-p2-c1 | 13:34:35 | 22,746 | 48,061 | claude-sonnet-5 |+| …d9725c9f | issues-review-p2-c3 | 13:34:35 | 22,746 | 36,256 | claude-sonnet-5 |+| …ae3cf135 | issues-review-p2-c2 | 13:34:36 | 22,746 | 50,329 | claude-sonnet-5 |+| …de356b7a | issues-review-p2-c3 | 13:34:36 | 22,746 | 36,252 | claude-sonnet-5 |+| …4605c3ae | issues-review-p3-c2 | 13:34:36 | 22,746 | 50,328 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …d5fbce63 | issues-review-p1-c1 | 13:34:38 | 22,746 | 48,059 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …6f95fab0 | issues-review-p3-c2 | 13:34:38 | 22,746 | 50,329 | claude-sonnet-5 |+| …15858fca | issues-review-p2-c2 | 13:34:38 | 22,746 | 50,327 | claude-sonnet-5 |+| …4ebf45fe | blind-spots-c3 | 13:52:47 | 0 | 63,065 | claude-sonnet-5 |+| …19cd105d | blind-spots-c4 | 13:52:48 | 0 | 55,442 | claude-sonnet-5 |+| …ee547b67 | blind-spots-c2 | 13:52:49 | 0 | 78,397 | claude-sonnet-5 |+| …6bbcde80 | blind-spots-c1 | 13:53:00 | 22,746 | 51,466 | claude-sonnet-5 |+| …341d05a5 | blind-spots-c2 | 14:13:42 | 22,746 | 55,655 | claude-sonnet-5 |+| …6a1375f9 | validation-c3 | 14:24:20 | 0 | 39,430 | claude-opus-4-8 |+| …f1f4c798 | validation-c4 | 14:24:20 | 0 | 39,424 | claude-opus-4-8 |+| …205d1aa2 | validation-c1 | 14:24:21 | 0 | 39,725 | claude-opus-4-8 |+| …51298e67 | validation-c2 | 14:24:24 | 17,420 | 23,008 | claude-opus-4-8 |+| …30b8dd1f | validation-c2 | 14:47:30 | 17,420 | 22,758 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **19/26** (report the distribution, not a median).+- ⚠️ 2 unit(s) switched models mid-session (overload rescue?) — cache sharing and cost pinning are broken for them: …4605c3ae, …d5fbce63++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 2m 24s |+| perspective selection | 18s |+| review wave (perspectives) | 26m 23s |+| blind-spot sweep | 30m 41s |+| dedup (incl. combine/clean) | 54s |+| validation | 40m 57s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 57m 04s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 2 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 4 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 3 |+| 2 | 3 | review-hog-perspective-logic-correctness | 3 |+| 3 | 1 | review-hog-perspective-performance-reliability | 3 |+| 3 | 2 | review-hog-perspective-performance-reliability | 3 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 2 |+| 1000 | 3 | review-hog-blind-spots-general | 2 |+| 1000 | 4 | review-hog-blind-spots-general | 3 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:113-121++**`_parse_pr_url` matches 'github.com/…/pull/N' as an unanchored substring anywhere in the string, not a validated GitHub PR URL**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` is used with `.search()`, which matches the pattern anywhere in the string rather than validating the URL's scheme and host. Because there's no anchor, a string like `"https://notgithub.com/owner/repo/pull/1"` or `"https://evil.example/redirect?to=github.com/owner/repo/pull/1"` parses successfully to `("owner/repo", 1)` even though the host isn't actually `github.com`. `_parse_pr_url` is the entry point for `process_inbox_pr_review`, which gates the self-driving inbox carve-out (bypasses bot-author refusal and the draft prerequisite downstream) — the same function class the PR's own security model treats as sensitive. The blast radius is currently limited because the resolved GitHub API call uses `repo_config.repository` from a team-scoped DB lookup rather than the regex-captured `owner/repo`, but the parsed `pr_number` from an unanchored match is trusted as-is, and this is the only validation standing between whatever string flows in as `pr_url` and 'fetch and self-driving-review PR #N in this team's configured repo'.+- **Suggestion:** Parse `pr_url` with `urllib.parse.urlparse` and validate `parsed.netloc == "github.com"` (or the configured enterprise host) plus an anchored path match (e.g. `re.fullmatch(r"/([^/]+/[^/]+)/pull/(\d+)/?", parsed.path)`) instead of an unanchored substring search, so a URL containing an embedded but not-actually-hosting `github.com/.../pull/N` segment can't be mistaken for a real GitHub PR link.+- **Validator:** - **Checked:** every caller of `_parse_pr_url`, the origin of the `pr_url` it parses, and every downstream use of its two return values (`repository`, `pr_number`).+- **Found (only caller):** `_parse_pr_url` is called in exactly one place — `process_inbox_pr_review` at `tasks.py:1130`. The webhook re-review carve-out the finding invokes as the sensitive surface (`_inbox_rereview_carve_out`, `tasks.py:144`) does NOT use it at all; it reads `pr.get("html_url")` from the verified webhook payload and gates on repo-native head + synced config + a team-scoped tasks-facade match + toggle re-check (`tasks.py:176-215`). So the bot-author/draft-bypass framing does not attach to this function.+- **Found (input is system-generated):** `pr_url` flows from `queue_inbox_pr_review` (`facade/api.py:128`) ← review_hog's `_start_stamphog_review` ← `output.get("pr_url")` in `receivers.py:93`, which the module docstring documents as "Written by the agent server when it observes the agent open the PR, or by the GitHub-webhook backstop." It is the real URL of a PR a PostHog Code run just opened, not free-form untrusted input crossing a boundary.+- **Found (host never used downstream):** in `process_inbox_pr_review`, `repository` is used solely as a lookup key against a team-scoped enabled config (`StamphogRepoConfig.objects.for_team(team_id)...filter(repository__iexact=repository, enabled=True...)`, `tasks.py:1141-1147`) — no match → silent no-op (`tasks.py:1151-1153`). The actual GitHub fetch uses `repo_config.repository` from that DB row, NOT the regex-captured owner/repo (`tasks.py:1159`). The URL's host/scheme is discarded after parsing.+- **Impact:** Anchoring the host closes no real hole. `pr_number` trust is identical whether the host is `github.com` or embedded in `notgithub.com` — a properly-anchored URL carries an equally-trusted number. In both cases the review target resolves to `repo_config.repository` PR #`pr_number`, gated by the team-scoped config lookup; a bogus/embedded host cannot redirect the fetch to another repo or team. The reviewer's own note concedes the fetch ignores the captured owner/repo, and the remaining `pr_number`-trust concern is unaffected by anchoring. Per the criteria this is speculative hardening against an input that can't occur as described and whose only real validation (team-scoped DB config + DB-repo fetch) is already present — precision-over-recall says drop.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:321-321++**Gate-bypass flag is derived with truthy `bool()` coercion instead of a strict boolean check**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self_driving=bool(context.get("self_driving_review"))` uses Python truthiness on a value pulled straight out of an externally-produced JSON blob. `self_driving` is not an ordinary display field — it is the single flag that relaxes the bot-author refusal and the draft prerequisite, i.e. it authorizes Stamphog to post a real GitHub approval on a bot-authored draft PR. `bool()` coercion means any JSON value other than `false`/`0`/`""`/`null`/absent is treated as `True` — critically, the JSON _string_ `"false"` (as opposed to the JSON boolean `false`) evaluates to `True` under `bool()`, since any non-empty Python string is truthy. If the context-assembly code on the server side (a different chunk, not reviewable here) ever emits this key as a string instead of a native JSON boolean, the carve-out would be silently enabled for a run it was never meant to cover, bypassing the exact defense-in-depth gates this feature is built around.+- **Suggestion:** Use a strict identity check for this specific flag given what it authorizes, e.g. `self_driving=context.get("self_driving_review") is True`, so any value other than the literal JSON boolean `true` fails closed rather than being coerced to enabled.+- **Validator:** - **Checked:** The full producer→consumer chain for `self_driving_review`, since the finding's own trigger ("server emits this key as a string") lives in a chunk it declined to inspect. Traced `review_local.py::run` (`self_driving=bool(context.get("self_driving_review"))`), plus the server-side assembly the finding speculates about: `products/stamphog/backend/logic/reviewer.py::build_reviewer_invocation` and `products/stamphog/backend/temporal/activities.py::run_review_in_sandbox`.+- **Found:** The context JSON is not an "externally-produced blob" — it is the server's own serialization of a native Python bool. `build_reviewer_invocation` is typed `self_driving_review: bool = False` (reviewer.py:101) and writes `context["self_driving_review"] = self_driving_review` verbatim; its only caller passes `self_driving_review=bool(output.get("inbox_review"))` (activities.py, `run_review_in_sandbox`). A `bool()` at the source → `json.dumps` → `json.load` round-trips as JSON `true`/`false`, so `context.get(...)` in `review_local.py` is always a native `bool` and `bool(...)` is a no-op. The string `"false"` cannot arise without a type-violating edit to `build_reviewer_invocation`'s `bool` parameter — code that ships in this same PR. Action-shaped contexts omit the key entirely → `bool(None)` → `False`, fail-closed (asserted by `test_bot_authored_context_without_the_flag_is_refused`).+- **Impact:** This is a speculative "what-if" that current call sites and types already rule out, i.e. defensive-coding hardening against an input that cannot occur — both explicit drop categories in the criteria. Decisively, the suggested `is True` fix closes no real attack surface: anyone able to inject a truthy string into the sandbox context file could equally inject the native JSON `true`, so the change yields no security benefit against any reachable threat. Precision-over-recall tiebreak also points to drop.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_pr.py:202-209++**The "no familiarity from machine-user history" invariant is not enforced inside Pipeline itself**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The PR description states as an explicit design invariant that for self-driving runs "the hosted server skips the author merged-PR fetch so the machine user's history never feeds familiarity." `self.self_driving` is added as a general attribute on the shared `Pipeline` class (used by both `review_pr.py`'s own `run()` and `review_local.py`'s bespoke offline `run(context)`), but that invariant is only actually true today because `review_local.py`'s `run(context)` never calls `Pipeline.run()` — it calls individual pipeline steps directly and uses its own `_attach_familiarity()` (which requires an explicit `author_pr_numbers` key the server chooses to omit). `Pipeline.run()` itself (line 241, calling `_maybe_compute_familiarity()` at line 510, which calls `_compute_familiarity()` at line 523) has no `self.self_driving` guard at all — it unconditionally fetches `compute_familiarity(author_login=pr.author, ...)`, which performs a live `gh` call to search for merged PRs by that author login. Since `self_driving` is meant to be one shared implementation of the relaxed gates on `Pipeline` (the PR's own stated "parity invariant"), the safety property that the machine user's merged-PR history must never feed familiarity is not actually encoded in `Pipeline` — it is an accidental byproduct of which caller code path happens to be used today. Any future caller that invokes `Pipeline.run()` directly with `self_driving=True` (e.g. a refactor that unifies the two entrypoints, or a new invocation site) would silently reintroduce exactly the signal the design explicitly rules out.+- **Suggestion:** Make `_maybe_compute_familiarity()` (or `_compute_familiarity()`) itself skip the `gh`-based merged-PR fetch when `self.self_driving` is true, so the invariant holds regardless of which code path calls into `Pipeline`, rather than relying entirely on `review_local.py` never calling `Pipeline.run()`.+- **Validator:** - **Checked:** All `Pipeline` instantiations and every `.run()` call site in `tools/pr-approval-agent/` (non-test), plus the two familiarity paths: `Pipeline._maybe_compute_familiarity`/`_compute_familiarity` (review_pr.py:510-537) and `review_local.py`'s bespoke `_attach_familiarity` (review_local.py:292-311), and how the hosted self-driving path actually enters the engine.+- **Found:** `self_driving=True` is reachable through exactly one path today — `review_local.py::run` (review_local.py:316), which never calls `Pipeline.run()`; it orchestrates steps directly and gates familiarity on `context.get("author_pr_numbers")` being present, which the server empties for inbox reviews (`activities.py`: `... if author and not is_inbox_review else []`), so the signal stays `None`. The only `.run()` caller is `review_pr.py:967` from `main()`, which builds `Pipeline(args.pr_number, args.repo, dry_run=..., verbose=...)` (line 966) with no `self_driving`, so `Pipeline.run()` → `_maybe_compute_familiarity` is only ever reached with `self_driving=False`. The finding's factual premise (no guard in the familiarity path) is correct, but so is its own concession: the invariant "is only actually true today because review_local.py's run(context) never calls Pipeline.run()."+- **Impact:** No reachable defect in the current code — the harm requires "any future caller that invokes Pipeline.run() directly with self_driving=True (e.g. a refactor that unifies the two entrypoints, or a new invocation site)." That is a speculative what-if about a call path that does not exist, i.e. future-proofing an out-of-scope case — three of the criteria's explicit drop categories (speculative what-if, overengineering/future-proofing, never-gonna-happen). The suggestion is pure defense-in-depth hardening against a hypothetical refactor, not a bug that real inputs hit today; precision-over-recall points to drop.++### [❌ dismissed] consider · code_quality — products/review_hog/frontend/CodeReviewScene.tsx:1058-1067++**Stamphog switch's disabledReason can mask the in-flight "Saving…" state**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new switch's disabledReason checks `settings && !settings.stamphog_connected && !settings.stamphog_review_inbox_prs` before falling back to `switchDisabledReason` (which carries 'Saving…' while `settingsLoading` is true). Because the not-connected check is evaluated first, if the user is mid-save on any of the settings fields (e.g. just flipped the 'Review all your Inbox PRs' switch) while Stamphog is disconnected and this toggle is off, the tooltip/disabledReason shown is 'Connect a repository to Stamphog first…' instead of 'Saving…', even though a PATCH request is actively in flight. The switch is correctly disabled either way, but the reason text doesn't reflect the actual in-flight state during that window.+- **Suggestion:** Check `switchDisabledReason` (the loading/saving state) first, and only fall back to the connect-Stamphog message when not loading/saving, e.g. `switchDisabledReason ?? (settings && !settings.stamphog_connected && !settings.stamphog_review_inbox_prs ? 'Connect a repository to Stamphog first...' : undefined)`.+- **Validator:** - **Checked:** Pulled the actual PR diff for `products/review_hog/frontend/CodeReviewScene.tsx` (the local checkout is at master, not the PR head, so the referenced line numbers don't map). Confirmed the flagged `LemonSwitch` block and traced `switchDisabledReason = settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined` (CodeReviewScene.tsx:1021 in the branch).+- **Found:** The connect-condition `settings && !settings.stamphog_connected && !settings.stamphog_review_inbox_prs` is only true in the disconnected + toggle-off state. In that exact state the switch is _already_ disabled with the connect message before, during, and after any sibling PATCH — so the tooltip stays stable at 'Connect a repository to Stamphog first…' rather than flipping to 'Saving…'. Every other state (settings null, connected+saving, toggle-on) correctly falls through to `switchDisabledReason`. The switch is non-interactive in all disabled states regardless of which string renders.+- **Impact:** Purely a tooltip-copy nuance during a sub-second PATCH window, with no behavioral difference — the switch is correctly disabled throughout and nothing the user can do changes. This is the 'pure style / taste with no behavioral difference' drop category; it names no concrete correctness/security/data/contract/perf/reliability consequence. The suggested reorder would in fact make the connect message flicker to 'Saving…' and back on every sibling save, arguably worsening the UX. Precision-over-recall → drop.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/reviewer.py:505-506,567-568,683-703++**Self-driving provenance block doesn't guarantee suppression of a contradictory familiarity block**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `_format_self_driving` tells the LLM that for self-driving reviews 'author familiarity, org membership, and merged-PR history carry no signal here,' and the prompt template concatenates it immediately after `familiarity_block` (`{constraint}{familiarity_block}{self_driving_block}`). Nothing in this chunk actually enforces that mutual exclusion: `_format_familiarity` (unchanged, reviewer.py) only checks `cl.get('familiarity')`, independent of `cl.get('self_driving')`. For the Action entrypoint (`review_pr.py`) this is safe because `self_driving` is always False there. But the hosted sandboxed engine (`review_local.py`) is the one that actually runs self-driving reviews with `self_driving=True`, and its `_attach_familiarity` populates real familiarity data for the T1-agent tier whenever the context happens to include `author_pr_numbers` — an invariant maintained only by a caller in a different, unreviewed chunk (the server deciding what to put in the context JSON), not by anything here. If that external invariant is ever violated (e.g. a future code path that reuses the same context-building logic for both flows), the reviewer prompt would contain two directly contradictory trusted-context statements about the same machine author in one run: a familiarity block asserting real blame-overlap/prior-PR numbers, next to a provenance block insisting that exact information 'carries no signal.'+- **Suggestion:** Make the suppression self-contained in the engine rather than an implicit cross-chunk contract: short-circuit familiarity rendering (in `_format_familiarity`, or where `familiarity_block` is computed) whenever `cl.get('self_driving')` is truthy, so the 'no signal' claim in the self-driving block is guaranteed by the code that emits it.+- **Validator:** - **Checked:** The two render paths (`_format_familiarity` reviewer.py:635-680, `_format_self_driving` from the PR), the prompt concatenation `{constraint}{familiarity_block}{self_driving_block}`, the familiarity-population gate in the self-driving entrypoint (`review_local.py::_attach_familiarity`, lines 299-303), and the server context assembly in `activities.py` that feeds both.+- **Found:** A contradiction requires `self_driving=True` AND `familiarity != None` in one run. `_format_familiarity` returns `""` when `fam is None` (reviewer.py:644-645), so the familiarity block is empty unless familiarity is actually populated. In the only path where `self_driving=True` (the hosted `review_local.py` inbox path), `_attach_familiarity` bails unless `context.get("author_pr_numbers")` is truthy — and the server sets `author_pr_numbers = ... if author and not is_inbox_review else []`, i.e. `[]` for inbox reviews. Decisively, both `self_driving_review=bool(output.get("inbox_review"))` and `is_inbox_review = bool((run.output or {}).get("inbox_review"))` derive from the _same_ `inbox_review` provenance value, so whenever the flag turns on, `author_pr_numbers` is emptied in the same breath → familiarity stays `None` → no familiarity block renders. The two blocks are logically coupled through one source, not held apart by luck.+- **Impact:** No reachable contradiction today — the finding's own trigger is "if that external invariant is ever violated (e.g. a future code path that reuses the same context-building logic)." That is a speculative what-if plus defense-in-depth future-proofing against a caller that doesn't exist, and the current invariant is confirmed already-handled by the shared `inbox_review` derivation. Even the hypothetical consequence is a soft prompt inconsistency for the LLM (and the provenance block pushes toward _less_ author trust, the safe direction), not a correctness/security/data-loss defect. Fails the bar; precision-over-recall points to drop, consistent with the parallel invariant-encoding finding already dropped.++### [❌ dismissed] consider · documentation — products/stamphog/README.md:14-15++**README's cross-reference text doesn't match AGENTS.md's actual heading**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The added sentence ends with 'See AGENTS.md § the self-driving carve-out,' but the heading actually added in AGENTS.md is '## The self-driving inbox carve-out (the one exception to the bot-author refusal)'. The phrase used in the cross-reference ('the self-driving carve-out') omits 'inbox' and doesn't match the real heading text, so a reader searching AGENTS.md for that exact phrase won't land on the right section.+- **Suggestion:** Match the cross-reference wording to the actual heading, e.g. 'See AGENTS.md § The self-driving inbox carve-out.'+- **Validator:** - **Checked:** the added README.md sentence (`products/stamphog/README.md`, the new line after line 11) and the actual heading added in AGENTS.md.+- **Found:** the finding's premise is factually correct — README says "See AGENTS.md § the self-driving carve-out" while the real heading is "## The self-driving inbox carve-out (the one exception to the bot-author refusal)", so an exact-phrase search omitting "inbox" would miss.+- **Impact:** this is a pure documentation cross-reference wording mismatch with no behavioral, correctness, security, or contract consequence. The validation bar keeps correctness/security/data-loss/contract/performance/reliability defects and explicitly drops "pure style / taste — naming, formatting, comment wording ... with no behavioral difference"; a slightly-off cross-reference phrase in an internal README is squarely that class. A reader lands on the section trivially by searching "carve-out" or "self-driving" (both distinctive substrings present in the heading), so even the stated inconvenience is negligible. Below the keep bar (precision over recall → drop); the reviewer's own `consider` rating already signals its triviality.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-81++**stamphog_connected check adds an unconditional cross-database round trip to a hot, always-called endpoint with no caching**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` performs a cross-product-database read (`has_reviewable_repo_config`, against the separate stamphog product DB) on every GET and PATCH of `ReviewUserSettings` — an endpoint this same file's own comment (around the `user_settings` action) describes as "the Code review tab's always-called endpoint." The method's comment notes protection via a "fail-fast circuit breaker," which is real for outages (`posthog/db_backends/failopen/base.py` raises `CircuitOpenError` in microseconds instead of waiting on `connect_timeout`), but that only covers the down/unreachable case. A live-but-slow stamphog DB (load, lock contention, etc.) still adds its full query latency to every settings page load and every toggle save, since nothing caches a value that only changes when a `StamphogRepoConfig` row is created, synced, enabled, or disabled — a low-frequency event.+- **Suggestion:** Consider caching `has_reviewable_repo_config(team_id)`'s result for a short TTL (e.g. 30-60s) keyed by team_id. It's purely informational (drives a disabled-state UI hint), so staleness on the order of a minute is inconsequential — unlike the actual review-gating checks. This keeps the hot settings endpoint's latency independent of the stamphog DB's routine response time, not just its availability.+- **Validator:** - **Checked:** The added `has_reviewable_repo_config` query shape in the PR (`products/stamphog/backend/facade/api.py`), the call site in `get_stamphog_connected` (`settings.py`), how often the settings endpoint is actually hit (`reviewHogSettingsLogic.ts` load/poll wiring), and the alpha gating.+- **Found:** The query is a single tenant-keyed `EXISTS`: `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` — indexed on `team_id`, not N+1, not unbounded, no missing index.+- **Found:** The `setInterval` poll (`reviewHogSettingsLogic.ts:758-760`) calls `loadRecentReviews`, a _different_ endpoint — **not** `loadSettings`. `get_stamphog_connected` therefore runs once per scene mount (`loadAll` → `loadSettings`) and once per toggle PATCH; it is not polled. The issue's 'hot, always-called endpoint' framing overstates it: it is a human-paced settings surface.+- **Found:** The trigger is gated to `REVIEWHOG_TEAM_ID` while in alpha (per the `can_trigger_reviews` help_text and PR body), so real traffic is minimal. The outage/unreachable case is already double-covered by the fail-fast circuit breaker and the `try/except → return False` fail-soft in `get_stamphog_connected`.+- **Impact:** No 'bites at real scale' failure mode applies (no N+1, unbounded loop, missing index on a hot path, or quadratic behavior) — it is one cheap indexed lookup per human-paced request. The residual 'live-but-slow DB' concern is speculative, and caching one informational flag wouldn't fix systemic DB slowness (which would degrade every other read of that DB anyway). The suggested short-TTL cache adds keying/invalidation complexity for a case not in scope — overengineering + speculative what-if. Does not meet the keep bar; precision-over-recall → drop.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:179,891++**Duplicate writer-DB repo-config resolution on the bot-author skip path**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** For every bot-authored PR on a `synchronize`/`reopened` action (dependabot, renovate, and self-driving inbox PRs alike), `_review_skip_reason` always returns a non-None reason, so `process_pull_request_event` now enters the new carve-out branch and calls `_inbox_rereview_carve_out`, which resolves `StamphogRepoConfig` via `_resolve_repo_config` at line 179 (pinned to `router.db_for_write(StamphogRepoConfig)`). When that carve-out does not produce provenance (the common case: dependabot/renovate PRs, or a self-driving PR whose acting reviewer opted out), execution falls into the pre-existing skip block, which resolves the exact same config a second time at line 891 (`skip_repo_config = _resolve_repo_config(installation_id, repo)`) — again against the writer connection. This is a new, redundant round trip to the primary DB introduced by wiring the carve-out check ahead of the existing skip-path retraction, on a path that fires on every dependabot/renovate push to any stamphog-enabled repo, not just the rare self-driving case.+- **Suggestion:** Have `_inbox_rereview_carve_out` surface the `StamphogRepoConfig` it already resolved (e.g. add a `repo_config` field to `_InboxCarveOut`, or return it alongside the carve-out result) so the skip-path retraction block reuses it instead of calling `_resolve_repo_config` again.+- **Validator:** - **Checked:** the carve-out guard order in `_inbox_rereview_carve_out` (tasks.py:167-179), the skip-retraction block in `process_pull_request_event` (tasks.py:881-903), the query in `_resolve_repo_config` (tasks.py:298-304), and what else runs on the same skip branch (`_retract_stale_approvals_on_skip`, tasks.py:483-509).+- **Found (claim is accurate):** for a bot-authored `synchronize`/`reopened` PR on an enabled repo, line 179 resolves the config (the earlier `_is_bot_authored`/fork-safety guards pass for dependabot/renovate), the carve-out returns empty, and line 891 resolves the same config again — so the double round trip is real.+- **Found (cost is trivial):** `_resolve_repo_config` is a single indexed single-row read (`filter(provider, installation_id, repository).order_by(...).first()`, tasks.py:298-304) — a constant +1 query, not N+1, not a loop, not quadratic. It runs on the Celery webhook path (one delivery per bot-PR push), not a synchronous or per-row hot path, and bot-PR synchronize/reopen events are low-frequency.+- **Found (dwarfed by neighbors):** the very block that re-resolves it then calls `_retract_stale_approvals_on_skip`, which itself issues a second writer-pinned `PullRequest` query (tasks.py:501-506) and a GitHub API dismissal round trip (`dismiss_stale_approvals_for_head`, tasks.py:509). The redundant config lookup is negligible beside the GitHub call already on the same branch.+- **Impact:** does not meet the performance keep bar ("N+1 / unbounded / missing index on a hot path / quadratic" that "bites at real scale"). It is a single cheap indexed query duplicated on an infrequent webhook path — a micro-optimization whose fix would require threading the config through `_InboxCarveOut` even in the empty/opted-out cases. Precision-over-recall → drop.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:100-105++**New carve-out doesn't address the file's own reader-lag invariant for its new toggle reads**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This bullet documents two new 'read-then-act' paths introduced by the carve-out: the receiver leg resolving 'both toggles checked on one acting reviewer' before calling the queue_inbox_pr_review facade, and the webhook leg re-checking the toggle through the facade/inbox_hooks.py resolver before re-reviewing. Both reads gate a real side effect (queuing a review that can end in a posted GitHub approval). This same file already states, in unambiguous terms, the exact invariant that applies here: 'Reader-lag: pin decision reads to the writer' (lines 59-64) — 'Any read that gates a side effect (GitHub write, Slack post, supersession, run creation) must be pinned via `.using(router.db_for_write(Model))`... If you add a read-then-act path, pin it; this class of bug has been found on five separate paths.' The new carve-out section neither states that these two new toggle reads are pinned to the writer nor cross-references the existing invariant, even though the file's own preamble frames it as 'the contract... hold new code to all of them.' A lagged-replica read of the toggle is exactly the shape of bug this file already warns about (e.g. a user who just flipped `stamphog_review_inbox_prs` off could still have a stale-replica read return 'on', triggering an unwanted real GitHub approval on their behalf).+- **Suggestion:** Add an explicit line under this bullet (or a short cross-reference to the 'Reader-lag' section) stating that both toggle reads — the acting-reviewer resolution in review_hog's receiver and the `facade/inbox_hooks.py` resolver call — must be pinned via `.using(router.db_for_write(...))`, and confirm the implementing code in tasks.py / inbox_hooks.py actually does this rather than reading from a default (possibly lagged) connection.+- **Validator:** - **Checked:** the flagged carve-out bullet in `products/stamphog/AGENTS.md` (lines ~100-105), the reader-lag invariant it references, the two implementing toggle reads in `products/review_hog/backend/receivers.py` (the receiver leg and `resolve_stamphog_acting_reviewer`), `ReviewUserSettings.load()`, and the model's DB placement.+- **Found:** both toggle reads route through `ReviewUserSettings.load(team_id, user_id)` → `cls.objects.for_team(team_id).filter(user_id=user_id).first()`. `ReviewUserSettings(UUIDModel, TeamScopedRootMixin)` with `team = ForeignKey("posthog.Team")` is on the **main** Postgres DB. The reader-lag invariant it's supposed to cross-reference opens with "**The product DB** has replicas" (AGENTS.md:59-64) — it is scoped to stamphog's separate product DB, not review_hog's main-DB model, so it does not cleanly apply to these reads.+- **Found:** the pre-existing `review_inbox_prs` gate used the identical unpinned `ReviewUserSettings.load(...)` read (the diff replaces `if not ReviewUserSettings.load(team_id, acting.id).review_inbox_prs`), and there is no `.using(db_for_write)` anywhere in review_hog receivers. The new `stamphog_review_inbox_prs` read follows the established review_hog convention verbatim — no new class of bug is introduced by this PR.+- **Found:** the same carve-out section states dismissal is never preference-gated, so even a hypothetically stale-triggered re-review's approval is voided on the next head change; the destructive-outcome window is already bounded.+- **Impact:** the finding is a documentation cross-reference nice-to-have on an internal invariants file, not a demonstrated correctness/security/reliability defect — it only asks to 'confirm' the code, and its technical premise misapplies a product-DB-scoped invariant to a main-DB read that already matches surrounding convention. This is documentation completeness bordering on style, below the keep bar; on the fence → drop (precision over recall).++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:84-91++**Carve-out invariant list omits the team-scoping requirement for the tasks-facade linkage match**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The PR description states a follow-up commit added 'team scoping enforced inside the tasks facade lookup itself (`find_signal_implementation_run(team_id=...)`, with tasks-side tests)', ported as hardening from a parallel implementation — implying an unscoped lookup was a real, previously-found gap. This file opens by billing itself as 'the contract: the invariants below were each earned through a real review finding — do not relax one without understanding what it closes' (lines 3-5), yet the new 'Rules that keep the exception narrow' list (lines 89-112) never states that the task-linkage match must be scoped to the reviewing repo's/PR's own team. Without that invariant written down here, a future change to the lookup (a caching layer, a query rewrite, a new caller) could silently drop the `team_id` filter and let a PR match a signal-implementation TaskRun belonging to a different team — reopening the exact class of bypass this carve-out was designed to avoid ('positively identified... never a trigger-side bypass').+- **Suggestion:** Add a bullet stating the tasks-facade match must be scoped to the acting team, e.g. 'the tasks-facade lookup (`find_signal_implementation_run`) is scoped to the repo's own team — an unscoped match would let another team's signal-implementation run authorize this repo's carve-out,' following this file's existing convention of naming the exact enforcement point for each rule.+- **Validator:** - **Checked:** `find_signal_implementation_run` in `products/tasks/backend/facade/api.py` (both PR commits), its call site in `products/stamphog/backend/tasks/tasks.py`, the AGENTS.md carve-out section, and the test coverage on both sides.+- **Found:** the team-scoping invariant is enforced in code, not left implicit. The facade returns `None` on any cross-team run: `if run is None or run.team_id != team_id: return None`, and its docstring explicitly states "the team scoping is enforced here — a run belonging to any other team returns None, and no caller can accidentally bind a PR to another tenant's run."+- **Found:** the stamphog call site re-enforces it belt-and-braces: `if run is None or run.team_id != repo_config.team_id: return None`, with the comment "The facade enforces the team scope; the recheck here is belt and braces for the boundary," plus the tasks.py docstring "a tasks-facade match for this exact repo, scoped to the config's team."+- **Found:** the exact regression the finding speculates about ("a future change could silently drop the `team_id` filter") is guarded by fail-closed tests on both sides — stamphog's `test_inbox_carve_out_scope` includes a `team_mismatch_fails_closed` case, and the tasks-side facade tests include an `other_team` / `team_id_offset` case asserting a mismatched team returns `None`.+- **Impact:** the finding is a documentation-completeness suggestion for an internal AGENTS.md invariants file. The tenant-isolation property it worries about is already enforced twice, documented at both enforcement points, and covered by tests that would catch a dropped `team_id` filter — so it is 'already handled', and the justification is a speculative future-regression argument rather than a present, reachable defect. A missing restatement in the invariants file does not itself constitute a correctness/security defect; below the keep bar (precision over recall → drop).++### [❌ dismissed] should_fix · security — products/review_hog/backend/receivers.py:126-138,210-236++**pr_url is forwarded into the privileged Stamphog approval leg without the format validation the sibling ReviewHog leg applies**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `handle_task_run_saved` takes `pr_url` straight from `TaskRun.output` and, when `stamphog_review_inbox_prs` is on, hands it unchanged to `_start_stamphog_review` → `queue_inbox_pr_review` (the stamphog facade), which mints a scoped credential and can post a real GitHub approval. The sibling ReviewHog leg (`_start_review` → `start_review_pr_workflow` in `products/review_hog/backend/temporal/client.py`) parses/validates the same kind of value via `PRParser().parse_github_pr_url(pr_url)` before use. The new stamphog leg has no equivalent check in this file, so an unexpected or malformed value in `output.pr_url` (written by the agent server observing the sandboxed self-driving run) reaches a higher-stakes, cross-product privileged write path with less scrutiny than the existing same-repo path applies to itself. The PR description states repo-config gating happens inside the queued Celery task, but that is a repo/team check, not necessarily a URL-shape/host check, and that code is outside this chunk so it can't be confirmed here.+- **Suggestion:** Validate/parse `pr_url` the same way the ReviewHog leg does (e.g. reuse `PRParser().parse_github_pr_url`) before calling `queue_inbox_pr_review`, or confirm and document that `queue_inbox_pr_review`/`process_inbox_pr_review` already performs equivalent validation prior to minting credentials or writing to GitHub, given this leg's action (a real approval) is materially more sensitive than ReviewHog's comment-only review.+- **Validator:** - **Checked:** The full receiver flow (`receivers.py` `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review`), and the actual privileged leg `process_inbox_pr_review` in `products/stamphog/backend/tasks/tasks.py` (fetched at PR head `1341596e`), plus `_parse_pr_url`/`_PR_URL_RE` and the repo-config gate.+- **Found:** `queue_inbox_pr_review` only does `process_inbox_pr_review.delay(...)` — no credential mint or GitHub write happens on the receiver/save path. The task's **first** statement is `parsed = _parse_pr_url(pr_url); if parsed is None: log('stamphog_inbox_pr_unparseable_url'); return` (tasks.py process_inbox_pr_review, ~line 271). `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` validates host+shape and returns None on anything malformed — the same regex-parse contract as the ReviewHog leg's `PRParser().parse_github_pr_url`.+- **Found:** Validation is strictly _stronger_ than the ReviewHog leg, not weaker: after parsing, the task requires the parsed `repository` to match a team-scoped, synced+enabled `StamphogRepoConfig` (`for_team(team_id).filter(repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="")`) before any GitHub call, and the minted credential uses `repo_config.installation_id` — derived from the positively-identified config, never from the raw URL. An unparseable or off-host URL, or a well-formed URL for a repo the team hasn't installed Stamphog on, is a logged no-op before any privileged action.+- **Impact:** No unvalidated `pr_url` can reach credential minting or a GitHub approval. The finding's core premise — 'reaches a higher-stakes privileged write path with less scrutiny' — is mistaken; the check exists, is equivalent-or-stronger, and lives in the queued task by design (the receiver comment explains the save path is intentionally light). Falls in the 'wrong / unreproducible' and 'already handled elsewhere' drop categories.++### [❌ dismissed] consider · code_quality — products/review_hog/backend/receivers.py:144,159++**Inconsistent type annotation for signal_report_id between the two acting-reviewer resolvers**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` (the new hook registered with stamphog's inbox registry, `products/stamphog/backend/facade/inbox_hooks.py`) types its `signal_report_id` parameter as `str`, while `_resolve_assigned_reviewer`, which it immediately delegates to and which is called with the exact same value, still types it as `Any`. Both ultimately feed the same `SignalReportArtefact.objects.filter(report_id=signal_report_id, ...)` lookup. Since `resolve_stamphog_acting_reviewer` is the concrete implementation of a cross-product callback contract (stamphog calls it without static type-checking across the product boundary), a tightened-but-inconsistent signature at this seam makes the actual accepted type ambiguous to callers and future maintainers, and works against the repo's mypy --strict-style guidance to avoid `Any` in new/touched signatures.+- **Suggestion:** Type `signal_report_id` consistently as `str` on `_resolve_assigned_reviewer` too (or explicitly narrow/cast at the one call site that currently passes `Any`), so the shared resolution path and the newly-exposed cross-product hook agree on the accepted type.+- **Validator:** - **Checked:** Both signatures in the PR (`resolve_stamphog_acting_reviewer(... signal_report_id: str ...)` vs `_resolve_assigned_reviewer(... signal_report_id: Any ...)`), the master baseline, and what each caller actually passes.+- **Found:** The `Any` is **pre-existing** — master's `_resolve_acting_reviewer` (receivers.py:112) was already `signal_report_id: Any`; the PR only renamed the function. It is not a newly-introduced `Any` in a touched signature the way the finding implies.+- **Found:** The two resolvers legitimately accept different concrete types. `_resolve_assigned_reviewer` has two callers: the receiver passes `task.signal_report_id` **raw** (a UUID-typed field value — elsewhere wrapped as `str(task.signal_report_id)` for workflows, receivers.py:95/175), while the stamphog hook passes `str(run.signal_report_id)` (tasks.py:923). `Any` is the loosest-correct annotation covering both UUID and str. `resolve_stamphog_acting_reviewer` only ever receives a `str`, so `str` is accurate there.+- **Found:** No mypy error exists today: `str`→`Any` delegation and UUID→`Any` are both valid. The suggested 'type it `str` consistently' would be _incorrect_ — the raw-UUID receiver call site would then fail `str` assignability. The cross-product contract callers see is the hook (`resolve_stamphog_acting_reviewer`), which is already typed `str`; the internal `Any` never crosses the boundary, so the 'ambiguous to cross-product callers' claim is overstated.+- **Impact:** Zero runtime effect, no type error, no correctness/security/contract consequence. Pure annotation style/taste — the explicit drop category under precision-over-recall — and the proposed change would introduce an inaccuracy rather than fix a defect.++### [❌ dismissed] should_fix · security — products/stamphog/backend/facade/api.py:112-157,129-129++**process_inbox_pr_review/queue_inbox_pr_review trust caller-supplied PR linkage with no independent re-verification, unlike the webhook leg**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `queue_inbox_pr_review` (and the `process_inbox_pr_review` Celery task it dispatches, `products/stamphog/backend/tasks/tasks.py` ~1107-1245) accept `team_id`, `pr_url`, `acting_user_id`, `signal_report_id`, and `task_run_id` as independent caller-supplied values and stamp them straight into `ReviewRun.output.inbox_review` with no internal check that they are mutually consistent. The moment that dict is non-empty, `temporal/activities.py` sets `self_driving_review=True`, which relaxes the sandboxed engine's bot-author refusal and draft prerequisite and (per the PR's own stated principle) is supposed to only ever fire behind a 'positively identified carve-out, never a trigger-side bypass'. The webhook leg (`_inbox_rereview_carve_out`, same file) honors that principle: before trusting anything, it independently re-derives the PR-to-task linkage via `find_signal_implementation_run(team_id=..., repository=..., pr_url=..., head_branch=...)` and re-checks `run.team_id == repo_config.team_id`. Leg 1 has no equivalent — it trusts whatever `pr_url`/`task_run_id`/`signal_report_id`/`acting_user_id` review_hog's receiver happened to pass, with no cross-check that `task_run_id`'s TaskRun actually produced `pr_url`, or that `acting_user_id` belongs to `team_id`. This file already applies exactly this kind of defense elsewhere in the same module — `create_review_run` deliberately re-resolves `pull_request` `for_team(team_id)` specifically 'rather than trusting the raw FK id: a caller passing another team's pull_request_id would otherwise create a run whose reads follow the FK across the tenant boundary' — so the precedent for not trusting a caller-supplied id blindly already exists right next to this new code. A bug in review_hog's receiver (wrong team_id, stale/mismatched pr_url, or an acting_user_id that isn't actually opted in) would silently grant an arbitrary PR the self-driving bypass with no safety net inside stamphog itself.+- **Suggestion:** Before creating the `ReviewRun` in `process_inbox_pr_review`, cross-validate the caller's claim against the tasks facade the same way the webhook leg does — e.g. call `products.tasks.backend.facade.api.find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url)` (or an equivalent lookup by `task_run_id`) and bail out (log + return, don't retry) if it returns `None`, doesn't match `task_run_id`/`signal_report_id`, or its `team_id` doesn't match. This makes leg 1 positively identified the same way leg 2 already is, instead of relying entirely on review_hog having gotten it right.+- **Validator:** - **Checked:** what each caller-supplied field actually gates downstream — `_mint_reviewer_gateway_token` (activities.py:123), `self_driving_review` derivation (activities.py:451), `is_inbox_review` (activities.py:237-238), every `acting_user_id`/`signal_report_id`/`task_run_id` usage across stamphog's temporal/logic (grep), the `for_team(team_id)` scoping in `process_inbox_pr_review` (tasks.py:1141-1229), and the sole caller `_start_stamphog_review` in review_hog's receiver.+- **Found (tenant boundary already enforced):** the `create_review_run` precedent the finding cites is already satisfied here — `process_inbox_pr_review` resolves `repo_config` via `StamphogRepoConfig.objects.for_team(team_id)` (enabled + non-blank installation + connecting user, else no-op), upserts the PullRequest under that config, and creates the run via `ReviewRun.objects.for_team(team_id).create(team_id=team_id, ...)`. A wrong `team_id` cannot make the run read or create another team's data, and the PR is only reviewable if that team has the repo configured+enabled+installed.+- **Found (credential not caller-controlled):** the sandbox gateway token is minted under `repo_config.connected_by_user_id` (activities.py:123), derived from the team-scoped config — never the caller's `acting_user_id`. A wrong `acting_user_id` grants no access.+- **Found (provenance-only fields):** `acting_user_id`/`signal_report_id`/`task_run_id` are stamped into `output.inbox_review` and never consumed as gates in the review pipeline (grep shows no downstream reads). `self_driving_review` keys only on `inbox_review` being truthy (activities.py:451), and its bypass is limited to bot-author + draft gates plus skipping the author merged-PR fetch — all on a PR in the team's own configured repo under the team's own credential.+- **Found (asymmetry is by design):** leg 2 needs `find_signal_implementation_run` because a GitHub webhook fires for any PR (dependabot/human/etc.) with no trusted linkage, so it must positively identify self-driving PRs before relaxing gates. Leg 1 is triggered BY the identified self-driving TaskRun save itself (review_hog only calls the facade for a non-internal signal-report task with the opt-in toggle on), and derives `pr_url`/`task_run_id`/`signal_report_id`/`team_id` coherently from that one TaskRun — the identification is inherent in the trigger, not reconstructed.+- **Impact:** does not meet the bar. The concrete trigger requires a hypothetical bug in review_hog's receiver (an upstream invariant, not a reachable input on this path), and no cross-tenant or privilege consequence can be named because tenant scoping and credential sourcing are already enforced inside stamphog. This is defense-in-depth against an upstream-ruled-out error — precision-over-recall says drop.++### [❌ dismissed] must_fix · best_practice — tools/pr-approval-agent/review_pr.py:590-590,225-225++**Draft-prerequisite bypass is not scoped to bot authors, unlike the bot-author bypass**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The two gates this PR relaxes use inconsistent conditions. The bot-author refusal bypass at line 225 requires `self.pr.author_is_bot and not self.self_driving` — i.e. it only ever matters (and only ever fires the bypass) for bot-authored PRs. But the draft-prerequisite bypass at line 590 is `pr.draft and not self.self_driving`, which drops the draft check for _any_ PR once `self.self_driving` is true, regardless of whether the author is a bot. The PR's own stated design goal is a 'positively identified carve-out' that is supposed to apply only to bot-authored self-driving inbox PRs, not a general draft-gate relaxation. If `self_driving` is ever mis-derived by an upstream caller for a human-authored draft PR (a bug in the context-assembly code that lives outside this chunk, or any future caller that sets this flag), this specific line would let a human's unfinished draft PR receive Stamphog's full approval-worthy review and verdict while still in draft — exactly the scenario the draft gate exists to prevent. Restricting the relaxation to human PRs would be a real behavior change that undermines the safety property described in the PR intent ("Both keep governing human PRs exactly as before").+- **Suggestion:** Make the draft-gate bypass require the same compound condition as the bot-author bypass, e.g. `if pr.draft and not (self.self_driving and pr.author_is_bot):`, or centralize the check as a single `self.self_driving and self.pr.author_is_bot` property on `Pipeline` and use it at both call sites so the two carve-out conditions can never drift apart.+- **Validator:** - **Checked:** Both relaxed-gate conditions in `review_pr.py` (bot-author refusal in `run`, draft check in `_check_prerequisites`), and the sole producer of `self_driving` — `activities.py::run_review_in_sandbox` (`self_driving_review=bool(output.get("inbox_review"))`) — plus how `inbox_review` provenance is stamped.+- **Found:** `self_driving` is derived exclusively from the run's `inbox_review` provenance, which is stamped only on PRs positively linked to a signals implementation task. Those PRs are opened by the GitHub App machine user, and GitHub fixes PR authorship at creation, so `self_driving=True ⟹ author_is_bot=True` for every reachable input. Consequently the existing `pr.draft and not self.self_driving` and the suggested `pr.draft and not (self.self_driving and pr.author_is_bot)` are equivalent for all inputs that can actually occur — the proposed fix is a no-op except in the human-author + `self_driving=True` state, which the derivation makes unreachable.+- **Impact:** The claimed harm (a human's draft PR getting a full approval-worthy review) requires `self_driving` to be "mis-derived by an upstream caller … or any future caller" for a human PR — the same speculative flag-misderivation what-if the criteria classifies as defensive-coding paranoia / conditions that can't occur given the call sites. Today human PRs never carry `self_driving`, so they are governed exactly as before, matching the stated design. This is the most concretely-framed finding of the set (the two conditions do differ textually), but the divergence has no reachable behavioral effect, so it fails the real-impact bar; precision-over-recall points to drop, consistent with the sibling invariant-encoding findings already dropped.+- **Priority:** Not adjusting — dropped, so the flagged must_fix is moot.++### [✅ VALID] must_fix · bug — products/tasks/backend/facade/api.py:504-509++**find_signal_implementation_run excludes exactly the tasks it is meant to identify (task.internal is always True for auto-started implementation tasks)**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `find_signal_implementation_run` rejects the match whenever `task.internal` is true: `if task.signal_report_id is None or task.internal: return None`. But the _only_ code path that actually auto-starts a self-driving implementation task from a Signals report — `products/signals/backend/auto_start.py` (`_create_and_record_task_atomic`, calling `tasks_facade.create_and_run_task(..., internal=True, ...)`) — explicitly sets `internal=True` on that task (comment: "Internal so the run stays out of the default task list; the report surfaces it by id"). The research sub-task created in `products/signals/backend/report_generation/research.py` and the repo-selection helper task in `products/tasks/backend/logic/repo_selection/agent.py` also set `internal=True`. In this product, `internal` is purely a task-list-visibility flag (see the `internal=False` filters used for the default task list at `products/tasks/backend/facade/api.py:3540,3590`), not a "is this a real/production implementation run" signal. Because every genuine self-driving implementation task has `internal=True`, this function will _always_ return `None` for the exact PRs the whole feature exists to identify. That silently breaks `_inbox_rereview_carve_out` in `products/stamphog/backend/tasks/tasks.py`, which is the sole caller: leg 2 (the webhook re-review) can never positively identify a self-driving PR, so every `synchronize`/`reopened` push after the initial draft-time review falls through to the ordinary bot-author skip path. Worse, that skip path (`_retract_stale_approvals_on_skip`) unconditionally dismisses any standing stamphog approval on every head-changing event — so the very first push after leg 1's initial approval permanently revokes it with no re-review ever following, for the lifetime of the PR.+- **Suggestion:** Drop the `task.internal` exclusion (or invert the intent) — it does not distinguish "real self-driving implementation run" from anything else; it only hides a task from the default list. If a positive signal is still needed to exclude non-implementation signal-report tasks (e.g. a human-linked "discussion"/"research" relationship — see issue below), use `task.origin_product == Task.OriginProduct.SIGNAL_REPORT` and/or the recorded task↔report relationship (`SignalReport.associated_task_runs(..., type=TASK_RUN_TYPE_IMPLEMENTATION)` / the `signal_report_task_relationship` artefact) instead of `internal`. Add a test that constructs a TaskRun exactly like `auto_start.py` produces (`internal=True`, `origin_product=SIGNAL_REPORT`) and asserts `find_signal_implementation_run` returns a match — the current test suite apparently never exercised this against the real task shape.+- **Validator:** - **Checked:** `find_signal_implementation_run` (tasks facade:484-516), the `internal` flag through `create_and_run_task` → `Task.create_and_run` → `Task.objects.create(internal=internal)` (models.py:585-597), every production signal-report task-creation call site, and the PR/existing test fixtures.+- **Found (premise holds):** `find_signal_implementation_run` bails when `task.signal_report_id is None or task.internal` (facade:508). Every production path that creates a signal-report task passes `internal=True` — auto_start.py:261 (the auto-started implementation task, comment "Internal so the run stays out of the default task list"), custom_agent/base.py:683, research.py:715 — and that value lands directly on `Task.internal` via `Task.objects.create(internal=internal)` (models.py:594). No production path creates an `internal=False` signal-report task; the only `internal=False` is the dev seeder `seed_inbox_data.py:279`.+- **Found (why tests miss it):** `test_inbox_trigger.py` builds the reviewable task with `internal=False` (line 66 default) and only asserts `internal=True` → skipped (`internal_pipeline_task` case, line 273). So the suite exercises the seeder/fixture shape, never the real auto-start shape — exactly the gap the finding calls out.+- **Impact (confirmed correctness bug):** `find_signal_implementation_run` — the linchpin of leg 2's `_inbox_rereview_carve_out` and its sole positive-identification step — can never return a match for a real self-driving PR (all such tasks are `internal=True`). The carve-out therefore never fires, so every `synchronize`/`reopened` on a bot-authored self-driving PR falls through to the bot-author skip path, whose `_retract_stale_approvals_on_skip` (stamphog tasks.py:894) dismisses any standing approval on the first push with no re-review following. (Note: review_hog's receiver applies the identical `if task.internal: return`, receivers.py:88, so leg 1 is exposed to the same mismatch — reinforcing, not weakening, the root cause.) Concrete trigger + concrete consequence both nameable; the feature's headline capability is non-functional against the real task shape.+- **Priority:** must_fix is correct — this defeats the PR's core webhook re-review carve-out for the exact PRs it exists to serve, and is invisible to the current tests.++### [❌ dismissed] should_fix · security — products/tasks/backend/facade/api.py:504-509++**find_signal_implementation_run doesn't check origin_product, only signal_report_id — insufficient to prove "implementation", not "discussion"/"research"**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The function treats any task with a non-null `signal_report_id` (and, after fixing issue #1, `internal=False`) as a self-driving implementation run. But `signal_report_id` can be set on tasks whose relationship to the report is `discussion` or `research`, not `implementation` — the `signal_report_task_relationship` field on `TaskWriteSerializer` (`products/tasks/backend/presentation/serializers.py`) explicitly documents this ('implementation' also opens the auto-start spend gate", implying the other values do not), and elsewhere in this same facade module (`create_task`, line ~3786) the established convention for "is this really a signal-report task" is `task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT` together — not `signal_report_id` alone. A human can create such a task manually via the generic task-creation API with `origin_product=SIGNAL_REPORT`, `signal_report_task_relationship="discussion"`, and leave `internal` at its default `False` (that field is client-writable and unrelated to the relationship value). If that manually-created, non-implementation task's PR happens to be bot-authored (common: the create-task path doesn't force a user GitHub integration for `origin_product=SIGNAL_REPORT`, so PRs default to the team's bot installation), `find_signal_implementation_run` would misidentify it as a self-driving implementation run and let stamphog bypass the bot-author/draft/review-mode/write-permission gates for it — directly undermining the PR's stated "positively identified carve-out rather than a trigger-side bypass" invariant.+- **Suggestion:** Once the `internal` exclusion in issue #1 is corrected, add an explicit `task.origin_product == Task.OriginProduct.SIGNAL_REPORT` check, and — ideally — verify the recorded relationship is `implementation` (via the signals-side work-log/artefact, mirroring `SignalReport.associated_task_runs(..., type=TASK_RUN_TYPE_IMPLEMENTATION)`) rather than inferring it from `signal_report_id` presence alone.+- **Validator:** - **Checked:** `find_signal_implementation_run` (products/tasks/backend/facade/api.py:484-516), the write-serializer that governs how `signal_report`/`signal_report_task_relationship`/`internal`/`origin_product` are set (products/tasks/backend/presentation/serializers.py:329-646), the `create_task` convention the issue cites (api.py:3796), the stamphog carve-out caller (products/stamphog/backend/tasks/tasks.py:144-215, 860-889), and the documented invariant in products/stamphog/CLAUDE.md.+- **Found:** The implementation faithfully upholds the _agreed, documented_ invariant, not a weaker version of it — CLAUDE.md defines the carve-out target verbatim as "a non-internal, signal-report-carrying TaskRun matched through the tasks facade," which is exactly `signal_report_id is not None and not internal` at api.py:508. The finding is a disagreement with that design decision.+- **Found:** The primary suggested fix is ineffective for the described scenario. The reviewer's own attack sets `origin_product=SIGNAL_REPORT`, so adding an `origin_product == SIGNAL_REPORT` check (api.py) would not block it.+- **Found:** The deeper suggestion (require `relationship == implementation`) gates on a field the codebase explicitly declares non-security: serializers.py:329-337 documents `signal_report_task_relationship` as "a free-form label ... which have never been access-controlled — so no relationship is reserved here either." It is a signals work-log annotation, not an authorization boundary, and lives cross-product from this tasks-facade function.+- **Impact:** The real tenant-isolation concern (IDOR) is already closed — team scoping is enforced at api.py:505 and belt-and-braces rechecked at tasks.py:199 — and misidentification alone cannot act: the acting-reviewer opt-in resolver gates every carved-out review (tasks.py:201-207; empty/opted_out otherwise). The residual scenario requires someone to deliberately craft, in their own team, a bot-authored (bot installation, no user integration) signal-report-carrying task, for a report whose acting reviewer has opted into inbox reviews — a self-inflicted, same-tenant path whose worst outcome is stamphog reviewing a genuine PostHog Code bot PR the opted-in reviewer wanted reviewed. No cross-tenant/cross-user escalation, no data loss. Per the "precision over recall, when unsure drop" bar, this is a speculative what-if against a deliberate design, not a user-affecting defect.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:1152-1245++**New inbox task logs `repository=` while the sibling webhook task logs `repo=`**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Every log call in the pre-existing `process_pull_request_event` path (and `_record_merged_pull_request`) uses `repo=` as the structured field for the repository slug. The new `process_inbox_pr_review` task instead uses `repository=repository` throughout (e.g. lines 1152, 1159-1160, 1197, 1245). Both tasks log events about the same PR/repo entity from the same module, so this inconsistency makes it harder to build one log query, dashboard, or alert that correlates the webhook leg and the new receiver leg for a given repository — a filter scoped to `repo:"org/name"` silently misses every inbox-leg event.+- **Suggestion:** Use `repo=repository` in the new task's log calls to match the established convention in this module.+- **Validator:** - **Checked:** every structured-log call in this module — the webhook path `process_pull_request_event` and `_record_merged_pull_request` (products/stamphog/backend/tasks/tasks.py:407-1099) versus the new `process_inbox_pr_review` (tasks.py:1152-1241).+- **Found:** The claim is factually correct — the pre-existing legs use `repo=` while the new leg uses `repository=`. But the two legs already emit entirely disjoint event-name families: the webhook/merged legs log `stamphog_pr_event_*` / `stamphog_merged_pr_*`, while the inbox leg logs `stamphog_inbox_pr_*`. Any cross-leg correlation query must already span two event namespaces, so the field-name difference adds no new obstacle a `repo:` filter wouldn't already face.+- **Impact:** This is a structured-log key naming inconsistency with no behavioral difference — logs still emit correctly, just under a differently-named key. The validation bar explicitly drops pure naming/style with no behavioral effect; it is neither a correctness, reliability, contract, nor performance defect. The mild operability framing (log correlation) is undercut by the already-distinct event names. Below the surfacing bar (precision over recall).++### [❌ dismissed] consider · code_quality — products/stamphog/backend/facade/api.py:112-123++**has_reviewable_repo_config's "reviewable" definition is inconsistent with the definition used by the actual review pipeline**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `has_reviewable_repo_config` (which drives the `stamphog_connected` UI flag review_hog uses to enable/disable the inbox toggle) filters only on `enabled=True`, `connected_by_user_id__isnull=False`, and a non-blank `installation_id`. Every other place in this PR that resolves a "synced+enabled" config for actually running a review — `process_inbox_pr_review`'s repo_config lookup and `_inbox_rereview_carve_out`'s inline check — additionally filters `provider="github"`. Today `provider` defaults to `"github"` everywhere so this can't yet diverge in practice, but the two "is stamphog usable here" predicates are not kept in lockstep, and this is exactly the kind of dormant inconsistency stamphog's own CLAUDE.md invariants warn about (checks that must agree drifting apart). If a second provider is ever added, a team's toggle could render enabled while the actual review/carve-out queries (which do filter provider) silently find nothing.+- **Suggestion:** Add `provider="github"` to `has_reviewable_repo_config`'s filter (or centralize the "synced+enabled" predicate in one helper both call) so the UI-facing check and the pipeline's actual eligibility check can never diverge.+- **Validator:** - **Checked:** the three config-resolution predicates — `has_reviewable_repo_config` (products/stamphog/backend/facade/api.py:120-124), `process_inbox_pr_review`'s lookup (products/stamphog/backend/tasks/tasks.py:1143), and `_resolve_repo_config` (products/stamphog/backend/tasks/tasks.py:301) — plus the `provider` field definition and every `StamphogRepoConfig` create path.+- **Found:** The factual claim is accurate: only the pipeline queries carry `provider="github"`; the UI-facing check omits it. But `provider` is `models.CharField(default="github")` (products/stamphog/backend/models.py:29), the model comment states "GitHub is the only implemented provider today" (models.py:26-27), and the sole creation site hardcodes `provider="github"` (tasks.py:668). No code path can store any other value.+- **Impact:** Because `provider` is single-valued in practice, the two predicates return identical result sets today — there is no reachable state where `has_reviewable_repo_config` returns True while the pipeline query finds nothing. The reviewer explicitly concedes it "can't yet diverge in practice"; the only named trigger is "if a second provider is ever added," which is not in scope. This is exactly the future-proofing / speculative-what-if class the criteria say to drop — a real 'keep' must name a concrete trigger and consequence that can occur given current types and call sites, and this cannot. No current user-facing or correctness effect.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:144-156++**Cross-boundary toggle resolver has no exception handling, unlike every other entry point in this module**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered via `connect()` as a hook that stamphog's webhook-processing path calls synchronously before every re-review of a carved-out PR (per its own docstring: "stamphog's webhook path calls it before re-reviewing a self-driving PR on a later push"). Every other entry point in this file is defensive: `handle_task_run_saved` wraps its whole body in `try/except Exception`, and `_start_review`/`_start_stamphog_review` wrap their dispatch in `try/except`. This new function has none. It calls `_resolve_assigned_reviewer`, which runs a `SignalReportArtefact` query and `resolve_org_github_login_to_users` (which only catches `Team.DoesNotExist`, not generic DB/connection errors), then `ReviewUserSettings.load(...)`. Any transient failure on review_hog's own database — unrelated to stamphog's DB health — propagates as an uncaught exception out of the hook and into stamphog's webhook Celery task. Per `products/stamphog/CLAUDE.md`'s stale-approval invariant, that task must reliably run retraction/dismissal logic on every relevant delivery; an uncaught exception here risks failing or retrying webhook processing for the whole PR event, not just the stamphog leg.+- **Suggestion:** Wrap the body of `resolve_stamphog_acting_reviewer` in a `try/except Exception` that logs (`logger.exception(...)`) and returns `None` on failure, mirroring `handle_task_run_saved`'s own pattern — a hiccup on review_hog's side should degrade to "don't re-review" rather than raising into stamphog's webhook path. Also consider a log line for the toggle-off / no-reviewer-resolved outcomes, consistent with the `review_hog_inbox_trigger_skipped` logging elsewhere in this file, since this function's return value now gates a real GitHub approval and currently produces no observability either way.+- **Validator:** - **Checked:** Every production caller of `resolve_stamphog_acting_reviewer` (it's reached only via the hook registry → `_inbox_rereview_carve_out`, tasks.py; plus one direct test call), and the surrounding control flow in `process_pull_request_event` including the stale-approval dismissal path.+- **Found:** The resolver is NOT called unguarded. Its sole production invoker `_inbox_rereview_carve_out` is wrapped at the call site: `if skip_reason is not None: try: carve_out = _inbox_rereview_carve_out(...) except Exception as e: logger.exception('stamphog_pr_event_inbox_carve_out_failed', ...); raise process_pull_request_event.retry(exc=e)`. So a review_hog DB blip is caught and turned into a Celery retry, not an uncaught exception — the finding's central premise is mistaken.+- **Found:** Retry-on-failure is deliberate here, with an inline comment: 'Retry (don't drop) on failure: a transient DB blip during the carve-out resolution must not silently drop a legitimate re-review.' The invariant is preserved: dismissal (`_retract_stale_approvals_on_skip`) is not silently skipped — the whole event retries until the carve-out resolves, then either re-reviews (dismiss handled in-workflow) or takes the skip path (which dismisses). `_mark_pr_event_processed` runs only on success, so retries safely reprocess.+- **Found:** The suggested fix (wrap resolver, log, `return None`) would _regress_ correctness: returning None on a transient blip makes the carve-out read as 'no reviewer opted in' → the PR is treated as an untrusted bot-author skip → its standing approval is dismissed and the re-review dropped. That is precisely the silent-drop the current design avoids by retrying. The `handle_task_run_saved` fail-soft pattern doesn't transfer — that runs in tasks' save path (no retry, must not raise into the saver); this runs in a Celery task built for retry.+- **Found:** The observability sub-suggestion is largely already met at the call site, which has `delivery_id` context: opt-out logs `stamphog_pr_event_skipped` with reason `inbox_opt_out`; no-reviewer falls through to the existing skip-reason log.+- **Impact:** No real reliability defect — the alleged uncaught propagation doesn't exist, and the proposed change would introduce the invariant violation it claims to prevent. Fails the keep bar (wrong/unreproducible premise; already handled at the caller).++### [❌ dismissed] should_fix · bug — products/review_hog/backend/receivers.py:210-217++**New Stamphog side-effect gate is not confirmed to pin its repo-config read to the writer DB, despite this being a documented, recurring bug class in this exact product**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `_start_stamphog_review`'s docstring states the repo-config gate ("a synced+enabled StamphogRepoConfig for the PR's repository") happens inside `queue_inbox_pr_review`'s queued Celery task, which decides whether to create a `ReviewRun`, start the sandboxed review, and eventually post a real GitHub approval. `products/stamphog/CLAUDE.md` documents an explicit invariant: "Any read that gates a side effect (GitHub write, Slack post, supersession, run creation) must be pinned via `.using(router.db_for_write(Model))` — a lagged reader silently skips retractions, resurrects disabled channels, or strands queued runs... this class of bug has been found on five separate paths." Every existing repo-config gate in `products/stamphog/backend/tasks/tasks.py` follows this (e.g. `_resolve_repo_config` explicitly pins to the writer for exactly this reason). This chunk doesn't include `queue_inbox_pr_review`'s implementation, so it can't be confirmed whether the new gate follows the same convention — if it reads through the default (possibly-replica) manager instead, a team that just connected/enabled Stamphog could have its first inbox PR silently skipped, or a just-disabled repo could still get reviewed, for as long as replication lag persists.+- **Suggestion:** Confirm (in whichever chunk implements `queue_inbox_pr_review`) that its `StamphogRepoConfig` lookup uses `.using(router.db_for_write(StamphogRepoConfig))`, matching every other decision-gating read in this product. If it already does, this is a non-issue; if not, it reproduces the exact bug class the product's own docs call out as already recurring five times.+- **Validator:** - **Checked:** The full chain the finding says it couldn't see — `queue_inbox_pr_review` (facade `api.py`) and the `process_inbox_pr_review` task (`products/stamphog/backend/tasks/tasks.py`) that actually gates run creation / the GitHub approval, fetched at PR head `1341596e`.+- **Found:** `queue_inbox_pr_review` performs no DB read — it only does `process_inbox_pr_review.delay(...)`. The authoritative repo-config gate lives in `process_inbox_pr_review`, and it IS writer-pinned exactly per the invariant: `write_db = router.db_for_write(StamphogRepoConfig)` then `StamphogRepoConfig.objects.for_team(team_id).using(write_db).filter(provider='github', repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False).exclude(installation_id='')...`, with an inline comment naming the reader-lag invariant. This matches `_resolve_repo_config` on the webhook leg.+- **Found:** The only non-writer-pinned repo-config read added by the PR is `has_reviewable_repo_config` in the serializer, but that gates nothing — it drives a disabled-state UI hint. The side-effect gate (ReviewRun creation → sandbox → approval) is the writer-pinned one, so the invariant the finding cites is satisfied where it matters.+- **Impact:** No reader-lag bug: a just-connected/enabled or just-disabled repo is evaluated against the writer at the moment the run would be created, so first-PR reviews aren't silently skipped and disabled repos aren't reviewed. The finding is a 'please confirm' flag whose own condition ('If it already does, this is a non-issue') resolves to non-issue on inspection.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1130-1159++**Receiver-leg inbox trigger has no debounce, risking installation-wide GitHub rate-limit exhaustion**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `queue_inbox_pr_review` (facade/api.py) unconditionally dispatches `process_inbox_pr_review.delay(...)` every time it's called, and `process_inbox_pr_review` unconditionally calls `StamphogGitHubClient(...).get_pr(...)` (tasks.py:1159) before it can even evaluate the head-sha dedupe — the docstring explains this is because the dedupe key only exists on GitHub. The caller (review_hog's `TaskRun` post_save receiver, per its own docstring) fires "on every TaskRun output save carrying the PR URL" and explicitly calls `TaskRun` "a hot model". Unlike the LABEL-mode re-review path in this same file, which guards an analogous repeat-trigger risk with `STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS`/`_label_cooldown_key`, this new receiver leg has no cooldown or coalescing: a self-driving task that saves `output` repeatedly while an agent iterates (any save that still includes the `output` field, even with `pr_url` unchanged, re-triggers the chain) issues one `get_pr` call against the installation's shared GitHub App token per save. Because GitHub's REST rate limit is per-installation, a single busy self-driving run can burn a meaningful share of that budget and degrade or block Stamphog reviews for every other repo/PR under the same installation — a blast radius beyond the one PR being iterated.+- **Suggestion:** Add a short-lived per-(team, task_run_id) or per-(team, pr_url) cooldown/coalescing lock — mirroring the existing `_label_cooldown_key`/`STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS` pattern — so a burst of output saves within a short window collapses into a single `process_inbox_pr_review` dispatch/GitHub fetch instead of one per save.+- **Validator:** - **Checked:** the whole trigger chain — the receiver `handle_task_run_saved` (products/review_hog/backend/receivers.py:72-141) and its early-exit guards, `_start_stamphog_review` (receivers.py:210-234), the facade dispatch (products/stamphog/backend/facade/api.py:128-155), `process_inbox_pr_review` (products/stamphog/backend/tasks/tasks.py:1130-1245), and the `output` write paths (`set_task_run_output` facade/api.py:2139-2154; the `set_output` PATCH view products/tasks/backend/presentation/views/api.py:1107).+- **Found:** The expensive path is already deduped, so a redundant fire wastes only one lightweight `get_pr` REST call, not a sandbox/LLM review. `process_inbox_pr_review` head-sha dedupe (tasks.py:1202-1221) returns without creating a review when a live/delivered run already exists at the current head. `get_pr` at tasks.py:1159 is a single REST call, and `GitHubRateLimitError` is caught and retried with backoff (tasks.py:1160-1162) rather than hard-blocking.+- **Found:** The trigger does NOT fire on a hot per-agent-step loop. Streaming goes through `append_log` (a separate field) which never touches `output`, and the receiver drops any save whose `update_fields` excludes `output` (receivers.py:86); status/heartbeat saves are excluded too. Only discrete `set_output` PATCH calls carrying `pr_url`, on a non-internal signal-report task whose acting reviewer opted in, reach the dispatch — a small, bounded set per run.+- **Found:** The 'one fetch per re-trigger' shape is a deliberate, documented tradeoff already shipped in the pre-existing ReviewHog inbox leg in this same receiver (receivers.py:76-79: "a same-head re-trigger costs one fetch (early-exit)"), not an omission unique to this new leg.+- **Impact:** The claimed installation-wide rate-limit exhaustion requires a single run to issue thousands of `pr_url`-carrying `set_output` saves/hour against a GitHub App installation budget of 5,000+/hour; realistic per-run `set_output` volume is single-digit, and the costly review work is already collapsed by the head dedupe. This is a speculative-scale / low-impact concern that does not meet the performance-at-real-scale bar (precision over recall).++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:144-160++**Webhook-leg toggle resolver re-runs the full, uncached reviewer-resolution query chain on every push to a carved-out PR**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered as the hook stamphog's webhook path calls before every re-review of a carved-out PR (per its docstring: called on `synchronize` / `reopened` / base-retarget events for the life of the PR). It delegates straight to `_resolve_assigned_reviewer`, which on every single call: (1) queries `SignalReportArtefact` for the report's latest `suggested_reviewers` artefact, then (2) calls `resolve_org_github_login_to_users`, which itself does a `Team` lookup, three separate candidate-id queries (`UserSocialAuth`, `UserIntegration`, `Integration`) via `_candidate_user_ids_for_org_and_logins`, and a further `User` query with `prefetch_related` for GitHub identities. That is roughly 6-8 DB queries, none of them cached, executed synchronously inside the webhook request path. Before this PR, `_resolve_assigned_reviewer`'s predecessor ran once per `TaskRun` save (leg 1 only); leg 2 is new and re-runs the identical query chain on every subsequent push to an actively-iterated PR, even though the report's suggested-reviewers artefact essentially never changes across those pushes. On a PR that receives many commits during active development, this multiplies an already report-sized query chain by the number of pushes, adding avoidable latency and DB load to a webhook handler that (per the PR intent) may already be doing other repo-config and task-linkage lookups on the same request.+- **Suggestion:** Cache the resolved acting-reviewer id (or the raw artefact content) for a short TTL keyed by `(team_id, signal_report_id)` — e.g. Django's cache framework with a TTL of a minute or two — so repeated pushes to the same PR within that window reuse the prior resolution instead of re-querying from scratch. Invalidate or let it expire naturally since a new `suggested_reviewers` artefact is a rare, low-frequency event. Alternatively, have the webhook caller pass through the already-known acting-reviewer id from the linked `TaskRun`/`Task` (found via `find_signal_implementation_run`) when it hasn't changed, and only fall back to a fresh resolution when necessary.+- **Validator:** - **Checked:** The resolver's only production caller and execution context (`_inbox_rereview_carve_out` inside `process_pull_request_event`), whether that handler is request-path or background, the query chain in `resolve_org_github_login_to_users`/`_candidate_user_ids_for_org_and_logins` (`products/signals/backend/report_generation/resolve_reviewers.py:522/573`), and the resolver's toggle re-check.+- **Found:** `process_pull_request_event` is a Celery `@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)` (tasks.py:694). The reviewer-resolution queries therefore run on a background worker, not synchronously in the webhook HTTP request as the finding claims — so there is no user-facing webhook latency to speak of.+- **Found:** The per-event cost is a fixed, bounded ~6-8 indexed lookups (by team_id / report_id / logins), and the same handler already performs a GitHub `get_pr` API fetch plus repo-config and task-linkage lookups on every event — the DB chain is dwarfed by that network I/O. The work is spread across separate background events over a PR's life, not an in-request N+1 or quadratic blow-up. It only runs for the narrow carved-out category (bot-authored self-driving inbox drafts behind a default-off per-user toggle), so volume is low.+- **Found:** Re-resolving on every push is a deliberate safety property, not accidental waste: `resolve_stamphog_acting_reviewer` re-reads `stamphog_review_inbox_prs` each time so an opt-out mid-PR stops further re-reviews (its docstring states exactly this). The finding's primary suggestion — cache the resolved acting-reviewer id for a TTL — would bypass that fresh toggle read, letting an opted-out reviewer's PR keep getting re-reviewed for the cache window: a correctness regression in the property the function exists to guarantee.+- **Impact:** Does not meet the 'performance problem that bites at real scale' bar (background worker, bounded per-event query count, I/O-dominated, low-volume PR class), and the proposed optimization carries a real correctness downside. Speculative optimization → drop under precision-over-recall.++### [❌ dismissed] should_fix · best_practice — products/tasks/backend/facade/api.py:484-518++**find_signal_implementation_run's gating read isn't pinned to the writer DB, breaking stamphog's own reader-lag invariant for this exact class of decision**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `find_signal_implementation_run` (line 505: `run = find_task_run(pr_url=pr_url, branch=head_branch, repository=repository)`) calls into `products/tasks/backend/webhooks.py::find_task_run`, which queries `TaskRun.objects.filter(...)` with no `.using(router.db_for_write(TaskRun))` pinning — it goes through Django's normal read routing. This function is the sole positive-identification mechanism `_inbox_rereview_carve_out` uses to decide whether to bypass the bot-author/draft/review-mode/write-permission gates for a webhook delivery (products/stamphog/backend/tasks/tasks.py). Every other read that gates a side effect on this exact carve-out path is deliberately writer-pinned in this same PR — `_resolve_repo_config` (`.using(router.db_for_write(StamphogRepoConfig))`) and the leg-1 repo_config lookup in `process_inbox_pr_review` (`write_db = router.db_for_write(StamphogRepoConfig)`, with an explicit comment: "Writer-pinned like every read that gates run creation (reader-lag invariant)"). Yet this new cross-product call — arguably the single most security-relevant read in the whole feature, since it's what turns 'a bot-authored draft' into 'a positively-identified self-driving PR eligible for bypass' — has no equivalent pin. `products/stamphog/CLAUDE.md` documents this precise bug class as having been "found on five separate paths" for stamphog's own reads; this PR imports a cross-product read into the identical decision point without applying the same discipline. Django's `ReplicaRouter` (`posthog/dbrouter.py`) makes replica routing for `TaskRun` a pure runtime env-var flip (`READ_REPLICA_OPT_IN` or `ALL_MODELS_USE_READ_REPLICA`) with zero code change required — so this isn't a hypothetical: if TaskRun is ever opted into the read replica (for capacity reasons unrelated to stamphog), this exact call path silently starts reading a lagging replica with no signal in the diff that it needs revisiting, and a TaskRun/Task written moments earlier by the signals auto-start flow could be invisible to the carve-out on the very first synchronize that follows.+- **Suggestion:** Thread writer-pinning through to `find_task_run`, e.g. add a `use_writer: bool = False` (or a queryset-level `.using(...)`) parameter to `find_task_run` that `find_signal_implementation_run` sets `True`, mirroring the `write_db = router.db_for_write(...)` pattern already used twice elsewhere in this same PR. Leave the existing webhook-backstop caller of `find_task_run` on its current (unpinned) behavior if that's intentional there, but don't let the new self-driving gating decision inherit it silently.+- **Validator:** - **Checked:** `find_task_run` (products/tasks/backend/webhooks.py:29-98) for pinning; the carve-out's consumption of the result (products/stamphog/backend/tasks/tasks.py:191-215, and the skip-path retraction at 881-898); replica routing (posthog/dbrouter.py:22-30) and its opt-in source (posthog/settings/data_stores.py:271-272).+- **Found:** The unpinned-read claim is factually correct — `find_task_run` uses plain `TaskRun.objects.filter(...)` (webhooks.py:41, 69, 86). But replica routing is entirely env-var driven with no in-code opt-in (data_stores.py:271-272), and the reviewer's own wording is conditional ('if TaskRun is ever opted in'), so `TaskRun` is not on a replica today — the read hits the primary and there is no lag. Not a current defect.+- **Found:** The failure direction is fail-CLOSED. `find_signal_implementation_run` returns a DTO only on a positive match; a stale/lagging read yields `None`, the carve-out resolves empty (tasks.py:199-200), and the PR keeps today's refuse behavior. A stale read cannot produce a false positive, so it can never grant an improper bypass — only miss a legitimate one. The 'most security-relevant read' framing is therefore inverted: lag can only make the gate more conservative.+- **Found:** Safety is preserved regardless — an empty carve-out on a head-changing action still runs `_retract_stale_approvals_on_skip` (tasks.py:881-898), so no approval stands over unreviewed commits; and a missed synchronize self-heals via the next webhook or the receiver leg's re-fire.+- **Found:** The invoked reader-lag invariant governs the stamphog product DB (which has replicas today) for reads gating safety side effects; the sibling pins in this PR are on `StamphogRepoConfig` (product DB). This is a main-DB `TaskRun` read on the liveness side — not the same risk class.+- **Impact:** Triggering requires two speculative conditions to coincide: an ops-level replica opt-in for `TaskRun`, and an auto-start write racing this read inside the <100ms replica window — on a path (push → GitHub → synchronize webhook → Celery) that takes seconds, making the read-after-write collision practically unreachable. Worst case is one delayed re-review with safety intact. This is defensive/consistency hygiene for a non-current, fail-closed, self-healing condition — below the 'real problem that plausibly affects users' bar (precision over recall).++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1107-1245++**process_inbox_pr_review never re-checks the acting reviewer's toggle at execution time — only the webhook leg does, leaving a TOCTOU window where a just-disabled toggle still gets honored**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This is distinct from the already-flagged 'no re-verification of caller-supplied linkage' finding: even granting that `team_id`/`pr_url`/`task_run_id`/`signal_report_id`/`acting_user_id` are all internally consistent and correctly resolved by review_hog's receiver at enqueue time, `process_inbox_pr_review` never re-derives whether the acting reviewer's `stamphog_review_inbox_prs` toggle is still on by the time the Celery task actually executes. It builds `inbox_review = {"trigger": "inbox", ..., "acting_user_id": acting_user_id}` (~line 1176) straight from the task's arguments and stamps it onto the new `ReviewRun` at creation (~line 1223-1229) with no call to `get_inbox_acting_reviewer_resolver()` anywhere in the function. Contrast this with `_inbox_rereview_carve_out` (the webhook leg, same file), which the PR's own design explicitly re-resolves the toggle for on every delivery specifically because — per the PR description — "the toggle is re-resolved through a hook review_hog registers at app-ready" rather than trusted from an earlier check. Leg 1 has no equivalent: if a user disables the toggle after review_hog's synchronous check but before this queued Celery task runs (a real possibility during broker backlog, worker restart/redeploy, or the retry backoffs already coded into this function — `default_retry_delay=5`, `max_retries=3`, plus GitHub rate-limit retries with `countdown` up to 60s), the review still proceeds and a real GitHub approval gets posted for a reviewer who had already opted out by the time it happened. Given the receiver 'fires on every TaskRun output save' (per the already-covered debounce finding), a busy self-driving run can also back up this queue, widening the window in practice.+- **Suggestion:** Before creating the `ReviewRun` (or at least before the `transaction.on_commit` that starts the workflow), re-check `get_inbox_acting_reviewer_resolver()` with the run's `signal_report_id`/`task_created_by_id` the same way `_inbox_rereview_carve_out` does, and no-op if the reviewer is no longer opted in — keeping leg 1's toggle semantics as live as leg 2's rather than trusting a snapshot that can go stale across the queue hop.+- **Validator:** - **Checked:** the full `process_inbox_pr_review` body (products/stamphog/backend/tasks/tasks.py:1107-1245) for any resolver call; the facade contract (`queue_inbox_pr_review` docstring, products/stamphog/backend/facade/api.py:136-142); leg 2's toggle re-resolution and its opted-out dismissal (tasks.py:201-207, 881-909); and the design stance in products/stamphog/CLAUDE.md.+- **Found:** The asymmetry is factually real — leg 1 stamps `acting_user_id` from its task args (tasks.py:1176-1180) and never calls `get_inbox_acting_reviewer_resolver()`, while leg 2 does. But it is the deliberate, documented contract: the facade docstring states the caller (review_hog's receiver) 'has already resolved the acting reviewer and checked their stamphog_review_inbox_prs toggle,' so leg 1 is a synchronously-gated hand-off; leg 2 re-resolves only because the webhook path has no equivalent synchronous gate.+- **Found:** Safety does not depend on leg 1 re-checking. If the reviewer opts out, the next head-changing webhook enters leg 2's `opted_out` branch (tasks.py:206-207) and dismisses any standing approval via `_retract_stale_approvals_on_skip(..., _INBOX_OPT_OUT_DISMISS_MESSAGE)` (tasks.py:894-898). CLAUDE.md codifies exactly this: the toggle gates whether new runs START, and 'Dismissal is never preference-gated' — a switched-off toggle self-corrects on the next push.+- **Impact:** The TOCTOU window is seconds (widened to ~a minute only under broker backlog / retry backoff) and requires the user to disable the toggle immediately after they themselves triggered the self-driving run that opened the PR. The worst outcome is a stamphog verdict on their own team's DRAFT PR — one they opted into reviewing at trigger time — which does not gate merge until ready and is dismissed on the next commit. Rare, self-inflicted, low-impact, self-correcting, and consistent with the intentional design: a never-gonna-meaningfully-bite edge case below the surfacing bar (precision over recall).++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_pr.py:587-591,859-912,937-938++**Prerequisites gate reports "all clear" for self-driving draft PRs, hiding the carve-out from the posted GitHub verdict**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** When `self.self_driving` relaxes the draft check, `_check_prerequisites` (new line 590: `if pr.draft and not self.self_driving:`) returns `True, "all clear"` for a PR that is, in fact, still a draft. That exact `GateResult` message flows unedited into `_render_review_body()` (the human-facing comment/approval body the hosted server posts verbatim to GitHub per `review_local.py`'s own docstring and the PR's stated pipeline) via the `rows` table (`| prerequisites | ✓ | all clear |`). The only place the carve-out is actually recorded is the machine-readable `to_dict()["classification"]["self_driving"]` field added at lines 937-938, whose own comment calls it "Audit trail for the carve-out: which gates ran relaxed, and why" — but that JSON field is never surfaced in `_render_review_body()`. So a human (or a future auditor) reading the actual posted Stamphog approval/comment on a self-driving draft PR sees a gate table claiming "all clear" on prerequisites with zero indication that the draft check — a real, known relaxation this PR intentionally introduces — was ever bypassed. That undermines the transparency goal implied by the carve-out being described as "positively identified" and audited: the audit trail exists in a JSON blob that isn't the thing displayed anywhere, while the displayed artifact silently asserts a stronger claim ("all clear") than is true.+- **Suggestion:** Have `_check_prerequisites` return a message that discloses the relaxation, e.g. `"all clear (draft check relaxed: self-driving carve-out)"` when `pr.draft and self.self_driving`, so the same string that reaches the LLM prompt's gate_lines and the posted comment's gate-mechanics table reflects reality rather than reporting a clean pass on a check that was actually skipped.+- **Validator:** - **Checked:** `_check_prerequisites` return values (review_pr.py:589-591), the posted-comment renderer `_render_review_body` (review_pr.py:843-896) and its gate table `rows` (line 884), the `to_dict` audit field (~937), and what the LLM prompt actually receives (the `_format_self_driving` provenance block).+- **Found:** The premise is factually accurate — the gate table would show `| prerequisites | ✓ | all clear |` on a self-driving draft and `_render_review_body` never surfaces `self_driving`. But the suggested fix is purely a change to a human-facing display string (`"all clear"` → `"all clear (draft check relaxed…)"`) with no behavioral difference: the verdict, the approval, and the gate pass/fail are unchanged. `"all clear"` is the generic gate-pass message shared by every gate (CI is likewise intentionally not a hard prerequisite, review_pr.py:586-587), not a specific assertion that the PR is non-draft.+- **Found:** The transparency the finding says is missing largely exists elsewhere — the machine-readable audit trail is in `to_dict()["classification"]["self_driving"]`, the LLM reviewer is explicitly told "It is a draft on purpose … draft state is not a caution signal" via `_format_self_driving`, and GitHub itself shows the PR's draft badge next to the approval. So no reader (LLM, auditor, or human on the PR) is actually misled about the draft state.+- **Impact:** No correctness, security, data-loss, contract, performance, or reliability effect — it is a wording/presentation nicety on a display string, which the criteria explicitly place in the pure-style/taste drop bucket ("comment wording … with no behavioral difference"). Precision-over-recall points to drop.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1.mdnew file mode 100644index 000000000000..57f787666fb9--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-1.md@@ -0,0 +1,354 @@+# Reviewer-quality run — `A-sonnet5-xhigh-1`++- **Dumped:** 2026-07-23T16:19:53+00:00+- **Report id:** `019f8f89-16b6-728c-9d31-b931d5b609c6` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 4044s (67.4 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-sonnet-5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 25 | 20 | 3 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| ------------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 126 | 109,152 | 766,564 | 14,950,199 | 184,082 | 8 | $17.41 | $17.41 |+| claude-sonnet-5 | review | 156 | 238,937 | 1,803,707 | 18,016,362 | 282,229 | 10 | $11.41 | $11.41 |+| claude-sonnet-5 | blind-spot | 103 | 114,878 | 1,121,718 | 12,039,644 | 148,030 | 0 | $6.92 | $6.92 |+| claude-opus-4-8 | review | 38 | 2,994 | 457,097 | 4,538,486 | 44,482 | 0 | $6.25 | $6.25 |+| claude-opus-4-8 | blind-spot | 26 | 3,769 | 207,726 | 4,168,690 | 37,439 | 3 | $4.34 | $4.34 |+| claude-sonnet-5 | dedup | 1 | 21,394 | 0 | 0 | 9,818 | 0 | $0.14 | $0.14 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,756 | 0 | $0.04 | $0.04 |+| @cf/zai-org/glm-5.2 | other | 1 | 20 | 0 | 0 | 50 | 0 | — | $0.00 |+| **total** | | **452** | **500,173** | **4,356,812** | **53,713,381** | **707,886** | **21** | **$46.52** | **$46.52** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `@cf/zai-org/glm-5.2` (1 gen(s), gw $0.00).+- naive method (all prompt tokens at input price): $203.82 — 4.4× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $35.4477 over 452 gen(s) (true $35.4477, Δ +0.0%)+ - · of which cache read: $17.8399 over 439 gen(s) (true $17.8399, Δ +0.0%)+ - · of which cache write: $16.2597 over 445 gen(s) (true $16.2597, Δ +0.0%)+ - · of which fresh (derived): $1.3481 over 452 gen(s) (true $1.3481, Δ +0.0%)+ - output: $11.0685 over 452 gen(s) (true $11.0684, Δ +0.0%)+- 21 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------------------------------- |+| …e82cbc47 | issues-review-p1-c3 | 15:13:35 | 22,746 | 36,255 | claude-sonnet-5 |+| …33a62b9f | issues-review-p3-c1 | 15:13:35 | 22,746 | 48,061 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …441cb406 | issues-review-p2-c2 | 15:13:36 | 22,746 | 50,335 | claude-sonnet-5 |+| …92889f35 | issues-review-p1-c1 | 15:13:36 | 22,746 | 48,065 | claude-sonnet-5 |+| …6ef14190 | issues-review-p2-c3 | 15:13:38 | 22,746 | 36,251 | claude-sonnet-5 |+| …afae5619 | issues-review-p2-c1 | 15:13:38 | 22,746 | 48,064 | claude-sonnet-5 |+| …a7859b17 | issues-review-p3-c2 | 15:13:40 | 22,746 | 50,337 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …8ea26595 | issues-review-p1-c2 | 15:13:41 | 22,746 | 50,336 | claude-sonnet-5 |+| …1aa7ddc5 | issues-review-p3-c3 | 15:13:41 | 22,746 | 36,254 | claude-sonnet-5 |+| …a6d6712f | blind-spots-c3 | 15:35:51 | 0 | 63,436 | claude-sonnet-5 |+| …e8b24e2c | blind-spots-c1 | 15:35:52 | 0 | 74,410 | claude-sonnet-5 |+| …e14f21fe | blind-spots-c4 | 15:35:53 | 0 | 55,445 | claude-sonnet-5 |+| …06074ce8 | blind-spots-c2 | 15:35:57 | 22,746 | 54,350 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …2e7aa565 | blind-spots-c3 | 15:44:08 | 0 | 63,434 | claude-sonnet-5 |+| …dad4f126 | validation-c4 | 16:00:07 | 17,420 | 22,204 | claude-opus-4-8 |+| …1707fe8f | validation-c1 | 16:00:14 | 17,420 | 22,588 | claude-opus-4-8 |+| …22973c2a | validation-c2 | 16:00:14 | 17,420 | 22,550 | claude-opus-4-8 |+| …df6cd322 | validation-c3 | 16:00:17 | 17,420 | 22,375 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **14/18** (report the distribution, not a median).+- ⚠️ 3 unit(s) switched models mid-session (overload rescue?) — cache sharing and cost pinning are broken for them: …33a62b9f, …a7859b17, …06074ce8++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 22s |+| review wave (perspectives) | 22m 19s |+| blind-spot sweep | 22m 18s |+| dedup (incl. combine/clean) | 1m 36s |+| validation | 20m 10s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 44m 38s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 2 |+| 1 | 2 | review-hog-perspective-contracts-security | 3 |+| 1 | 3 | review-hog-perspective-contracts-security | 4 |+| 2 | 1 | review-hog-perspective-logic-correctness | 3 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 2 |+| 1000 | 4 | review-hog-blind-spots-general | 2 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider · security — products/stamphog/backend/facade/api.py:128-155++**queue_inbox_pr_review/process_inbox_pr_review trust acting_user_id with no ownership check against team_id**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `queue_inbox_pr_review` accepts `team_id`, `pr_url`, `acting_user_id`, `signal_report_id`, and `task_run_id` as plain scalars and forwards them verbatim into `process_inbox_pr_review.delay(...)` with no validation that `acting_user_id` is actually a member of `team_id` or has any relationship to the signal report/task run being reviewed. The docstring places the entire trust burden on the caller ("the caller has already resolved the acting reviewer and checked their toggle"), and `process_inbox_pr_review` (`products/stamphog/backend/tasks/tasks.py`) stamps this unchecked `acting_user_id` into `ReviewRun.output['inbox_review']` and proceeds straight to a real Temporal review/approval workflow. This is inconsistent with the sibling webhook-leg carve-out in the same PR, which re-verifies `run.team_id != repo_config.team_id` as explicit "belt and braces" defense-in-depth even though the tasks facade already enforces it — the receiver leg has no equivalent second check on the reviewer identity it is given.+- **Suggestion:** Add a lightweight defense-in-depth check before queuing/creating the run — e.g. confirm `acting_user_id` resolves to an active user with organization/team membership for `team_id` (or re-derive/re-check the reviewer via the same toggle resolver used on the webhook leg) — so a bug in the review_hog caller can't silently attribute a real GitHub approval to, or persist provenance for, a user who has no relationship to the team being reviewed.+- **Validator:** - **Checked:** the sole caller of `queue_inbox_pr_review`, what stamphog actually does with `acting_user_id`, and the webhook-leg belt-and-braces the finding cites as the missing precedent.+- **Found:** The only caller is `_start_stamphog_review` (`products/review_hog/backend/receivers.py:210-234`), an in-process TaskRun `post_save` receiver — not an external API. It passes `team_id=instance.team_id` and `acting_user_id` from `_resolve_assigned_reviewer(instance.team_id, …)` (`receivers.py:111`), which resolves GitHub logins to org members _of that team_ via `resolve_org_github_login_to_users(team_id, logins)` (`receivers.py:202-207`). `acting_user_id` is therefore server-derived within `team_id`; no external input reaches it, so the finding's premise (a reviewer with no relationship to the team) is unreachable through the actual call graph.+- **Found:** In stamphog `acting_user_id` is write-only provenance — stamped into `output["inbox_review"]` (`tasks.py:1180`, `1229`) and never read back for any privileged operation. The sandbox LLM credential is minted under `repo_config.connected_by_user_id` (`activities.py:123`), the engine's `self_driving_review` carve-out flag is `bool(output.get("inbox_review"))` (`activities.py:451`) not the user id, and the real GitHub approval is posted by the App machine user gated on a synced+enabled repo config — none of it is authorized by or attributed to `acting_user_id`.+- **Found:** The cited webhook-leg check `run.team_id != repo_config.team_id` (`tasks.py:199`) guards the task-run/team boundary that the cross-product facade `find_signal_implementation_run` could widen if refactored — it does NOT re-verify reviewer membership. The webhook leg derives its reviewer via the same trusted resolver scoped to `repo_config.team_id` (`tasks.py:201-205`), exactly as the receiver leg trusts the caller's resolution. The claimed asymmetry ("receiver leg has no equivalent second check on reviewer identity") does not exist: neither leg membership-checks the reviewer.+- **Impact:** No reachable IDOR/tenant-isolation hole and no real attribution bug — `acting_user_id` crosses no tenant boundary and drives no side effect in stamphog. The suggestion is a redundant membership check on a server-derived, non-authorizing provenance field, guarding against a hypothetical future caller bug the current code rules out. That is speculative + defensive-paranoia, below the bar; drop for precision over recall.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/facade/api.py:120-124++**has_reviewable_repo_config omits the provider filter used by every other repo-config lookup**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** has_reviewable_repo_config() filters only on `enabled=True`, `connected_by_user_id__isnull=False`, and non-blank `installation_id`. Every other repo-config lookup touched or added by this PR (`_resolve_repo_config` in tasks.py, and the new `process_inbox_pr_review`'s repo_config query) explicitly filters on `provider="github"` as well. Today this is harmless because GitHub is the only implemented provider, but this function drives the `stamphog_connected` flag the UI uses to enable/disable the new inbox toggle — if a second provider's config row (enabled, synced, non-blank installation_id) ever exists for a team without a matching GitHub config, this check would report the team as "connected" even though no GitHub-backed review path actually exists for it, silently diverging from the other three lookups it's meant to mirror.+- **Suggestion:** Add `provider="github"` to the filter for consistency with `_resolve_repo_config` and `process_inbox_pr_review`, e.g. `.filter(provider="github", enabled=True, connected_by_user_id__isnull=False)`.+- **Validator:** - **Checked:** the `StamphogRepoConfig.provider` field definition, the create/sync path that populates `installation_id`/`connected_by_user_id`, and whether the "every other repo-config lookup filters provider" premise actually holds.+- **Found:** `provider = models.CharField(max_length=32, default="github")` with no `choices` (`products/stamphog/backend/models.py:29`); GitHub is the only implemented provider. Reaching the state `has_reviewable_repo_config` gates on — `enabled=True`, non-blank `installation_id`, and `connected_by_user_id` set (`api.py:120-124`) — is unreachable for a non-github row: `installation_id` and `connected_by_user_id` are stamped only by the GitHub App installation/sync flow (provider-specific), and a manually-created config binds disabled with a blank installation and no connecting user. So no non-github row can ever satisfy the predicate today.+- **Found:** the premise that this diverges from "every other repo-config lookup" is inaccurate — `get_repo_config` (`api.py:107-109`) also omits `provider=`, filtering only `repository=`. A team-scoped lookup without the provider filter already has precedent in the same file, so the pattern the finding says it should mirror isn't uniform.+- **Impact:** The finding's own text concedes "Today this is harmless because GitHub is the only implemented provider." The consequence requires a second SCM provider to exist AND have a synced, enabled, non-blank-installation config for a team lacking a GitHub config — none of which is implemented or reachable. That is future-proofing for an out-of-scope case / a speculative what-if / a never-gonna-happen edge case, all of which the criteria list as drop. No real input affects any user today, so it is below the bar; drop for precision over recall.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/reviewer.py:683-703++**`_format_self_driving` asserts "the author is a machine user" to the LLM with no cross-check against pr.author_is_bot, so a self_driving/author mismatch doesn't just skip a gate — it actively feeds the reviewer a false trusted fact**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `_format_self_driving(self, cl: dict)` renders its block purely off `cl.get("self_driving")`, with no visibility into `pr.author_is_bot` at all (its signature only receives `cl`, not `pr`). The rendered text is placed in the `== TRUSTED CONTEXT ==` section of the prompt (line 568, ahead of `--- BEGIN UNTRUSTED CONTENT ---`), where the reviewer is instructed to take every claim at face value, and it makes unconditional, specific factual assertions: "The author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here — judge the diff strictly on its own merits" and "draft state is not a caution signal for this PR." If `self.self_driving` is ever `True` for a PR whose author is not actually a bot — the exact desync scenario already flagged for the bot-author/draft gates elsewhere in this chunk — this method doesn't merely fail to apply a gate; it hands the LLM a false, TRUSTED-labeled claim instructing it to specifically disregard the real author-familiarity, org-membership, and draft-state signals it would otherwise weigh for what is, in that scenario, an ordinary human PR. That is a materially different and arguably worse failure mode than a skipped gate: it's active misdirection inside the one section of the prompt the reviewer is told never to second-guess, and no other reviewed file (review_pr.py's gates, review_local.py's flag plumbing) touches this specific rendering path, so it has no independent defense-in-depth of its own.+- **Suggestion:** Pass `pr.author_is_bot` (or the equivalent field already on `PRData`) into `_format_self_driving` alongside `cl`, and only render the machine-user provenance claims when both `cl.get("self_driving")` and `pr.author_is_bot` hold; when they disagree, treat it the same as classification being unavailable (render nothing, or better, surface the mismatch itself as a reason to ESCALATE) rather than asserting a fact that isn't corroborated by the same author-identity data the rest of the prompt already carries.+- **Validator:** - **Checked:** `_format_self_driving` (reviewer.py:683-702), where `cl["self_driving"]` is populated (review_pr.py:477 `"self_driving": self.self_driving`), both gates keyed off the same flag (bot-author refusal review_pr.py:225, draft prerequisite review_pr.py:590), the server-side derivation of the flag (activities.py:449-451), both provenance-stamping legs (tasks.py `_inbox_rereview_carve_out`:144-229 and `process_inbox_pr_review`:1110+), and the two bot definitions (`_is_bot_authored` tasks.py:124 vs engine `is_bot_author` github.py:79).+- **Found:** The code premise is real — reviewer.py:692 renders the TRUSTED "author is a machine user" block purely off `cl.get("self_driving")`, with no `pr.author_is_bot` cross-check even though `pr.author_is_bot` is available (used at `review_pr.py:225`). But the posited desync (`self_driving=True` on a genuinely human-authored PR) is prevented at the source: `self_driving` is derived _only_ from inbox provenance (activities.py:451). The webhook leg refuses to stamp provenance unless `_is_bot_authored(pr)` holds (tasks.py:169 early return), and the receiver leg stamps it for a PR opened by the PostHog Code machine user by construction. The engine's `is_bot_author` (github.py:79) matches `type=='Bot'` OR `[bot]` login OR machine-user logins — a strict superset of the facade's `_is_bot_authored` (github/tasks.py:124-127) — so any PR that clears the facade gate also reads `author_is_bot=True` in the engine. There is no reachable path to `self_driving=True` + non-bot author.+- **Impact:** Does not meet the bar. This is a speculative "what-if"/defensive-coding suggestion guarding against a state upstream provenance derivation and the carve-out's positive-identification checks already rule out on both legs — a "drop" category under the criteria (precision over recall). The same root desync would also drive the sibling gate concerns, and it is prevented at the source rather than needing a redundant cross-check in the prompt renderer. Even in the impossible desync, the block only instructs the LLM to judge the diff on its merits and not treat draft state as a caution signal; the reviewer still evaluates the actual code and can REFUSE/ESCALATE, so it is not an unconditional approval.++### [❌ dismissed] must_fix · documentation — products/stamphog/AGENTS.md:100-105++**New carve-out's linkage lookup isn't documented as pinned to the writer DB, despite the file's own Reader-lag invariant**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This bullet documents the two new read-then-act gates for the carve-out — the tasks-facade linkage lookup (`find_signal_implementation_run`) and the `facade/inbox_hooks.py` toggle resolver — that decide whether the bot-author-refusal/review-mode/write-permission bypass fires and a real GitHub approval gets posted. That is exactly the pattern the file's own 'Reader-lag: pin decision reads to the writer' section (lines 59-64, immediately above) calls out: 'Any read that gates a side effect... must be pinned via `.using(router.db_for_write(Model))`... If you add a read-then-act path, pin it; this class of bug has been found on five separate paths.' The new section neither cross-references this invariant nor states whether the new reads honor it. I checked the actual PR implementation (products/tasks/backend/facade/api.py::find_signal_implementation_run → products/tasks/backend/webhooks.py::find_task_run) and confirmed the underlying read is a plain `TaskRun.objects.filter(...)` with no `.using(router.db_for_write(...))` pin — unlike the `StamphogRepoConfig` and `ReviewRun` reads added in the same PR (products/stamphog/backend/tasks/tasks.py), which are explicitly pinned via `router.db_for_write(...)`. A lagged replica read here can silently return 'not linked' right after a signal-implementation TaskRun is created (losing a legitimate re-review), or — the more consequential direction — return a stale 'still linked' result if a task's signal linkage is ever revoked after creation, incorrectly extending the bot-author-refusal bypass past the point it should have closed. Given this file is described as 'the contract' that 'hold[s] new code to all of them' (the invariants), this is a documentation gap for a security-relevant new code path, not just a stylistic nit.+- **Suggestion:** Either add a line noting that `find_signal_implementation_run`'s read (and the review_hog toggle resolver's `ReviewUserSettings.load`) must be pinned per the Reader-lag invariant — and pin them, mirroring the `StamphogRepoConfig`/`ReviewRun` reads already pinned elsewhere in this same PR — or, if pinning was deliberately skipped for this path, state why the invariant doesn't apply here so a future reader doesn't have to re-derive it.+- **Validator:** - **Checked:** `find_signal_implementation_run` (`products/tasks/backend/facade/api.py:484`), its delegate `find_task_run` (`products/tasks/backend/webhooks.py:29-99`), the carve-out caller `_inbox_rereview_carve_out` + `process_pull_request_event` (`products/stamphog/backend/tasks/tasks.py:144-217, 855-970`), and the sibling reads the finding cites as pinned.+- **Found:** The finding's three factual claims are all correct: `find_task_run` uses a plain `TaskRun.objects.filter(...)` with no `.using(router.db_for_write(...))` (`webhooks.py:38`); the stamphog-DB reads added in this PR ARE pinned (`_resolve_repo_config` `tasks.py:299-300`, `_resume_existing_delivery_run` `tasks.py:395-396`); and the read gates a GitHub approval.+- **Found (scope):** The Reader-lag invariant is written for the _stamphog_ product DB ("The product DB has replicas"). `find_signal_implementation_run` reads the _tasks_ DB through the pre-existing `find_task_run` (unchanged by this PR, also used by tasks' own merge webhook) — a different product with its own conventions. Every stamphog-DB read _inside_ the carve-out is pinned, so the invariant is honored for the DB it governs.+- **Impact:** The reachable failure direction is fail-closed and non-harmful. On a lagged false-negative the carve-out resolves empty, the PR stays refused (today's byte-for-byte behavior), and `_retract_stale_approvals_on_skip` (`tasks.py:~890`, head-changing branch) still dismisses any standing approval unconditionally — no approval is minted, none is left stale. A missed webhook-leg re-review is recovered by leg 1's head-keyed receiver dedupe. The webhook leg fires only on later pushes (synchronize/reopen/retarget), by which point the TaskRun linkage has long been committed, so the 'just created' race the finding posits isn't reachable on this path. The 'more consequential' false-positive direction requires a task's `signal_report_id`/`internal` to be revoked after creation, which does not occur.+- **Impact (bar):** This is a documentation cross-reference request on an invariants file whose underlying concern is fail-closed-safe in its reachable direction and speculative (never-gonna-happen linkage revocation) in its harmful one. It does not meet the keep bar for a correctness/security/reliability defect; under precision-over-recall it drops.++### [❌ dismissed] consider · documentation — products/stamphog/AGENTS.md:93-99++**Engine parity section doesn't cross-reference the new self_driving divergence it now has to accommodate**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The unchanged 'Engine parity' section states that `review_local.py` (hosted) 'must mirror `review_pr.py` (Action) semantics wherever both apply' and that divergence between the two runtimes 'has produced real approve-when-should-wait findings.' The new carve-out section (bullet 2, lines 92-99) introduces exactly this kind of runtime divergence by design: the hosted server can set `self_driving_review=True` while the Action never does. That's a deliberate, well-justified exception, but the Engine parity section — the place a future engineer would naturally look before touching either runtime — gives no hint that a documented exception exists, so someone auditing runtime parity could flag the divergence as a regression without realizing it's covered above.+- **Suggestion:** Add a one-line pointer in the Engine parity section (e.g. 'Exception: the `self_driving` carve-out flag — see the self-driving inbox carve-out section above') so the two invariants stay linked instead of relying on a reader to notice the connection unaided.+- **Validator:** - **Checked:** The PR version of `products/stamphog/AGENTS.md` — the Engine parity section (`:127-133`) and the new self-driving carve-out section (`:80-112`), plus what the carve-out already states about runtime divergence.+- **Found:** The premise is accurate: Engine parity (`:129-133`) warns that runtime divergence 'has produced real approve-when-should-wait findings' and does not mention the `self_driving` flag. But the carve-out section already documents the divergence completely, and bullet 2 (`:92-94`) explicitly says the flag 'defaults closed and the Action never sets it, so Action behavior is unchanged by construction' — so this is not a 'wherever both apply' divergence the parity rule governs; the Action never sets it.+- **Found:** The Engine parity section is unchanged by this PR (identical to base); the finding asks to edit an untouched section purely to add a pointer to the new one.+- **Impact:** No correctness/security/data-loss/contract/performance/reliability consequence. The only posited harm is a hypothetical future auditor briefly mistaking an intentional, already-documented exception for a regression — a documentation-navigation nicety, not a defect. Adding a cross-reference has no behavioral effect and both sections are already individually correct. This is pure documentation taste, which sits outside the keep bar; under precision-over-recall it drops. The reviewer already rated it the lowest priority ('consider'), consistent with it not meeting the surface threshold.++### [❌ dismissed] consider · code_quality — products/review_hog/backend/receivers.py:111-111,144-160++**Loose typing on signal_report_id undermines the cross-product hook contract**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer(team_id: int, signal_report_id: str, task_created_by_id: int | None)` is registered via `register_inbox_acting_reviewer_resolver` as a callback that stamphog's webhook path invokes across the product boundary — i.e. it's a formal cross-product interface, not just an internal helper. It declares `signal_report_id: str`, but delegates straight to `_resolve_assigned_reviewer(team_id: int, signal_report_id: Any, ...)`, whose only same-file caller (`handle_task_run_saved`, line 111) passes `task.signal_report_id` un-stringified. The shared helper's `Any` typing papers over whatever the real type is (likely a UUID from `SignalReportArtefact`), so there's no static guarantee that stamphog's runtime string actually matches what `SignalReportArtefact.objects.filter(report_id=...)` expects. Since this resolver's job is a security-relevant re-check (whether to let a later push get auto-approved), a silent type/format mismatch would fail closed (returning None, blocking review) but is worth tightening given it's an externally-consumed contract.+- **Suggestion:** Normalize `signal_report_id` to a single concrete type on both sides of the hook boundary (e.g. always `str`, converting at the `_resolve_assigned_reviewer` call sites the same way `_start_review`/`_start_stamphog_review` already do with `str(task.signal_report_id)`), and tighten `_resolve_assigned_reviewer`'s signature away from `Any` to match.+- **Validator:** - **Checked:** the flagged helper (`_resolve_acting_reviewer`/`_resolve_assigned_reviewer` at `products/review_hog/backend/receivers.py:112`), its ORM filter (`SignalReportArtefact.objects.filter(report_id=...)` at `:135`), the `SignalReportArtefact.report` field, and the underlying model types.+- **Found:** `SignalReport` extends `UUIDModel` (`posthog/models/utils.py:66`, `id = models.UUIDField(...)`), so `SignalReportArtefact.report = ForeignKey(SignalReport)` (`products/signals/backend/models.py:749`) makes `report_id` a UUID FK and `Task.signal_report_id` a UUID object. Django's `UUIDField` coerces a `str` and a `UUID` identically in query preparation — `filter(report_id=<str>)` and `filter(report_id=<UUID>)` emit the same SQL and match the same rows. The signals codebase already relies on this, annotating `report_id: str` while passing UUIDs and coercing with `str(...)` at boundaries (`products/signals/backend/models.py:825`, `:953`).+- **Impact:** The feared cross-boundary 'type/format mismatch' is unreachable: both call sites reference the same real report UUID, and the ORM normalizes str↔UUID, so results are identical. The issue itself concedes any mismatch 'would fail closed (returning None, blocking review)' — the safe direction, not a security hole; the loose `Any` cannot cause wrong-reviewer resolution or an unwarranted auto-approval. The suggestion is a type-annotation tightening (`Any` → concrete type) with no runtime behavior change — code quality/hygiene, explicitly framed as 'worth tightening,' rated lowest priority ('consider'). It names no concrete trigger+consequence that affects users, so under precision-over-recall it drops.+- **Checked (caveat):** PR #72680's changes are not in this checkout (migration 0019, `stamphog_review_inbox_prs`, `queue_inbox_pr_review`, `resolve_stamphog_acting_reviewer`, `register_inbox_acting_reviewer_resolver` all absent; `pull/72680/head` resolves to a master commit and the PR head SHA is unreachable), so the exact stamphog wrapper couldn't be inspected — but the Django UUID semantics above make the substance a non-defect regardless of the wrapper's `str` annotation.++### [✅ VALID] must_fix (validator→should_fix) · security — products/tasks/backend/facade/api.py:504-509++**find_signal_implementation_run keeps granting the self-driving carve-out after the backing task run is cancelled/failed or the task is deleted**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `find_signal_implementation_run` is the sole positive-identification check that lets stamphog's webhook carve-out bypass the bot-author refusal, draft prerequisite, per-repo review-mode gate, and author-write-permission gate for a PR (see `products/stamphog/backend/tasks/tasks.py`'s `_inbox_rereview_carve_out`, which calls this facade and only checks `run is None`/`run.team_id != team_id`). It delegates to `webhooks.find_task_run`, whose `pr_url` leg explicitly prefers non-terminal runs but falls back to a terminal one (`order_by('terminal_rank', '-created_at')` then `.first()`), and none of `find_task_run`'s legs filter on `task.deleted`. Cancelling a `TaskRun` (`TaskRun.Status.CANCELLED`/`FAILED`) or soft-deleting its `Task` only flips internal DB flags and tears down the sandbox — no code path closes the associated GitHub PR (confirmed: `cancellation.py`, `loop_lifecycle.py`, `Task.soft_delete()` in `models.py` never call the GitHub client). So once a team cancels or deletes a misbehaving self-driving task while its bot-authored PR/branch stays open on GitHub, any later push to that PR (a `synchronize`/`reopened` delivery from anyone with write access to the repo) still resolves through `find_signal_implementation_run` to a match, and stamphog re-applies the full gate bypass — including a real GitHub approval — to a PR whose backing automation was explicitly stopped.+- **Suggestion:** Exclude cancelled/failed runs and deleted tasks from the positive-identification check, e.g. `if run is None or run.team_id != team_id or run.status in (TaskRun.Status.CANCELLED, TaskRun.Status.FAILED) or task.deleted: return None` (leave `COMPLETED` runs matchable, since a later legitimate push to an already-merged/completed self-driving PR is the intended leg-2 case). This keeps the carve-out's authorization window scoped to the lifetime of the automation it is meant to represent.+- **Validator:** - **Checked:** `find_task_run`'s three legs (`products/tasks/backend/webhooks.py:36-98`), the facade gate (`find_signal_implementation_run`, `api.py:504-516`), the sole caller `_inbox_rereview_carve_out` (`products/stamphog/backend/tasks/tasks.py:144-215`), the cancellation/soft-delete paths, and the webhook/carve-out tests.+- **Found:** The `pr_url` leg's `order_by("terminal_rank", "-created_at").first()` (`webhooks.py:46-57`) returns a terminal run when no active one exists — `test_pr_url_prefers_active_run_over_terminal` (`test_webhooks.py:881`) only asserts the _preference_ when an active run coexists. `_TERMINAL_RUN_STATUSES` = COMPLETED/FAILED/CANCELLED (`webhooks.py:26`). Neither the `pr_url` leg nor the first branch leg (`webhooks.py:64-78`) filters `task__deleted`; only the wizard-head-branch leg does (`webhooks.py:89`).+- **Found:** `find_signal_implementation_run` gates only on `team_id`, `signal_report_id`, `internal` (`api.py:505-509`), and `_inbox_rereview_carve_out` adds only bot-author/fork/repo-config/toggle checks (`tasks.py:169-207`) — nothing keyed to run status or `task.deleted`.+- **Found:** Cancellation/lifecycle code makes no GitHub PR-close call (no such reference in `cancellation.py`/`loop_lifecycle.py`) and `Task.soft_delete()` only flips DB flags (`models.py:445-448`). So a cancelled/failed/deleted task's bot PR stays open and still resolves, and a later synchronize/reopen/retarget re-applies the full gate bypass (bot-author, draft, review-mode, write-permission) and can post a real head-pinned approval for automation the team explicitly stopped.+- **Impact:** Confirmed authorization-scoping gap: the carve-out's window outlives the automation it represents. This clears the keep bar (auth/permission scoping + edge case real workflows hit — cancelling/deleting misbehaving self-driving tasks is routine, and their PRs are confirmed left open).+- **Priority:** Lowering must_fix → should_fix. The positive-identification linkage cannot be forged (it needs a genuine signal-report-carrying, non-internal run bound to that PR in the same team), so this is strictly the team's own self-driving PR — not externally exploitable or cross-tenant. It also still requires the acting reviewer's `stamphog_review_inbox_prs` toggle ON and only yields an approval if the engine judges the content approvable, with a human still merging. That bounds it to a within-tenant, opt-in-gated defense-in-depth fix rather than a merge-blocking critical vulnerability.++### [❌ dismissed] should_fix · code_quality — products/tasks/backend/facade/api.py:507-509++**Security-sensitive identification relies solely on the deprecated Task.signal_report field**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `find_signal_implementation_run` identifies a task as "self-driving" purely via `task.signal_report_id is None`. `Task.signal_report` is explicitly annotated `# DEPRECATED - do not use` in `products/tasks/backend/models.py`, and the codebase's own existing precedent for this exact check pairs it with `origin_product`: `if task.signal_report_id and task.origin_product == SIGNAL_REPORT:` (`products/tasks/backend/facade/api.py:3786`). The relationship is also tracked in parallel by two other mechanisms (`SignalReportTask` bridge rows and `SignalReportArtefact` task_run artefacts, per that model's own docstring, which is described as the mechanism `signal_report` is "being migrated out in favour of"). A new, security-relevant gate (this identification directly controls whether stamphog bypasses bot-author/draft/review-mode/write-permission checks) built on a single field marked for removal, without corroborating `origin_product` or using the superseding artefact mechanism, risks silently breaking (most likely fail-closed, but unverified) if/when that field is fully retired.+- **Suggestion:** Pair the check with `task.origin_product == Task.OriginProduct.SIGNAL_REPORT` as the existing code at facade/api.py:3786 does, or resolve the signal-report linkage via the newer `SignalReportArtefact`/`task_run` artefact mechanism that is already the documented replacement, so this new gate isn't the last remaining consumer of a field the codebase is actively moving away from.+- **Validator:** - **Checked:** the `signal_report` FK deprecation note (`products/tasks/backend/models.py:190`), the cited precedent (`facade/api.py:3796`), the sibling self-driving identification in review_hog (`receivers.py:98-105`), and how live/populated `signal_report_id` still is.+- **Found:** The claim that this gate is "the last remaining consumer of a field the codebase is actively moving away from" is false — `signal_report_id` has ~37 non-test references across the tasks backend and is still written on every signal-report task creation (`models.py:566`), read in DTO conversions (`api.py:241,414,514`) and event stamping (`models.py:1494`). The `# DEPRECATED - do not use` note is aspirational, not an imminent removal.+- **Found:** `find_signal_implementation_run`'s check (`signal_report_id is not None` + `not internal`, `api.py:508`) deliberately mirrors review_hog's leg-1 trigger (`receivers.py:98-105`), whose comment states `internal` is the discriminator because internal plumbing tasks also carry `signal_report_id`. That is the directly relevant precedent — the facade matches the code that produces these runs. The `api.py:3796` pairing with `origin_product` is task-creation bookkeeping, and signal-report tasks set both fields together, so adding `origin_product` changes no outcome for real data.+- **Impact:** The finding's own text concedes the failure mode is "most likely fail-closed": were the field ever retired, `signal_report_id` reads None → the carve-out returns None → bot PRs refused (over-refusal, the safe default the design already relies on), not a bypass. So the security framing does not hold, and no real input misbehaves today. What remains is speculative future-proofing ("if/when that field is fully retired", not in scope) plus a consistency preference with no behavioral delta — both explicit drop categories under precision-over-recall.++### [❌ dismissed] must_fix · best_practice — tools/pr-approval-agent/review_pr.py:202-209,225-225,587-590++**self_driving flag relaxes the bot-author and draft gates independently, with no assertion that it only applies to a bot-authored PR**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self.self_driving` is stored as an unconstrained boolean and used to relax two unrelated checks independently: `if self.pr.author_is_bot and not self.self_driving` (bot-author refusal) and `if pr.draft and not self.self_driving` (draft prerequisite, in `_check_prerequisites`). Nothing in `Pipeline` asserts the two are meant to travel together — the draft-prerequisite relaxation is not conditioned on `pr.author_is_bot` at all. The whole design intent (per the PR description) is that this carve-out is only supposed to apply to a positively-linked, bot-authored inbox PR, with the narrowing logic living upstream (in the stamphog/review_hog facades, outside this chunk). This `Pipeline` class is explicitly the shared, reusable engine both runtimes rely on for gate parity, so it is the natural last line of defense — yet it has zero defense-in-depth here: if `self_driving=True` is ever set for a PR that is not bot-authored (an upstream bug, a race in the task-linkage matching, or a mistake in a future caller), the draft-prerequisite gate silently disappears for that human PR too, independent of the bot check. `_refuse_bot_author`'s own docstring calls out this kind of layered protection ("defense-in-depth layer for any manual or out-of-band invocation") for the bot check, but no equivalent safeguard exists for the draft check or for the flag itself.+- **Suggestion:** Couple the two relaxations to the actual invariant they're meant to protect, e.g. in `__init__` or at the top of `run()`/`_check_prerequisites`, assert or hard-guard that `self_driving` only takes effect when `pr.author_is_bot` is true (once `self.pr` is populated), for example: `if self.self_driving and not self.pr.author_is_bot: self.self_driving = False` (fail closed) right after `_fetch()`, so a mis-set flag on a human-authored PR can't silently drop the draft gate.+- **Validator:** - **Checked:** Every construction of `Pipeline` (review_pr.py:984 CLI `main()`, review_local.py:321 hosted), the argparse surface in `main()` (review_pr.py:974-979), the server derivation of the flag (activities.py:451), both provenance-stamping legs (tasks.py `_inbox_rereview_carve_out`:169 and `process_inbox_pr_review`), and the two bot definitions (facade `_is_bot_authored` tasks.py:124 vs engine `is_bot_author` github.py:79).+- **Found:** The code observation holds — the draft-gate relaxation (`if pr.draft and not self.self_driving`, review_pr.py:590) is not conditioned on `pr.author_is_bot`, only on the flag. But no current caller can set `self_driving=True` for a non-bot PR. The Action/CLI entry `main()` (review_pr.py:984) builds `Pipeline(...)` without the `self_driving` kwarg and defines no flag for it, so it is always `False` there. The sole setter is review_local.py:321 `self_driving=bool(context.get("self_driving_review"))`, and `self_driving_review` is derived server-side only from inbox provenance (activities.py:451); the webhook leg refuses to stamp that provenance unless `_is_bot_authored(pr)` (tasks.py:169 early return) and the receiver leg stamps it for a PR opened by the PostHog Code machine user by construction. The engine's `is_bot_author` matches `Bot` type OR `[bot]` login OR machine-user logins — a superset of the facade check — so any PR that clears the upstream gate also reads `author_is_bot=True` in the engine.+- **Impact:** Does not meet the bar. The finding's own trigger list is entirely hypothetical ("an upstream bug, a race..., or a mistake in a future caller") — it names no concrete currently-reachable path, which the criteria flag as a reason to be skeptical. This is a defensive-coding / speculative-what-if hardening suggestion guarding against a state upstream validation already rules out on every caller — a "drop" category (precision over recall). The cited `_refuse_bot_author` defense-in-depth is not analogous: that guards a genuinely reachable manual CLI invocation on a bot PR, whereas the proposed `self_driving`-vs-author guard protects an unreachable state. The `must_fix` severity is unsupported: there is no exploitable path, and even in the hypothetical the only effect is that a _draft_ human PR could be reviewed rather than auto-refused, still subject to every other gate and the LLM verdict — not a silent approval.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_local.py:316-321++**self_driving_review is read from the context JSON with a bare bool() coercion instead of an explicit boolean check**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `Pipeline(0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")))` uses Python's generic truthiness coercion on an externally-supplied JSON value to derive the single flag that disables both the bot-author refusal and the draft prerequisite for what becomes a real, head-pinned GitHub approval. `bool(x)` treats any non-empty string as `True`, including the string `"false"` — so if the hosted server (or any future producer of this context JSON) ever emits `"self_driving_review": "false"` instead of a JSON boolean `false` (e.g. due to a templating bug, an env-var-style stringification, or a serialization change upstream), this line would silently flip the flag on and bypass both gates for an otherwise-ordinary run. Given the sensitivity of what this flag unlocks, relying on generic truthy coercion rather than an explicit type check is a real input-validation gap.+- **Suggestion:** Validate the type explicitly rather than coercing, e.g. `self_driving = context.get("self_driving_review") is True` (or check `isinstance(..., bool)` and raise/log on unexpected types), so a malformed or mistyped value fails closed instead of silently enabling the carve-out.+- **Validator:** - **Checked:** The full producer→consumer chain for `self_driving_review`: `activities.py:451` (`self_driving_review=bool(output.get("inbox_review"))`), `logic/reviewer.py:101` (param typed `self_driving_review: bool = False`), `logic/reviewer.py:131` (placed in the context dict unchanged), the serialization at `logic/reviewer.py` (`context_json=json.dumps(context, ensure_ascii=False)`), and the consumer at review_local.py:321.+- **Found:** The value is always a genuine Python `bool` at the producer (typed parameter, fed a `bool(...)` at activities.py:451) and is serialized with `json.dumps`, which emits JSON `true`/`false` and round-trips back to Python `True`/`False`. When the key is absent it is `None`, and `bool(None)` is `False` — fail-closed. There is no code path where `context.get("self_driving_review")` yields the string `"false"`; that requires the typed internal serializer to be rewritten to emit a string, which is the finding's own hypothetical ("a templating bug... or a serialization change upstream"). The flag is also server-set from the ReviewRun's inbox provenance, not from author-controlled PR data, so it is not an untrusted-input surface.+- **Impact:** Does not meet the bar. `bool()` is correct for every value the current producer can emit (`True`/`False`/absent), so the flagged input-validation gap is not reachable given the types and `json.dumps` guarantee in place — a speculative-what-if / defensive-coding drop under the criteria (precision over recall). The `should_fix` severity is unsupported: there is no realistic trigger, only a hypothetical future serialization regression. `is True` would be a marginal stylistic hardening, but that alone (with no reachable bug) is not a ReviewHog concern.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:144-160,161-207++**Acting-reviewer identity for the stamphog toggle can drift between the initial trigger and later webhook re-reviews**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` calls `_resolve_assigned_reviewer`, which re-derives the 'assigned reviewer' from scratch on every invocation: it re-queries the signal report's _latest_ `suggested_reviewers` artefact and re-resolves GitHub logins to org members each time. The module's own top-of-file docstring (new lines 17-20) describes this as checking 'the same resolved acting reviewer' across both the `review_hog` trigger and the stamphog re-check, but nothing actually pins that identity. `resolve_stamphog_acting_reviewer` is registered as a hook that stamphog's webhook path calls on later pushes (`synchronize`/`reopened`/retarget) — potentially long after the PR was opened and the original TaskRun-save trigger fired. If the report's `suggested_reviewers` artefact is regenerated, or GitHub org membership changes, in the intervening time, `_resolve_assigned_reviewer` can resolve to a _different_ user on the later call than it did on the first one (e.g. a previously-unresolved login becomes an org member and moves to the front of the list, or the task creator newly falls inside the resolved set). Leg 2 would then gate the re-review on a different user's `stamphog_review_inbox_prs` setting than the one that actually governed the PR's initial approve-first review — silently changing whether the PR keeps getting reviewed, with no log or signal distinguishing this from an intentional toggle change by the original acting reviewer.+- **Suggestion:** Pin the acting reviewer's identity at leg-1 resolution time (e.g. stamp `acting_user_id` onto the queued review's inbox provenance/output, as is already done for other run-scoped values like `urgency_threshold`) and have the webhook-leg resolver look up that stored id instead of re-running `_resolve_assigned_reviewer` against the current artefact and current org-membership state. If re-derivation on every call is intentional, at minimum log when the newly-resolved identity differs from the identity used for the same signal report's prior resolution, so the behavior change is observable and debuggable.+- **Validator:** - **Checked:** whether re-deriving the acting reviewer per call is an oversight or the intended design — the resolver body (`receivers.py:132-160`), the receiver's firing model (`receivers.py:56-64`, `:95`), and how `suggested_reviewers` artefacts evolve (`products/signals/backend/views.py:857`, `products/signals/backend/auto_start.py:397`).+- **Found:** `suggested_reviewers` is explicitly append-only and 'only the newest row is the live reviewer set' (`views.py:857-859`); the resolver docstring binds the acting reviewer to 'the report's **latest** `suggested_reviewers` artefact — the exact set the Inbox "For you" filter matches' (`receivers.py:115-116`). Resolving against current state each time is the documented semantics, not a missing pin.+- **Found:** the base leg-1 receiver already re-derives on every firing — `handle_task_run_saved` fires on every TaskRun save (`receivers.py:56-64`) and re-calls the resolver fresh (`receivers.py:95`). The PR extends this established 'follow current assignment' pattern to leg 2; it does not introduce a new inconsistency.+- **Found:** the 'artefact regenerated' precondition is a supported user edit that re-runs auto-start (`auto_start.py:397`), so when the resolved reviewer changes it's because the live assignment changed — gating later re-reviews on the new assignee's toggle is consistent with 'gated by the report's current assignees,' arguably correct.+- **Impact:** the consequence is a rare, fail-closed nuance in whether a _later push_ gets re-reviewed (skipped when the current toggle is off) — no wrong results, data loss, security hole, or crash; per the PR the stale-approval dismissal is unconditional, so the safety invariant holds regardless. The premise mis-frames an intentional design choice as a silent bug, and the suggested 'pin identity at leg 1' fix would regress the intended follow-current-assignment behavior. Under precision-over-recall it does not clear the bar. (Caveat: PR head `1341596e` is absent from this checkout — migration 0019 / `stamphog_review_inbox_prs` / `queue_inbox_pr_review` / the webhook hook are not present — so the exact leg-2 path couldn't be inspected; the analysis rests on the base receiver design and the append-only latest-artefact semantics both legs share.)++### [❌ dismissed] consider · best_practice — products/review_hog/backend/api/settings.py:50-54,71-82++**stamphog_connected reports project-wide connectivity, not per-repository, so the toggle can appear enabled for PRs whose repo isn't actually connected**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `get_stamphog_connected` calls `has_reviewable_repo_config(instance.team_id)`, which per its own `help_text` answers 'does this project have at least one synced, enabled Stamphog repository' — a project-wide check. The actual gating that determines whether a specific inbox PR gets a Stamphog review (the queued `queue_inbox_pr_review` task, and the webhook carve-out described in the PR intent) requires a synced+enabled `StamphogRepoConfig` for the _specific repository_ the PR lives in. For a team with multiple repositories where only some are connected to Stamphog, `stamphog_connected` can report `true` (because some unrelated repo is connected) while the repository that actually receives self-driving inbox PRs has no Stamphog config at all. A user would see the toggle rendered as available and turn it on, expecting reviews, but every review would silently no-op inside the queued task with no visible feedback anywhere in the UI.+- **Suggestion:** Either scope the connectivity check to the repositories that inbox implementations actually target for this team (so the flag reflects real coverage), or adjust the field's help_text/UI copy to make explicit that this is a project-wide 'at least one repo' signal rather than a per-repository guarantee, so users aren't misled about whether the toggle will take effect for their inbox PRs.+- **Validator:** - **Checked:** the granularity of the toggle and whether a per-repository check is even computable where `stamphog_connected` is derived — the settings endpoint (`products/review_hog/backend/api/settings.py:66-73`), the `StamphogRepoConfig` model, and the real per-PR review gate.+- **Found:** the endpoint resolves one project-scoped `ReviewUserSettings` row for `(team_id, user_id)` (`settings.py:70-71`) with **no repository in context**. The `stamphog_review_inbox_prs` toggle is a project-wide per-user setting, not per-repo, so there is no 'the repository' to scope the indicator to at render time — a per-repo check would require guessing which repos future inbox PRs target.+- **Found:** the actual per-PR review gate is already correctly per-repository — `StamphogRepoConfig` is uniquely keyed `(team_id, repository)` (`products/stamphog/backend/models.py`, `unique_stamphog_repo_per_team`) and the review path resolves `get_repo_config(team_id, repository)` for the specific repo (`products/stamphog/backend/facade/api.py:107`). An unconnected repo fails closed: no review runs, no false approval.+- **Impact:** the coarse project-level flag is the deliberate, correct granularity for a project-wide setup gate (render the toggle disabled-with-reason when nothing is connected). The residual mismatch needs a narrow combination (multi-repo team + partial Stamphog coverage + inbox PRs in the uncovered repo) and yields only a rare, fail-closed UX expectation gap — no wrong results, data loss, or security hole. The primary suggested fix (per-repo scoping) is ill-defined for a project-wide toggle; the fallback is a copy tweak. This is a low-impact product-granularity/UX nicety, dropped under precision-over-recall. (Caveat: PR head `1341596e` is absent from this checkout — `get_stamphog_connected`/`has_reviewable_repo_config` don't exist locally — but the base per-repo model, per-repo review-gate facade, and project-scoped settings endpoint establish the substance.)++### [❌ dismissed] consider · best_practice — products/review_hog/backend/receivers.py:210-236++**Deferred import in `_start_stamphog_review` sits outside the try/except, contradicting its own 'never surface into the saver' guarantee**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `_start_stamphog_review`'s docstring states 'the broker being down must never surface into the saver,' and the function wraps the `queue_inbox_pr_review(...)` call itself in `try/except Exception`. However, the deferred `from products.stamphog.backend.facade.api import queue_inbox_pr_review` import executes before that `try:` block. Because this function runs inside a `transaction.on_commit` callback rather than inside `handle_task_run_saved`'s own exception-proofed body, any exception raised while importing that module (a bug in the stamphog facade's module-level code, a broken transitive import, a circular-import edge case, etc.) would propagate straight out of Django's on-commit callback execution — surfacing in whatever code path happened to commit the enclosing transaction (a Celery task, a webhook handler, or similar) — which is precisely the outcome the docstring says must never happen.+- **Suggestion:** Move the `from products.stamphog.backend.facade.api import queue_inbox_pr_review` import inside the `try:` block so an import-time failure is caught the same way a call-time failure already is, matching the exception-safety the docstring promises.+- **Validator:** - **Checked:** whether the flagged import-outside-try can actually fail and surface, and whether it is a new defect — the on_commit callback semantics, Python import caching, the reachability of a facade import failure, and the analogous merged code.+- **Found:** the identical pattern is the established convention in the already-merged `_start_review` — deferred imports at `products/review_hog/backend/receivers.py:181-182` sit outside the `try:` at `:188`, under the same 'Temporal being down must never surface into the saver' docstring at `:173`. The PR's `_start_stamphog_review` mirrors this; it introduces no new gap.+- **Found:** `products.stamphog.backend.facade.api` is a broadly-imported facade (webhook path, settings serializer, etc.). A real import error would fail deterministically at app startup / in CI, not as a subtle on-commit edge. After first import the module is cached in `sys.modules`, so by the time this post-commit callback runs in a fully-initialized app the import is a dict lookup that cannot re-execute code or raise; the deferral's circular-import concern only applies at `django.setup()`, not at call time.+- **Impact:** `on_commit` runs after the transaction commits, so the TaskRun save is already durable — the hypothetical import failure causes no rollback or data loss, only a logged exception in the committing path, and a genuinely un-importable facade would break the entire review feature with far louder symptoms. Guarding it is defensive paranoia against a practically-unreachable failure — a never-gonna-happen edge with benign impact — which drops under precision-over-recall. (Caveat: PR head `1341596e` is absent from this checkout so `_start_stamphog_review` couldn't be read directly; the base `_start_review` analog it mirrors establishes both the pattern and the analysis.)++### [❌ dismissed] must_fix · best_practice — tools/pr-approval-agent/review_local.py:292-311,314-327++**Self-driving carve-out doesn't guard familiarity attachment against the machine author's own PR history**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self-driving flag correctly guards the two documented gates (bot-author refusal at `pipeline.pr.author_is_bot and not pipeline.self_driving` in `run()`, and the draft prerequisite via `self.self_driving` in `Pipeline._check_prerequisites`), but `_attach_familiarity()` — the only other author-trust signal that reaches the reviewer prompt — has no equivalent guard on `pipeline.self_driving`. It bails out only when `context.get('author_pr_numbers')` is empty/absent, i.e. it trusts the hosted server (a different, unreviewed chunk) to have skipped the author merged-PR fetch for self-driving runs. That's exactly the kind of externally-assumed, trigger-side behavior this PR explicitly avoids for the two gates it does relax (per `_refuse_bot_author`'s own comment: 'A human applying the stamphog label can't override this... this is the defense-in-depth layer for any manual or out-of-band invocation'). Before this PR, `_attach_familiarity` was unreachable for a bot author at all, because `run()` always exited via `_refuse_bot_author()` first — so this is a new interaction introduced by the self_driving flag, not a pre-existing gap. Concretely: the self-driving machine account (matched by `is_bot_author` via `_BOT_MACHINE_USERS`/`[bot]` login) is expected to accumulate many real merged PRs over time as this feature runs, so if the server's context builder ever populates `author_pr_numbers` for a self-driving run (shared code path, future refactor, or simply not special-cased), `_familiarity_offline` will compute genuine (not spurious) blame-overlap and prior-PR-count signals from the bot's own commit history — since `_blame_overlap` credits any blamed line whose squash-commit PR number is in `author_prs`, and `_prior_prs_in_paths` counts the bot's own merged PRs touching the same paths. If that lands the run in the T1-agent tier, `_format_familiarity` in reviewer.py will render a concrete 'Author familiarity with the changed code... band STRONG/MODERATE...' block right next to the new `_format_self_driving` block, whose whole purpose is to tell the LLM that for this exact provenance 'author familiarity, org membership, and merged-PR history carry no signal here — judge the diff strictly on its own merits.' Both blocks are documented as TRUSTED context, so the prompt would hand the reviewer two directly contradictory trusted facts about the same PR. The same familiarity data would also leak into the human-facing posted comment via `Pipeline._render_review_body()` ('Author wrote X% of the modified lines and has N merged PRs in these paths'), which is nonsensical/misleading when the 'author' is a machine account — undermining the provenance-based trust model this whole feature is built on.+- **Suggestion:** Gate `_attach_familiarity` on `pipeline.self_driving` directly, e.g. add `if pipeline.self_driving: return` at the top of `_attach_familiarity` (or short-circuit the call site in `run()`: `if not pipeline.self_driving: _attach_familiarity(pipeline, context)`), so the machine author's familiarity is never computed or attached regardless of what the server happens to put in `context['author_pr_numbers']`. This mirrors the same-file pattern already used for the bot-author check and keeps the 'positively identified carve-out, not a trigger-side bypass' invariant enforced inside the engine itself rather than relying on caller behavior from another component.+- **Validator:** - **Checked:** `_attach_familiarity` (review_local.py:292-311) and its bail condition, its call site in `run()` (review_local.py:353), and the server-side context builder that populates `author_pr_numbers` (activities.py:233-238).+- **Found:** The familiarity carve-out is already enforced upstream, so the contradiction cannot arise today. `_attach_familiarity` returns immediately when `author_pr_numbers` is empty (review_local.py:301-302 `raw_prs = context.get("author_pr_numbers"); if not raw_prs: return`). The server sets that list to `[]` for exactly the self-driving case: activities.py:237-238 computes `is_inbox_review = bool((run.output or {}).get("inbox_review"))` and `author_pr_numbers = client.get_author_merged_pr_numbers(repo, author) if author and not is_inbox_review else []`, with a comment stating the machine author's merged-PR fetch is skipped precisely so familiarity stays absent. Result: for a self-driving run, familiarity is never computed, `_format_familiarity` renders nothing, and there is no dual-TRUSTED contradiction with `_format_self_driving` and no machine-author familiarity in the posted comment.+- **Impact:** Does not meet the bar. The finding's own trigger is hypothetical ("if the server's context builder _ever_ populates author_pr_numbers for a self-driving run... future refactor"), i.e. it guards against a redundant check the parent caller already performs (activities.py:238) — the criteria's "already handled" and "defensive-coding paranoia" drop categories. It is the same engine-should-redundantly-re-enforce-a-caller-narrowed-carve-out pattern as the sibling gate findings; keeping a stack of these is exactly the noise the precision-over-recall bar rejects. The `must_fix` severity is unsupported: no current path yields the described contradictory prompt or misleading comment. The engine-parity/defense-in-depth argument has some design merit, but with the behavior correct as shipped it is a hardening preference, not a ReviewHog-worthy defect.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected adds an uncached cross-database read to the always-called settings endpoint**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The new `get_stamphog_connected` SerializerMethodField calls `has_reviewable_repo_config(instance.team_id)` on every serialization of `ReviewUserSettings`. This serializer backs the settings `user_settings` action, and the code comment (settings.py:107-108) states this GET is "the Code review tab's always-called endpoint" — it also runs on every PATCH response. `has_reviewable_repo_config` reads the Stamphog product DB, which the author's own comment describes as "a separate database behind a fail-fast circuit breaker." So this couples the latency of a hot, user-facing settings endpoint to a second database's health on every request, with no caching of the result. The reliability side is well-handled (try/except fails soft to False and logs via `logger.exception`, and the circuit breaker guards the DB-down case), so the residual concern is operational: a Stamphog DB that is up-but-slow (before the breaker trips) adds a synchronous cross-DB round-trip to every Code review tab load, and repo-connection state changes rarely so the value is highly cacheable. There is no N+1 here — the serializer is only ever used on a single instance (never `many=True`) — so the impact is one extra cross-DB query per request rather than per row.+- **Suggestion:** Cache the connectivity result rather than reading the Stamphog DB on every request. A short-TTL per-team cache (e.g. Django's cache framework keyed by team_id, TTL on the order of minutes) fits well because a synced+enabled StamphogRepoConfig changes rarely and this is a purely informational UI flag — a slightly stale value only affects whether the toggle renders disabled, which the frontend already treats as advisory. This removes the cross-database round-trip from the hot settings path in the common case while keeping the existing fail-soft behavior for cache misses.+- **Validator:** - **Checked:** the actual cost profile of the flagged cross-DB read and whether it meets the 'bites at real scale' performance bar — the `StamphogRepoConfig` indexing, the analogous facade query, and the frequency/nature of the endpoint.+- **Found:** the connectivity check is a single index-backed existence query. `StamphogRepoConfig` is uniquely keyed `(team_id, repository)` (`unique_stamphog_repo_per_team`), so a `team_id`-scoped lookup is index-backed, mirroring `get_repo_config`'s `.for_team(team_id).filter(...).first()` at `products/stamphog/backend/facade/api.py:108`. Not an N+1 (the issue concedes single-instance serialization), unbounded loop, missing index, or quadratic behavior.+- **Found:** the endpoint backs the Code review _settings tab_ — its call frequency is bounded by human navigation (tab open / PATCH), not per-row/per-event machine load, so 'always-called' does not make it a hot path in the scale sense. One indexed cross-DB query per settings load is ordinary cost.+- **Impact:** the reliability side is already closed by the author's fail-soft try/except + circuit breaker (the issue itself concedes this); 'up-but-slow before the breaker trips' is a speculative operational what-if. The suggested TTL cache is overengineering for a purely-informational advisory flag and adds a real downside — staleness during the exact Stamphog-setup flow the flag guides (toggle stuck disabled for the TTL after a user connects). A single fast query that does not bite at scale, flagged at lowest priority — drops under precision-over-recall. (Caveat: PR head `1341596e` is absent from this checkout, so `has_reviewable_repo_config` couldn't be read directly; the base per-repo index and facade query establish the cost profile.)++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1155-1159++**Unbounded GitHub get_pr calls on every receiver refire (no pre-fetch dedupe)**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** process_inbox_pr_review fetches the PR from GitHub (StamphogGitHubClient(...).get_pr) on every single invocation, before any dedupe. Per the task's own docstring (lines ~1124-1128), review_hog's TaskRun receiver 're-fires on every TaskRun output save carrying the PR URL', and the dedupe deliberately keys on the PR's CURRENT head — which is only known after the fetch. So a self-driving run that saves its output multiple times enqueues multiple Celery tasks, each performing a synchronous GitHub get_pr, and all but one resolve to a no-op ('already reviewed at this head') after the fetch. Unlike the webhook path — which short-circuits duplicate deliveries via the idempotency cache (`_is_duplicate_pr_event` / `_mark_pr_event_processed`) before any GitHub call — this leg has no pre-fetch guard, debounce, or rate limiting. Across many concurrent self-driving tasks each saving output several times, this multiplies calls against the shared per-installation GitHub rate limit and burns Celery worker capacity on redundant fetches.+- **Suggestion:** Add a short-TTL debounce/idempotency guard keyed on (team_id, pr_url), checked at the top of process_inbox_pr_review before the GitHub fetch and set after a successful run/no-op — mirroring the existing `_is_duplicate_pr_event`/`_mark_pr_event_processed` pattern already used on the webhook path. A short window (tens of seconds) collapses a burst of refires into a single fetch while preserving the intended lost-synchronize recovery (a genuinely new head is still reviewed once the window lapses). Alternatively, dedupe at enqueue time inside queue_inbox_pr_review so repeat receiver fires within the window never spawn a task at all.+- **Validator:** - **Checked:** every `get_pr` call site in `products/stamphog/backend/tasks/tasks.py`, the webhook idempotency helpers (`_is_duplicate_pr_event`/`_mark_pr_event_processed`), the receiver refire guards (`products/review_hog/backend/receivers.py:72-134`), and the rate-limit handling.+- **Found:** The webhook path makes NO GitHub call — the only `get_pr` in the file is the inbox leg's (`tasks.py:1159`). The webhook has the PR payload in the delivery body; its cache dedupes redelivered events by `delivery_id` (`tasks.py:737,812`) and never prevents a GitHub fetch. So the finding's asymmetry ("unlike the webhook path… before any GitHub call") is a false parallel: URL-only receiver vs payload-in-hand webhook are structurally different.+- **Found:** The fetch-before-dedupe is structurally required and documented: the dedupe keys on the PR's current head, which only GitHub knows (`tasks.py:1155-1157`), and the receiver docstring explicitly accepts that "a same-head re-trigger costs one fetch (early-exit)" (`receivers.py:75-79`) — a deliberate tradeoff, not an oversight.+- **Found:** Refires are bounded and already rate-limit-safe. The receiver proceeds only on `output`-touching saves for a non-internal signal-report task with an opted-in reviewer (`receivers.py:85-132`) — a handful per run, not a loop — and `GitHubRateLimitError` is caught and retried with `countdown ≥ 60s` (`tasks.py:1160-1162`).+- **Impact:** At the finding's own scale scenario (many concurrent tasks × several saves) the volume is tens-to-low-hundreds of lightweight GETs/hour against GitHub's ~5000/hr per-installation budget — not unbounded, not N+1/quadratic, and it does not bite at real scale. The proposed (team_id, pr_url) debounce also isn't the claimed mirror and would partially defeat the intended lost-synchronize recovery the every-time fetch deliberately provides. This is a factually-accurate but low-impact, self-limiting inefficiency that is an intentional, documented design decision — in the "so rare and low-impact that handling it isn't worth the code" / speculative-scale drop zone. Drop for precision over recall.++### [✅ VALID] consider · performance — products/tasks/backend/facade/api.py:501-504++**Carve-out triggers unindexed posthog_task_run.branch scan for non-self-driving bot PRs**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** find_signal_implementation_run calls find_task_run(pr_url=..., branch=head_branch, repository=...). The pr_url leg is served by a functional index (task_run_output_pr_url_idx), but when it misses, find_task_run falls through to a branch-only lookup: `filter(branch=branch, task__repository__iexact=repository, state__wizard_head_branch__isnull=True)`. Neither TaskRun.branch nor the case-insensitive `task__repository` is indexed (posthog_task_run Meta indexes cover `output__pr_url`, `state__wizard_head_branch`, created_at, task+created_at, and team+stage+task only), so this is a sequential scan of a table that grows unbounded with every agent run. The new stamphog carve-out (`_inbox_rereview_carve_out`) invokes this for every bot-authored, head-changing PR delivery on a stamphog-enabled repo. Genuine self-driving PRs match on the indexed pr_url leg, so the scan is hit precisely by the non-self-driving bots that push repo-native branches frequently (dependabot/renovate synchronize events), which never match and always return nothing.+- **Suggestion:** Self-driving runs are positively identified by their recorded output.pr_url (indexed), so consider having the carve-out pass head_branch=None (or otherwise skip the branch-only leg) to avoid the scan for bot PRs that will never match. If the branch fallback is intentionally retained for robustness, add a scoped index on TaskRun.branch. Note the query is reused from the tasks webhook backstop, so the scan is pre-existing on that path — this PR adds a new hot-path caller (bot-authored head-changing PR webhooks) that exercises it.+- **Validator:** - **Checked:** `TaskRun.Meta.indexes` (`products/tasks/backend/models.py:1147-1174`), the branch-leg query in `find_task_run` (`products/tasks/backend/webhooks.py:64-78`), and the carve-out's call path (`_inbox_rereview_carve_out` → `find_signal_implementation_run`, `tasks.py:167-196` / `facade/api.py:504`).+- **Found:** The declared indexes cover only `output__pr_url` (functional), `state__wizard_head_branch` (functional), `created_at`, `task+created_at+id`, and `team+stage+task`. None serves `filter(branch=..., task__repository__iexact=..., state__wizard_head_branch__isnull=True)` — there is no index on `TaskRun.branch`, and the case-insensitive `iexact` join on `task.repository` cannot use a btree. So the first branch leg is a sequential scan of `posthog_task_run`, a table that grows with every agent run.+- **Found:** The scan is reachable exactly for the bots described. The carve-out gates on head-changing action + bot-authored + repo-native head + synced/enabled config (`tasks.py:167-196`) before calling `find_signal_implementation_run`, which passes both `pr_url` and `head_branch` (`api.py:504`). For a dependabot/renovate PR the indexed `pr_url` leg always misses (no `TaskRun.output.pr_url` matches a non-PostHog-agent PR), so it falls through to the unindexed branch leg, which also never matches — pure waste. Genuine self-driving PRs match on the `pr_url` leg, so in the carve-out context the branch leg only ever runs for PRs that cannot match; on a stamphog-enabled repo with no self-driving tasks, every bot head-change triggers a full scan.+- **Impact:** A reachable missing-index seq scan on an unbounded-growth table on the webhook-processing path — a category the criteria keep. It has a concrete trigger (routine dependabot/renovate synchronize on stamphog repos) and a cheap, safe mitigation (pass `head_branch=None`, since self-driving PRs are positively identified by the indexed `pr_url`). It is latent rather than urgent — pre-existing on the tasks backstop, this PR only adds a new caller, and cost scales with table growth — so the `consider` rating is correct; keep it there.++### [❌ dismissed] should_fix · code_quality — tools/pr-approval-agent/review_pr.py:225,587-590++**Self-driving carve-out relaxes two safety gates with no observable trace in logs, gate messages, or the posted review comment**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Both relaxed gates fail to leave any trace that the carve-out fired. (1) `run()` at line 225 (`if self.pr.author_is_bot and not self.self_driving:`) silently skips the bot-author refusal — no print/log statement anywhere records that a bot-authored PR was let through, unlike every other branch in this file which prints an explicit `_ok`/`_warn`/`_fail` line for its outcome. (2) `_check_prerequisites` at line 590 (`if pr.draft and not self.self_driving:`) means a draft PR bypassed via self_driving produces the exact same `passed, 'all clear'` result as a genuinely non-draft PR — the gate's own message loses the fact that draft was true and was carved out. That message flows into two places that matter operationally: the console/CI gate table printed by `_run_gates` (`_ok(f"{name}: {message}")`), and the `gates` array + rendered `review_body` table returned by `to_dict()`/`_render_review_body()`, which is what actually gets posted back to GitHub and what a human in Inbox triage reads to decide whether to trust the automated approval. Since `self.self_driving` is tracked only as a separate top-level boolean (in `classification` and in `to_dict()`'s audit-trail comment: "Audit trail for the carve-out: which gates ran relaxed, and why"), nothing links that boolean back to which specific gate result it explains. In production this manifests through `review_local.py`, the only caller that ever sets `self_driving=True`: its `run()` mirrors the same `author_is_bot and not pipeline.self_driving` check and reuses `pipeline.to_dict()` verbatim, so the same masked messaging reaches the server-posted comment for real self-driving inbox PRs.+- **Suggestion:** Make the two relaxed-gate outcomes self-describing instead of relying solely on the disconnected top-level `self_driving` flag. For example, in `_check_prerequisites`, when `pr.draft and self.self_driving`, still surface it in the passing message (e.g. `return True, "all clear (draft bypassed: self-driving carve-out)"` instead of the generic `"all clear"`). For the bot-author bypass in `run()` (and its mirror in `review_local.run()`), add an explicit print/log line before falling through to `_classify_and_gate()`, e.g. `print(_warn(f"self-driving carve-out active — bot author @{self.pr.author} not refused"))`, so the console/CI log and the eventual audit record both show why the safety gate didn't fire, without requiring a reader to separately cross-reference the `self_driving` boolean.+- **Validator:** - **Checked:** Both relaxed-gate sites (review_pr.py:225 bot-author, review_pr.py:590 draft prerequisite), where the carve-out is recorded (`to_dict()` at review_pr.py:938, classification at review_pr.py:477), the telemetry path (`_capture_review_completed` review_pr.py:806-855 + `analytics_extra_properties()` merge at 819-820, fed `stamphog_self_driving_review=True` from activities.py:176), and the posted-comment renderer (`_render_review_body` review_pr.py:859-912).+- **Found:** The carve-out is not trace-less. `to_dict()` emits `classification.self_driving` with an explicit `# Audit trail for the carve-out: which gates ran relaxed, and why` comment (review_pr.py:937-938), and the hosted runtime stamps `stamphog_self_driving_review=True` onto the `stamphog_review_completed` analytics event (activities.py:176). Under the carve-out the prerequisites gate genuinely passes — a draft is intentionally not a blocker (review_pr.py:587-590 comment) — so the `"all clear"` message is correct, not a masked failure; nothing is being silently swallowed.+- **Impact:** Does not meet the bar. The gates function correctly and the carve-out is already auditable via the structured flag and telemetry; the ask is to echo the bypass into human-readable gate-message strings and add a console `print`. That is observability/message-wording polish — the criteria's "pure style/taste" and "add more logging" (overengineering) drop categories — not a correctness/security/data-loss/contract/performance/reliability defect, which is what the KEEP list requires. The `should_fix` severity and the "no observable trace" title are both undercut by the existing `self_driving` audit field and `stamphog_self_driving_review` analytics property.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:114-139++**Two independently-toggled on_commit dispatches share a commit-hook queue; a failure in the first silently cancels the second**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `handle_task_run_saved` now registers up to two separate `transaction.on_commit(lambda: ...)` callbacks in sequence: `_start_review` (when `settings.review_inbox_prs`) first, then `_start_stamphog_review` (when `pr_url is not None and settings.stamphog_review_inbox_prs`) second. Both `transaction.on_commit` calls use the default `robust=False`. Django's `BaseDatabaseWrapper.run_and_clear_commit_hooks` (posthog/.venv/lib/python3.13/site-packages/django/db/backends/base/base.py:752-764) pops queued hooks off a FIFO list and runs non-robust ones with no try/except: if the first hook raises, the exception propagates out of `run_and_clear_commit_hooks` immediately and every hook still left in the queue — here, the second, independent `_start_stamphog_review` call — is simply never invoked. `_start_review` itself only wraps `start_review_pr_workflow(...)` in try/except; its own deferred imports (`from products.review_hog.backend.temporal.client import start_review_pr_workflow` / `.temporal.types import TRIGGER_INBOX`) sit outside that try, mirroring the exact unguarded-import shape already flagged for `_start_stamphog_review` in this chunk. So when a user has BOTH `review_inbox_prs` and `stamphog_review_inbox_prs` enabled — the primary scenario this PR is built to support — any uncaught exception surfacing from the first callback (a broken temporal-client import, or any other bug escaping `_start_review`'s narrow try block) doesn't just fail the ReviewHog leg: it silently prevents the Stamphog leg from ever firing for that PR, with no log line pointing at the stamphog dispatch at all, since its callback body never executes. This is a new hazard introduced by this PR's change from a single on_commit registration to two independently-gated ones in the same transaction; the codebase already has an established fix for exactly this class of problem (`robust=True` is used elsewhere in the repo for fire-and-forget on_commit hooks) that wasn't applied here.+- **Suggestion:** Pass `robust=True` to both `transaction.on_commit(...)` calls in this function (matching the existing repo convention of `robust=True` for independent fire-and-forget on_commit hooks), so an exception in one callback is logged by Django and does not prevent sibling callbacks registered on the same commit from running. This is a small, targeted change: `transaction.on_commit(lambda: _start_review(...), robust=True)` and `transaction.on_commit(lambda: _start_stamphog_review(...), robust=True)`.+- **Validator:** - **Checked:** the Django commit-hook mechanism, whether `robust=True` is a real repo convention, and — decisively — whether the _first_ callback can realistically raise (the precondition the whole hazard depends on).+- **Found (mechanism is real):** Django's `run_and_clear_commit_hooks` (`django/db/backends/base/base.py:752-764`) pops hooks into a local list, empties `run_on_commit`, then runs each; a `robust=False` hook runs with no try/except, so a raise aborts the `while` loop and the already-popped remaining hooks are lost. `robust=True` is an established repo pattern (6 fire-and-forget usages, e.g. `products/signals/backend/views.py:2108`). The reviewer's technical claims all check out.+- **Found (trigger is unreachable):** `_start_review` (base analog `receivers.py:164-201`) wraps its only realistically-failing operation — the `start_review_pr_workflow(...)` Temporal call — in try/except (`:188-200`); the code outside that try is just the deferred imports (`:181-182`) and trivial dict construction (`:184-187`), which cannot fail. So the only path to the first callback raising is a deferred-import failure, which is practically unreachable at callback time (modules cached in `sys.modules` after first import; a genuine break is a loud, feature-wide ReviewHog outage, not a subtle edge).+- **Impact:** in the sole triggering scenario (broken shared temporal import) the ReviewHog leg is itself entirely down, so the shared-queue coupling adds negligible marginal harm — the sibling stamphog leg being skipped is subsumed by an already-loud outage; there is no reachable case where ReviewHog is healthy yet the first hook silently starves the second. Real mechanism and idiomatic fix, but the 'cancels the second' consequence depends on a condition that doesn't occur in practice given `_start_review`'s existing try/except — defensive hardening against a never-gonna-happen trigger, dropped under precision-over-recall. (Caveat: PR head `1341596e` is absent from this checkout, so `_start_stamphog_review` and the two-hook registration couldn't be read directly; assessed against the base `_start_review` the PR mirrors plus Django's confirmed hook semantics.)++### [✅ VALID] should_fix (validator→consider) · security — products/stamphog/backend/tasks/tasks.py:1158-1230++**Receiver leg posts a real approval with zero positive identification of the PR (no bot-author or task-linkage re-check)**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `process_inbox_pr_review` is the initial-review leg: it fetches whatever PR sits at the caller-supplied `pr_url`, then creates a `ReviewRun` stamped with `output={"inbox_review": ...}` and starts the review workflow. That provenance flips `self_driving_review=True` in the engine (relaxing the bot-author refusal and the draft prerequisite), and — because this leg starts the workflow directly rather than passing through `process_pull_request_event` — the per-repo `review_mode` gate and the author-write-permission gate are never applied at all (the workflow/`post_verdict` only consult `review_mode` for cosmetic label-stripping, confirmed at activities.py:768). The ONLY protection this leg applies is resolving a synced+enabled `StamphogRepoConfig` for the PR's repository. Unlike the sibling webhook leg (`_inbox_rereview_carve_out`, lines 144-215), it never verifies the fetched PR is bot-authored (`_is_bot_authored`), never re-confirms task linkage via `find_signal_implementation_run`, and never checks fork-safety. The webhook leg treats those checks as load-bearing precisely because they are what let it bypass the human-PR gates safely. If `output.pr_url` on a non-internal signal-report `TaskRun` ever points at a PR that is not a genuine bot-authored self-driving PR — e.g. mis-bound by the tasks webhook backstop's branch-name matching (`find_task_run`'s plain-branch leg matches on a colliding head ref like `main`), or any future change to how `pr_url` is populated — hosted Stamphog will post a real, head-pinned GitHub approval on that PR, satisfying branch protection with zero human review and bypassing every gate the webhook path preserves. This is a different axis from the already-noted `acting_user_id` ownership gap: that concerns reviewer identity, this concerns the identity of the PR being approved.+- **Suggestion:** Mirror the webhook leg's positive identification before granting the self-driving carve-out. At minimum, after fetching the PR, drop out (log + return) if `not _is_bot_authored(pr)`. Better, re-verify the linkage the caller asserts by calling `find_signal_implementation_run(team_id=..., repository=repository, pr_url=pr.get("html_url"), head_branch=...)` and confirming it resolves to a run whose `signal_report_id`/`run_id` match the `signal_report_id`/`task_run_id` passed in — only then stamp the inbox provenance and create the run. That keeps the two trigger legs symmetric and prevents this leg from being the one path that approves a human-authored PR when a stale/mis-bound `pr_url` slips through.+- **Validator:** - **Checked:** every guard in `process_inbox_pr_review` (`products/stamphog/backend/tasks/tasks.py:1130-1234`), the source of its `pr_url` argument (`products/review_hog/backend/receivers.py:93,126-138`), how `output.pr_url` is written (`products/tasks/backend/webhooks.py:184-212`), and how the provenance stamp drives the engine (`temporal/activities.py:451`).+- **Found:** The receiver leg applies no PR-identity verification at all — no `_is_bot_authored(pr)`, no `find_signal_implementation_run` re-check, no fork-safety (only repo-config resolution, `tasks.py:1140-1153`) — whereas the sibling webhook leg treats exactly those checks as load-bearing (`_inbox_rereview_carve_out`, `tasks.py:169-200`). The stamped `output.inbox_review` flips `self_driving_review=True`, relaxing the bot-author/draft gates and yielding a real head-pinned approval, so skipping identity verification on this leg is materially different from skipping it elsewhere.+- **Found:** The finding's stated mechanism is imprecise for this leg: `pr_url` is read directly from the run's own `TaskRun.output["pr_url"]` (`receivers.py:93`), not fuzzy-matched via `find_task_run` here. The only way a non-bot PR URL lands there is upstream mis-binding by the tasks webhook backstop `_record_run_pr_url` (`webhooks.py:212`), which does use branch matching — but it is fork-guarded (`is_internal_branch`, `webhooks.py:178-184`) and only writes when the URL isn't already set. Normally a self-driving run records its own bot-authored PR, so the fetched PR is bot-authored by construction.+- **Impact:** Real but narrow. A same-repo branch-name collision mis-binding a repo-native human PR onto a non-internal signal-report run (whose own PR URL isn't yet recorded), plus an opted-in reviewer, would let this leg post a trusted-provenance approval on a human PR with every human gate bypassed. That is a legitimate defense-in-depth asymmetry on a high-stakes path, and the `_is_bot_authored` guard is a cheap mirror of the webhook leg — worth keeping on record.+- **Priority:** Downgrading should_fix → consider. The harmful path is a low-probability, multi-condition edge case already partially guarded upstream (fork-safety, write-once), and the normal invariant (a self-driving run records its own bot PR) holds, so the fetched PR is bot-authored in every ordinary run. That reachability doesn't justify should_fix, but the cheap fix and severe worst case justify keeping it visible rather than dropping.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-2.mdnew file mode 100644index 000000000000..b82c7bc38d15--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-2.md@@ -0,0 +1,407 @@+# Reviewer-quality run — `A-sonnet5-xhigh-2`++- **Dumped:** 2026-07-23T19:23:20+00:00+- **Report id:** `019f9020-8c8e-792b-ac33-32efdaac6176` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 5128s (85.5 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-sonnet-5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 26 | 24 | 5 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 173 | 144,889 | 1,103,166 | 22,890,842 | 259,744 | 31 | $25.56 | $25.56 |+| claude-sonnet-5 | review | 230 | 246,792 | 2,417,675 | 31,329,071 | 391,347 | 37 | $16.72 | $16.72 |+| claude-sonnet-5 | blind-spot | 72 | 118,465 | 953,491 | 9,422,372 | 104,159 | 10 | $5.55 | $5.55 |+| claude-opus-4-8 | blind-spot | 33 | 1,264 | 372,306 | 3,354,637 | 50,027 | 0 | $5.26 | $5.26 |+| claude-opus-4-8 | review | 22 | 431 | 223,309 | 2,368,679 | 27,107 | 0 | $3.26 | $3.26 |+| claude-sonnet-5 | dedup | 1 | 19,698 | 0 | 0 | 5,232 | 0 | $0.09 | $0.09 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,676 | 0 | $0.03 | $0.03 |+| **total** | | **532** | **540,568** | **5,069,947** | **69,365,601** | **839,292** | **78** | **$56.47** | **$56.47** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- naive method (all prompt tokens at input price): $254.78 — 4.5× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $43.0236 over 532 gen(s) (true $43.0236, Δ -0.0%)+ - · of which cache read: $22.4574 over 503 gen(s) (true $22.4574, Δ +0.0%)+ - · of which cache write: $19.0453 over 529 gen(s) (true $19.0453, Δ +0.0%)+ - · of which fresh (derived): $1.5209 over 532 gen(s) (true $1.5209, Δ -0.0%)+ - output: $13.4461 over 532 gen(s) (true $13.4461, Δ +0.0%)+- 78 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------------------------------- |+| …50764ce9 | issues-review-p3-c3 | 17:59:14 | 0 | 58,718 | claude-sonnet-5 |+| …b6bcbeec | issues-review-p3-c2 | 17:59:15 | 0 | 72,800 | claude-sonnet-5 |+| …60d94f4f | issues-review-p1-c3 | 17:59:15 | 0 | 58,718 | claude-sonnet-5 |+| …93cd1f61 | issues-review-p3-c1 | 17:59:16 | 0 | 70,529 | claude-sonnet-5 |+| …225e9e33 | issues-review-p2-c2 | 17:59:16 | 0 | 72,798 | claude-sonnet-5 |+| …599c50bb | issues-review-p2-c1 | 17:59:17 | 0 | 70,530 | claude-sonnet-5 |+| …bbd6f6ea | issues-review-p1-c2 | 17:59:17 | 0 | 72,796 | claude-sonnet-5 |+| …cbcdc354 | issues-review-p2-c3 | 17:59:18 | 0 | 58,717 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …0b006751 | issues-review-p1-c1 | 17:59:26 | 22,467 | 48,066 | claude-sonnet-5 |+| …6ba59385 | issues-review-p1-c3 | 18:07:37 | 0 | 58,731 | claude-sonnet-5 |+| …87b24e31 | blind-spots-c2 | 18:15:59 | 0 | 79,037 | claude-sonnet-5 |+| …ca6992ab | blind-spots-c4 | 18:15:59 | 0 | 55,178 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …746b5e6e | blind-spots-c1 | 18:16:00 | 0 | 73,880 | claude-sonnet-5 |+| …a95794f6 | blind-spots-c3 | 18:16:00 | 0 | 62,470 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …8bf55a9c | blind-spots-c1 | 18:23:58 | 0 | 73,872 | claude-sonnet-5 |+| …be43771a | validation-c2 | 18:32:46 | 0 | 39,910 | claude-opus-4-8 |+| …7dbab6c1 | validation-c1 | 18:32:49 | 0 | 39,416 | claude-opus-4-8 |+| …074f698c | validation-c3 | 18:32:51 | 0 | 39,137 | claude-opus-4-8 |+| …c92ab2d3 | validation-c4 | 18:32:54 | 17,141 | 22,112 | claude-opus-4-8 |+| …14147298 | validation-c2 | 18:46:51 | 0 | 41,007 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **2/20** (report the distribution, not a median).+- ⚠️ 3 unit(s) switched models mid-session (overload rescue?) — cache sharing and cost pinning are broken for them: …cbcdc354, …ca6992ab, …a95794f6++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 20s |+| review wave (perspectives) | 16m 42s |+| blind-spot sweep | 13m 28s |+| dedup (incl. combine/clean) | 3m 41s |+| validation | 50m 04s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 30m 11s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 4 |+| 1 | 3 | review-hog-perspective-contracts-security | 3 |+| 2 | 1 | review-hog-perspective-logic-correctness | 3 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 6 |+| 3 | 3 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | review-hog-blind-spots-general | 1 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider · security — products/stamphog/backend/tasks/tasks.py:113-121++**`_parse_pr_url` uses an unanchored regex search, accepting any string that merely contains a github.com PR substring**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` is applied with `.search()`, not `.match()`/full-string validation, and never checks the URL scheme/host boundary. A string like `https://evil.example/?next=https://github.com/owner/repo/pull/123` would still parse to `("owner/repo", 123)` even though it isn't a github.com URL at all. `pr_url` currently only arrives as a Celery task argument from `queue_inbox_pr_review` (not directly from an HTTP/webhook body), so today's blast radius is limited, but this is the kind of loose boundary-input parsing that's easy to reuse later against a less-trusted source.+- **Suggestion:** Anchor the pattern to the start of the string and validate the scheme/host explicitly, e.g. `^https://github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)/?$` with `re.match`, or parse with `urllib.parse.urlsplit` and check `netloc == "github.com"` before extracting the path segments.+- **Validator:** - **Checked:** every caller of `_parse_pr_url`/`_PR_URL_RE` (tasks.py:113-121), how the parsed tuple is consumed in the only caller `process_inbox_pr_review` (tasks.py:1130-1170), and where `pr_url` originates.+- **Found:** the sole caller is `process_inbox_pr_review` (tasks.py:1130). `pr_url` is a Celery argument sourced from `TaskRun.output["pr_url"]` (receivers.py:93) via `queue_inbox_pr_review` (receivers.py:222-231) — there is no HTTP/webhook path into it, exactly as the finding concedes.+- **Found:** the parsed `repository` is used _only_ as a filter term in a team-scoped lookup — `StamphogRepoConfig.objects.for_team(team_id)...filter(repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False)` (tasks.py:1140-1147) — which no-ops silently on no match. The subsequent GitHub fetch uses `repo_config.repository`, the config's own slug, NOT the parsed string (tasks.py:1159). Only `pr_number` carries through, and it addresses a PR in a repo the team's Stamphog App is already installed on and authorized to review.+- **Impact:** no reachable correctness/security/data-loss consequence at the current call site: a decoy `github.com/...` substring can neither redirect a request (no SSRF — the fetch host/repo come from the matched config, not the parsed URL) nor bypass any auth boundary (the team-scoped, enabled-only config gate stands regardless of what the URL parses to). The finding itself frames the risk as future — "easy to reuse later against a less-trusted source" — which is precisely the speculative "what-if depends on a call site that doesn't exist yet" the bar says to drop. Per precision-over-recall, this is hardening hygiene, not a real problem affecting users.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:130-143++**The `inbox_review` provenance shape is an untyped ad-hoc dict duplicated across both trigger legs**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The `{"trigger": ..., "signal_report_id": ..., "task_run_id": ..., "acting_user_id": ...}` shape is hand-built independently in `_inbox_rereview_carve_out`'s `_InboxCarveOut.provenance` (webhook leg) and again in `process_inbox_pr_review`'s `inbox_review` literal (receiver leg), then read back via `run.output.get("inbox_review")` in `temporal/activities.py` to derive the security-relevant `self_driving_review` flag. There's no shared TypedDict/dataclass constant for the key names, so a future rename of one key in one of the three sites (e.g. `task_run_id` vs `run_id`) would silently break the flag/attribution with no static check to catch it, since `ReviewRun.output` is a schemaless JSONField.+- **Suggestion:** Define a small typed structure (e.g. a `TypedDict` or frozen dataclass with a `to_dict()`) for the inbox-review provenance payload in one place (e.g. alongside `_InboxCarveOut`), and have both `_inbox_rereview_carve_out` and `process_inbox_pr_review` build it through that shared definition so the three consumption sites can't drift out of sync.+- **Validator:** - **Checked:** the two build sites (`_inbox_rereview_carve_out` provenance at tasks.py:208-215, `process_inbox_pr_review` `inbox_review` literal at tasks.py:1176-1181) and every consumer of `run.output["inbox_review"]`, plus a repo-wide grep for any read of the inner keys (`trigger`/`signal_report_id`/`task_run_id`/`acting_user_id`).+- **Found:** all three consumption sites key on the _presence_ of the dict, never an inner key — the security-relevant flag is `self_driving_review=bool(output.get("inbox_review"))` (activities.py:451), the analytics stamp is `if (run.output or {}).get("inbox_review"):` (activities.py:175), and the author-fetch skip is `bool((run.output or {}).get("inbox_review"))` (activities.py:237). The gating in the webhook leg likewise tests `inbox_review is None` (tasks.py:881/944/968/1064), never a sub-key.+- **Found:** a repo-wide grep for any getitem/`.get` on `task_run_id`/`signal_report_id`/`acting_user_id`/`run_id` out of `inbox_review` returns nothing — the inner keys are a write-only provenance record, read by no decision logic.+- **Impact:** the finding's stated consequence is disproven — renaming an inner key in one build site leaves the dict non-empty, so `bool(output.get("inbox_review"))` stays True and neither the `self_driving_review` carve-out nor the analytics stamp nor the author-skip changes. There is no correctness, security, contract, or attribution break to catch. What remains is a request to add a shared TypedDict/dataclass to future-proof two small 4-key literals (both in one file, tasks.py) against a hypothetical rename — textbook overengineering + speculative 'what-if' on top of a mistaken premise, which the criteria say to drop (precision over recall).++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:316-321++**self_driving_review flag is parsed with truthy bool() coercion instead of a strict boolean check**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self_driving=bool(context.get("self_driving_review"))` (line 316) coerces the JSON-sourced value with Python truthiness rather than verifying it is the literal boolean True. The accompanying comment stresses this field 'defaults closed' when absent — but that guarantee only covers the missing-key case. Any other truthy-but-wrong representation (e.g. the string "false", the string "0", or any non-empty string a future bug in the server's context-assembly produces) evaluates to bool(...) == True and silently opens the carve-out — bypassing both the bot-author refusal and the draft prerequisite (review_local.py lines 319-321 and the shared_check_prerequisites gate) — for what should be an ordinary, non-self-driving review. This one boolean is the entire trust boundary between a normal sandboxed review and one that skips two hard security gates, which makes it a poor candidate for the same loose bool() coercion used elsewhere in this file for informational fields like draft state.+- **Suggestion:** Parse the flag with an explicit identity check, e.g. `context.get("self_driving_review") is True`, so any value that isn't the literal JSON boolean `true` fails closed instead of being coerced to True by Python truthiness.+- **Validator:** - **Checked:** the full producer→transport→consumer path for `self_driving_review`, at PR head `1341596e` (the working tree is on master and lacks the change, so I fetched the file and PR diff from the GitHub API). Producer: `products/stamphog/backend/logic/reviewer.py::build_reviewer_invocation(self_driving_review: bool = False)` writes `"self_driving_review": self_driving_review` into the context dict. Call sites: `tasks.py` passes `self_driving_review=bool(output.get("inbox_review"))`, and the only other producer is the typed default `False`. Transport: the dict is `json.dumps`'d to the sandbox context file. Consumer: `review_local.py` reads `bool(context.get("self_driving_review"))`.+- **Found:** every producer of this key yields a genuine Python `bool`, and JSON round-trips `true`/`false` back to Python `True`/`False` (the integration test at `products/stamphog/backend/tests/test_integration.py` even asserts `context["self_driving_review"] is True` on the decoded JSON). So at the read site the value can only be `True`, `False`, or absent (`None`) — `bool(...)` and `is True` are behaviorally identical for every value the system actually produces.+- **Impact:** the reviewer's trigger (`"false"`, `"0"`, or another truthy-but-wrong string) is explicitly premised on "a future bug in the server's context-assembly" — a value that cannot occur given the typed-bool pipeline in place today. It is speculative-what-if / defensive paranoia against inputs the upstream types already rule out, which the validation bar says to drop. The framing as a 'trust boundary' also doesn't survive scrutiny: the context JSON is server-produced trusted input written into the sandbox, not attacker-controlled, and anyone able to forge that file could just write `true` — a strict `is True` check defends against nothing reachable. Precision-over-recall → drop.++### [❌ dismissed] should_fix · code_quality — tools/pr-approval-agent/reviewer.py:694-702++**Provenance block hard-codes "It is a draft on purpose" even when the self-driving PR is no longer a draft**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `_format_self_driving` renders the sentence "It is a draft on purpose (the verdict is wanted at Inbox triage time); draft state is not a caution signal for this PR" unconditionally whenever `cl.get("self_driving")` is truthy. Per the PR's own design, carved-out self-driving runs are re-reviewed on the webhook leg for `synchronize`/`reopened`/base-retarget events, and a self-driving PR can be flipped from draft to ready before those later pushes (the design explicitly keeps the draft-time verdict when it goes ready, and `ready_for_review` is excluded from re-review — so a subsequent `synchronize` re-review runs with `self_driving=True` while `pr.draft` is now False). In that re-review the trusted-context region of the prompt asserts a factually false statement about the PR's current state. Given how carefully the rest of this prompt is kept accurate in the trusted region (e.g. the assurance/familiarity comments about never misleading the LLM), feeding a false draft-status fact is an inconsistency.+- **Suggestion:** Condition the draft sentence on the PR's actual draft state, or reword it so it does not assert current draft status. `_format_self_driving` only receives `cl`, so either thread the draft flag into the classification dict (e.g. add `"draft": pr.draft`) and branch on it, or soften the copy to something like "If this PR is still a draft, that is on purpose (the verdict is wanted at Inbox triage time) and draft state is not a caution signal for it."+- **Validator:** - **Checked:** `_format_self_driving` in the PR head of `tools/pr-approval-agent/reviewer.py` (lines 683-702; the working tree is on master and lacks the change, so I fetched the file and PR diff from the GitHub API), plus the webhook-leg re-review scope in the stamphog backend and its tests.+- **Found:** the reviewer's premise is mechanically reachable — `ready_for_review` is excluded from re-review (parameterized test `ready_for_review_keeps_the_draft_verdict`, diff line 1462, expects 0 reviews), while a later `synchronize` re-reviews with `self_driving=True`; by then `pr.draft` can be `False`. So the block's clause "It is a draft on purpose ... draft state is not a caution signal for this PR" (reviewer.py:698-700) can render present-tense-stale.+- **Impact:** the consequence is confined to one stale clause in an LLM prompt, and it is inert rather than misleading. The clause exists solely to _relax_ draft-caution; on a now-ready PR there is no draft state to be cautious about, so telling the model not to treat draft as a caution signal changes no verdict. Every other fact in the trusted block (machine author, judge on merits, provenance verified, treat PR body as untrusted) stays accurate. There is no wrong review outcome, no security bypass, no data effect — the reviewer itself frames it as "an inconsistency" in prompt accuracy. That is prompt-wording hygiene with no behavioral difference, which the criteria place in the drop bucket (style/taste, no behavioral difference; low-impact edge case). Precision over recall → drop.++### [❌ dismissed] consider · code_quality — tools/pr-approval-agent/reviewer.py:505-506++**Engine does not enforce familiarity-absence for self-driving runs, so the prompt can carry contradictory trust guidance**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self-driving provenance block states that "author familiarity, org membership, and merged-PR history carry no signal here" and its docstring says "familiarity is deliberately absent." However the engine renders `familiarity_block` and `self_driving_block` from independent inputs (`familiarity_block = self._format_familiarity(cl)` then `self_driving_block = self._format_self_driving(cl)`), and nothing suppresses familiarity when `self_driving` is set. `_attach_familiarity` (review_local.py) and `_maybe_compute_familiarity` (review_pr.py) gate only on `tier == "T1-agent"` and the presence of injected PR numbers — not on `pipeline.self_driving`. If a self-driving run is ever handed author history (e.g. `author_pr_numbers` present in the context JSON), the prompt would show both a populated familiarity block and the provenance block that tells the model familiarity carries no signal — directly contradictory guidance in the trusted region. The design relies on the caller omitting that data rather than the engine enforcing the invariant it advertises.+- **Suggestion:** Make the engine self-enforce the invariant it claims: when `self.self_driving` is True, do not attach/compute familiarity (guard `_attach_familiarity`/`_maybe_compute_familiarity` with `and not self.self_driving`, or force `classification["familiarity"] = None`). This honors the block's "replaces human-author trust context" contract regardless of what the caller provides, matching the parity/self-contained-engine intent.+- **Validator:** - **Checked:** the two-block render at `tools/pr-approval-agent/reviewer.py:505-506`, the familiarity renderer (`_format_familiarity`, reviewer.py:636-681), the familiarity-attach gates (`_attach_familiarity` in review_local.py, `_maybe_compute_familiarity` in review_pr.py), and the server-side context assembly (`fetch_review_context` / `run_review_in_sandbox` in `products/stamphog/backend/tasks/tasks.py`). Fetched PR-head versions via the GitHub API since the working tree is on master.+- **Found:** the contradictory-prompt scenario requires a self-driving run to carry a populated familiarity block, which requires non-empty `author_pr_numbers`. But the server derives _both_ signals from the single `inbox_review` provenance flag: `is_inbox_review` forces `author_pr_numbers = []` for exactly the runs where `self_driving_review=bool(output.get("inbox_review"))` is True. With empty `author_pr_numbers`, `_attach_familiarity` early-returns (`if not raw_prs: return`), `cl['familiarity']` stays None, and `_format_familiarity` returns `""` (reviewer.py:644-646). So the populated-familiarity + provenance-block combination cannot co-occur given the current caller.+- **Impact:** the reviewer's own trigger is conditional — "If a self-driving run is _ever_ handed author history" — and it explicitly notes "the design relies on the caller omitting that data." That is a defense-in-depth request to have the engine redundantly enforce an invariant the parent caller already guarantees, guarding against an input that can't occur given the call sites. Per the criteria (drop 'already handled elsewhere' and 'defensive-coding paranoia against invariants the caller already rules out'; precision over recall), this is noise, not a reachable correctness defect. Already flagged `consider` by the reviewer; I drop it entirely.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected cross-database read fires on every settings write, not just reads**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` (a `SerializerMethodField`) is re-evaluated whenever `ReviewUserSettingsSerializer(instance).data` is built — including on `PATCH`, where `serializer.save()` is followed by `Response(serializer.data)` (see `user_settings` below). That means every settings write, even one that only toggles `urgency_threshold` or `review_labeled_prs` and has nothing to do with Stamphog, pays for an extra cross-product-database round trip (and a try/except around it) purely to re-render a field the PATCH request didn't change.+- **Suggestion:** Either skip recomputing `stamphog_connected` on the PATCH response (e.g. reuse the value already known from the GET that populated the form, or drop it from the PATCH response schema since the frontend already has it from the initial load) or cache the repo-config check briefly (it changes rarely) so repeated writes in a short window don't each pay for the extra DB hit.+- **Validator:** - **Checked:** the PR-head `get_stamphog_connected` (settings.py serializer), `has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`, and whether the PR alters the view's PATCH branch (via `gh pr diff 72680`, since the local checkout is at a master commit, not the PR head).+- **Found:** the premise is factually correct — `has_reviewable_repo_config` is a single `StamphogRepoConfig.objects.for_team(...).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` (facade/api.py:120-125), and the view method is untouched by the PR, so `PATCH` still returns `Response(serializer.data)`, which re-renders the `stamphog_connected` SerializerMethodField on every write.+- **Impact:** the confirmed cost is exactly one lightweight indexed `.exists()` query per write, wrapped in a fail-soft try/except — not an N+1, unbounded, quadratic, or async-blocking pattern. This is a per-user settings toggle in the Code review scene; PATCHes are human-driven (flipping a switch), inherently low-frequency, and not a hot path, so the 'repeated writes in a short window' scenario the caching suggestion relies on isn't realistic. The GET path (scene load, the more frequent access) already performs this exact read, and the try/except means a stamphog-DB outage cannot take the write path down — so PATCH merely adds one more marginal read to an infrequent write.+- **Impact:** the suggested remedies add complexity for negligible gain — dropping the field from the PATCH response creates GET/PATCH schema asymmetry (and generated-type awkwardness), and caching a cross-DB check introduces invalidation concerns. Under the criteria this is a micro-optimization that does not bite at real scale; precision-over-recall says drop.++### [✅ VALID] should_fix (validator→consider) · performance — products/stamphog/backend/tasks/tasks.py:179-186++**Inbox carve-out resolves StamphogRepoConfig twice against the writer DB per event**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `_inbox_rereview_carve_out` calls `_resolve_repo_config(installation_id, repo)` (writer-pinned per its docstring) to validate the repo config, but the caller (`process_pull_request_event`) unconditionally re-runs the exact same `_resolve_repo_config(installation_id, repo)` call again a few lines later once `inbox_review` is non-None, to get `repo_config` for the rest of the function (author-permission/review-mode gates, run creation). That is two identical writer-pinned Postgres reads for every synchronize/reopened/base-retarget webhook delivery on a self-driving PR, where one would do.+- **Suggestion:** Have `_InboxCarveOut` carry the resolved `StamphogRepoConfig` (or return it alongside the provenance) so the caller reuses it instead of calling `_resolve_repo_config` a second time on the same code path.+- **Validator:** - **Checked:** the call graph of `_resolve_repo_config` on the self-driving webhook path — the carve-out call (tasks.py:179), the main-path call (tasks.py:918), the base-retarget call (tasks.py:858) — plus what `_resolve_repo_config` actually costs (tasks.py:183-189) and how config is resolved elsewhere in `process_pull_request_event`.+- **Found:** the redundancy is real. A self-driving PR is a bot-authored draft by construction, so `skip_reason` is always set (tasks.py:870), which runs `_inbox_rereview_carve_out` (tasks.py:876) → `_resolve_repo_config` (tasks.py:179); the main path then re-runs the identical `_resolve_repo_config` (tasks.py:918). A base-retarget delivery adds a third identical call (tasks.py:858). So 2 (or 3) identical writer-pinned reads per qualifying delivery, as claimed.+- **Impact:** the consequence is minor, not `should_fix`. `_resolve_repo_config` is a single indexed point-lookup (`filter(provider, installation_id, repository).order_by(...).first()`, tasks.py:183-189) against `StamphogRepoConfig`, a tiny table (one row per configured repo). The path is cold — only self-driving inbox PRs receiving synchronize/reopen/retarget deliveries — not a hot loop; it is not N+1, unbounded, quadratic, or a missing-index-on-hot-path, so it does not meet the skill's 'bites at real scale' performance bar. The handler already re-resolves config independently across branches (tasks.py:858, 891, 918), each wrapped in its own retry — the extra read is consistent with a deliberate per-branch retry-isolation pattern, and consolidating it would couple the carve-out helper's return to the main path's needs for a sub-millisecond saving.+- **Priority:** downgraded to `consider` — a genuine, correctly-identified redundant read (not speculation or noise), but negligible impact on a low-frequency path, so it belongs on record at the lowest priority rather than as a `should_fix`.++### [✅ VALID] must_fix (validator→should_fix) · performance — products/stamphog/backend/tasks/tasks.py:941-944,967-969,1059-1067++**Carved-out inbox re-reviews reach the webhook leg's unconditional supersede+create path, which has no head-based dedup against the new receiver leg — routine self-driving PR pushes get double-reviewed**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** When `_inbox_rereview_carve_out` identifies a delivery as a self-driving re-review, `inbox_review` bypasses `_review_mode_skip_reason` (L941-944) and `_author_lacks_write_permission` (L967-969) and falls through into the pre-existing `_supersede_prior_runs(pr_obj)` + `ReviewRun.objects.create(...)` block (L1059-1067, unchanged by this PR). That block was written for a world with exactly one run-creating entry point (the webhook) and has no head_sha-aware dedup: it unconditionally marks every non-terminal run for the PR as SUPERSEDED and creates a fresh one. Its only anti-duplication guard is the `payload_updated_at` staleness check a few lines above (L871-909), which compares GitHub's PR-level `updated_at` timestamp — not head_sha — and has no knowledge of runs created by a different origin.++This PR adds exactly that second origin: `process_inbox_pr_review` (leg 1) creates ReviewRun rows for the same self-driving PR heads, triggered by review_hog's TaskRun-output-save receiver (in-process, near-instant), while `process_pull_request_event` (leg 2) creates them via GitHub's webhook (network-latency delayed) for the very same pushes. Leg 1 was given its own explicit head_sha-based dedup (`existing = ReviewRun.objects...filter(pull_request=pr_obj, head_sha=head_sha)...` before create) specifically because it re-fires repeatedly — but leg 2's much older supersede-then-create logic was never taught about leg 1's runs. Concretely: the self-driving agent pushes commit A; the TaskRun output save fires first and `process_inbox_pr_review` creates ReviewRun R1 for head A and starts its workflow (sandbox+LLM begins). Moments later GitHub's `synchronize` webhook for the same push is processed by `process_pull_request_event`: `skip_reason` is "draft", the carve-out re-identifies the same self-driving PR/toggle, `inbox_review` is set, the mode and permission gates are bypassed, and the staleness check at L871-909 does not block it (GitHub's `updated_at` for this one push is identical whichever leg observed it, so `payload_updated_at > incoming_updated_at` is False). Execution proceeds to L1059-1067: `_supersede_prior_runs` marks R1 (QUEUED or IN_PROGRESS) as SUPERSEDED purely because a new relevant event arrived — with no check that R1 already targets this exact head — and a second ReviewRun R2 is created for the identical head A, starting a second full sandbox+LLM review of the same commit.++This is not a narrow race window: self-driving implementation tasks push iteratively (push, get CI feedback, fix, push again) and save TaskRun output throughout that loop, so both trigger paths fire for most heads a self-driving PR produces, not just in an edge case. `post_verdict`'s superseded-status guard (per `products/stamphog/CLAUDE.md`'s stale-approval invariant) does stop R1 from ever posting a second GitHub approval once superseded, so this isn't a double-approval bug — but a full sandbox provisioning + LLM review is wasted on R1 every time leg 1 happens to win the race, which will be routine rather than exceptional given in-process Celery dispatch is typically much faster than a GitHub webhook round trip.++- **Suggestion:** Before the unconditional `_supersede_prior_runs(pr_obj)` + create in the carved-out (`inbox_review is not None`) branch, add the same head-based existence check `process_inbox_pr_review` already uses: look up a non-superseded/non-failed `ReviewRun` for `pr_obj` at `head.get("sha", "")`, and if one already exists (created by the other leg), skip creating a duplicate — at most restart its workflow if it's still QUEUED, exactly as `process_inbox_pr_review` does for its own repeat fires. This keeps the two entry points from treating a single self-driving PR head as two independent reviews.+- **Validator:** - **Checked:** Local checkout is stale (master, 960 lines) so I fetched the PR head (`1341596e`, 1245 lines) via the GitHub API and read both legs: `process_pull_request_event`'s carve-out branch, `process_inbox_pr_review`'s create block, `_inbox_rereview_carve_out`, and review_hog's `handle_task_run_saved` receiver.+- **Found:** The asymmetry is real. Leg 1 (`process_inbox_pr_review`) guards its create with a head-keyed dedup (pr_tasks.py:1202-1210) that selects every non-SUPERSEDED/FAILED run for the PR at `head_sha` — leg-2 runs included — and no-ops (or restarts a QUEUED one). Leg 2's carve-out branch skips the mode gate (L944, `if inbox_review is None`) and write-permission gate (L967-969) and falls into the unchanged shared block (L1054-1065): `_supersede_prior_runs(pr_obj)` marks ALL non-terminal runs SUPERSEDED regardless of head, then `create(...)`s a fresh run — no head existence check.+- **Found:** Both legs genuinely target the same later head. The receiver re-fires on every `output` save carrying `pr_url` (receivers.py:76-79, 126-139), and leg 1 is explicitly documented as a backstop that reviews "a head the webhook leg never delivered" (pr_tasks.py:1125-1128) — the authors knew both legs can create runs for one head yet only guarded leg 1. No other guard blocks leg 2: the stale-payload check (L1045-1053) compares PR-level `updated_at`, identical for a single push whichever leg observed it, so it evaluates False; and leg 2's delivery-id dedup/resume path can't match leg-1 runs (`delivery_id=None`, L1227).+- **Impact:** Confirmed. When leg 1 wins the race for a later push (creates R1 at head B, starts its workflow), the subsequent synchronize webhook drives leg 2 to supersede R1 and create R2 for the identical head; R1's sandbox+LLM review runs to completion and is wasted (bails at post_verdict on SUPERSEDED). This is a resource/cost defect consistent with the code's repeated concern about burning sandbox+LLM credits. As the reviewer concedes, there's no double-approval — the superseded guard holds — so it is not a correctness or data-integrity issue.+- **Priority:** Lowering must_fix → should_fix. The impact is bounded, race-gated compute waste confined to an opt-in feature, not correctness/data-loss/security. The claim that it is "routine" is unproven: the receiver's `output` save typically lands at end-of-turn, often after the webhook, which lets leg 2 win the race and leg 1 correctly no-op — so the wasteful ordering is intermittent, not the norm. Worth closing (the fix is a small mirror of leg 1's existing dedup), but it doesn't block the PR.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:110-112,82-82,94-96++**Carve-out bypass enumeration omits the untrusted-association pre-filter gate**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new section names `_review_skip_reason` as the webhook pre-filter that refuses bot PRs (line 82), then enumerates what the carve-out relaxes: the engine bullet relaxes "exactly two gates — the bot-author refusal and the draft prerequisite" (lines 94-96), and the last bullet bypasses "the review-mode and author-write-permission gates" (lines 110-112). But `_review_skip_reason` (products/stamphog/backend/tasks/tasks.py:102-119) refuses on THREE independent conditions, not two: `draft`, `bot_author`, and `untrusted_author_association` (`author_association not in PAYLOAD_GATE_AUTHOR_ASSOCIATIONS`, line 117-118). A self-driving PR opened by the App's machine user — which this very section calls out as "not a collaborator" (line 111) — would carry `author_association = NONE`, tripping the `untrusted_author_association` branch. On the webhook re-review leg (leg 2), which the section says flows through the normal webhook path (i.e. `process_pull_request_event` → `_review_skip_reason`), that third gate would refuse the PR, yet the contract never lists it among the bypassed gates. As written the enumeration does not match the branches of the pre-filter it names.+- **Suggestion:** Make the bypass enumeration cover all three branches of `_review_skip_reason`. Either add the association gate explicitly (e.g. state that positive task-linkage subsumes the fork/external-author `untrusted_author_association` check for carved-out runs), or say plainly that carved-out runs skip `_review_skip_reason` wholesale (draft + bot + association) rather than only relaxing the two engine gates. This matters because the file is explicitly the security "contract": a maintainer auditing or tightening the carve-out could re-apply the association gate believing only review-mode and write-permission are intended bypasses, silently breaking the webhook re-review leg (the tests assert any gate accidentally re-applied fails).+- **Validator:** - **Checked:** `_review_skip_reason` (products/stamphog/backend/tasks/tasks.py:102-119), the new `_inbox_rereview_carve_out` (tasks.py, PR diff), the webhook skip block in `process_pull_request_event`, the added AGENTS.md carve-out section (PR diff), and the carve-out test in test_tasks.py.+- **Found:** `_review_skip_reason` returns on the FIRST matching branch: `draft` → `bot_author` → `untrusted_author_association` (tasks.py:110-118). `_inbox_rereview_carve_out` returns `None` immediately `if not _is_bot_authored(pr)`, so every carved-out run is bot-authored by construction. For any bot-authored PR the function returns `"draft"` or `"bot_author"` and NEVER reaches the association branch — that branch is unreachable for the exact PR shape the carve-out handles. So the finding's premise ("a self-driving PR ... would carry `author_association = NONE`, tripping the `untrusted_author_association` branch ... that third gate would refuse the PR") is factually wrong: the bot_author/draft branch always short-circuits first.+- **Found:** The webhook leg bypasses `_review_skip_reason` wholesale, not gate-by-gate — `if skip_reason is not None and inbox_review is None:` skips the entire block once `inbox_review` resolves, so all three reasons are relaxed together. The enumeration the finding wants (call out the association gate specifically) would document bypassing a gate the PR never reaches.+- **Found:** The exhaustive gate list already lives in code — the `_inbox_rereview_carve_out` docstring lists "bot author, draft, author association, write permission, review mode." The AGENTS.md intro also frames the carve-out as the exception to being "refused at every layer — the webhook pre-filter (`_review_skip_reason`) ...". The "exactly two gates" line is scoped to the ENGINE flag (`Pipeline(self_driving=...)`), which genuinely has only bot-author + draft gates; it is not a claim about `_review_skip_reason`.+- **Found:** `test_inbox_carve_out_rereviews_a_selfdriving_pr_past_every_gate` uses `author_association: "NONE"` and asserts a run IS queued, so accidentally re-applying the association gate fails CI. The finding's own suggestion concedes "the tests assert any gate accidentally re-applied fails," which directly contradicts its "silently breaking the webhook re-review leg" rationale.+- **Impact:** This is a documentation-precision nit whose technical premise is mistaken (the association branch is unreachable for bot-authored carved-out runs), the code is correct and the bypass is tested, and the claimed silent-break risk is precluded by existing CI coverage. It is not a correctness, security, data-loss, or code-contract defect. Under precision-over-recall it does not meet the bar — drop.++### [❌ dismissed] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1245++**Receiver-leg Celery task (`process_inbox_pr_review`) grants the self-driving bypass with no server-side verification of the PR-to-run linkage**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `process_inbox_pr_review` (queued by the new facade `queue_inbox_pr_review` in `facade/api.py#L119-157`) trusts its caller-supplied `pr_url`, `task_run_id`, `signal_report_id`, and `acting_user_id` completely. It never calls `find_signal_implementation_run` (or any equivalent check) to confirm that `pr_url` actually corresponds to a non-internal, team-scoped signal-implementation `TaskRun`. It also never re-runs `_review_skip_reason`, `_review_mode_skip_reason`, or `_author_lacks_write_permission` before creating the `ReviewRun` with `output={'inbox_review': inbox_review}` and starting the workflow. Compare this to the webhook leg's `_inbox_rereview_carve_out` (same file, ~L144-215), which explicitly performs 'positive identification, never author-login matching' via `find_signal_implementation_run` plus a `run.team_id != repo_config.team_id` recheck before granting the same bypass. Since `run.output['inbox_review']` truthiness is what flips `self_driving_review=True` in `temporal/activities.py#L448-451` (which relaxes the engine's bot-author and draft gates and swaps in a TRUSTED provenance block per the PR description), any bug in review_hog's receiver (stale/incorrect `output.pr_url`, a race between two TaskRuns, or any other future caller of this facade) results in stamphog fetching an arbitrary PR in the team's connected repo and running the trust-relaxed review — potentially posting a real GitHub APPROVE — with zero independent verification inside the stamphog product boundary. This is the exact class of caller-trust gap the facade/tach.toml isolation boundary is meant to prevent.+- **Suggestion:** Before creating the ReviewRun in `process_inbox_pr_review`, call `find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url, head_branch=<pr head ref once fetched>)` (mirroring `_inbox_rereview_carve_out`) and bail out (log + return, no retry) if it returns `None` or if the returned `run.task_run_id`/`signal_report_id` don't match the arguments the caller supplied. This makes leg 1 as self-defending as leg 2 and removes the implicit trust in review_hog's receiver being bug-free forever.+- **Validator:** - **Checked:** Fetched the PR head (`1341596e`) since the local checkout is stale, and read `process_inbox_pr_review` (pr_tasks.py:1109-1245), the `queue_inbox_pr_review` facade (facade/api.py:128-155), review_hog's `handle_task_run_saved` receiver (receivers.py:72-141), and the `self_driving_review` derivation (activities.py:175, 237-238, 451).+- **Found:** The facade is documented as "The programmatic entry for review_hog's inbox trigger" with a single in-process first-party caller; the reviewer's own wording ("any other future caller of this facade") concedes none exists today. The receiver derives every argument from the actual TaskRun it fires on — `pr_url = instance.output.get('pr_url')`, `task_run_id = str(instance.id)`, `signal_report_id = str(task.signal_report_id)` — only after asserting `task.signal_report_id is not None` (receivers.py:98) and `not task.internal` (L104). That IS the non-internal, signal-report linkage leg 2 reconstructs via `find_signal_implementation_run`; leg 1 starts from the identified run itself, so the check would re-derive what it already holds. The premise that leg 1 has 'no verification of the PR-to-run linkage' is mistaken — the verification lives at the trigger, in review_hog.+- **Found:** `process_inbox_pr_review` is fully team-scoped (repo_config via `for_team(team_id)` + `enabled=True` + `connected_by_user_id__isnull=False`, pr_tasks.py:1140-1147; run via `for_team(team_id)`, L1223), with `team_id = instance.team_id`. The target is bounded to the team's OWN synced+enabled repos — there is no cross-tenant/IDOR reach and not "an arbitrary PR." Per CLAUDE.md the sandbox credential is minted under the repo's `connected_by_user_id`, not the caller-supplied `acting_user_id`, so a bad `acting_user_id` is mis-attribution, not privilege escalation.+- **Found:** The leg-1/leg-2 asymmetry is by design, driven by trust level: leg 2's trigger is a GitHub webhook that fires for every push (human, dependabot, arbitrary bot drafts) and carries no PostHog identity, so it must positively identify before relaxing gates; leg 1's trigger is an internal TaskRun the platform created and whose `output.pr_url` it recorded. Not re-running `_review_skip_reason`/`_review_mode_skip_reason`/`_author_lacks_write_permission` is intentional — self-driving PRs are bot-authored drafts by construction that those gates exist to refuse.+- **Impact:** Does not meet the bar. Every concrete trigger the finding offers — 'any bug in review_hog's receiver,' 'stale/incorrect output.pr_url,' 'a race between two TaskRuns,' 'any other future caller' — is a hypothetical that cannot occur given the current, single, arg-deriving call site. This is defense-in-depth / future-proofing against a caller being buggy 'forever,' which maps directly to the criteria's DROP categories (speculative what-if, defensive paranoia, overengineering). The tach/facade boundary governs imports, not a requirement that every facade entry re-validate first-party args against the DB. No concrete, currently-reachable correctness or security defect.++### [❌ dismissed] consider · code_quality — products/review_hog/backend/receivers.py:130-130++**Redundant local alias stamphog_pr_url adds no closure safety and obscures intent**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `stamphog_pr_url = pr_url` is assigned immediately before being passed into the lambda as `pr_url=stamphog_pr_url`. There is no loop here, so there is no late-binding closure hazard this alias could be protecting against — `pr_url` itself is never reassigned after this point, and the sibling `_start_review` lambda a few lines above closes over `pr_url` directly. The extra variable reads as if it exists for a reason (e.g. closure safety) when it doesn't, which can mislead a future reader into thinking removing it would introduce a bug.+- **Suggestion:** Pass `pr_url=pr_url` directly to `_start_stamphog_review`, matching the pattern used for `_start_review` just above, and drop the `stamphog_pr_url` local.+- **Validator:** - **Checked:** the PR-head `handle_task_run_saved` in `products/review_hog/backend/receivers.py` — both `transaction.on_commit` lambdas (`_start_review` and `_start_stamphog_review`) and whether `pr_url` is reassigned between them.+- **Found:** the observation is factually correct — the stamphog branch does `stamphog_pr_url = pr_url` and passes `pr_url=stamphog_pr_url`, while `_start_review` just above closes over `pr_url` directly; there is no loop and `pr_url` is never reassigned after either lambda is defined, so the alias offers no late-binding protection and is redundant.+- **Impact:** this is a pure style/readability nit with no behavioral difference whatsoever — both closures resolve to the same never-mutated value at commit time, so removing or keeping the alias changes nothing at runtime. The only asserted cost is that a future reader might over-interpret the variable's purpose. Under the criteria, 'Pure style / taste ... with no behavioral difference' is an explicit drop, and precision-over-recall says drop cosmetic findings. It is not a correctness, security, reliability, contract, or performance problem, so it does not clear the bar.++### [✅ VALID] must_fix · bug — products/tasks/backend/facade/api.py:484-516,507-509++**find_signal_implementation_run excludes internal=True tasks, but every real self-driving implementation task is created with internal=True — the carve-out can never positively identify a self-driving PR**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `find_signal_implementation_run` returns `None` whenever `task.internal` is true (`if task.signal_report_id is None or task.internal: return None`). This is meant to isolate 'the auto-start implementation task' from the signals pipeline's other plumbing tasks, but every production call site that creates a signal-report implementation task passes `internal=True`: `products/signals/backend/auto_start.py::_create_implementation_task_if_absent` (the sole entry point invoked from `maybe_autostart_implementation_task`, used by both the agentic pipeline and custom-agent flows) sets `internal=True` on line 261, and `products/signals/backend/report_generation/research.py:715` and `products/signals/backend/custom_agent/base.py:683` do the same for their own signal_report_id-linked tasks. There is no call site anywhere in the codebase that creates a `SIGNAL_REPORT`-origin task with `internal=False`. Because of this, for a genuine self-driving inbox PR, `run.task.internal` is always `True`, so `find_signal_implementation_run` always returns `None` — it can never positively identify the very PRs it exists to identify. Since `_inbox_rereview_carve_out` in `products/stamphog/backend/tasks/tasks.py` depends entirely on this facade call to produce `provenance`, the webhook-triggered re-review carve-out (leg 2 of the design) is permanently unreachable: `run` is always `None`, so the function returns an empty `_InboxCarveOut()` before ever calling the toggle resolver. This silently defeats a core deliverable of the PR — later pushes (`synchronize`/`reopened`/base retarget) to a self-driving inbox PR will never be re-reviewed via the webhook path, and the `opted_out` dismissal-message branch (and its associated test scenario) becomes unreachable dead code too, since `acting_user_id = resolver(...)` is never even called.+- **Suggestion:** Re-verify the intended semantics of `Task.internal` for self-driving implementation runs against the actual task-creation call sites. If the implementation task is genuinely always `internal=True` (as every current call site shows), the check should require `task.internal` to be true, not exclude it (or the `internal` check should be dropped entirely, since `find_task_run`'s `output.pr_url`/branch matching already narrows to the task whose run actually opened this PR — pipeline plumbing tasks like research/repo-selection never carry a PR URL and would already be excluded by that match). Add a test that exercises this against a task shaped exactly like `_create_implementation_task_if_absent`'s real output (`origin_product=SIGNAL_REPORT`, `internal=True`, with a `TaskRun.output.pr_url` set) to catch this class of regression — a test that manually sets `internal=False` would pass without ever exercising the real-world case.+- **Validator:** - **Checked:** Traced the full identification chain at the PR head: `find_signal_implementation_run` (facade/api.py:504-509) → `find_task_run` (webhooks.py:41) → the three signal-report task creators (auto_start.py, research.py, custom_agent/base.py) → `Task._build_task` (models.py:564) → and the git history / #68752 diff for the implementation task's `internal` value. Also read the receiver (receivers.py) and the PR's own inbox-trigger tests.+- **Found:** The reviewed self-driving PR is opened by the auto-started implementation task — `_create_implementation_task_if_absent` creates it with `interaction_origin="signal_report" # Makes the agent auto-push and open a draft PR` and `internal=True` (auto_start.py:250-261). `Task._build_task` writes that flag straight onto the row (`Task.objects.create(..., internal=internal)`, models.py:564). Commit `0da0b8dc` (#68752, "mark auto-started implementation task as internal") made this deliberate and even added `assert call_kwargs["internal"] is True`. So every real self-driving PR's run carries `output.pr_url` on an `internal=True` task.+- **Found:** `find_task_run` matches `output__pr_url=pr_url`, and only the implementation run carries a pr_url (the plumbing tasks "push nothing"), so it returns that `internal=True` run; `find_signal_implementation_run` then hits `if task.signal_report_id is None or task.internal: return None` (api.py:508) and returns `None`. `_inbox_rereview_carve_out` (stamphog tasks.py:191-200) therefore always sees `run is None` and returns an empty `_InboxCarveOut()` before ever calling the toggle resolver — leg 2 is unreachable, and the `opted_out` branch is dead.+- **Found:** The docstring (api.py:491 "a non-internal task carrying a signal report") and the pre-existing receiver comment (receivers.py: "the auto-start implementation task is the only non-internal signal-report task") both encode a belief that #68752 falsified a week before the receiver shipped. The PR's tests don't catch it: the `_task` helper defaults `internal=False` (`test_inbox_trigger.py:66`), and the one `internal=True` case — `internal_pipeline_task` with `signal_report` + `pr_url` (line 273), i.e. the exact production shape — asserts the review is _skipped_. Green tests, wrong assumption, exactly as the finding warns.+- **Impact:** Confirmed correctness bug that silently defeats a core PR deliverable: later pushes (synchronize/reopen/base-retarget) to self-driving inbox PRs are never re-reviewed via the webhook path. The same `internal` gate also sits on the receiver leg (receivers.py `if task.internal: return`), so if anything the defect is broader than flagged, not narrower. must_fix stands — a headline feature is non-functional against real inputs and no existing test exercises the real `internal=True` shape.++### [❌ dismissed] consider · best_practice — products/tasks/backend/facade/api.py:484-518++**`find_signal_implementation_run` filters cross-tenant data after the fact rather than scoping the query itself**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `find_signal_implementation_run(team_id=..., ...)` delegates to `find_task_run` (products/tasks/backend/webhooks.py), which queries `TaskRun.objects.filter(output__pr_url=pr_url)` (or branch+repository) with no team filter at all — `TaskRun` doesn't use a fail-closed/team-scoped manager, so this is a genuine cross-tenant read at the DB layer. The facade only enforces the tenant boundary afterward, via `if run is None or run.team_id != team_id: return None`. The docstring's claim that 'the team scoping is enforced here' is only true for the _returned value_, not for the underlying query, so any future edit to this function that reorders logic or drops the recheck would silently reopen a cross-team data path with no test likely to catch it (unlike `StamphogRepoConfig`'s equivalent cross-team reads elsewhere in this codebase, which are marked with an explicit `.unscoped()` call precisely so they're greppable).+- **Suggestion:** Either push `team_id` into `find_task_run`'s query (e.g. `TaskRun.objects.filter(output__pr_url=pr_url, team_id=team_id)` when a team_id is supplied) so the tenant boundary is enforced at the SQL level, or at minimum add a short comment/test at this call site making clear that the post-hoc `run.team_id != team_id` check is load-bearing and must never be removed or reordered.+- **Validator:** - **Checked:** Fetched the PR head (`1341596e`) and read `find_signal_implementation_run` (products/tasks/backend/facade/api.py:484-516), `find_task_run` (products/tasks/backend/webhooks.py:29-98), and the pre-existing webhook caller (webhooks.py:159, 346, 372-384).+- **Found:** The unscoped read is real — `find_task_run` runs `TaskRun.objects.filter(output__pr_url=pr_url)` with no team filter (webhooks.py:41). But it is pre-existing, by-design cross-team access, not introduced here: the GitHub webhook itself calls `find_task_run` with no team_id (webhooks.py:159) and resolves the team only afterward from the installation (`_resolve_external_team`, L372-384) — the tenant is genuinely unknown until the run is found. This is the codebase's sanctioned 'unscoped lookup → scope after' idiom (mirrors stamphog's `_resolve_repo_config`).+- **Found:** The new wrapper is fail-closed at the return: `if run is None or run.team_id != team_id: return None` (api.py:505) and the DTO is built with `team_id=run.team_id` (L513), so no foreign-tenant data can traverse the return value. In the only edge case that reaches a foreign run (two teams sharing a pr_url+repository), the caller receives `None` — a safe false-negative that falls back to the stricter no-carve-out refusal, never a downgrade.+- **Impact:** Does not meet the bar. There is no current tenant-isolation hole — the boundary is enforced and fails closed, which the finding itself concedes. The only stated harm is a hypothetical 'future edit that reorders logic or drops the recheck,' i.e. a speculative what-if, and the fix is defensive hardening of an already-correct boundary (redundantly scoping a query the post-check already guards, or adding a load-bearing-comment/test). A good keep must name a concrete, currently-reachable trigger and consequence; this names only a future regression. The `.unscoped()`-greppability comparison is also weaker than implied: `StamphogRepoConfig` is a fail-closed model, whereas `TaskRun.objects` is a plain manager, so plain `.filter(...)` is the normal idiom here, not an unmarked bypass.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_pr.py:202-209,222-228++**self_driving carve-out doesn't gate the author-familiarity fetch inside the shared Pipeline**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `Pipeline.__init__` adds self.self_driving (lines 202-209) as an additive flag the PR intent describes as living on Pipeline specifically 'so both runtimes share one implementation of the relaxed gates' (parity invariant). But Pipeline.run() still calls `self._maybe_compute_familiarity()` unconditionally further down (unchanged by this diff), which calls `_compute_familiarity()` -> familiarity.compute_familiarity(), performing a live `gh` fetch of the PR author's merged-PR history and git-blame overlap. The PR description states a specific security-relevant guarantee — 'the hosted server skips the author merged-PR fetch so the machine user's history never feeds familiarity' — but nothing in this chunk enforces that guarantee inside Pipeline itself; it holds today only because review_local.py's `_attach_familiarity()` happens to no-op when the context omits 'author_pr_numbers'. If Pipeline(..., self_driving=True).run() (the real network-backed runtime) is ever exercised for a self-driving PR — which is exactly the scenario this shared flag is designed to support — the live fetch would run unconditionally and thread the bot account's own commit/blame history into both the TRUSTED reviewer prompt and the posted review-body bullet ('Author wrote X% of the modified lines...' in `_render_review_body`), directly contradicting the new `_format_self_driving()` text in reviewer.py that tells the LLM 'author familiarity ... carr[ies] no signal here.'+- **Suggestion:** Gate the familiarity computation on self.self_driving inside the shared Pipeline class (e.g. short-circuit `_maybe_compute_familiarity()` or have `_compute_familiarity()` return None immediately when self.self_driving is True), rather than relying on the caller to omit author_pr_numbers. That enforces the 'no machine-user history feeds familiarity' invariant at the point that owns the carve-out.+- **Validator:** - **Checked:** every caller of `Pipeline.run()` and every path to the live familiarity fetch. Fetched PR-head `review_pr.py` and `review_local.py` from the GitHub API (working tree is on master). Traced `run()` → `_maybe_compute_familiarity()` (review_pr.py:251,523) → `_compute_familiarity()` → `compute_familiarity()` live `gh` fetch (review_pr.py:536-547), plus `main()` (review_pr.py:973-985), `review_local.py::run()` (line 314+), and the server's engine invocation command.+- **Found:** the live fetch is only reachable via `Pipeline.run()`, whose sole caller is `review_pr.py::main()` — which constructs `Pipeline(args.pr_number, args.repo, dry_run=..., verbose=...)` with no `self_driving` argument and exposes no `--self-driving` CLI flag (review_pr.py:984, 974-979). So `Pipeline(self_driving=True).run()` has no call site anywhere. Self-driving reviews run exclusively through `review_local.py::run(context)`, which sets `self_driving=True` (review_local.py:321) but drives steps manually and uses `_attach_familiarity`→`_familiarity_offline` (offline, no network), never `Pipeline.run()`/`_compute_familiarity()`. The hosted server invokes the engine via `uv run review_local.py --context ...`, never the network runtime.+- **Impact:** the finding's own trigger — "If `Pipeline(..., self_driving=True).run()` is ever exercised" — cannot occur given the call sites, and its premise that this is "exactly the scenario this shared flag is designed to support" is mistaken: the flag lives on `Pipeline` to share the relaxed-gate logic (`author_is_bot and not self_driving`, `pr.draft and not self_driving`) that `review_local` reuses, while the Action provably never sets it. This is a defense-in-depth request to self-enforce an invariant the callers already guarantee, guarding an unreachable path. Per the criteria (drop speculative-what-if / defensive paranoia / already-handled; premise unreproducible; precision over recall), it does not meet the bar. It would only become relevant if a _new_ caller wired self_driving into the network runtime — itself a reviewable change.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_pr.py:587-590++**Draft-gate bypass is not scoped to bot-authored runs, unlike the bot-author bypass it's paired with**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The new draft-prerequisite bypass reads `if pr.draft and not self.self_driving:` (lines 587-590), relaxing the gate purely on self.self_driving. Compare this to the bot-author bypass a few lines above in run() (`if self.pr.author_is_bot and not self.self_driving:`), which only ever changes behavior for bot-authored PRs by construction — it's a compound condition. The draft bypass has no equivalent anchor to author_is_bot: any PR the caller marks self_driving=True skips the draft check regardless of who authored it. The PR's own framing describes self_driving as a carve-out specifically for 'a bot-authored draft PR that the hosted runtime positively linked to a PostHog Code signals implementation task' (docstring at lines 202-209) — i.e. the draft relaxation is only ever supposed to fire together with a bot author. Nothing in this chunk enforces that joint precondition, so a caller-side bug that sets self_driving=True without author_is_bot also being true would silently disable draft-gating for what the engine otherwise treats as an ordinary PR review.+- **Suggestion:** Couple the draft bypass to the same precondition as the bot-author bypass, e.g. `if pr.draft and not (self.self_driving and self.pr.author_is_bot):`, so the shared Pipeline enforces the intended joint carve-out itself instead of trusting the caller to only ever set self_driving alongside a bot author.+- **Validator:** - **Checked:** the draft-gate bypass at `review_pr.py:590` (`if pr.draft and not self.self_driving`) versus the bot-author bypass at `review_pr.py:225` (`if self.pr.author_is_bot and not self.self_driving`), plus every producer of the `self_driving` flag (review_pr.py `main()` at 973-985; review_local.py:321 `Pipeline(..., self_driving=bool(context.get("self_driving_review")))`; and the server derivation `self_driving_review=bool(output.get("inbox_review"))` in `products/stamphog/backend/tasks/tasks.py`).+- **Found:** the cited asymmetry is structural, not a defect — each gate's condition references its own subject (`author_is_bot` for the bot gate, `pr.draft` for the draft gate), and `self_driving` relaxes both. There is no call site that sets `self_driving=True` on a non-bot PR: the network runtime `main()` never passes the flag (no `--self-driving` arg), and the only producer, the hosted server, derives it from `inbox_review` provenance stamped exclusively on positively-linked signals implementation runs, which are bot-authored drafts by construction.+- **Impact:** the reviewer's trigger is stated verbatim as "a caller-side bug that sets `self_driving=True` without `author_is_bot` also being true" — i.e. it depends on a hypothetical caller bug that the current code rules out. That is textbook defensive-coding paranoia / speculative what-if under the validation bar (guarding against inputs the callers already prevent), and the suggested fix makes two independent gates redundantly cross-reference each other's predicates. Even if it somehow fired, the effect is skipping the draft _prerequisite_ (a caution gate) on a human draft PR — the review still runs its gates and LLM and can REFUSE/ESCALATE on merits; it is not a gate that, once bypassed, forces approval. Per precision-over-recall and the explicit drop of defensive paranoia and unreachable what-ifs, this does not meet the bar. Consistent with the sibling self_driving findings whose triggers likewise require a nonexistent caller.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:144-156++**resolve_stamphog_acting_reviewer has no exception guard despite being invoked from another product's webhook path**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** Every other function in this module that gets invoked from an external trigger (handle_task_run_saved, `_start_review`, `_start_stamphog_review`) is deliberately wrapped in try/except with the explicit rationale that it 'must never raise into' the caller's path. resolve_stamphog_acting_reviewer breaks that pattern: it is registered via register_inbox_acting_reviewer_resolver and is now called directly from stamphog's GitHub webhook handler on every synchronize/reopen/base-retarget event for a self-driving PR (per the PR description, 'stamphog's webhook path re-checks the acting reviewer's stamphog toggle before every re-review'). Internally it calls `_resolve_assigned_reviewer`, which queries SignalReportArtefact and calls resolve_org_github_login_to_users (an org-membership resolution that can hit external/DB errors) and does json.loads on stored content. If any of that raises (DB blip, unexpected artefact shape not caught by the existing json.JSONDecodeError/TypeError/ValueError guard, transient error in the login-resolution call), the exception now propagates straight into stamphog's webhook processing — a path this module does not control and cannot guarantee wraps hook calls defensively.+- **Suggestion:** Wrap resolve_stamphog_acting_reviewer's body in the same try/except Exception -> log and return None pattern used elsewhere in this file (e.g. mirroring handle_task_run_saved's `except Exception: logger.exception(...)`), so a failure here degrades to 'don't re-review' rather than risking an unhandled exception inside another product's webhook handler.+- **Validator:** - **Checked:** the PR-head `resolve_stamphog_acting_reviewer` and `_resolve_assigned_reviewer` in `products/review_hog/backend/receivers.py`, the hook registry `products/stamphog/backend/facade/inbox_hooks.py`, and every call site of the registered resolver (grepped the full PR diff for `get_inbox_acting_reviewer_resolver` / `resolve_stamphog_acting_reviewer`).+- **Found:** the resolver's only production caller is `_inbox_rereview_carve_out` in `products/stamphog/backend/tasks/tasks.py` (`resolver = get_inbox_acting_reviewer_resolver()` then `acting_user_id = resolver(...)`), and that function is invoked in `process_pull_request_event` inside an explicit guard: `try: carve_out = _inbox_rereview_carve_out(...) except Exception as e: logger.exception("stamphog_pr_event_inbox_carve_out_failed", ...); raise process_pull_request_event.retry(exc=e)`. The comment documents this as intentional: 'Retry (don't drop) on failure: a transient DB blip during the carve-out resolution must not silently drop a legitimate re-review.' The only other diff reference to the resolver slot is a test patch target, not a production path.+- **Impact:** the finding's premise — that the exception propagates into a webhook path that 'cannot guarantee wraps hook calls defensively' — is mistaken; the sole caller already wraps it and retries. This is an 'already handled by a parent caller' drop.+- **Impact:** the suggested fix would actively regress. If `resolve_stamphog_acting_reviewer` swallowed the error and returned `None`, `_inbox_rereview_carve_out` treats `acting_user_id is None` as `_InboxCarveOut(opted_out=True)`, which routes into the skip-dismiss branch and dismisses the standing approval (with the opt-out message) on a transient DB blip — exactly the 'silently drop a legitimate re-review' failure the caller's retry design was built to avoid. The current propagate-to-caller design is the reliability-correct one.++### [✅ VALID] should_fix (validator→consider) · performance — products/stamphog/backend/tasks/tasks.py:1202-1219++**process_inbox_pr_review's same-head dedupe excludes FAILED runs, so a persistently-failing review is retried on every TaskRun output-save refire with no cooldown**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The dedupe query in `process_inbox_pr_review` only excludes `SUPERSEDED` and `FAILED` runs when deciding whether the PR's current head already has a review 'handled' (`.exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))`). Excluding `FAILED` means a run that previously failed at this exact `head_sha` does NOT count as already-handled, so the next receiver refire creates a brand-new `ReviewRun` and kicks off a fresh sandbox + LLM review for the same head. The receiver this task is called from fires 'on every TaskRun output save' (per the review_hog docstring for this trigger, which this task's own docstring cross-references), and that same docstring documents the expected cost of a repeat fire as 'one fetch (early-exit)' — i.e. the design assumes repeat fires at an unchanged head are cheap no-ops. For a deterministically-failing review (e.g. a persistent GitHub API error, a bad context payload, or any bug that reliably fails the same PR), every subsequent output-save refire will instead re-run the full pipeline (GitHub fetch, upsert, supersede, create, start workflow, provision sandbox, invoke the LLM) at the same head, with no cooldown analogous to `STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS` on the webhook LABEL-mode path. This can spend unbounded sandbox/LLM budget on a single stuck PR.+- **Suggestion:** Either keep a very recently `FAILED` run out of the 'needs a fresh attempt' set for some cooldown window (mirroring the LABEL-mode cooldown pattern already used elsewhere in this file), or explicitly cap/backoff retries per (pull_request, head_sha) so repeated output-save refires against a persistently failing head don't unboundedly re-spend sandbox + LLM runs.+- **Validator:** - **Checked:** Read the dedupe block (pr_tasks.py:1202-1234), the `ReviewRunStatus` enum (facade/enums.py:19-32), the receiver refire semantics (receivers.py), and how a run reaches `FAILED` (workflow `mark_review_failed`).+- **Found:** The claim is factually accurate — the dedupe excludes `(SUPERSEDED, FAILED)` (pr_tasks.py:1207), so a `FAILED` run at `head_sha` is not treated as handled and the next refire runs `_supersede_prior_runs` + `create` + `_start_review_workflow` for the same head. This leg has no cooldown analogous to `STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS`.+- **Found (mitigation the finding omits):** The exclude's complement — `QUEUED`, `GATED`, `REVIEWING`, `COMPLETED` — all early-exit at L1211-1221. So a refire that lands while the prior review is still `QUEUED`/`REVIEWING` no-ops; a new run is created only _after_ the prior one reaches `FAILED`, which occurs via the workflow's `mark_review_failed` after its own retries (minutes), not on the output-save timescale (seconds). The retry cadence is therefore throttled to roughly once per review duration, and total spend is bounded by the self-driving task's finite lifetime (sandbox/inactivity timeouts). The finding's 'every subsequent output-save refire will re-run the full pipeline' materially overstates the frequency.+- **Found:** Excluding `FAILED` is a deliberate recovery mechanism — most review failures are transient (GitHub blips, sandbox hiccups) and a refire is meant to retry and eventually land a verdict, the same spirit as re-reviewing 'a head the webhook leg never delivered.' The actual gap is only the missing backoff for the rarer _deterministic_-failure case (a stamphog bug or persistently bad payload), combined with the agent continuously saving output at an unchanged head.+- **Impact:** Real but bounded resource waste: a handful of full sandbox+LLM reviews on a persistently-failing head over the task's lifetime, gated by review duration and requiring a deterministic failure plus continuous same-head saves. A legitimate hardening opportunity (a per-head cooldown/backoff mirroring the label path), aligned with the codebase's concern about sandbox/LLM spend, but self-limiting rather than the unbounded per-refire spend described.+- **Priority:** Lowered should_fix → consider: the natural throttle (in-flight refires no-op; FAILED only arrives after minutes of workflow retries) and the finite task lifetime cap the damage, and it only bites under a specific deterministic-failure + continuous-refire combination — a real low-priority resource note, not a clear should-fix.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:144-160++**Webhook-leg toggle re-check repeats the full reviewer-resolution query chain on every push**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered as the hook stamphog's webhook path calls before _every_ re-review of a carved-out self-driving PR (synchronize/reopened/base-retarget). It re-runs `_resolve_assigned_reviewer`, which issues the `SignalReportArtefact` lookup plus the full `resolve_org_github_login_to_users` chain (`Team` lookup + three separate candidate-id subqueries over `UserSocialAuth`/`UserIntegration`/`Integration` + a final `User` query with prefetches — roughly 6 DB round trips), then adds a `ReviewUserSettings.load` query on top. This exact resolution already ran once at PR-open time in `handle_task_run_saved` (leg 1), and the assignee set for a given signal report does not change between pushes to the same PR. Because the whole point of the self-driving flow is that the agent iterates and pushes fixes in response to review feedback, this multi-query chain re-executes on every one of those pushes just to answer a single boolean ("is the toggle still on"), for every carved-out PR across every team using the feature.+- **Suggestion:** Cache/memoize the resolved acting-reviewer id for the lifetime of the PR (e.g. stamp it on the `ReviewRun`/task provenance at leg-1 time, or key a short-lived cache on `signal_report_id`) and have the webhook-leg hook read that instead of re-deriving reviewers from scratch on every push. At minimum, short-circuit before calling `resolve_org_github_login_to_users` when the artefact hasn't changed since the last resolution.+- **Validator:** - **Checked:** `resolve_org_github_login_to_users` and its helpers in `products/signals/backend/report_generation/resolve_reviewers.py:304-374`, the resolver `resolve_stamphog_acting_reviewer` / `_resolve_assigned_reviewer` in `products/review_hog/backend/receivers.py`, and the call site `process_pull_request_event` → `_inbox_rereview_carve_out` in `products/stamphog/backend/tasks/tasks.py`.+- **Found:** the resolution is a batched, fixed-cardinality query set, not an N+1: `Team` org lookup (l.314), three candidate-id queries whose `OrganizationMembership` filter is an inlined `Subquery` (l.359-374), and one `User.objects.filter(id__in=...).prefetch_related(...)` (l.322). Logins are capped at `MAX_SUGGESTED_REVIEWERS=3` (l.30), so the count is constant (~7-9 queries with the artefact lookup and `ReviewUserSettings.load`) regardless of input size — no unbounded or quadratic behavior.+- **Impact:** this runs in `process_pull_request_event`, a background Celery webhook task, not a user-facing request path. On a carved-out PR that proceeds it spins up a sandboxed LLM review that dwarfs ~8 indexed queries, and the pre-filter path already does GitHub API calls. Each self-driving 'push' is a full agent iteration (minutes of LLM work), and the feature is opt-in/niche, so frequency is inherently low. Against the 'bites at real scale' bar (N+1, unbounded, missing index on a hot path, quadratic, blocking async I/O) none apply — it is a bounded, low-frequency micro-cost, so it does not clear the bar.+- **Impact:** the suggested caching also risks correctness — `_resolve_assigned_reviewer` deliberately reads the report's _latest_ `suggested_reviewers` artefact each time (its docstring), so the 'assignee set never changes between pushes' premise isn't guaranteed; memoizing the resolved id could apply a stale reviewer's toggle, while the toggle read itself must stay fresh anyway.++### [✅ VALID] should_fix (validator→consider) · performance — products/stamphog/backend/tasks/tasks.py:1155-1165++**process_inbox_pr_review fetches the PR from GitHub on every TaskRun-output refire, with no short-circuit before the network call**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The docstring for `process_inbox_pr_review` states the review_hog receiver "re-fires on every TaskRun output save carrying the PR URL," and this task unconditionally makes a live `client.get_pr(...)` GitHub API call before any dedupe check runs (the comment even explains why: dedupe needs the current head, which only GitHub knows). For a long-running self-driving task that saves output many times while the PR stays open, this means one live GitHub API call per output save, even when the head hasn't changed since the last check. `get_pr` has no caching layer (confirmed in `logic/github_client.py`), and each call consumes the installation's shared GitHub App rate-limit budget — the same budget the webhook leg and every other stamphog review for that installation depends on.+- **Suggestion:** Add a short-TTL cache (e.g. keyed on `pr_url`, a few seconds to a minute) that short-circuits the fetch when the task was already checked very recently, or have review_hog's receiver pass the head/branch it already knows so this task can skip the round trip when nothing could plausibly have changed. Preserve the recovery behavior (still fetch periodically) rather than removing it outright.+- **Validator:** - **Checked:** Read the fetch/dedupe ordering in `process_inbox_pr_review` (pr_tasks.py:1155-1174), `get_pr`/caching in logic/github_client.py, the `queue_inbox_pr_review` facade args (facade/api.py:128-155), and the receiver refire semantics (receivers.py).+- **Found:** The claims check out. `get_pr` runs before any dedupe for every synced+enabled repo (`pr_tasks.py:1158-1159`); `github_client.py` caches only the installation _token_ (L359-403), not `get_pr` responses, so each refire is a live REST read on the installation's shared rate budget. And `queue_inbox_pr_review` carries only `pr_url` (facade/api.py:131), not the head SHA, while the dedupe keys on `head_sha` (pr_tasks.py:1206) — so the fetch is genuinely required to learn the current SHA, not an avoidable round trip.+- **Found (bounds severity):** This is a deliberate, documented cost, not an oversight — the task comment states the fetch precedes dedupe because 'the dedupe keys on the PR's current head, which only GitHub knows' (`pr_tasks.py:1157`), and the receiver docstring explicitly accepts that 'a same-head re-trigger costs one fetch (early-exit).' Crucially, the expensive pipeline stages (sandbox provisioning + LLM) are gated _behind_ the dedupe, so an unchanged-head refire costs exactly one cheap REST read and nothing else.+- **Found (suggestion partly unworkable):** 'Have the receiver pass the head/branch it already knows' does not remove the fetch — the receiver knows the branch name, not the current head SHA the dedupe requires; only the short-TTL `pr_url` cache would help, and that trades correctness (a real push within the TTL window silently missed) for a marginal saving.+- **Impact:** Real but minor — one GitHub REST read per output-save refire, incremental to the many GitHub calls a stamphog review already makes. Rate-limit exhaustion is speculative for an opt-in, default-off, low-concurrency feature against GitHub's generous per-installation budget (thousands/hour); it is a linear per-event cost, not an N+1 or unbounded loop that 'bites at real scale.'+- **Priority:** Lowered should_fix → consider: the cost is deliberate and documented, the fetch is necessary for the SHA-keyed dedupe, the expensive work is already gated, and exhaustion is unproven at realistic scale — a legitimate cheap-to-address efficiency note worth recording, not a should-fix.++### [❌ dismissed] should_fix · bug — products/stamphog/backend/tasks/tasks.py:1202-1230++**Check-then-act dedupe in process_inbox_pr_review has nothing to lock on the first review of a given head, allowing duplicate runs/workflows under concurrent refires**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The only protection against two concurrent invocations of `process_inbox_pr_review` for the same PR is `existing = ReviewRun.objects...select_for_update()...filter(pull_request=pr_obj, head_sha=head_sha)...first()` plus `_supersede_prior_runs`'s own `select_for_update()`. Both only lock rows that already exist. The first time a given `head_sha` is reviewed (which is exactly the common case right after a push, or after the prior run at that head was superseded), the `existing` query returns nothing for both transactions under Postgres' default read-committed snapshot, since neither can see the other's uncommitted INSERT. Two overlapping Celery workers processing two refires for the same head can both pass the dedupe, both call `_supersede_prior_runs` (which also finds nothing), and both `create()` a ReviewRun and start a Temporal workflow — two full sandbox+LLM review runs for the identical PR state. This task's own docstring says refires happen "on every TaskRun output save," which is a materially higher-frequency trigger for this race than the webhook path's rare redeliveries where this same locking pattern originated, and unlike the webhook path there is no `delivery_id` unique constraint here at all (`delivery_id=None` always) to backstop a genuine race.+- **Suggestion:** Lock a row that is guaranteed to exist before the dedupe check — e.g. `PullRequest.objects.select_for_update().filter(id=pr_obj.id).first()` — so all concurrent invocations for the same PR serialize on that lock before checking/creating a ReviewRun, rather than relying on a lock that only bites once a matching row already exists.+- **Validator:** - **Checked:** Traced the full transaction body of `process_inbox_pr_review` (pr_tasks.py:1185-1234), the `_upsert_pull_request` helper it calls first (L1186 → the conditional UPDATE), the webhook path's own serialization comment (pr_tasks.py:1037-1044), and the `PullRequest` model constraints.+- **Found:** The premise omits the actual serialization. Every path that could reach `create()` first passes through `_upsert_pull_request`, whose conditional UPDATE on the PR row acquires a row lock held to commit — the webhook path documents this exact mechanism as 'takes the PR row lock ... held to commit, serializing deliveries' (pr_tasks.py:1037-1044), and `process_inbox_pr_review` reuses the same helper (its own comments at L1182/L1189 note it mirrors the webhook path). A second concurrent invocation for the same PR blocks on that row lock; after the first commits, its `existing` SELECT runs on a fresh read-committed snapshot, sees the first's committed `ReviewRun`, and returns at L1211-1221. No second `create()`.+- **Found:** The 'first review of a brand-new PR' corner (no PR row, so `_upsert` takes the created=True early return without an UPDATE) is closed by the `unique_stamphog_pull_request` constraint on `(team_id, repo_config, pr_number)` (models.py:120-121): concurrent `get_or_create` INSERTs collide, the loser blocks on the winner's uncommitted INSERT, then retries as a GET and its `existing` query sees the winner's committed run → dedupe. The finding's other 'common cases' (new head after a push, after a supersede) are all on an _existing_ PR row, so the UPDATE-lock path applies and they are serialized.+- **Found:** The 'no delivery_id unique constraint here' point is a non-sequitur — in the webhook path the `delivery_id` constraint only backstops exact redeliveries of one delivery; two different same-head events are serialized there by the same `_upsert_pull_request` lock that this task also holds, not by `delivery_id`.+- **Impact:** Does not meet the bar — the described duplicate-run race is already prevented (premise mistaken / already handled). Concurrent refires for the same PR serialize at the PullRequest level and the loser dedupes, so no second sandbox+LLM run is created. The `select_for_update()` the finding critiques is belt-and-braces on top of that primary serialization, not the sole guard.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:1140-1147++**`repository__iexact` filter can't use StamphogRepoConfig's existing indexes**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `process_inbox_pr_review` filters `repository__iexact=repository`. `StamphogRepoConfig` only has case-sensitive unique indexes on `(team_id, repository)` and `(provider, installation_id, repository)` (`products/stamphog/backend/models.py`) — there is no functional index on `UPPER(repository)`/`lower(repository)`, so Django's Postgres `iexact` translation can't use either index and falls back to scanning the team's config rows. `for_team(team_id)` bounds this to one team's rows, so today's impact is small, but it's a real, avoidable index miss on a hot path (every leg-1 review) that will grow with the number of repos a team connects.+- **Suggestion:** Add a functional index on `upper(repository)` (or normalize/store a lowercased mirror column) if `iexact` lookups against this table are expected to become common, or confirm per-team config counts will stay small enough that this is acceptable and leave a note explaining the tradeoff.+- **Validator:** - **Checked:** The query in `process_inbox_pr_review` (pr_tasks.py:1140-1147), `StamphogRepoConfig`'s constraints/indexes (models.py:56-72), and how `for_team(team_id)` interacts with the `(team_id, repository)` index.+- **Found:** The factual claim holds — `repository__iexact` translates to `UPPER(repository)=UPPER(val)`, the two unique constraints (`unique_stamphog_repo_per_team` on `(team_id, repository)`, `unique_stamphog_installation_repo` on `(provider, installation_id, repository)`) are case-sensitive, and there is no functional `upper()`/`lower()` index on the model (the `indexes=[...]` at models.py:124 is on `PullRequest`, not this table).+- **Found:** But the query is not left to a full scan: it filters `for_team(team_id)` first, and the `(team_id, repository)` index serves the `team_id` equality prefix. Postgres does an index range scan on `team_id`, then applies the `iexact`/`provider`/`enabled`/`connected_by_user_id` predicates as a filter over just one team's config rows. The only thing unindexed is the case-insensitive `repository` comparison, evaluated over a set the `team_id` prefix has already bounded to a handful-to-dozens of rows.+- **Impact:** Does not meet the bar. This is a bounded, once-per-review lookup over a tiny team-scoped row set — not an N+1, unbounded loop, or a hot-path full scan that 'bites at real scale.' The reviewer concedes today's impact is small; the 'grows with repos a team connects' concern is speculative future-scaling that won't realistically reach a point where an `UPPER()` filter over one team's configs is measurable. Adding a functional index (migration + write/maintenance overhead) to fix this is speculative micro-optimization — overengineering for a non-problem — which the criteria drop, and which the reviewer's own `consider` rating already signals as marginal.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:1235-1237++**stamphog_inbox_pr_create_run_failed log drops the exception detail present on every sibling error log in this task**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Every other exception path in `process_inbox_pr_review` (`stamphog_inbox_pr_config_resolution_failed`, `stamphog_inbox_pr_fetch_failed`) logs `error=str(e)` as a structured field alongside `logger.exception(...)`. The final catch-all (`stamphog_inbox_pr_create_run_failed`) omits it, making this one failure mode harder to filter/alert on by error message in log tooling compared to its siblings.+- **Suggestion:** Add `error=str(e)` to the `stamphog_inbox_pr_create_run_failed` log call for consistency with the rest of the function.+- **Validator:** - **Checked:** The three exception handlers in `process_inbox_pr_review` (pr_tasks.py:1148-1150, 1160-1165, 1235-1237).+- **Found:** The observation is factually correct — `stamphog_inbox_pr_config_resolution_failed` (L1149) and `stamphog_inbox_pr_fetch_failed` (L1164) pass `error=str(e)`, while `stamphog_inbox_pr_create_run_failed` (L1236) omits it.+- **Found:** But the exception detail is not actually dropped: all three calls use `logger.exception(...)`, which attaches the full traceback and the exception message via `exc_info`, so the failure is fully logged regardless of the missing kwarg. The title's 'drops the exception detail' overstates it — only a discrete, filterable `error` structured field is absent, not the detail itself. The handler also re-raises via `.retry(exc=e)` (L1237) identically to its siblings, so failure visibility and control flow are unchanged.+- **Impact:** Does not meet the bar. This is a cosmetic structured-logging consistency nit with no behavioral difference and no lost information — squarely the 'pure style / taste, no behavioral difference' category the criteria drop, and low enough value that surfacing it adds review noise under precision-over-recall. Not a swallowed error (the failure is logged and retried), so it doesn't reach the reliability bar either.++### [❌ dismissed] consider · best_practice — products/tasks/backend/facade/api.py:504-506++**find_signal_implementation_run's underlying read isn't writer-pinned despite gating the self-driving carve-out**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `find_signal_implementation_run` (new in this chunk) delegates to `products.tasks.backend.webhooks.find_task_run`, whose queries use the default manager (`TaskRun.objects.filter(...)`) with no `.using(router.db_for_write(TaskRun))` pin. `products/stamphog/CLAUDE.md`'s reader-lag invariant is explicit that "any read that gates a side effect... must be pinned via `.using(router.db_for_write(Model))`" and calls out that this exact bug class has recurred five times on other paths. This new call is precisely such a read: it gates whether a bot-authored/draft PR bypasses every other trust gate and gets carved into the self-driving re-review path. A lagged replica can miss a `TaskRun` that was created or updated moments earlier by the same self-driving pipeline (e.g. right after the PR was opened), causing the carve-out to resolve empty this delivery.+- **Suggestion:** This is fail-closed (a miss just skips the re-review, not a bad approval) and self-heals on the next push, so it's not a correctness bug, but it's worth pinning `find_task_run`'s queries to the writer — or having `find_signal_implementation_run` call a writer-pinned variant — to keep this path consistent with the product's own documented invariant and avoid the same class of transient miss recurring here.+- **Validator:** - **Checked:** `find_signal_implementation_run` (products/tasks/backend/facade/api.py:484-516) and its delegate `find_task_run` (products/tasks/backend/webhooks.py:41,69,86), the stamphog reader-lag invariant text in products/stamphog/CLAUDE.md, and how the stamphog-side reads in the carve-out are pinned.+- **Found:** The factual claim holds — `find_task_run` uses unpinned `TaskRun.objects.filter(...)`. But it is pre-existing tasks code whose original and primary caller is the tasks GitHub webhook itself (webhooks.py:159), also unpinned — so not-pinning this read is the tasks product's own established convention, not an omission introduced here. The cited invariant is scoped to stamphog's replica'd product DB ('The product DB has replicas'), and the stamphog-side reads in the same carve-out (`_resolve_repo_config`) already carry `.using(router.db_for_write(StamphogRepoConfig))`; the flagged read is a tasks-DB read behind a tasks facade, governed by tasks' conventions.+- **Found:** The concrete trigger is unlikely and misaligned with the code. Leg 2's carve-out fires only on synchronize/reopened/base-retarget — later pushes — not `opened`, so by the time it runs the TaskRun's `output.pr_url` was written when the PR first opened and has had time to replicate; GitHub webhook delivery latency (seconds) typically exceeds replica lag (sub-second), and `find_task_run` has a branch+repository fallback if the pr_url row hasn't landed. The reviewer's 'right after the PR was opened' scenario doesn't match when leg 2 actually triggers.+- **Impact:** Does not meet the bar. The reviewer concedes it is fail-closed and self-healing (a lagged miss just skips one delivery's re-review and recovers on the next push) — no bad approval, no data issue, no user-visible harm. That makes it defense-in-depth consistency hardening against a speculative, self-correcting transient, applying a stamphog-DB invariant across the boundary to a tasks-DB read that tasks itself leaves unpinned — squarely the speculative/defensive category the criteria drop, which the `consider` rating already signals as marginal.++### [❌ dismissed] must_fix — tools/pr-approval-agent/review_pr.py:195-225,462-480,584-593,934-940++**Chunk's described diff is not present in the checked-out repository — cannot verify any of the claimed self_driving changes**+_perspective: review-hog-perspective-performance-reliability · directly-related: False_++- **Problem:** This chunk's file-change payload describes an additive `self_driving` flag threaded through `review_pr.py`, `review_local.py`, `reviewer.py`, and a version bump to `2.0.0b4`. Independent verification against the actual checked-out working tree (branch `pull/72680/head`, HEAD commit `1438ae30` "fix(alerts): guard alert check preview against missing checks (#73310)") shows none of these changes exist: `grep -c self_driving` returns 0 for all four files in this chunk, `git diff HEAD` for each file is empty, `git log` for `review_pr.py` shows no stamphog-related commit, and `version.py` still reads `STAMPHOG_VERSION = "2.0.0b3"` (not `2.0.0b4` as the diff claims). A SHA-256/stat check of `review_pr.py` confirms it is the on-disk file, not a stale cache. Separately, a full-file `Read` of `review_pr.py` earlier in this session returned content matching the described diff verbatim (the `self_driving` kwarg, the TRUSTED-provenance comments, etc.), but a subsequent targeted `Read` with an explicit offset over the identical line range, cross-checked with `awk`/`sed`/`grep` on the same path, returned the true, unmodified file content with no trace of `self_driving` anywhere. That inconsistency means at least one tool result in this session did not reflect the real file — i.e., the review context handed to this pass cannot be trusted at face value for this chunk.+- **Suggestion:** Do not merge or act on a performance/reliability verdict for this chunk until the mismatch is resolved. Re-derive the review context from the actual PR #72680 diff against a freshly synced checkout (verify with `git log -- <file>` and `grep` for `self_driving` post-sync), and re-run this pass once the working tree demonstrably contains the changes described. Any Read/tool result that disagrees with an independent `git diff`/`grep` check should be treated as unreliable and re-fetched rather than used as the basis for findings, since it may reflect stale cache, a mismatched sandbox, or injected content rather than the repository's real state.+- **Validator:** - **Checked:** working-tree state vs. actual PR content. The checkout here is on the base branch (HEAD `1d7e709c`, `master`) and `grep self_driving` over the four files returns 0 on disk — matching the finding's observation. I then fetched each file at PR head `1341596e` via `gh api repos/PostHog/posthog/contents/...?ref=1341596e`.+- **Found:** the `self_driving` changes are real and fully verifiable in PR #72680: `review_pr.py` (`self_driving` kwarg :196, attr :209, bot gate :225, draft gate :590, provenance stamps :477/:938), `review_local.py:321`, `reviewer.py::_format_self_driving` :683-702, and `version.py` bumped to `2.0.0b4`. The working tree lacks them only because the harness checked out the base branch and supplies the PR diff separately (the review payload and `@file#L` blocks carry PR-head content). The finding itself cites a _different_ base commit (`1438ae30`, a `fix(alerts)` commit) than this session's HEAD — further evidence that the on-disk tree is just an arbitrary base snapshot, not the PR, and not a corrupted/injected context.+- **Impact:** this is not a finding about the PR — it names no code defect, is flagged `is_directly_related_to_changes: false`, and is not actionable by the author (nothing in the diff to change). Its premise ("context cannot be trusted," "may reflect injected content") is a misdiagnosis of a benign base-branch-checkout setup and is disproved by fetching the real PR content, which reviews cleanly. It fails every axis of the validation bar (no user-affecting code problem; wrong premise; process/environment meta-note), and its `must_fix` severity is unwarranted. Drop.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-3.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-3.mdnew file mode 100644index 000000000000..9bf6b2dc0065--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-3.md@@ -0,0 +1,388 @@+# Reviewer-quality run — `A-sonnet5-xhigh-3`++- **Dumped:** 2026-07-30T22:49:10+00:00+- **Report id:** `019fb388-48ec-73a9-a2eb-6f4bc0e13591` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 28184s (469.7 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-sonnet-5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 10 | 28 | 23 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 121 | 97,145 | 699,183 | 12,628,165 | 162,428 | 3 | $15.23 | $15.23 |+| claude-sonnet-5 | review | 228 | 312,420 | 2,211,397 | 26,927,121 | 325,740 | 5 | $14.80 | $14.80 |+| claude-sonnet-5 | blind-spot | 78 | 149,273 | 996,896 | 8,565,019 | 138,022 | 3 | $5.88 | $5.88 |+| claude-opus-4-8 | blind-spot | 17 | 291 | 142,782 | 1,871,711 | 28,892 | 0 | $2.55 | $2.55 |+| claude-sonnet-5 | dedup | 1 | 19,626 | 0 | 0 | 9,358 | 0 | $0.13 | $0.13 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 1,331 | 0 | $0.03 | $0.03 |+| **total** | | **446** | **584,736** | **4,050,258** | **49,992,016** | **665,771** | **11** | **$38.62** | **$38.62** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- naive method (all prompt tokens at input price): $165.10 — 4.3× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $29.0932 over 446 gen(s) (true $29.0932, Δ -0.0%)+ - · of which cache read: $14.3484 over 428 gen(s) (true $14.3484, Δ +0.0%)+ - · of which cache write: $13.2830 over 444 gen(s) (true $13.2830, Δ +0.0%)+ - · of which fresh (derived): $1.4618 over 446 gen(s) (true $1.4618, Δ -0.0%)+ - output: $9.5275 over 446 gen(s) (true $9.5275, Δ +0.0%)+- 11 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------------------------------- |+| …171abd07 | issues-review-p2-c1 | 14:59:08 | 0 | 68,696 | claude-sonnet-5 |+| …c7a7b994 | issues-review-p3-c2 | 14:59:08 | 0 | 70,969 | claude-sonnet-5 |+| …280576fb | issues-review-p2-c2 | 14:59:08 | 0 | 70,971 | claude-sonnet-5 |+| …e2ce435e | issues-review-p1-c3 | 14:59:10 | 22,467 | 34,417 | claude-sonnet-5 |+| …01a89dc7 | issues-review-p2-c3 | 14:59:10 | 22,467 | 34,418 | claude-sonnet-5 |+| …59690d8b | issues-review-p1-c1 | 14:59:14 | 22,467 | 46,226 | claude-sonnet-5 |+| …5b847747 | issues-review-p3-c1 | 14:59:18 | 22,467 | 46,228 | claude-sonnet-5 |+| …dbf1ef6f | issues-review-p1-c2 | 14:59:20 | 22,467 | 48,498 | claude-sonnet-5 |+| …7d977d15 | issues-review-p2-c2 | 15:09:25 | 22,467 | 48,501 | claude-sonnet-5 |+| …a9efc769 | blind-spots-c1 | 15:40:02 | 0 | 73,039 | claude-sonnet-5 |+| …26e7c323 | blind-spots-c4 | 15:40:03 | 0 | 53,326 | claude-sonnet-5 |+| …45cfc93d | blind-spots-c2 | 15:40:04 | 0 | 76,133 | claude-opus-4-8, claude-sonnet-5 ⚠️SWITCHED |+| …708cfe5d | blind-spots-c3 | 15:40:06 | 22,467 | 37,643 | claude-sonnet-5 |+| …90488845 | blind-spots-c2 | 22:15:40 | 0 | 76,127 | claude-sonnet-5 |+| …f3cb2cb1 | validation-c4 | 22:28:48 | 0 | 37,728 | claude-opus-4-8 |+| …d640d258 | validation-c1 | 22:28:51 | 17,141 | 20,663 | claude-opus-4-8 |+| …220f4dbe | validation-c2 | 22:28:52 | 17,141 | 20,622 | claude-opus-4-8 |+| …f85252ab | validation-c3 | 22:28:53 | 17,141 | 20,196 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **10/18** (report the distribution, not a median).+- ⚠️ 1 unit(s) switched models mid-session (overload rescue?) — cache sharing and cost pinning are broken for them: …45cfc93d++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 16s |+| review wave (perspectives) | 12m 36s |+| blind-spot sweep | 35m 47s |+| dedup (incl. combine/clean) | 401m 08s |+| validation | 19m 51s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 48m 23s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 2 |+| 1 | 2 | review-hog-perspective-contracts-security | 3 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | review-hog-perspective-logic-correctness | 3 |+| 2 | 3 | review-hog-perspective-logic-correctness | 3 |+| 3 | 1 | review-hog-perspective-performance-reliability | 3 |+| 3 | 2 | review-hog-perspective-performance-reliability | 6 |+| 1000 | 1 | review-hog-blind-spots-general | 2 |+| 1000 | 3 | review-hog-blind-spots-general | 2 |+| 1000 | 4 | review-hog-blind-spots-general | 2 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:316-321++**self_driving=bool(context.get("self_driving_review")) truthy-coerces the flag without checking it is an actual JSON boolean**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `pipeline = Pipeline(0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")))` applies Python's generic truthiness coercion to a value whose entire job is to gate two hard security checks (bot-author refusal and the draft prerequisite). `bool(x)` treats any non-empty string as `True`, including the literal string `"false"` — a classic hazard whenever a JSON value has passed through a stringifying layer upstream (shell/env-var interpolation, a templating step using something like `jq --arg` instead of `--argjson`, or a server-side serializer that stringifies booleans before embedding them in the context JSON). If the hosted server's assembly of this context JSON ever produces `"self_driving_review": "false"` (or any other non-empty falsy-looking string) instead of the real JSON boolean `false`, `bool("false")` evaluates to `True` and both gates — bot-author refusal and the draft-in-progress check — are waived for a PR that was never actually meant to be self-driving. Unlike the other GitHub-API-sourced booleans in this same function (e.g. `draft=bool(pr.get("draft"))` at line 197), which come from GitHub's own REST/GraphQL JSON and reliably deserialize as real booleans, `self_driving_review` is a custom value "stamped by the server" (per the new comment at line 316) specifically for this feature — a different trust/serialization origin that the identical `bool(...)` pattern doesn't distinguish.+- **Suggestion:** Use a strict boolean check instead of truthy coercion for this specific flag, e.g. `self_driving=context.get("self_driving_review") is True`, so any non-boolean value (including a stray `"false"` string) fails closed rather than silently unlocking the bot-author and draft gates.+- **Validator:** - **Checked:** The full serialization pipeline for `self_driving_review` — `activities.py` (`self_driving_review=bool(output.get("inbox_review"))`, a real Python bool), `products/stamphog/backend/logic/reviewer.py` (typed param `self_driving_review: bool = False`, placed into the context dict as `"self_driving_review": self_driving_review`), `review_local.py:391` (`context = json.loads(Path(args.context).read_text())`), and the integration test.+- **Found:** The flag is a Python `bool` produced by server code, serialized through JSON (`json.dumps` → `true`/`false`) and read back via `json.loads` as a real Python boolean. No stringifying layer exists on this path — the context is a JSON file, not env-var interpolation, `jq --arg`, or shell templating. The integration test `test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end` round-trips the actual sandbox context write (`json.loads(...sandbox_writes...[STAMPHOG_SANDBOX_CONTEXT_PATH])`) and asserts `context["self_driving_review"] is True`, which would fail if the value were the string `"true"`. So the serialization is verified to emit a genuine JSON boolean.+- **Impact:** The hypothesized `"self_driving_review": "false"` → `bool("false") == True` bypass depends on a stringifying serializer that this code path does not use and that a test explicitly rules out (`is True`). This is a speculative what-if / defensive-coding hardening against a condition that can't occur given the JSON round-trip already in place — below the keep bar, dropped per precision-over-recall. The `is True` suggestion is a harmless micro-hardening but guards nothing reachable.++### [❌ dismissed] consider · security — products/tasks/backend/facade/api.py:484-518++**find_signal_implementation_run leaves fork-safety as an unenforced caller precondition at a cross-product facade boundary**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The docstring states "the caller supplies the repository the PR event came from and is responsible for fork safety (only branch-match PRs whose head repo IS that repository)" — but this facade function is exactly the seam `products.architecture.md`'s isolation model designates as the sole sanctioned entry point for other products into `products.tasks`. Today's only caller (`_inbox_rereview_carve_out` in stamphog) does perform the fork check first, but the function itself accepts no `head_repo`/fork-safety input and enforces nothing beyond the `team_id` recheck. A future caller (in stamphog or any other product) that forgets this documentation-only precondition would silently bind an attacker-controlled fork PR (matching `repository` + `branch`) to a legitimate signals-implementation run, inheriting its `signal_report_id`/`task_created_by_id` identity — the exact hazard the existing in-file comment about branch-keyed fork PRs warns about.+- **Suggestion:** Push the fork-safety invariant into the facade itself rather than leaving it as caller discipline: accept the PR's `head_repo` (or a `require_repo_native_head: bool` derived from it) as a parameter and return `None` when it doesn't match `repository`, so every current and future cross-product caller gets the guarantee for free instead of having to re-derive it correctly each time.+- **Validator:** - **Checked:** Fetched the PR diff (not in local checkout) and traced every production call site of `find_signal_implementation_run`, the facade body (`products/tasks/backend/facade/api.py`), both stamphog callers (`_inbox_rereview_carve_out`, `process_inbox_pr_review`), and the sibling convention in `products/tasks/backend/webhooks.py`.+- **Found:** The only production caller, `_inbox_rereview_carve_out`, already performs the fork check before calling — `head_repo = ((pr.get('head') or {}).get('repo') or {}).get('full_name'); if head_repo.strip().lower() != repo.strip().lower(): return _InboxCarveOut()` (tasks.py:894-896) — and re-checks team scope after (tasks.py:917). The finding concedes this. The other leg, `process_inbox_pr_review`, never calls the facade; its `pr_url` is the bot's own recorded run output, so there is no attacker-controlled input.+- **Found:** The facade itself already enforces the real tenant-isolation boundary: `if run is None or run.team_id != team_id: return None` (api.py:1715). Cross-tenant binding — the IDOR-class hazard — is closed inside the facade; only same-team fork-branch collision is left to the caller.+- **Found:** This split is the established, intentional convention, not an oversight. `webhooks.py:175-186` does exactly the same: `find_task_run` matches by branch+repo without fork enforcement, and the caller applies the `is_internal_branch` check before trusting the match. The new facade mirrors it and documents the precondition in its docstring.+- **Impact:** As written and as actually reached, no current caller is unsafe and no tenant boundary is crossed. The described hazard is only reachable if a _future_ caller is written to pass `head_branch` without a fork check — a speculative "what-if" ruled out by present call sites. The suggested fix (bake `head_repo` matching into the facade to protect hypothetical future callers) is defensive future-proofing for a case not in scope, and would also complicate the precise `pr_url` match leg where fork safety is irrelevant. Per precision-over-recall, this does not meet the bar.++### [❌ dismissed] consider · code_quality — tools/pr-approval-agent/reviewer.py:683-703++**Self-driving provenance block asserts "it is a draft on purpose" without checking whether the PR is still a draft**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `_format_self_driving` unconditionally states "It is a draft on purpose (the verdict is wanted at Inbox triage time); draft state is not a caution signal for this PR" whenever `cl.get("self_driving")` is true, regardless of the PR's actual current draft state. Per the PR's own Case 2 ("new commits land on that PR") and Case 4, a self-driving PR can be re-reviewed after it has already been marked ready for review (draft→ready is listed only as a case where _no new review is triggered_, not as something that can never precede a later re-review triggered by a new commit while still opted in). In that situation the block asserts a stale/incorrect fact ("it is a draft on purpose") to the reviewer, which could cause it to discount an actual, currently-true non-draft state as if it were the expected draft case.+- **Suggestion:** Thread the PR's live draft state into `_format_self_driving` (it already receives `cl`; either add `pr.draft` as a parameter or a `cl["pr_draft"]` classification field) and only emit the draft sentence when the PR is currently a draft, e.g. omit or rephrase it to "It may still be a draft — the verdict is wanted at Inbox triage time" when `pr.draft` is False.+- **Validator:** - **Checked:** `_format_self_driving` in the PR's `reviewer.py` diff (renders the TRUSTED provenance block into the LLM prompt), the classification build in `review_pr.py` `_classify` (`"self_driving": self.self_driving`), the draft-prerequisite carve-out in `_check_prerequisites`, and the re-review trigger path in `products/review_hog/backend/receivers.py` (stamphog webhook re-review re-checks the toggle on later pushes).+- **Found:** The disputed sentence's operative clause is a _caution suppression_ — "draft state is not a caution signal for this PR" — and it is immediately preceded by "judge the diff strictly on its own merits." The re-review-after-ready scenario is reachable (a self-driving PR flips to ready, a new commit lands while still opted in, the webhook re-review fires with `self_driving=True` and `pr.draft=False`), so the sentence can indeed be stale.+- **Impact:** Even in that reachable case the consequence is negligible. The sentence only tells the reviewer _not_ to treat draft-ness as a warning; when the PR is already ready there is no draft-ness to caution about, so the instruction is moot rather than harmful. The finding's asserted harm ("discount a currently-true non-draft state") maps to no concrete wrong verdict: a ready PR is the more-complete state, and a reviewer that mistakenly believes it is still a draft drifts toward _more_ caution — the safe direction for an approve-first tool — never toward wrongly approving unsafe code. This is a one-clause factual imprecision in a trusted LLM prompt, not a correctness bug that plausibly affects users or the codebase, so it falls under the skill's "speculative what-if / low-impact" drop bar (precision over recall).++### [❌ dismissed] should_fix · performance — products/review_hog/backend/api/settings.py:71-82,50-54++**Every settings read/write now depends synchronously on a second product's database**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` calls `has_reviewable_repo_config(instance.team_id)`, a query against the `stamphog` product database (a genuinely separate DB per `products/db_routing.yaml`, routed via `ProductTeamModel`). Because it's a `SerializerMethodField`, it recomputes on every serialization of `ReviewUserSettingsSerializer` — which fires on both the GET path and every PATCH via `user_settings()` (settings.py L99-105), including PATCHes that only touch unrelated fields like `urgency_threshold` or `review_labeled_prs`. There is no caching of this boolean, even though the underlying `StamphogRepoConfig` sync/enabled state changes rarely. The `try/except` only guards against exceptions (fail-soft to `False`); it does nothing about added latency or connection-pool pressure on the `stamphog` alias when that database is merely slow rather than erroring. The net effect: the review_hog settings endpoint, previously self-contained on one database, now pays a second DB round-trip on every single call regardless of which field changed.+- **Suggestion:** Cache the connected flag per team with a short TTL (e.g. Django's cache framework, a few minutes) so repeated GET/PATCH calls don't re-hit the stamphog DB, and invalidate it when a `StamphogRepoConfig` for the team is created/enabled/disabled. Alternatively, skip recomputing `stamphog_connected` on PATCH responses that don't touch stamphog-related fields and let the frontend keep its previously-loaded value.+- **Validator:** - **Checked:** Pulled the real PR diff (local checkout HEAD `7120703f` is not the PR head, so the working-tree `settings.py` lacks these changes). Confirmed `get_stamphog_connected` and traced `has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`, plus the GET/PATCH flow in `user_settings`.+- **Found:** `has_reviewable_repo_config` is a single `.exists()` — `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` — one `team_id`-scoped row-existence check, not an N+1 or per-row query. It re-runs on every serialization (GET + PATCH's `Response(serializer.data)`), so the premise is factually correct.+- **Impact:** The bar is "performance that bites at real scale." This is one indexed EXISTS on the ReviewHog settings endpoint, which is hit at human-interaction rate (Code review tab load, toggle click) — not a hot path or high-throughput route. The GET path already runs `get_or_create` + `seed_canonicals_tolerantly`, so the added query is marginal, not a new bottleneck. The reliability sub-claim (latency / pool pressure on a slow-but-not-erroring stamphog DB) is bounded by the same low call frequency, and the `try/except` already fails soft to `False` so an erroring DB cannot break the endpoint.+- **Impact:** The proposed remedy — a per-team TTL cache with invalidation on `StamphogRepoConfig` create/enable/disable — is disproportionate complexity for a single indexed EXISTS on a low-frequency endpoint, matching the criteria's "add caching / add an abstraction" overengineering category. On the fence resolves to drop (precision over recall).++### [❌ dismissed] consider — products/stamphog/backend/facade/api.py:149-155++**`queue_inbox_pr_review` dispatches its Celery task immediately instead of via `transaction.on_commit`**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `queue_inbox_pr_review` calls `process_inbox_pr_review.delay(...)` directly. Its own docstring describes it as being invoked synchronously from "the caller's save path" (review_hog's TaskRun receiver), which strongly suggests it runs inside or immediately alongside a DB write. Elsewhere in the codebase, exactly this fire-and-forget dispatch pattern is wrapped in `transaction.on_commit` specifically to avoid dispatching a task before its triggering transaction durably commits — see `products/customer_analytics/backend/facade/api.py:3082` ("Dispatch only after the delivery rows commit; a rollback must not leave a phantom task") and `products/tasks/backend/facade/api.py:2041`. If the caller's transaction that saves the PR-URL-carrying TaskRun output later rolls back for an unrelated reason, this facade would already have queued a Celery task that fetches the PR from GitHub and creates a ReviewRun referencing a `task_run_id`/`signal_report_id` whose originating save never actually committed.+- **Suggestion:** Either wrap the `.delay()` call in `transaction.on_commit(lambda: process_inbox_pr_review.delay(...))` here, or (if the caller is guaranteed to invoke this only after its own transaction commits) note that invariant explicitly in the docstring so it isn't silently relied upon by a future caller that doesn't hold it.+- **Validator:** - **Checked:** Traced the only production caller of `queue_inbox_pr_review` through the PR diff — review_hog's `post_save` receiver `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review` — plus the facade body itself and the sibling review_hog dispatch on the same save path.+- **Found:** The dispatch is already guarded by `transaction.on_commit` at the caller. In `handle_task_run_saved` (review_hog receivers), the `_start_stamphog_review(...)` call — which invokes `queue_inbox_pr_review` → `process_inbox_pr_review.delay(...)` — is wrapped in `transaction.on_commit(lambda: ...)` (PR diff lines 203-211). The Celery task is therefore published only after the TaskRun-save transaction durably commits; on rollback the callback is discarded and no task fires. The finding's phantom-task premise cannot occur on this path.+- **Found:** This is a deliberate, consistent convention, not a one-off. The classic review_hog leg `_start_review` in the same receiver is wrapped in `transaction.on_commit` too (diff lines 188-197). The codebase places the commit-ordering guard in the receiver that owns the transaction boundary, not inside the import-light fire-and-forget facade. Pushing `on_commit` into the facade would be redundant here and incorrect for any caller invoked outside a transaction (autocommit mode runs `on_commit` immediately).+- **Impact:** The claimed reliability defect is already handled by an existing guard one frame up the only call stack, so it does not meet the bar (wrong premise / already handled). The residual fallback — a docstring note documenting the commit invariant for a hypothetical future caller — is speculative future-proofing of the same class the criteria explicitly drop.++### [❌ dismissed] consider · best_practice — products/review_hog/frontend/CodeReviewScene.tsx:1048-1071++**stamphog_connected is loaded once on mount and never revalidated, so connecting Stamphog in another tab leaves the new switch stuck showing "not connected" until a manual reload**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new switch's `disabledReason` gates on `settings.stamphog_connected`, which is populated once by `loadSettings()` in `reviewHogSettingsLogic`'s `afterMount` and never re-fetched afterward (no polling, no focus/visibility refresh, no invalidation hook tied to the Stamphog connection flow). A user who lands on this Code review settings page with Stamphog not yet connected, then goes to connect a Stamphog GitHub App/repository (a separate flow, plausibly in another browser tab or a separate scene navigation that doesn't remount this settings block), returns to find the switch still disabled with "Connect a repository to Stamphog first..." even though the connection now exists — because the in-memory `settings.stamphog_connected` value is stale until the user does a full page reload. This is a real, unnecessary dead end for the exact discovery flow this UI is designed to prompt (the disabled message tells the user to go connect Stamphog, but coming back doesn't reflect that they did).+- **Suggestion:** Revalidate `stamphog_connected` when it matters: e.g., re-run `loadSettings()` on window `focus`/`visibilitychange` while this scene is mounted, or expose a lightweight manual refresh (a "Recheck connection" affordance next to the disabled tooltip) so the user isn't forced into a full page reload after connecting Stamphog elsewhere.+- **Validator:** - **Checked:** `reviewHogSettingsLogic.ts` — the `settings` loader (L459-471), the `updateSettings` reducer/loader paths, `afterMount`→`loadAll`→`loadSettings` (L1042-1044, L850-857), and every listener/reducer touching `settings`; plus the switch's `disabledReason` in `CodeReviewScene.tsx` (PR diff) and the `stamphog_connected` field in the generated `ReviewUserSettingsApi`.+- **Found:** The literal premise holds — `loadSettings()` runs once at mount with no polling, focus/visibility, or invalidation hook. BUT `stamphog_connected` is _not_ purely load-once: the `updateSettings` loader (L464-469) returns the full serialized settings (including `stamphog_connected`), so toggling any other setting on the page refreshes it, and `updateSettingsFailure` (L858-861) reloads. A kea logic also re-fires `afterMount` on scene remount, so in-app navigate-away-and-back refreshes too — contradicting the issue's 'separate scene navigation that doesn't remount' framing. The only truly stale path is same-tab-open + connect-in-another-tab + no reload.+- **Impact:** Doesn't map to any 'keep' category — the switch correctly shows the last-loaded value; there's no correctness, security, data-loss, contract, performance, or reliability defect. It's minor UI staleness with a trivial workaround (reload, renavigate, or change any setting), a narrow cross-tab trigger, on an alpha/internal-gated settings surface. The proposed fix (focus/visibility polling or a 'Recheck connection' button) is scope-add polish. Below the precision-over-recall bar → drop.++### [❌ dismissed] must_fix · documentation — products/stamphog/AGENTS.md:80-113++**AGENTS.md documents a facade/toggle integration that doesn't exist anywhere in the codebase**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new "self-driving inbox carve-out" section names a specific set of symbols as the mechanism for the exception to the bot-author refusal: a `self_driving_review` flag threaded through `Pipeline(self_driving=...)`, a `ReviewRun.output["inbox_review"]` provenance key, a `process_inbox_pr_review` receiver entered via a `queue_inbox_pr_review` facade call, a `products/stamphog/backend/facade/inbox_hooks.py` resolver registered by review_hog at app-ready, and a per-user `stamphog_review_inbox_prs` toggle. A repo-wide search (not just `products/stamphog/`) finds none of these: `Pipeline.__init__` in `tools/pr-approval-agent/review_pr.py` takes only `pr_number, repo, dry_run, verbose` (no `self_driving` param exists at all); `review_local.py` calls `_refuse_bot_author()` unconditionally with no carve-out branch; `products/stamphog/backend/facade/` contains only `api.py`, `contracts.py`, `enums.py`, `tasks.py`, `temporal.py`, `webhooks.py` — no `inbox_hooks.py`; and no file in the repo defines or reads `stamphog_review_inbox_prs`, `queue_inbox_pr_review`, or `process_inbox_pr_review`. The one functionally similar piece of code that does exist — a per-user inbox-review toggle gating a Temporal workflow — lives entirely inside the separate `products/review_hog` product (`review_inbox_prs` on `ReviewUserSettings`, `products/review_hog/backend/models.py:300`, consumed by `products/review_hog/backend/temporal/workflow.py`'s own self-contained `ReviewPRWorkflow`), with zero import coupling to `products/stamphog` in either direction. `products/stamphog/CLAUDE.md` explicitly frames this AGENTS.md as "the contract" whose "invariants... were each earned through a real review finding" and instructs future agents to "hold new code to all of them" — shipping a fabricated invariant here will send the next engineer or agent hunting for code that was never written, or worse, cause them to assume protections (fail-closed re-review, task-linkage verification, dismissal-before-carve-out) are enforced when no such enforcement exists anywhere in this codebase.+- **Suggestion:** Either (a) remove this section entirely if the self-driving inbox integration was implemented differently (as it appears to have been, entirely within `products/review_hog` with no stamphog facade), or (b) if this design is genuinely still planned, clearly mark it as a forward-looking design note rather than documenting it as current, contract-level behavior with specific file/function names that a reader would reasonably expect to `grep` for and find. If the real implementation is the `review_inbox_prs` toggle in `products/review_hog`, update this section (and cross-link stamphog/review_hog's actual relationship, if any) to reflect what actually ships.+- **Validator:** - **Checked:** Whether the symbols the finding says exist nowhere are actually added by this PR. The local `pull/75215/head` branch points at base master (`7120703f`) and the real PR head (`1341596e`) is absent, so I pulled the true diff via `gh pr diff 75215`.+- **Found:** Every claimed-missing symbol is defined in the PR diff. `Pipeline.__init__` gains `self_driving: bool = False` (`tools/pr-approval-agent/review_pr.py`, diff L1955) and the bot-author refusal is gated on it (L1977: `if self.pr.author_is_bot and not self.self_driving`). `products/stamphog/backend/facade/inbox_hooks.py` is a **new file** (diff L720) exporting `register_inbox_acting_reviewer_resolver` (L752). `queue_inbox_pr_review` is defined (`facade/api.py`, L687) and `process_inbox_pr_review` (L1041). `stamphog_review_inbox_prs` is a real `BooleanField` on `ReviewUserSettings` (`products/review_hog/backend/models.py`, L121) with migration `0019_reviewusersettings_stamphog_review_inbox_prs.py`. `review_local.py` adds `_inbox_rereview_carve_out` (L862) and threads `self_driving_review`, and the workflow keys off the `inbox_review` provenance (`self_driving_review=bool(output.get("inbox_review"))`, L1227).+- **Found:** The finding's "zero import coupling" claim is also contradicted — the PR deliberately builds a facade bridge: review_hog registers a resolver into stamphog's `inbox_hooks` registry at app-ready (inversion hook to avoid a dependency cycle) and calls `queue_inbox_pr_review`. The AGENTS.md carve-out section describes code the PR actually ships, not a fabricated invariant.+- **Impact:** Falls squarely under the skill's "Wrong / unreproducible — investigating the actual code shows the premise is mistaken" drop category. The finding is an artifact of a checkout that contained the doc change but not the implementation; surfacing it would send the author chasing a non-problem.++### [❌ dismissed] must_fix · documentation — products/stamphog/README.md:14-15++**README.md's new "non-webhook entry" paragraph repeats the same fabricated symbol names as the AGENTS.md addition**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This paragraph asserts that "review_hog's inbox receiver calls the `queue_inbox_pr_review` facade" in stamphog, gated by a `stamphog_review_inbox_prs` toggle, with re-review "through `facade/inbox_hooks.py`". None of `queue_inbox_pr_review`, `stamphog_review_inbox_prs`, or `facade/inbox_hooks.py` exist anywhere in the repository (verified by grep across all `.py` files, not just this product). This is internally consistent with the equally fabricated AGENTS.md section it links to ("See AGENTS.md § the self-driving carve-out"), but consistency between two fictional descriptions doesn't make the described integration real — both documents describe the same nonexistent facade call. The actual toggle that exists, `review_inbox_prs`, lives on `ReviewUserSettings` in the unrelated `products/review_hog` product (`products/review_hog/backend/models.py:300`) and gates review_hog's own independent Temporal workflow (`TRIGGER_INBOX` handling in `products/review_hog/backend/temporal/workflow.py:436`), with no call into stamphog at all.+- **Suggestion:** Update or remove this paragraph to match whichever product actually owns the inbox-PR-review trigger. If review_hog implements this independently (as the code suggests), state that plainly instead of describing a stamphog-side facade (`queue_inbox_pr_review`) that isn't called from anywhere.+- **Validator:** - **Checked:** Whether the README paragraph's three named symbols exist and whether review_hog's inbox receiver actually calls into stamphog. Local `pull/75215/head` points at base master (`7120703f`) with the real PR head (`1341596e`) absent, so I verified against the true diff (`gh pr diff 75215`). Diff L650-658 confirms the paragraph is in `products/stamphog/README.md`.+- **Found:** `queue_inbox_pr_review` is defined in `products/stamphog/backend/facade/api.py` (diff L687) and is imported and called by review_hog's inbox receiver: `products/review_hog/backend/receivers.py` L276 `from products.stamphog.backend.facade.api import queue_inbox_pr_review` and L279 `queue_inbox_pr_review(...)`. This directly refutes the finding's "with no call into stamphog at all."+- **Found:** `stamphog_review_inbox_prs` is a real `BooleanField` on `ReviewUserSettings` (`products/review_hog/backend/models.py`, diff L121) plus migration `0019_reviewusersettings_stamphog_review_inbox_prs.py`, and the receiver gates on it at L198 (`if pr_url is not None and settings.stamphog_review_inbox_prs`). `products/stamphog/backend/facade/inbox_hooks.py` is a new file whose `register_inbox_acting_reviewer_resolver` is called from review_hog's `connect()` (receivers.py L149 import, L166 registration) — the exact inversion hook the README describes.+- **Impact:** The premise ("none of these exist anywhere, verified by grep across all .py files") is mistaken — an artifact of a checkout carrying the doc change but not the implementation. Falls under the skill's "Wrong / unreproducible" drop category; the README accurately documents shipped code, so surfacing this would send the author chasing a non-problem.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:1-17++**New migration collides with the already-merged 0019 migration (conflicting migration graph)**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This migration is named `0019_reviewusersettings_stamphog_review_inbox_prs.py` and declares `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]`. The `review_hog` app already has a different, already-merged migration also numbered 0019 — `0019_reviewreport_author_login_and_more.py` — which depends on the exact same parent (`0018_backfill_urgency_threshold_to_consider`), and `products/review_hog/backend/migrations/max_migration.txt` records `0019_reviewreport_author_login_and_more` as the current head. Two sibling migrations both claiming node `0019` off the same parent is a Django migration-graph conflict: `makemigrations`/`migrate` will report "Conflicting migrations detected; multiple leaf nodes" until a merge migration is added, and this is precisely the collision the `max_migration.txt`-based CI check exists to catch. As written, this migration was generated (2026-07-21) before `0019_reviewreport_author_login_and_more.py` (2026-07-22) landed on the base branch, so the PR branch is stale relative to master and will fail CI's migration-conflict check on this file alone.+- **Suggestion:** Rebase onto the current base branch, renumber this migration to the true next number after the real head (e.g. `0020_reviewusersettings_stamphog_review_inbox_prs.py`), update its `dependencies` tuple to point at the actual current head migration, and regenerate `max_migration.txt` (typically via `python manage.py makemigrations` after rebasing, or the project's migration-fixing tooling) so the two 0019 migrations don't coexist as parallel leaves.+- **Validator:** - **Checked:** The live `products/review_hog/backend/migrations/` directory on the base checkout, the `dependencies` of master's existing `0019`, and `max_migration.txt`.+- **Found:** Master already ships `0019_reviewreport_author_login_and_more.py`, whose `dependencies` are `[("review_hog", "0018_backfill_urgency_threshold_to_consider")]` — the identical parent the PR's new `0019_reviewusersettings_stamphog_review_inbox_prs.py` declares. Two migrations both numbered `0019` off `0018` is the exact 'Conflicting migrations detected; multiple leaf nodes' case Django rejects.+- **Found:** The chain has advanced well past `0019` on master (`0020`–`0024` exist; `max_migration.txt` = `0024_reviewreport_published_head_shas`). The PR rewrites `max_migration.txt` to `0019_reviewusersettings_stamphog_review_inbox_prs`, which both regresses the recorded head and directly trips the `max_migration.txt`-based linearity CI check.+- **Impact:** `makemigrations`/`migrate` fail with conflicting leaf nodes and the migration-linearity gate blocks the merge — a confirmed, blocking defect (branch generated 2026-07-21, before the other 0019 merged, so it is stale). Fix is rebase + renumber to `0020`+ off the true head. Reviewer's `must_fix` is correct.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1245++**process_inbox_pr_review trusts caller-supplied PR/task linkage with no independent verification, letting an unverified pr_url drive an automated GitHub approval**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `process_inbox_pr_review` (fired via `queue_inbox_pr_review` in `facade/api.py:112-157`) is the sole gate before a fully automated, bot-authored, draft-eligible PR review — including a real GitHub APPROVE — runs with `self_driving_review=True` (see `temporal/activities.py`'s `self_driving_review=bool(output.get("inbox_review"))`), which bypasses every one of this file's own security gates: `_review_skip_reason` (bot author, draft, untrusted author association) and `_author_lacks_write_permission` are never called on this path at all. The only inputs are caller-supplied `pr_url`, `signal_report_id`, `task_run_id`, and `acting_user_id` (facade/api.py:119-142), which are stamped into `run.output["inbox_review"]` verbatim (lines ~1176-1181) with **no verification that the PR at `pr_url` actually corresponds to `task_run_id`/`signal_report_id`**, no bot-author check, and no fork-safety check (`head.repo.full_name == repository`). Contrast this with the sibling webhook carve-out `_inbox_rereview_carve_out` (same file), which authoritatively re-derives the PR↔run linkage via `find_signal_implementation_run` (looking the run up FROM the PR, not trusting a caller-supplied id) and explicitly checks `_is_bot_authored(pr)` and the fork-safety `head_repo != repo` comparison before treating a PR as self-driving. `process_inbox_pr_review` has neither check.++This matters because `pr_url` is not trustworthy input: `TaskRun.output["pr_url"]` is written by the sandboxed coding agent itself via its own `task:write`-scoped PATCH to `set_output` (`products/tasks/backend/presentation/views/api.py` → `facade/api.py`'s `set_task_run_output`), with only a URL-shape/owner-repo check (`_is_github_pull_request_url_for_repository`) and no live GitHub lookup anywhere in `products/tasks` to confirm the PR exists, is open, targets the right branch, or was actually opened by that run. If review_hog's TaskRun receiver forwards this agent-self-reported value into `queue_inbox_pr_review` (as its docstring implies — "the caller has already resolved the acting reviewer and checked their toggle", nothing about validating the PR itself), a compromised or prompt-injected agent (the whole premise of self-driving PRs is an LLM acting on a signal report, which can carry attacker-influenced content) can redirect the review to an arbitrary open PR in a team's connected repo — including a legitimate external contributor's fork PR that the normal gates exist specifically to refuse — and get it auto-approved with zero human in the loop, exactly the outcome `TRUSTED_AUTHOR_ASSOCIATIONS`'s comment (this same file) says must never happen.++- **Suggestion:** Before creating the ReviewRun, have `process_inbox_pr_review` independently re-verify the self-driving linkage the same way `_inbox_rereview_carve_out` does: call `products.tasks.backend.facade.api.find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url, head_branch=...)` (or a variant keyed on `task_run_id` directly) and confirm the returned run's `task_run_id`/`signal_report_id` match what was passed in, and confirm the fetched `pr` is bot-authored (`_is_bot_authored(pr)`) and not a fork (`(pr.get("head") or {}).get("repo", {}).get("full_name") == repo_config.repository`) before stamping `inbox_review` and creating the run. Treat any mismatch as a no-op (log and return), the same fail-closed posture the webhook path already uses.+- **Validator:** - **Checked:** The full receiver-leg body `process_inbox_pr_review` (PR diff ~1041-1176), the `self_driving_review` derivation in `temporal/activities.py` (diff 1215-1227), the engine's use of the flag in `tools/pr-approval-agent/review_pr.py`/`review_local.py` (diff 1937-2009), the agent-write path for `output.pr_url` (`_is_github_pull_request_url_for_repository` api.py:1995-2018, `_apply_caller_output` api.py:1821-1836), the review_hog forwarder (`receivers.py:77`, `_start_stamphog_review`), and the sibling webhook carve-out `_inbox_rereview_carve_out` (diff 887-918).+- **Found:** `process_inbox_pr_review` gates only on repo_config-enabled + PR open + head_sha present; it never calls `_is_bot_authored`, `_review_skip_reason`, `_author_lacks_write_permission`, or `find_signal_implementation_run`, and stamps caller-supplied `signal_report_id`/`task_run_id` into `output['inbox_review']` with no check that the PR at `pr_url` belongs to that run. The webhook path does all three checks (bot, `head_repo == repo` fork check, facade linkage) before treating a PR as self-driving — the receiver leg has none.+- **Found:** `self_driving_review=bool(output.get('inbox_review'))` relaxes exactly the bot-author refusal and draft prerequisite in the engine, which has no fork check; APPROVE stays reachable, so a human-authored fork PR passes (its author isn't even a bot) and can receive a real GitHub approval.+- **Found:** `output.pr_url` is agent-written and only shape-validated (owner/repo + `/pull/{digits}`); `_apply_caller_output`'s own comment contemplates a `task:write` caller repointing `pr_url`. review_hog forwards `output.get('pr_url')` unverified. So a prompt-injected self-driving agent — the feature's explicit untrusted-input premise — can name an arbitrary open PR in the connected repo, including an external contributor's fork PR.+- **Impact:** A fork/external PR can be auto-APPROVED with zero human in the loop, satisfying required reviews — the exact outcome tasks.py:73-75 (`TRUSTED_AUTHOR_ASSOCIATIONS`) says must never happen, and contradicting the `activities.py` comment (diff 1224-1226) that claims both trigger paths positively link the PR to a signals run before stamping provenance. Concrete trigger and consequence, directly introduced by this PR, not prevented anywhere on the receiver-leg path — meets the security bar.++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1176-1231++**Initial inbox review never re-checks the acting reviewer's opt-in toggle at execution time (TOCTOU)**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `acting_user_id` is resolved and its `stamphog_review_inbox_prs` toggle checked once by the caller (review_hog) before `queue_inbox_pr_review.delay(...)` is enqueued, but `process_inbox_pr_review` never re-resolves or re-checks that toggle before it fetches the PR, creates the `ReviewRun`, and (via `transaction.on_commit`) starts the workflow that can post a real GitHub approval. The webhook carve-out (`_inbox_rereview_carve_out`) does the opposite correctly — it calls `get_inbox_acting_reviewer_resolver()` fresh on every delivery so a toggle flipped off mid-flight is honored immediately. Because this task can retry (`max_retries=3`, plus a rate-limit `countdown` of up to 60s on `GitHubRateLimitError`), there's a real window between "caller confirmed the toggle was on" and "the review actually executes and can post an approval" in which the last opted-in reviewer could switch the toggle off — yet the review proceeds anyway, contradicting the PR's own stated invariant (Case 3: "nobody is opted in, so no review runs").+- **Suggestion:** Re-resolve the acting reviewer via `get_inbox_acting_reviewer_resolver()` inside `process_inbox_pr_review` immediately before creating the `ReviewRun` (using the same `(team_id, signal_report_id, task_created_by_id)` inputs the webhook path uses), and bail out (logging an opt-out skip) if the resolver returns `None` at that point — mirroring the fail-closed behavior already implemented for later webhook deliveries.+- **Validator:** - **Checked:** `process_inbox_pr_review` gates (PR diff ~1061-1160), the dispatch-time toggle check in review_hog's `handle_task_run_saved` (receivers.py:186-211) and its receiver-leg docstring (diff 1046-1047), the per-delivery re-check in `_inbox_rereview_carve_out` (diff 919-925), and PR Case 3's stated invariant.+- **Found:** The toggle IS checked once, at dispatch, before the `transaction.on_commit` enqueue — this is the documented design for the one-shot initial review, not a forgotten check. The receiver leg genuinely does not re-check it, as claimed.+- **Found:** The webhook path re-checks per delivery because each push is an independent trigger separated by minutes-to-days — a large, realistic opt-out window. The initial review is a single dispatch→execute with a seconds-scale window (retries fire only on transient config/GitHub/rate-limit errors). The asymmetry tracks the paths' different temporal nature.+- **Found:** Case 3's safety property ('turning off never leaves an approval on code nobody checked') is upheld by the stale-approval retraction paths on head change, independent of the toggle. An initial-review approval landing during the race is an approval of code stamphog actually reviewed at that head, and is retracted on the next head-changing delivery — so it does not violate that invariant.+- **Impact:** The acting reviewer was opted in at dispatch (not 'zero human'); the finding requires them to flip off within a seconds-scale window of a one-shot job, and the only consequence is one already-authorized review running against PostHog's own bot draft PR, with any approval retractable. The toggle is a per-user preference, not a cross-principal authorization boundary, so there is no security/IDOR dimension. This is a rare, low-impact preference-timing race — the never-gonna-happen/defensive-coding bucket the criteria drop under precision-over-recall.++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_pr.py:195-209,225,587-590++**self_driving relaxes the bot-author and draft gates without cross-checking the PR is actually bot-authored**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The new `self_driving` flag independently disables the two hard gates that keep StampHog from auto-approving unreviewed code: the bot-author refusal in `run()` (`if self.pr.author_is_bot and not self.self_driving:`) and the draft prerequisite in `_check_prerequisites` (`if pr.draft and not self.self_driving:`). Neither guard is cross-checked against `PRData.author_is_bot`, which `_build_pr_data`/`fetch_pr` already computes and stores on the same `pr` object. So the code has no local invariant that `self_driving=True` may only apply to a genuinely bot-authored PR — it trusts a single, independently-set boolean read straight from the hosted context JSON (`context.get("self_driving_review")` in review_local.py:316) to unlock both gates at once. If that flag is ever mis-set for the wrong PR (e.g. a stale/mismatched context, a bug in the external task-linkage lookup that stamps it, or the context being reused/misrouted across a concurrent run) it would waive the draft-review prerequisite for a PR that isn't actually a bot's draft at all — including a human-authored draft PR intentionally kept unreviewed as work-in-progress — and let it receive a real, unattended GitHub approval. The existing `_refuse_bot_author` docstring explicitly frames the bot-author check as "the defense-in-depth layer for any manual or out-of-band invocation" (review_pr.py:268-274); this change removes exactly that backstop for the new out-of-band (sandboxed/hosted) invocation path without adding an equivalent one back. `PRData` also carries no fork/head-repo field, so nothing in this engine can independently confirm the PR is same-repo/non-fork either — the entire trust chain for this carve-out rests on one caller-supplied boolean with zero redundant validation in the reviewed code.+- **Suggestion:** Pair the flag with the authorship data the engine already has before honoring it. For example, in review_local.py build `PRData` first, then derive `self_driving = bool(context.get("self_driving_review")) and pr_data.author_is_bot` and pass that into `Pipeline(..., self_driving=self_driving)` instead of trusting the context key verbatim. Mirror the same guard in review_pr.py's `Pipeline` (e.g. assert/normalize `self.self_driving = self_driving and False` is not needed there since the Action CLI never sets it, but add a defensive check in `run()`/`_check_prerequisites` — or a single property like `self._effective_self_driving` — that only relaxes the draft/bot-author gates when `self.pr.author_is_bot` is also true, and otherwise treats a self_driving=True + non-bot-author combination as an anomaly to ESCALATE rather than silently proceed). This keeps the new carve-out from becoming a single point of failure for the two gates that exist specifically to stop unattended auto-approval.+- **Validator:** - **Checked:** Both paths that stamp the flag (`products/stamphog/backend/tasks/tasks.py`), the engine's consumption of it (`review_pr.py` `run`/`_check_prerequisites`, `review_local.py:316`), and where `pr.author_is_bot` originates.+- **Found (validation already in place):** The webhook re-review path (`_inbox_rereview_carve_out`) explicitly cross-checks `_is_bot_authored(pr)`, fork-safety (`head_repo.lower() == repo.lower()`), an enabled repo config, `find_signal_implementation_run` linkage with a `run.team_id == repo_config.team_id` recheck, and the opt-in resolver — a human/fork PR resolves empty, so no `inbox_review` is stamped and the engine receives `self_driving=False`. The receiver leg (`process_inbox_pr_review`) fires only for an inbox signals-implementation task whose `output.pr_url` is the PR the agent opened as the bot (bot-authored by construction). So no normal, non-buggy path stamps `self_driving_review=True` onto a human-authored PR.+- **Found (suggested guard is weak against its own premise):** In the engine, `pr.author_is_bot` is derived from the _same_ context JSON that carries `self_driving_review` (`_build_pr_data(context)`). The finding's headline scenarios — "stale/mismatched context, context reused/misrouted across a concurrent run" — carry that context's own author data, so a misrouted bot-PR context has `author_is_bot=True` and the proposed `self_driving and pr.author_is_bot` check passes anyway. The guard only catches an internally-inconsistent context (flag True but author non-bot), a narrow sub-case.+- **Found (half the relaxation is inert):** Relaxing the bot-author refusal for a non-bot PR is a no-op — `if pr.author_is_bot and not self.self_driving` never fires when `author_is_bot` is False. Only the draft-prerequisite waiver is behaviorally live, so the "unlocks both gates at once" framing overstates the exposure.+- **Impact:** The claimed harm (a human draft PR getting an unattended approval) requires an upstream bug that mis-stamps `inbox_review` — a condition that can't occur given the bot-author/fork/task-linkage validation the two trigger paths already perform. This is speculative "what-if" plus defense-in-depth against a check a parent caller already does; per the precision-over-recall bar it drops, and `must_fix` (implying a concrete reachable defect) is unsupported.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_pr.py:587-590,790-839,843-896,937-938++**The self-driving carve-out is invisible in the human-facing review comment and the analytics audit trail**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The PR adds `"self_driving": self.self_driving` to `to_dict()`'s classification (review_pr.py:937-938) with a comment calling it "Audit trail for the carve-out: which gates ran relaxed, and why" — but that key only reaches the raw JSON blob the hosted server parses. The two other places this system actually surfaces review decisions for humans/monitoring don't carry it: `_check_prerequisites` (line 590) silently drops the "PR is still in draft" issue for a self-driving PR, so the gate result still reads `prerequisites: ✓ all clear` in both the posted GitHub review comment's gate-mechanics table (`_render_review_body`, lines 843-896) and nowhere does that table or its bullets mention the carve-out was applied; and `_capture_review_completed`'s PostHog analytics event (lines 790-839), which is this system's own telemetry/audit channel (tier, breadth, familiarity, gate/llm verdicts, etc.), has no `stamphog_self_driving` property. A human reading the actual posted review, or someone querying `stamphog_review_completed` events to audit/monitor approval behavior, has no way to see that the draft/bot-author gates were bypassed for a given approval — undermining the stated audit-trail purpose of the new field.+- **Suggestion:** Surface the carve-out in the channels that are actually inspected: add `"stamphog_self_driving": self.self_driving` to the properties dict in `_capture_review_completed`, and make the relaxation visible in the human-facing output — e.g. have `_check_prerequisites` return a distinguishable message when it waives the draft check (`"all clear (draft check waived: self-driving inbox PR)"` instead of the generic `"all clear"`), or add a bullet/note in `_render_review_body` when `self.self_driving` is true.+- **Validator:** - **Checked:** `_capture_review_completed` (`review_pr.py:799-838`), `analytics_extra_properties` (`gateway.py:17-33`), the PR's `activities.py` env-stamping change, and the integration test `test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end`.+- **Found (analytics half is factually wrong):** `_capture_review_completed` opens its `properties` dict with `**analytics_extra_properties()` (`review_pr.py:806`), which parses the `STAMPHOG_EXTRA_PROPERTIES` env JSON. The PR stamps `stamphog_self_driving_review = True` into that env for inbox runs (`activities.py`, comment: "so the engine's completed events and LLM traces segment cleanly in analytics"), and the integration test asserts `json.loads(sandbox_env['STAMPHOG_EXTRA_PROPERTIES'])['stamphog_self_driving_review'] is True`. So the `stamphog_review_completed` event DOES carry a self-driving marker — anyone auditing approval behavior can filter `stamphog_self_driving_review = true`. The finding's claim that the analytics event has "no way to see" the carve-out is mistaken; it looked only for the exact key `stamphog_self_driving` and missed the cross-file `analytics_extra_properties()` → env mechanism the author deliberately used.+- **Found (human-comment half is a minor nicety):** `_render_review_body` (`review_pr.py:843-896`) does not add a note when the draft check is waived, so the gate table reads generically. But the carve-out is already surfaced three other ways: self-evident in the GitHub UI (the approval sits on a visibly draft, bot-authored PR), in the `to_dict()` classification blob, and in the analytics event above. Adding a comment bullet is an observability/copy enrichment, not a correctness/security/contract/data/reliability defect.+- **Impact:** Half the finding rests on a false premise (the analytics audit trail exists), and the remaining half is a best-practice observability nicety below the keep bar. Drop per precision-over-recall.++### [❌ dismissed] should_fix · documentation — products/review_hog/backend/receivers.py:144-160,114-139++**Stamphog toggle only checks one 'acting' reviewer, not 'at least one of the assigned users' as the PR describes**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The PR's stated behavior is that Stamphog reviews an inbox PR when "at least one of the assigned users has `stamphog_review_inbox_prs` enabled." Both the initial dispatch in `handle_task_run_saved` (settings loaded for the single `acting_user_id` at lines 111/114-139) and the webhook re-check `resolve_stamphog_acting_reviewer` (lines 144-160) only ever evaluate ONE reviewer's toggle: whichever user `_resolve_assigned_reviewer` designates as "acting" — the task's creator if they're in the resolved `suggested_reviewers` set, otherwise the _first_ resolved reviewer (`next(..., resolved[0])`). If a report has multiple assigned reviewers and the one selected as acting has the toggle off while a _different_ assigned reviewer has it on, Stamphog will never review the PR (and the reverse: switching off the non-acting reviewer's toggle has no effect at all) — contradicting the described "any assigned user" gate.+- **Suggestion:** Either correct the PR description to reflect the actual single-acting-reviewer semantics (matching the pre-existing `review_inbox_prs` gate it mirrors), or, if "any assigned reviewer opted in" is genuinely the intended behavior, change the gate to iterate all resolved reviewers from the `suggested_reviewers` artefact and trigger when any of them has `stamphog_review_inbox_prs=True`, instead of only checking the single reviewer `_resolve_assigned_reviewer` designates as acting.+- **Validator:** - **Checked:** PR diff of `receivers.py` (`handle_task_run_saved` dispatch, `resolve_stamphog_acting_reviewer`, `_resolve_assigned_reviewer`), master's pre-existing `_resolve_acting_reviewer` (receivers.py:158-160), and the `queue_inbox_pr_review` facade docstring.+- **Found:** The code claim is accurate — both legs check only one reviewer. `_resolve_assigned_reviewer` sets `acting = next((u for u in resolved if u.id == task_created_by_id), resolved[0])`, and both the initial dispatch and `resolve_stamphog_acting_reviewer` evaluate only that user's `stamphog_review_inbox_prs`; a non-acting reviewer's toggle is inert.+- **Found:** But single-acting-reviewer is the deliberate, pre-existing design, not a defect this PR introduces. Master's `_resolve_acting_reviewer` already gates `review_inbox_prs` on the identical `acting.id` resolution (receivers.py:158-160); the PR mirrors it. The docstring documents it as canon ('the first resolved reviewer is canonical — maintainer decisions, 2026-07-02/03'), and it is architecturally necessary: the acting reviewer's ReviewHog options and the Stamphog sandbox-credential principal must come from one user, so multiple users' configs can't drive one run. The PR's added tests assert exactly this behavior.+- **Impact:** The flagged code does what it's designed to do; the only real discrepancy is with the PR description's loose 'at least one of the assigned users' wording — prose, not a code defect, and outside every keep category (correctness/security/data/contract/perf/reliability). The reviewer's own primary suggestion (fix the description) concedes the code matches the established `review_inbox_prs` pattern; the 'iterate all reviewers' alternative contradicts the intended one-config design. Premise that the code is wrong is mistaken → drop.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:144-160++**Full reviewer-resolution chain re-runs uncached on every push to a self-driving PR**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered with stamphog's inbox hook registry and, per the PR's own description ("Case 2 — new commits land on that PR"), is invoked by stamphog's webhook path on every subsequent push to a self-driving PR so it can re-check the toggle. Each invocation re-runs the full chain: a `SignalReportArtefact` lookup ordered by `-created_at`, then `resolve_org_github_login_to_users` (a Team lookup plus two candidate-id queries across `UserSocialAuth`/`UserIntegration` plus a `User` query with `prefetch_related`), then a separate `ReviewUserSettings.load` call. Previously this same resolution only ran once, at the review_hog TaskRun-save trigger. There is no memoization/caching keyed on `signal_report_id` across repeated webhook calls, so a PR that receives many commits during active development re-pays this multi-query cost on every push — and because this hook runs inside stamphog's webhook handler, it also introduces a new cross-database dependency (main DB reads) into stamphog's webhook hot path.+- **Suggestion:** Cache the resolved acting-reviewer id (and/or the resolved settings) per `signal_report_id` for a short window (e.g. a minute), invalidated when the suggested-reviewers artefact changes, so bursts of pushes to the same PR don't each re-run the full org-membership resolution.+- **Validator:** - **Checked:** PR `resolve_stamphog_acting_reviewer`/`_resolve_assigned_reviewer` (receivers.py diff), `resolve_org_github_login_to_users` and its candidate-id helpers (`products/signals/backend/report_generation/resolve_reviewers.py:532-560, 563-592`), and the AGENTS.md webhook re-review trigger note.+- **Found:** The per-call cost is bounded and small — ~1 indexed `SignalReportArtefact` query + `resolve_org_github_login_to_users` (1 `Team` lookup + ~3 bulk `user_id__in` candidate queries + 1 `User` query with prefetch) + 1 `ReviewUserSettings.load` ≈ 7-9 indexed queries. The candidate/user queries are bulk `__in`, so cost does not scale per-reviewer: no N+1, nothing unbounded, no quadratic behavior.+- **Found:** Frequency is human-rate, not a hot path — it runs once per GitHub push webhook (synchronize/reopen/base-retarget) on a self-driving PR, processed async, and each passing gate then launches a full sandboxed-LLM review that dwarfs the ~8 gating queries. The webhook handler already hits the DB for repo-config/PR/dedup, so these reads are marginal.+- **Found:** The proposed per-`signal_report_id` TTL cache is the 'add caching/abstraction' pattern the criteria drop, and here it is actively risky: caching the toggle would break the PR's documented 'Case 3 — toggle off mid-PR stops new runs' semantics (a stale 'on' re-reviews after opt-out). The fresh per-push read is deliberate.+- **Impact:** Bounded indexed queries on a low-frequency async path that gates far costlier work — below the 'performance that bites at real scale' bar. Cross-DB main-DB reads are inherent (the toggle/reviewer identity live there) and tiny in volume, not a reliability defect. Drop (precision over recall).++### [❌ dismissed] consider · best_practice — products/review_hog/backend/receivers.py:65-69++**New inbox-hook registration has no duplicate-registration guard, unlike the sibling signal connect**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `connect()` wires two things: `post_save.connect(handle_task_run_saved, ..., dispatch_uid="review_hog_task_run_completed")`, which explicitly guards against being wired twice via `dispatch_uid`, and the new `register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer)`, which has no visible equivalent guard. If `connect()` (or `AppConfig.ready()`) ever runs more than once in a process — autoreload, test-harness app-registry reloads, or multiple Django app instances sharing the registry — and `register_inbox_acting_reviewer_resolver` appends to a list rather than overwriting a single slot, every subsequent stamphog webhook call would invoke the (non-trivial, multi-query) resolver multiple times per event, silently multiplying DB load without any error being raised.+- **Suggestion:** Confirm `register_inbox_acting_reviewer_resolver` in the stamphog facade is idempotent (overwrites rather than appends), or make the registration idempotent from this side (e.g. skip re-registering if already set), mirroring the `dispatch_uid` protection already used for the `post_save` connection just above it.+- **Validator:** - **Checked:** The new `products/stamphog/backend/facade/inbox_hooks.py` (full module in PR diff) — `register_inbox_acting_reviewer_resolver`, the module-level `_inbox_acting_reviewer_resolver` slot, and `get_inbox_acting_reviewer_resolver`.+- **Found:** Registration is a single-slot overwrite, not a list append: `def register_inbox_acting_reviewer_resolver(fn): global _inbox_acting_reviewer_resolver; _inbox_acting_reviewer_resolver = fn`. The getter returns that one callable and the webhook leg invokes it once. Re-running `connect()`/`AppConfig.ready()` any number of times simply re-assigns the same slot to the same function — the resolver still runs exactly once per event.+- **Impact:** The finding is explicitly conditional on the registry appending ('if ... appends to a list rather than overwriting a single slot'); the actual code takes the safe branch, so the 'multiplied DB load per event' scenario cannot occur. The reviewer's own first proposed action — confirm the registration is idempotent (overwrites) — is satisfied by inspection, leaving nothing to fix. Premise is mistaken and the guard it asks for is redundant → drop.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:167-196++**`_inbox_rereview_carve_out` re-runs uncached cross-product lookups for every bot-authored PR push, not just self-driving ones**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `_inbox_rereview_carve_out` is invoked (via the `skip_reason is not None` branch) on every `synchronize`/`reopened`/base-retarget delivery for a bot-authored PR whose head branch lives in the base repo — this matches ordinary dependabot/renovate/other-bot PRs, not just self-driving ones (the fork check only excludes actual forks, and bot services like Dependabot push branches directly to the target repo). For every such delivery it does a writer-pinned `_resolve_repo_config` query (line 179) and then, once config checks pass, a deferred import plus `find_signal_implementation_run` call (lines 189-196) that fans out into up to three queries inside `find_task_run` (pr_url leg, branch leg, wizard leg) against the tasks product's DB. None of this is cached, even though the answer ("this PR isn't a signals-implementation run") is stable for a given (repo, pr_number) across an entire burst of pushes (e.g. a dependabot rebase storm). The file already establishes the precedent for exactly this problem: `_author_lacks_write_permission` caches its GitHub lookup per (repo_config, login) specifically "to absorb synchronize bursts" (lines 122-142), but the new carve-out has no equivalent guard.+- **Suggestion:** Add a short-TTL negative cache keyed on (repo_config.id or installation_id, pr_number) — e.g. `cache.set(f"stamphog:inbox_carve_out_miss:{repo_config.id}:{pr_number}", True, ttl)` — set once the carve-out resolves to "not self-driving", and checked before doing the `find_signal_implementation_run` call. This mirrors the existing author-permission caching pattern in the same file and would keep repeated dependabot/renovate synchronize bursts from re-querying two products' databases on every push.+- **Validator:** - **Checked:** The carve-out's early-exit ladder and query sites (`_inbox_rereview_carve_out`, diff 885-918), `find_signal_implementation_run` → `find_task_run`'s three legs (webhooks.py:30-90), the `task_run_output_pr_url_idx` partial index backing the pr_url leg (tasks facade), and the cited precedent `_author_lacks_write_permission` (diff 122-142).+- **Found:** For the dependabot/renovate case the finding targets, the work is a small bounded constant of indexed reads: the `pr_url` leg (`output__pr_url=`, index-served) returns empty, the branch leg (`branch=` + `task__repository__iexact=`) returns empty, the wizard leg is skipped (non-wizard branch prefix), plus one `_resolve_repo_config` lookup — roughly three cheap queries per head-changing delivery, not N+1 and not unbounded.+- **Found:** This runs in an async webhook Celery task (`process_pull_request_event`), only when the repo has an enabled Stamphog config, and only on bot-authored non-fork head-changing deliveries — a low-frequency cold path, not a hot request path.+- **Found:** The precedent doesn't transfer: `_author_lacks_write_permission` caches a rate-limited GitHub API call (network + external quota), which is why it guards synchronize bursts; local indexed Postgres reads have neither cost, so the analogy overstates the need.+- **Impact:** ~3 millisecond-scale indexed reads on a low-frequency path — negligible even under a rebase storm — does not meet the 'performance problem that bites at real scale' bar. The proposed negative cache adds a key + TTL + invalidation reasoning to save trivial DB work, i.e. premature optimization, which the criteria drop.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:179-179,873-891++**`_resolve_repo_config` is queried twice for the same (installation_id, repo) on the same skip path**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Inside `_inbox_rereview_carve_out`, `repo_config = _resolve_repo_config(installation_id, repo)` (line 179) resolves the repo config against the writer DB. When this returns a config but the delivery is ultimately not treated as a carve-out (resolver returns None/opted-out, or the tasks-facade match fails), control returns to `process_pull_request_event`, which — inside the same `if skip_reason is not None and inbox_review is None:` block — calls `skip_repo_config = _resolve_repo_config(installation_id, repo)` again (line 891) purely to retract stale approvals. That's a second identical writer-pinned query for the exact same (installation_id, repo) pair within a single task execution, for every bot-authored PR push that reaches this far (which, per the finding above, is most bot traffic, not just self-driving PRs).+- **Suggestion:** Have `_InboxCarveOut` (or `_inbox_rereview_carve_out`) also return the resolved `repo_config` (when it got that far) so the caller can reuse it for the retraction step instead of re-querying, e.g. add a `repo_config: StamphogRepoConfig | None` field to `_InboxCarveOut` and thread it into `_retract_stale_approvals_on_skip` when set.+- **Validator:** - **Checked:** The skip-path flow in `process_pull_request_event` (diff 956-980), the carve-out's internal `_resolve_repo_config` call (diff 897) and its early-exits (diff 885-896), and the `_resolve_repo_config` query body (diff 183-189).+- **Found:** The double query is real: on a bot-authored, non-fork, head-changing, skipped delivery with no carve-out provenance, `_inbox_rereview_carve_out` runs `_resolve_repo_config` once, then the retraction block runs it again (diff 972). Since `_resolve_repo_config` applies no `.enabled` filter itself, both calls return the same row — the finding's premise holds.+- **Found:** The redundancy is exactly ONE extra indexed `SELECT` (`provider+installation_id+repository`, `.first()`), and only for bot-authored PRs on Stamphog-enabled repos — human PRs early-exit at `_is_bot_authored` before the first query. It's an async webhook Celery path, not a hot request path.+- **Impact:** A single redundant cheap indexed read on a low-frequency path is not N+1, unbounded, quadratic, or blocking I/O — it does not bite at real scale, so it falls below the performance-keep bar. There's no correctness angle (both reads are writer-pinned and deterministic). The suggested cleanup is a minor DRY improvement with no behavioral difference — a micro-optimization the criteria drop under precision-over-recall (and a strict subset of the already-dropped 3-2-1 cost).++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1125-1128,1155-1165++**`process_inbox_pr_review` hits the GitHub API on every refire with no debounce before the head-based dedupe**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The task's own docstring states "The receiver re-fires on every TaskRun output save carrying the PR URL" (lines 1125-1128), and the GitHub PR fetch (`StamphogGitHubClient(...).get_pr(...)`, lines 1158-1159) runs unconditionally before any deduplication — the docstring explicitly justifies this ordering because "the dedupe keys on the PR's current head, which only GitHub knows." For an agent task run that saves output frequently (streaming progress updates), every save triggers a full Celery dispatch (`queue_inbox_pr_review` → `process_inbox_pr_review.delay`) and a live GitHub API call, even though the PR's head SHA is very likely unchanged between most of those saves. There's no short-lived cache of "last known head for this PR" to skip the network round trip when nothing has changed, so a chatty task run can generate a burst of redundant GitHub API calls. The only mitigation present is reactive (retrying on `GitHubRateLimitError`), not preventive.+- **Suggestion:** Consider a short-TTL cache keyed on (repository, pr_number) storing the last-seen head SHA once a review is queued for it, and short-circuit the task (skip the GitHub fetch) when a refire arrives within the TTL and nothing else has changed — or have the caller (the TaskRun receiver) debounce/coalesce repeated saves before invoking `queue_inbox_pr_review` at all, since that's the actual source of the refire frequency.+- **Validator:** - **Checked:** How `TaskRun.output` is written during a run (`relay_sandbox_events._persist_final_message` at :830-839, the pr_url milestone write), the progress mechanism (`emit_progress_activity.py:23-29`), the receiver's save filter and its own cost note (`receivers.py:60-72`), and `process_inbox_pr_review`'s fetch-then-head-dedupe ordering (PR diff ~1089-1152).+- **Found:** The finding's premise is wrong: progress streaming goes through `emit_progress` → a `_posthog/progress` notification and never writes `output`, so progress ticks do not refire the receiver. `output` is saved only at discrete milestones — `pr_url` on PR open and `final_message` at session end (`save(update_fields=["output","updated_at"])`) — i.e. ~1–2 pr_url-carrying saves per run, not a per-tick stream.+- **Found:** The receiver drops saves whose `update_fields` don't include `output` (receivers.py:69-72), and the design already documents and bounds the refire cost: 'a same-head re-trigger costs one fetch (early-exit)' (receivers.py:60-63), with the deterministic workflow id + USE_EXISTING collapsing duplicate workflows and the head-based dedupe collapsing duplicate ReviewRuns. The fetch-before-dedupe ordering is deliberate — the dedupe keys on the current head, which only GitHub knows.+- **Impact:** Realistic redundant volume is on the order of one extra `get_pr` per run, not the 'burst of redundant GitHub API calls' claimed — well below the scale at which a rate-limited call bites. The premise that makes the concern serious (frequent output saves from progress streaming) does not hold, so the proposed last-head cache/debounce is a premature optimization. Does not meet the performance-keep bar.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:1140-1147++**`repository__iexact` lookup in `process_inbox_pr_review` can't use the model's existing indexes**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The repo-config resolution here filters on `repository__iexact=repository` (case-insensitive), but `StamphogRepoConfig`'s only relevant indexes are the case-sensitive unique constraints on `(team_id, repository)` and `(provider, installation_id, repository)`. A case-insensitive lookup (`UPPER(...)`/`ILIKE`) generally can't use a plain btree index built on the raw column, so this query falls back to scanning every `StamphogRepoConfig` row for the team rather than using an index seek. Impact is likely small today since the row count per team is small, but it's a real deviation from every other repo-config lookup in this file (`_resolve_repo_config` uses an exact `repository=repo` match that is index-backed).+- **Suggestion:** If case-insensitive matching is required because tasks stores repository slugs lowercased, consider normalizing `repository` to a canonical case at write time (or adding a functional/expression index on `lower(repository)`) rather than relying on `__iexact` at read time across every team's config set.+- **Validator:** - **Checked:** `StamphogRepoConfig` constraints/indexes (models.py:57-68: composite unique `(team_id, repository)` and `(provider, installation_id, repository)`), the receiver-leg query (`for_team(team_id).filter(provider=..., repository__iexact=..., enabled=True, ...)`, diff 1071-1078), and the in-file rationale for `__iexact` (diff 1067-1068).+- **Found:** The query is team-scoped, so the `(team_id, repository)` index seeks on the `team_id` leading column and `UPPER(repository)=UPPER(...)` is applied as a filter over only that team's rows — not a full-table scan. Per-team config count is bounded by `unique_stamphog_repo_per_team` to one row per repository, i.e. a few-to-dozens of rows.+- **Found:** `__iexact` is deliberate and required: tasks stores repository slugs lowercased while configs keep GitHub's casing (comment at diff 1067-1068), which also explains why `_resolve_repo_config` can use exact match (it gets GitHub-cased input from the webhook payload) and this path cannot.+- **Impact:** A case-insensitive filter over a team's handful of config rows, on a low-frequency webhook Celery path (~1–2 runs per self-driving PR), is negligible — the finding itself concedes 'impact is likely small today.' It doesn't bite at real scale (no hot path, bounded per-team cardinality already indexed by the team_id prefix), so it's below the performance-keep bar; the proposed functional index / write-time normalization migration is overengineering for that row count.++### [❌ dismissed] consider · best_practice — products/stamphog/backend/tasks/tasks.py:1236-1236++**Exception log for `process_inbox_pr_review`'s run-creation failure omits the error field used everywhere else**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `logger.exception("stamphog_inbox_pr_create_run_failed", repository=repository, pr_number=pr_number)` doesn't include `error=str(e)`, unlike every other `logger.exception(...)` call added or touched in this same file (e.g. `stamphog_inbox_pr_config_resolution_failed`, `stamphog_inbox_pr_fetch_failed`, and all the `process_pull_request_event` failure paths), which consistently pass `error=str(e)` as a structured field alongside the auto-captured traceback. This makes the failure harder to filter/alert on by error message in structured log queries compared to its siblings.+- **Suggestion:** Add `error=str(e)` to this `logger.exception` call for consistency with the rest of the file's error-logging convention.+- **Validator:** - **Checked:** The three sibling `logger.exception` calls in the receiver leg (diff 1080 `stamphog_inbox_pr_config_resolution_failed` with `error=str(e)`, diff 1095 `stamphog_inbox_pr_fetch_failed` with `error=str(e)`, diff 1167 `stamphog_inbox_pr_create_run_failed` without it) and the surrounding control flow.+- **Found:** The claim is factually correct — the create-run-failed log omits the `error=str(e)` field its siblings include. But `logger.exception` auto-captures the full traceback (exception type + message via `exc_info`), and the very next line re-raises via `raise ...retry(exc=e)` (diff 1168), so the failure is fully logged and retried — nothing is swallowed or hidden.+- **Impact:** The only difference is a redundant top-level structured `error` field for marginally easier message filtering; the error content is already present in the captured traceback. This is a pure logging-convention consistency nit with no behavioral difference and no information loss — exactly the style/taste category the criteria drop. Below the keep bar under precision-over-recall.++### [❌ dismissed] must_fix · best_practice — products/review_hog/backend/receivers.py:144-160,127-161++**resolve_stamphog_acting_reviewer has no exception guard, unlike every other entry point in this module, despite being invoked directly from stamphog's webhook hot path**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** Every other public entry point in this module is deliberately exception-proof: `handle_task_run_saved`'s own docstring states "this executes inside tasks' save path and must never raise into it" and wraps its whole body in `try/except Exception: logger.exception(...)` (lines 65-109); `_start_review` and `_start_stamphog_review` are documented fire-and-forget with their own try/except. `resolve_stamphog_acting_reviewer` (lines 144-160) breaks this pattern: it is registered via `register_inbox_acting_reviewer_resolver` and called directly by stamphog's webhook path (per this PR's own description, on every subsequent push to a self-driving PR) with zero exception handling of its own. Its body calls `_resolve_assigned_reviewer`, which does a `SignalReportArtefact` query, a `resolve_org_github_login_to_users` call (Team lookup + two candidate-id queries + a prefetching User query), and a `ReviewUserSettings.load` call — none of these are wrapped, and only a narrow `json.loads` block (lines 143-146) catches anything. A transient DB error, a connection hiccup, or any exception type outside `(json.JSONDecodeError, TypeError, ValueError)` (e.g. `KeyError`/`AttributeError` from malformed artefact content, or a `DatabaseError`) now propagates out of review_hog's code straight into stamphog's synchronous webhook handler — a component whose own CLAUDE.md documents a hard invariant that every code path (including skip/error paths) must deliberately retract stale approvals, and treats fail-open vs fail-closed behavior as a carefully engineered property. An uncaught exception raised mid-webhook here is exactly the kind of unplanned-for path that invariant exists to prevent: it can surface as a 500 to GitHub (triggering webhook redelivery storms) or interrupt whatever retraction/adopt logic stamphog's handler was midway through, depending on how (or whether) the caller wraps this specific call — which this PR does not control or guarantee, since the call originates entirely inside another product.+- **Suggestion:** Wrap `resolve_stamphog_acting_reviewer`'s body (or at minimum the `_resolve_assigned_reviewer` call and the `ReviewUserSettings.load` call) in a try/except that logs and returns `None` on any exception, matching the fail-safe contract every other function in this module already honors. Given the registered-hook shape means review_hog's code runs synchronously inside stamphog's webhook request, treat this the same as `handle_task_run_saved`: any exception must degrade to "no reviewer found" rather than propagate, so stamphog's caller can rely on a plain `int | None` return without also having to guard against arbitrary exceptions escaping across the product boundary.+- **Validator:** - **Checked:** How stamphog invokes the registered resolver — `_inbox_rereview_carve_out` (calls `resolver(...)`), its caller `process_pull_request_event`, and that caller's decorator on the base checkout (`products/stamphog/backend/tasks/tasks.py:694-695`).+- **Found:** `process_pull_request_event` is a Celery task — `@shared_task(ignore_result=True, max_retries=3, default_retry_delay=5)` (tasks.py:694), 'the durable hand-off from the GitHub webhook.' GitHub is ACKed at the receive layer and processing is async, so the finding's central harm ('surface as a 500 to GitHub → redelivery storms') cannot occur.+- **Found:** The resolver call IS guarded by the caller, added in this same PR: `try: carve_out = _inbox_rereview_carve_out(...) except Exception as e: logger.exception('stamphog_pr_event_inbox_carve_out_failed', ...); raise cast(Any, process_pull_request_event).retry(exc=e)` — comment: 'Retry (don't drop) on failure: a transient DB blip during the carve-out resolution must not silently drop a legitimate re-review (the webhook is already ACKed).' The finding's hedge that 'this PR does not control or guarantee' the wrapping is factually wrong.+- **Found:** Carve-out resolution runs (fully guarded) before the retraction block (`if skip_reason is not None and inbox_review is None:`), so an exception aborts into a retry of the whole idempotent task (dedup via `_mark_pr_event_processed`), never mid-retraction.+- **Found:** The suggested internal try/except-return-None would harm the engineered behavior: resolver `None` → `_InboxCarveOut(opted_out=True)` → caller dismisses the standing approval and skips re-review on a transient DB blip — the exact silent drop the retry-don't-drop design prevents. Propagation is deliberate.+- **Impact:** Risk is prevented by the parent caller (confirmed) and misdescribes the context (Celery, not a sync 500 path); the fix would worsen the intended fail-with-retry semantics. 'Already handled' / 'wrong premise' → drop; `must_fix` does not hold.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_local.py:314-354++**review_local.py never populates pipeline.provenance, so the self-driving carve-out's own audit trail is silently empty on the only path that uses it**+_perspective: review-hog-blind-spots-general · directly-related: False_++- **Problem:** The repo already has a trusted, git-derived signal for exactly the question the `self_driving` flag answers: `pr_provenance(base_sha, head_sha, repo_root)` (github.py) parses `Generated-By:`/`Task-Id:` trailers straight out of the PR's own commits in the checkout and exposes them as `CommitProvenance` (`agent_authored`, `task_ids`, `generated_by`, `commit_count`). In `review_pr.py`, `_fetch()` (line 375) calls this and assigns it to `self.provenance` before the bot-author gate even runs, and it flows into both the audit JSON (`to_dict()['provenance']`, line 922) and the `stamphog_review_completed` analytics event (`stamphog_agent_authored`/`stamphog_generated_by`/`stamphog_task_ids`/`stamphog_commit_count`, lines 827-831). `review_local.py`'s `run()` — the offline entrypoint that is, per its own module docstring and the already-noted absence of a `--self-driving` CLI flag on `review_pr.py`, the _only_ code path through which `self_driving=True` is ever actually reached — never calls `pr_provenance()` and never assigns `pipeline.provenance`. It stays at its `Pipeline.__init__` default of `None` (review_pr.py:202) for the PR's entire offline review. Nothing crashes: `provenance_evidence(None)` returns `None` and `_capture_review_completed`'s ternaries (`prov.agent_authored if prov else None`, etc.) degrade quietly to `None`/`[]`. The result is that for every single self-driving review, `to_dict()['provenance']` is `null` and the task/agent-authorship analytics fields are always empty — even though `pipeline.pr.base_sha`/`head_sha` are available at that point (set in `_build_pr_data`, review_local.py:127-128) and the module's own docstring says this runs "against a LOCAL checkout", so `pr_provenance()` is technically callable here with the same call pattern review_pr.py already uses. This is the one independent, harder-to-spoof corroborating fact (real commit trailers already in the checkout, not another hosted-context boolean) that could substantiate or contradict the externally-supplied `self_driving_review` flag, and it is never even computed on the path where that flag actually unlocks the bot-author and draft gates — silently, with no error to signal the gap.+- **Suggestion:** In `review_local.py`'s `run()`, after `pipeline.pr = _build_pr_data(context)`, call `pipeline.provenance = pr_provenance(pipeline.pr.base_sha, pipeline.pr.head_sha, REPO_ROOT)` (import `pr_provenance` from `github`) the same way `review_pr.Pipeline._fetch()` does, so the offline path's audit JSON and analytics carry real commit-trailer evidence instead of always-null/empty fields. Longer term, consider having the self-driving gate relaxation itself require `pipeline.provenance is not None and pipeline.provenance.agent_authored` (or a matching task id) as a second, locally-verifiable factor alongside the hosted `self_driving_review` boolean.+- **Validator:** - **Checked:** `review_local.py` `run()` (grep: zero `provenance`/`pr_provenance` references — never assigned, stays at the `Pipeline.__init__` `None` default), `review_pr.py._fetch` (line 375 sets `self.provenance = pr_provenance(...)`), `pr_provenance` (github.py:528, parses `Generated-By:`/`Task-Id:` trailers via git), how the hosted backend consumes the engine output (`products/stamphog/backend/logic/reviewer.py:170-176`), and where the self-driving audit trail actually lives.+- **Found (claim is accurate but telemetry-only):** provenance really is always `None` on the offline path, so `to_dict()['provenance']` is null and the `stamphog_agent_authored`/`agent_commit_count`/`commit_count`/`generated_by`/`task_ids` analytics fields are empty for every offline/self-driving review. However, the hosted backend never reads `output['provenance']` — `reviewer.py` stashes only `gates`/`classification`/`policy` for audit (line 174), and a repo-wide grep of `products/stamphog/backend/` finds no provenance consumption. The review verdict is entirely unaffected.+- **Found (the audit trail is not actually empty):** self-driving auto-approvals are recorded server-side in `run.output["inbox_review"]` — `signal_report_id`, `task_run_id`, `acting_user_id` from `find_signal_implementation_run` — plus the `stamphog_self_driving_review` analytics marker. The git-trailer provenance the finding wants is a redundant corroborating signal, not the sole or primary record, so "the carve-out's own audit trail is silently empty" overstates the consequence.+- **Impact:** A telemetry/observability completeness gap with no verdict impact and no functional consumer of the missing field, on a feature whose real audit trail is robustly captured elsewhere. The proposed security "second factor" is an explicit "longer term, consider" hardening, not a present defect. This sits below the keep bar (not correctness/security/data-loss/contract/perf/reliability); dropped per precision-over-recall, consistent with the sibling telemetry finding.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-4.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-4.mdnew file mode 100644index 000000000000..737c6d82d36c--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/A-sonnet5-xhigh-4.md@@ -0,0 +1,419 @@+# Reviewer-quality run — `A-sonnet5-xhigh-4`++- **Dumped:** 2026-07-30T23:50:27+00:00+- **Report id:** `019fb538-de9e-7147-96de-ffd75925a9fe` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 3571s (59.5 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-sonnet-5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 30 | 26 | 4 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 135 | 98,734 | 741,181 | 15,086,587 | 228,765 | 5 | $18.39 | $18.39 |+| claude-sonnet-5 | review | 158 | 211,409 | 1,669,905 | 20,887,307 | 349,477 | 9 | $12.27 | $12.27 |+| claude-sonnet-5 | blind-spot | 141 | 132,651 | 1,130,065 | 15,456,066 | 171,204 | 11 | $7.89 | $7.89 |+| claude-sonnet-5 | dedup | 1 | 20,635 | 0 | 0 | 6,087 | 0 | $0.10 | $0.10 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 1,345 | 0 | $0.03 | $0.03 |+| gpt-5.6-terra | other | 1 | 13 | 0 | 0 | 5 | 0 | — | $0.00 |+| **total** | | **437** | **469,423** | **3,541,151** | **51,429,960** | **756,883** | **25** | **$38.68** | **$38.68** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `gpt-5.6-terra` (1 gen(s), gw $0.00).+- naive method (all prompt tokens at input price): $169.66 — 4.4× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $27.6793 over 437 gen(s) (true $27.6793, Δ +0.0%)+ - · of which cache read: $14.8120 over 424 gen(s) (true $14.8120, Δ +0.0%)+ - · of which cache write: $11.6323 over 433 gen(s) (true $11.6323, Δ +0.0%)+ - · of which fresh (derived): $1.2351 over 437 gen(s) (true $1.2350, Δ +0.0%)+ - output: $11.0003 over 437 gen(s) (true $11.0003, Δ +0.0%)+- 25 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …d43f9d7c | issues-review-p1-c1 | 22:51:26 | 0 | 68,686 | claude-sonnet-5 |+| …53906820 | issues-review-p2-c2 | 22:51:26 | 0 | 70,957 | claude-sonnet-5 |+| …2b274477 | issues-review-p3-c1 | 22:51:27 | 22,467 | 46,223 | claude-sonnet-5 |+| …fb271fd0 | issues-review-p3-c2 | 22:51:42 | 22,467 | 48,488 | claude-sonnet-5 |+| …9ae94d57 | issues-review-p1-c3 | 22:51:50 | 22,467 | 34,412 | claude-sonnet-5 |+| …d8a5ba6a | issues-review-p2-c1 | 22:51:52 | 22,467 | 46,222 | claude-sonnet-5 |+| …6f2f1a42 | issues-review-p2-c3 | 22:51:54 | 22,467 | 34,408 | claude-sonnet-5 |+| …3dbfd49f | issues-review-p1-c2 | 22:51:59 | 22,467 | 48,490 | claude-sonnet-5 |+| …d47b7c99 | blind-spots-c1 | 23:05:58 | 0 | 73,297 | claude-sonnet-5 |+| …6d37ee4d | blind-spots-c2 | 23:05:58 | 0 | 76,328 | claude-sonnet-5 |+| …b844f3a2 | blind-spots-c3 | 23:05:59 | 22,467 | 37,191 | claude-sonnet-5 |+| …3f8aaec6 | blind-spots-c4 | 23:06:23 | 22,467 | 30,857 | claude-sonnet-5 |+| …01a93707 | blind-spots-c3 | 23:10:34 | 22,467 | 37,193 | claude-sonnet-5 |+| …d34e325f | validation-c3 | 23:24:37 | 17,141 | 20,129 | claude-opus-4-8 |+| …395bfa5b | validation-c1 | 23:24:38 | 0 | 37,541 | claude-opus-4-8 |+| …c0d2fa0c | validation-c2 | 23:24:46 | 0 | 38,137 | claude-opus-4-8 |+| …a516fa44 | validation-c4 | 23:24:46 | 0 | 37,324 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **10/17** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 15s |+| review wave (perspectives) | 14m 19s |+| blind-spot sweep | 17m 38s |+| dedup (incl. combine/clean) | 58s |+| validation | 26m 15s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 31m 58s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 3 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 3 |+| 2 | 1 | review-hog-perspective-logic-correctness | 3 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 4 |+| 3 | 2 | review-hog-perspective-performance-reliability | 5 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 3 |+| 1000 | 4 | review-hog-blind-spots-general | 3 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:113-121++**`_PR_URL_RE` is not anchored to the github.com host, so lookalike domains parse as valid GitHub PR URLs**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE` = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)") is used with re.search (unanchored), so it matches "github.com/..." as a substring anywhere in the input rather than requiring it to be the actual host. A string like "https://evilgithub.com/owner/repo/pull/1" or "https://attacker.example/x?u=github.com/owner/repo/pull/1" would still match and yield owner/repo + pr_number, since "evilgithub.com" literally contains the substring "github.com". Given pr_url passed into process_inbox_pr_review can originate from a sandboxed coding agent's own TaskRun output (an untrusted-ish surface per this same product's stated trust model — "PR content is untrusted input everywhere" in products/stamphog/CLAUDE.md), the parser should not be this permissive about what counts as a GitHub URL.+- **Suggestion:** Parse with urllib.parse.urlparse and require parsed.hostname in {"github.com"} (or www.github.com) before applying a path-only regex like r"^/([^/\s]+/[^/\s]+)/pull/(\d+)$" to parsed.path, instead of a single unanchored regex over the whole URL string.+- **Validator:** - **Checked:** The only consumer of `_parse_pr_url` is `process_inbox_pr_review` (the webhook carve-out `_inbox_rereview_carve_out` uses GitHub's own `pr.html_url`, never this parser). Traced how the parsed values flow downstream and what gates them.+- **Found:** `_parse_pr_url` returns only `match.group(1)` (owner/repo) and `int(match.group(2))` (pr_number) — the URL host is discarded and never read again. In `process_inbox_pr_review`, the parsed `repository` is used solely as a lookup key: `StamphogRepoConfig.objects.for_team(team_id).using(write_db).filter(provider="github", repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="")`. The subsequent GitHub fetch uses the config's canonical name, not the URL: `StamphogGitHubClient(repo_config.installation_id).get_pr(repo_config.repository, pr_number)`.+- **Impact:** The claimed exploit produces no consequence. `https://evilgithub.com/owner/repo/pull/1` and `https://attacker.example/x?u=github.com/owner/repo/pull/1` parse to the identical `(owner/repo, 1)` a canonical github.com URL would — the lookalike host changes nothing about the extracted values. Those values then must positively match a synced+enabled, team-scoped `StamphogRepoConfig`, and the PR is fetched via the team's own App installation against the config's stored repo name. A spoofed host can neither redirect the fetch off github.com nor select an unconfigured repo. Anchoring to `hostname == "github.com"` would close no reachable path. The regex's only real trust-relevant surface — an attacker-chosen `pr_number` within an already-configured repo — is unaffected by host anchoring (a strict `github.com/<configured-repo>/pull/<n>` URL passes it too), so the suggested fix doesn't even address the adjacent concern it gestures at. This is defensive URL-parsing hygiene with no demonstrable failure scenario — a confirmed non-impact, which the precision-over-recall bar drops.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:316-321++**`bool(context.get("self_driving_review"))` uses loose Python truthiness to gate a security-sensitive bypass**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `Pipeline(0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")))` coerces the hosted-context field with Python's generic truthiness. Because this flag directly controls whether the bot-author refusal and draft-prerequisite gates are bypassed (see companion findings on review_pr.py/reviewer.py), any non-boolean truthy value would silently enable the carve-out — including a mistakenly-serialized string like `"false"`, `"0"`, or any non-empty string, all of which are truthy in Python despite reading like negatives. The docstring states this key is 'stamped by the server' and expected to default closed, but the code doesn't enforce that the value is actually the JSON boolean `true` rather than any other truthy JSON value (non-empty string, non-empty object/array, non-zero number).+- **Suggestion:** Use a strict identity check instead of bare truthiness, e.g. `self_driving=context.get("self_driving_review") is True`, so only an actual JSON `true` can enable the bypass and any malformed or unexpected value fails closed.+- **Validator:** - **Checked:** The flagged consumer (`tools/pr-approval-agent/review_local.py:321` at PR head, where `Pipeline(..., self_driving=bool(context.get("self_driving_review")))` lives), how `context` is loaded (`review_local.py:396` — `json.loads(Path(args.context).read_text())`), and every producer of the `self_driving_review` context key.+- **Found:** The value is stamped only by trusted server code and is already a real `bool` before it is serialized. `products/stamphog/backend/temporal/activities.py` (`run_review_in_sandbox`) passes `self_driving_review=bool(output.get("inbox_review"))` — explicit `bool()` coercion. `products/stamphog/backend/logic/reviewer.py` `build_reviewer_invocation(..., self_driving_review: bool = False)` types the parameter as `bool` and writes `"self_driving_review": self_driving_review` into the context dict, which is JSON-serialized. JSON round-trips a Python `bool` as `true`/`false`, so `context.get(...)` in the sandbox is always `True`, `False`, or absent (`None` for Action-shaped contexts → `bool(None)` = closed). The integration test asserts exactly this: `context["self_driving_review"] is True`.+- **Impact:** The reviewer's failure trigger — a serialized non-boolean truthy value like `"false"`, `"0"`, or a non-empty string reaching this line — cannot occur given the producer: the flag is coerced with `bool()` and passed through a `bool`-typed parameter before serialization, and the PR author (the untrusted party) controls PR content, not the server-stamped context JSON. `bool(x)` and `x is True` are therefore behaviorally identical for every value that can actually arrive here; the change is pure belt-and-suspenders hardening against a value the upstream types already rule out.+- **Impact:** Per the validation criteria this is a drop: it is a speculative "what if" (depends on an input that can't occur given the call sites and types) and defensive-coding paranoia (guarding against a malformed value upstream coercion already prevents), and the concern is "already handled" at the producer. A real "keep" needs a reachable trigger; this one has none.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected recomputed via a live cross-database call on every settings fetch**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` performs a live query into the separate stamphog product database (`has_reviewable_repo_config`) on every serialization of `ReviewUserSettingsSerializer`. Per the viewset's own docstring, this settings GET is "the Code review tab's always-called endpoint," so every tab load now pays a cross-database round trip for a value (whether a repo is connected to Stamphog) that changes rarely. It's protected by the product-DB circuit breaker and fails soft, so it won't take the endpoint down, but it still adds needless per-request latency/load to a hot path.+- **Suggestion:** Consider caching `has_reviewable_repo_config(team_id)` for a short TTL (e.g. via Django's cache framework) since repo-connection state changes infrequently, rather than hitting the stamphog DB on every settings fetch.+- **Validator:** - **Checked:** The added call `has_reviewable_repo_config(instance.team_id)` in `get_stamphog_connected` (settings.py get_stamphog_connected), its implementation in `products/stamphog/backend/facade/api.py`, the GET handler in `user_settings`, and the frontend fetch cadence in `reviewHogSettingsLogic.ts`.+- **Found:** `has_reviewable_repo_config` is a single fail-soft, circuit-broken existence query — `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` — O(1) per call, not an N+1 or unbounded scan.+- **Found:** `reviewHogSettingsLogic.ts:1043` fires `loadAll` → `loadSettings` once in `afterMount`; the only re-fetch is `updateSettingsFailure`. The 10s `setInterval` at line ~807 polls `loadRecentReviews`, not settings — so this endpoint is per-tab-load, not a polled hot path.+- **Found:** The same GET already runs `seed_canonicals_tolerantly(instance.team_id, sync_canonical_authoring)` (settings.py:110) plus a `get_or_create` on every read; a lone existence query is negligible next to that, and the trigger UI is alpha-gated to the designated ReviewHog team (viewset docstring).+- **Impact:** The consequence is marginal, fail-soft per-page-load latency the reviewer concedes "won't take the endpoint down" — it clears none of the performance bar's triggers (no N+1, no quadratic/unbounded work, no blocking async I/O, no missing index on a genuinely hot path). The suggested TTL cache would leave the toggle stuck "disabled" for the whole TTL immediately after a user connects Stamphog, trading correctness/UX for micro-latency — premature optimization. Precision over recall: drop.++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/facade/api.py:128-155++**queue_inbox_pr_review dispatches the Celery task without transaction.on_commit(), against this repo's own stated convention**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `process_inbox_pr_review.delay(...)` (line 149) fires immediately rather than being deferred via `transaction.on_commit()`. The docstring states the caller "has already resolved the acting reviewer and checked their ... toggle" right before invoking this facade — the classic shape of a post_save-style listener (per the PR description: "Saving the PR's link onto the task wakes a ReviewHog listener") that typically runs inside the same transaction as the triggering save. If that surrounding transaction later rolls back, the Celery task has already been irrevocably queued and will run against a save that never committed. CLAUDE.md's own architecture guidance explicitly names this exact anti-pattern: "Avoid performing irreversible side effects (... enqueuing Celery tasks) inside an atomic block ... Schedule such side effects after the commit, or use transaction.on_commit() for Celery task dispatch."+- **Suggestion:** Wrap the `.delay()` call in `transaction.on_commit(lambda: process_inbox_pr_review.delay(...))` inside `queue_inbox_pr_review`, so the dispatch only happens once the caller's transaction (if any) actually commits — consistent with how `_start_review_workflow` is scheduled via `transaction.on_commit` elsewhere in this same product.+- **Validator:** - **Checked:** The sole production caller of `queue_inbox_pr_review`, and how it is invoked relative to the triggering `post_save` transaction. Traced the full chain from the `handle_task_run_saved` receiver in `products/review_hog/backend/facade/inbox_hooks.py` down to `.delay()`.+- **Found:** The receiver already defers the whole thing: `if pr_url is not None and settings.stamphog_review_inbox_prs: transaction.on_commit(lambda: _start_stamphog_review(...))`. `_start_stamphog_review` is the ONLY caller of `queue_inbox_pr_review` (which calls `process_inbox_pr_review.delay(...)`), and it is invoked exclusively from inside that `on_commit` callback — there is no other call site. So the Celery dispatch fires only after the TaskRun-save transaction commits (or immediately under autocommit, which `on_commit` handles).+- **Impact:** The finding's premise — that `.delay()` "fires immediately rather than being deferred" and would run against a save that later rolled back — does not hold at the actual invocation. The deferral is correctly placed one level up, at the receiver that actually knows the transaction context; the facade is a generic programmatic entry whose docstring explicitly delegates context to the caller ("the caller has already resolved... and checked their toggle"). Adding a second `on_commit` inside the facade would be redundant defense against a hypothetical future caller that doesn't defer — speculative defensive coding, not a reachable defect. The CLAUDE.md anti-pattern it cites is already satisfied. Drop as already-handled / wrong-premise.++### [✅ VALID] should_fix · bug — products/tasks/backend/facade/api.py:509-511++**find_signal_implementation_run doesn't exclude soft-deleted tasks, so a deleted task's PR keeps getting self-driving auto-reviews**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** find_signal_implementation_run gates a positive self-driving match on `task.signal_report_id is None or task.internal` only — it never checks `task.deleted`. Task uses DeletedMetaFields/soft_delete() as its sole deletion path (Task.delete() is overridden to raise 'Cannot hard delete Task. Use soft_delete() instead.'), and Task has no custom manager that filters out deleted rows by default, so `run.task` here can resolve to a row with `deleted=True`. The underlying find_task_run (products/tasks/backend/webhooks.py) reinforces this gap: its pr_url leg and its plain-branch leg carry no `task__deleted` filter at all — only its separate wizard-head-branch leg adds `task__deleted=False`. Once a user calls soft_delete() on a signals-implementation task whose PR is still open on GitHub (e.g. they remove it from their Inbox after deciding they don't want it), `_inbox_rereview_carve_out` in products/stamphog/backend/tasks/tasks.py will keep resolving that PR as a positively identified self-driving PR on every subsequent synchronize/reopen/base-retarget webhook delivery, as long as any of its assignees still has stamphog_review_inbox_prs on. That continues to bypass the bot-author/draft/write-permission/review-mode gates and post real GitHub APPROVE reviews under the bot's identity for a task the user explicitly deleted — and since the task is gone from the Inbox UI, there is no remaining surface for the user to stop it short of disabling their own toggle or the repo config entirely.+- **Suggestion:** Add the deleted check alongside the existing internal check: `if task.signal_report_id is None or task.internal or task.deleted: return None`. This mirrors the `task__deleted=False` filter find_task_run already applies on its wizard-head-branch leg and keeps the 'positive identification only' guarantee this feature is built on from silently surviving a task's deletion.+- **Validator:** - **Checked:** `find_signal_implementation_run` body in the PR diff, the `find_task_run` legs it mirrors (products/tasks/backend/webhooks.py:30-99), the Task soft-delete model (products/tasks/backend/models.py), and whether `run.task` can resolve a deleted row.+- **Found:** `find_signal_implementation_run` gates only on `if task.signal_report_id is None or task.internal: return None` — no `task.deleted` check. Its `find_task_run` lookup filters `task__deleted=False` **only** on the wizard-head-branch leg (webhooks.py:90); the `pr_url` leg (webhooks.py:42) and the plain repository+branch leg (webhooks.py:69-77) carry no such filter. Task soft-deletes: `delete()` raises `Cannot hard delete Task` (models.py:486-487) and `soft_delete()` just sets `deleted=True` and saves (models.py:476-479), so the row persists. Task declares no default manager overriding `objects` (none between the class def at models.py:115 and :476), and `find_task_run` pulls the task via `select_related`, which JOIN-fetches the row regardless of any manager filtering — so `run.task` resolves a `deleted=True` task.+- **Impact:** After a user soft-deletes a signals-implementation task whose bot-authored draft PR is still open, `find_signal_implementation_run` still returns a positive DTO (signal_report_id set, non-internal), so stamphog's `_inbox_rereview_carve_out` keeps positively identifying that PR on every subsequent head-changing delivery (synchronize / reopen / base-retarget) — including pushes from a run that soft_delete never stopped. That bypasses the bot-author/draft/write-permission/review-mode pre-filters and can post a real GitHub APPROVE under the bot identity for a task the user explicitly deleted, with the task gone from the Inbox leaving no surface to stop it short of flipping the toggle or repo config off. Concrete trigger, concrete consequence, touching this product's 'positive identification only' and stale-approval invariants; the fix is a one-line mirror of the filter `find_task_run` already applies on its wizard leg, so it is not overengineering or a speculative edge. Meets the keep bar.++### [❌ dismissed] must_fix · documentation — products/stamphog/AGENTS.md:84-87++**Carve-out identification criterion says "non-internal" TaskRun, which appears to invert the actual `internal` flag semantics**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new section identifies the self-driving carve-out target as "a non-internal, signal-report-carrying TaskRun matched through the tasks facade" (line 85). But everywhere else in the codebase the `internal` boolean on `Task`, `Loop`, and `SandboxEnvironment` (products/tasks/backend/models.py:229-231, 1336-1338, 2499-2501) is documented as meaning "created by a backend flow ... not exposed to end users", and products/tasks/backend/facade/loops.py:746-748 explicitly says `internal=True` loops are "created by a backend flow (e.g. signals scheduling a one-off PR follow-up)" — i.e. exactly the self-driving/signals-triggered scenario this PR carves out. products/tasks/backend/logic/repo_selection/agent.py passes `internal=True` together with `signal_report_id=signal_report_id` for that same repo-selection flow. This also matches the PR's own description of the change: "The listener now checks 'internal' tasks" (Case 1, step 3) — not 'non-internal'. Wizard/manual (user-facing) tasks are the `internal=False` ones. As written, the doc tells a future maintainer to gate the exception on the opposite condition from what the rest of the codebase (and the PR description) establishes, for a check whose entire purpose is keeping a bot-author-refusal bypass narrow.+- **Suggestion:** Change "a non-internal, signal-report-carrying TaskRun" to "an internal, signal-report-carrying TaskRun" (or otherwise reconcile with the `Task.internal` / `Loop.internal` semantics), and verify against the actual linkage-check implementation before merging — this is a security-relevant invariant document and an inverted condition here would mislead whoever next touches this gate.+- **Validator:** - **Checked:** The actual identification code on both trigger legs — `products/review_hog/backend/receivers.py:80-88` (the Celery receiver) and the tasks-facade matcher added by this PR (`gh pr diff` lines 1701-1718, plus its parameterized test at 1841) — against the `Task.internal` semantics the reviewer cites (`products/tasks/backend/models.py:229`, `facade/loops.py:746`, `repo_selection/agent.py:467-469`).+- **Found:** The receiver skips internal tasks and reviews only non-internal ones: `receivers.py:88` is `if task.internal: return`, and its comment at `receivers.py:84-87` states plainly "...all created internal=True; the auto-start implementation task is the only **non-internal** signal-report task." The PR's own facade matcher agrees — its docstring reads "a non-internal task carrying a signal report" and it early-returns on `if task.signal_report_id is None or task.internal:`; the test `("internal_pipeline_task", {"internal": True}, {})` asserts an internal task is NOT matched. So the reviewed implementation task is `internal=False`.+- **Found:** The reviewer's cited counter-evidence (`repo_selection/agent.py` passing `internal=True` with `signal_report_id`) is precisely one of the "internal plumbing tasks (report research, repo selection, custom agents)" the receiver comment says to skip — not the PR-opening implementation task. The reviewer conflated the two.+- **Impact:** The doc phrase "a non-internal, signal-report-carrying TaskRun matched through the tasks facade" is accurate and matches both implementation paths. Applying the suggested edit (change to "an internal ... TaskRun") would make this security-relevant invariant doc contradict the code — the opposite of the reviewer's intent. The premise is mistaken ("Wrong / unreproducible" per the criteria), so this does not meet the bar.++### [✅ VALID] must_fix · compatibility — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9++**New migration branches off a stale point in the migration graph, colliding with an already-merged 0019**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This new migration is numbered 0019 and declares `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]`. On the target branch, review_hog's migration graph has already advanced well past that point (the app's `max_migration.txt` tracker — the django-linear-migrations linear-history marker — records `0024_reviewreport_published_head_shas` as the current head), and a different migration already named `0019_reviewreport_author_login_and_more.py` also depends on 0018 and is already merged. Two sibling migrations sharing the number "0019" and both branching off 0018 is a migration-graph conflict: it indicates the branch wasn't rebased before the migration was generated, and it will fail the linear-migrations check (or at best apply in a non-deterministic/confusing order) rather than cleanly extending the current head.+- **Suggestion:** Rebase onto the current review_hog migration head, delete/regenerate this file so its `dependencies` points at the actual current leaf (`0024_reviewreport_published_head_shas` or later after rebase), and renumber the file to the next free sequence (e.g. `0025_reviewusersettings_stamphog_review_inbox_prs.py`). Regenerate via `python manage.py makemigrations` after rebasing instead of hand-editing the dependency, and update `max_migration.txt`.+- **Validator:** - **Checked:** review_hog's migration graph on the target branch (`git show master:.../max_migration.txt` and `git ls-tree master` on the migrations dir), the dependency of the already-merged 0019, whether django-linear-migrations is active, and CI enforcement.+- **Found:** master's `max_migration.txt` = `0024_reviewreport_published_head_shas`, and `0019_reviewreport_author_login_and_more.py` already exists on master with `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]` — the identical parent the PR's new `0019_reviewusersettings_stamphog_review_inbox_prs.py` declares (both branch off 0018 as sibling 0019s).+- **Found:** the PR's own `max_migration.txt` diff goes `0018 → 0019_reviewusersettings_stamphog_review_inbox_prs`, i.e. its pre-image is 0018 not 0024 — the branch was generated on stale master before 0019–0024 landed.+- **Found:** `django-linear-migrations~=2.17.0` is installed (`pyproject.toml:219`, `posthog/settings/web.py:207`) and migrations are validated in `.github/workflows/ci-backend.yml`; its single-linear-leaf invariant is violated by two 0019 leaves off 0018, and `max_migration.txt` conflicts on merge (master 0024 vs PR 0019).+- **Impact:** Confirmed, non-speculative merge/deploy break: the linear-migrations check fails and the migration graph forks; the fix is to rebase onto the current head and renumber to the next free sequence (0025+). Correctly rated must_fix.++### [❌ dismissed] consider · security — products/review_hog/backend/receivers.py:144-156++**Cross-product hook trusts caller-supplied team_id/signal_report_id with no verification tying them to the PR being re-reviewed**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered as a raw callback in Stamphog's inbox hook registry and is invoked directly by Stamphog's webhook path with a `team_id`/`signal_report_id` pair to decide whether to re-review a pushed PR update. The function trusts these identifiers outright: it queries `SignalReportArtefact` and `ReviewUserSettings` scoped to whatever `team_id` it is handed, with no assertion that the pull request Stamphog is about to re-review actually belongs to that team or signal report. Because this crosses a product boundary through a bare function reference rather than a validated request/response contract (contrast with the DTO-based `facade/api.py` pattern used elsewhere in stamphog), a mismatch on the Stamphog side between the PR being processed and the `team_id`/`signal_report_id` passed in would cause this hook to silently resolve and act on a different team's reviewer settings.+- **Suggestion:** Have the resolver (or the call site that invokes it) assert that the PR/webhook event being processed is actually associated with the given `team_id` and `signal_report_id` before consulting `ReviewUserSettings`, or at minimum document this precondition prominently where the hook is registered so future changes on the Stamphog side can't violate it unnoticed.+- **Validator:** - **Checked:** The actual Stamphog-side call site of the registered resolver (`_inbox_rereview_carve_out` in stamphog's PR event path), the `find_signal_implementation_run` tasks-facade it derives identifiers from, and the resolver's own query scoping in `receivers.py`.+- **Found:** The resolver is not handed arbitrary caller identifiers. `team_id` = `repo_config.team_id`, resolved from the GitHub App `installation_id` + repo (positively identified). `signal_report_id` = `run.signal_report_id` from `find_signal_implementation_run(team_id=repo_config.team_id, repository=repo, pr_url=..., head_branch=...)`, which matches the run to _this exact PR_ (`find_task_run` on pr_url/branch) and enforces `if run is None or run.team_id != team_id: return None`. The carve-out then re-asserts `run.team_id != repo_config.team_id` (belt-and-braces) and applies fork-safety (`head_repo == repo`) before calling `resolver(repo_config.team_id, str(run.signal_report_id), run.task_created_by_id)`.+- **Found:** The resolver queries are internally single-team-consistent — `SignalReportArtefact.filter(team_id=team_id, report_id=signal_report_id, ...)`, `resolve_org_github_login_to_users(team_id, ...)`, `ReviewUserSettings.load(team_id, ...)`. A hypothetical mismatched (team A, report B) pair finds no artefact (report B isn't team A's) and returns None; it cannot "act on a different team's reviewer settings."+- **Found:** The precondition the reviewer asks to document already is: the `_inbox_rereview_carve_out` docstring ("positive identification only ... a tasks-facade match for this exact repo, scoped to the config's team") and the facade docstring ("team scoping is enforced here ... no caller can accidentally bind a PR to another tenant's run"), plus the explicit recheck comment.+- **Impact:** Premise is mistaken and the tenant-isolation concern is already handled by call-site positive identification + team-scope recheck + fork safety + the resolver's consistent single-team scoping. Falls under the drop list (wrong/unreproducible, already-handled, speculative what-if). No IDOR is reachable.++### [❌ dismissed] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1245++**process_inbox_pr_review grants self-driving bypass on caller-supplied data with no independent verification**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** process_inbox_pr_review is the function that actually mints "inbox_review" provenance on a ReviewRun — the single fact that later causes the sandbox engine to bypass its bot-author/draft refusal (self_driving_review=True in reviewer.py/activities.py) and causes the webhook path (`_inbox_rereview_carve_out`) to skip the bot_author, draft, untrusted_author_association, review_mode, and author-write-permission gates on subsequent deliveries. Unlike its sibling `_inbox_rereview_carve_out` (same file), which independently re-derives self-driving status on every later webhook delivery by calling find_signal_implementation_run (team-scoped) and checking pr.head.repo.full_name against the base repo (fork safety) and `_is_bot_authored(pr)`, process_inbox_pr_review performs none of these checks. It only: (1) resolves a repo_config for team_id + the repository parsed out of the caller-supplied pr_url, and (2) fetches the PR from GitHub. It never calls find_signal_implementation_run to confirm task_run_id/signal_report_id actually correspond to a real, team-scoped signals-implementation TaskRun tied to this exact PR, never checks `_is_bot_authored(pr)`, and never checks the PR's head repo is non-fork. The signal_report_id, task_run_id, and acting_user_id parameters are copied verbatim into the stored `inbox_review` dict with zero server-side validation against the database. This means the entire security guarantee this feature is built on ("positive identification only" — see products/stamphog/CLAUDE.md and this same file's `_inbox_rereview_carve_out` docstring) is enforced only by an out-of-chunk caller (review_hog's receiver) with no defense-in-depth at the trust boundary this Celery task actually represents (a fire-and-forget async entry point, decoupled from the request that queued it). A bug in the caller, a future caller that skips the same rigor, or a compromised/misbehaving agent run that reports an unexpected pr_url in TaskRun.output would cause a real GitHub review (potentially an APPROVE) to be posted on a PR that was never verified to be a genuine self-driving bot-authored, non-fork PR belonging to that task.+- **Suggestion:** Before creating the ReviewRun, call find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url) and verify the returned run's run_id/signal_report_id match the task_run_id/signal_report_id parameters (bail with a warning log if they don't). Also check `_is_bot_authored(pr)` and that `pr['head']['repo']['full_name']` equals repo_config.repository (case-insensitive) before proceeding, mirroring `_inbox_rereview_carve_out`'s checks. This makes the initial receiver leg fail closed the same way later deliveries already do, instead of trusting the Celery payload outright.+- **Validator:** - **Checked:** What the stored `inbox_review` provenance actually drives downstream, the sole call path into `process_inbox_pr_review`, and the origin/trust of the `pr_url` argument. Traced `_inbox_rereview_carve_out`, `activities.py`'s `self_driving_review` derivation, the `review_hog` receiver, and `output.pr_url` write paths.+- **Found:** The webhook carve-out re-derives self-driving status independently on every later delivery — `find_signal_implementation_run` (team-scoped) + head-repo fork check + `_is_bot_authored` (diff L907-928) — and stamps a fresh `{"trigger": "webhook"}` provenance (diff L927-928, L962-966). It never consults the `inbox_review` provenance `process_inbox_pr_review` wrote, so that provenance drives only the initial run's own engine flag (diff L777: "only a run stamped with inbox provenance turns it on"), not any cross-delivery gate-skip. The finding's stated impact — stored provenance causing the webhook path to skip gates on subsequent deliveries — does not hold.+- **Found:** The only caller is `review_hog`'s receiver via `_start_stamphog_review` → `queue_inbox_pr_review`, which fires solely for a signals-implementation TaskRun (origin signal_report) whose acting reviewer has `stamphog_review_inbox_prs` on, passing that run's own `output.pr_url`. That field is written from verified GitHub webhook `html_url` (products/tasks/backend/webhooks.py:137,229) or the bot's own opened PR — i.e. a real bot-authored PR in the team's Stamphog-enabled repo, bound to the run. The `signal_report_id`/`task_run_id`/`acting_user_id` args are stamped verbatim into `output` as provenance/analytics only (diff L1107-1112, L1200) and gate no security decision on this leg, so their lack of validation is inert.+- **Impact:** As actually reached, the initial leg self-driving-reviews exactly the bot-authored draft PR its signals run opened in an enabled, team-scoped repo — the intended behavior. The named triggers are a caller bug and a hypothetical future caller (speculative future-proofing) or a "misbehaving agent forging pr_url" that would still resolve to a bot-authored PR in the team's own repo via verified sourcing — no demonstrated path to an APPROVE on a non-self-driving PR. Positive identification is already enforced by the parent caller, which the validation bar treats as "already handled." This is reasonable defense-in-depth hardening at an async boundary, not a reachable defect, so under precision-over-recall it does not meet the keep bar.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_pr.py:195-209,225-225,587-590++**Draft-PR gate bypass is keyed on a bare `self_driving` flag, not on verified bot authorship**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self_driving` disables two hard security gates — the bot-author refusal (`run()`, `if self.pr.author_is_bot and not self.self_driving`) and the draft prerequisite (`_check_prerequisites`, `if pr.draft and not self.self_driving`) — but the draft-gate relaxation at line 590 is conditioned on `self.self_driving` alone, with no local re-check that `self.pr.author_is_bot` (or repo/fork identity) is actually true. `_refuse_bot_author`'s own docstring frames the bot-author check as 'the defense-in-depth layer for any manual or out-of-band invocation' precisely because upstream gating (a workflow condition, a label) can't be fully trusted. This chunk removes exactly that layer for the draft check based purely on a caller-supplied boolean, with the only real corroboration (verifying the PR is genuinely bot-authored, same-repo, non-fork) living entirely outside this chunk in an unaudited background job. If `self_driving` is ever true when the PR is not actually a verified bot-authored Inbox PR — a bug in that upstream job, stale/replayed context data, or a human pushing directly to the bot's branch (PR intent Case 2) — a still-draft PR skips the draft gate entirely with no local safeguard.+- **Suggestion:** Derive the effective carve-out from `self.pr.author_is_bot and self.self_driving` at the single point they're combined (e.g. in `_classify()` or as a computed property), rather than trusting the caller-supplied `self.self_driving` alone at each gate site. That way a flag that arrives true for a non-bot-authored PR can never independently unlock the draft-prerequisite bypass.+- **Validator:** - **Checked:** The two gates in `tools/pr-approval-agent/review_pr.py` that `self_driving` relaxes (bot-author refusal at line 225 `if self.pr.author_is_bot and not self.self_driving`, draft gate at line 590 `if pr.draft and not self.self_driving`), and every path that can set `self_driving=True` — both upstream stamping legs in `products/stamphog/backend/tasks/tasks.py` and `products/stamphog/backend/temporal/activities.py`.+- **Found (webhook / Case-2 leg):** `_inbox_rereview_carve_out` sets the `inbox_review` provenance (which becomes `self_driving_review=bool(output.get("inbox_review"))`) only after a local `if not _is_bot_authored(pr): return _InboxCarveOut()` check (diff line 887), a fork-safety check that `head_repo == repo` (line 891-897), a team-scoped task-linkage match, and a belt-and-braces `run.team_id != repo_config.team_id` recheck. So on the re-review leg `self_driving=True` implies `author_is_bot=True`, re-verified on every head-changing push — exactly the Case 2 the finding worries about.+- **Found (receiver / initial leg):** `process_inbox_pr_review` fires only when a PostHog Code signals implementation run saves its own PR link (AGENTS.md: it "opens its (bot-authored, draft) PR"); the PR is bot-authored by construction of who opened it.+- **Impact:** The proposed `author_is_bot and self_driving` guard only changes behavior when `self_driving=True` while `author_is_bot=False`, and no non-buggy path produces that state. The finding's one concrete trigger — "a human pushing directly to the bot's branch (Case 2)" — does not produce it: GitHub PR authorship stays the bot (the opener), so `author_is_bot` remains True and the suggested guard would still evaluate True, i.e. the fix does not address its own example, which is meanwhile re-verified by the webhook leg. The remaining triggers ("a bug in that upstream job, stale/replayed context data") are speculative upstream-bug hypotheticals, and replays are already guarded by the `payload_updated_at` stale-snapshot recheck and `select_for_update` dedupe.+- **Impact:** Even in the hypothesized state the differential is mild: the draft gate is a "reviewing one now is wasted" policy gate (per `_review_skip_reason`'s draft comment), not a hard security boundary; the true security backstop — the bot-author refusal — is retained at line 225, and any resulting review still passes through all other prerequisites and the LLM verdict. Per the criteria this is defensive-coding paranoia against an upstream invariant the stamping code already enforces, with no nameable reachable trigger — a drop under precision-over-recall.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/reviewer.py:506-506,568-568,683-703++**Reviewer prompt asserts "the author is a machine user" without checking `author_is_bot`, weakening scrutiny if the flag is ever set for a non-bot PR**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_format_self_driving` renders its TRUSTED provenance block purely from `cl.get("self_driving")` and tells the LLM reviewer, as fact, that 'the author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here' and that 'draft state is not a caution signal for this PR' — without cross-checking `pr.author_is_bot`. This block sits in the TRUSTED section of the prompt (not the untrusted region), so the model is instructed to weight it as ground truth. If `self_driving` is ever true for a PR that isn't genuinely bot-authored (see companion finding on review_pr.py's decoupled draft-gate bypass), the reviewer is actively told to discount legitimate human-authorship signals and to disregard the draft state as a caution signal for what may be human-controlled, unreviewed code — the opposite of the intended effect.+- **Suggestion:** Gate `_format_self_driving`'s output (and/or the `self_driving` value written into `classification` in review_pr.py's `_classify()`) on `pr.author_is_bot` being true as well, so the provenance narrative can only ever be shown for PRs the engine itself confirms are bot-authored.+- **Validator:** - **Checked:** `_format_self_driving` in `tools/pr-approval-agent/reviewer.py` (PR-head lines 683-701) and what feeds its only condition, `cl.get("self_driving")`. The classification value comes from `review_pr.py::_classify()` writing `"self_driving": self.self_driving` (diff line 477) — i.e. the identical `self.self_driving` flag that guards the two deterministic gates, so the prompt block appears under exactly the same condition, and the reachability of "self_driving true for a non-bot PR" is the same question already answered.+- **Found:** No non-buggy path produces `self_driving=True` with `author_is_bot=False`. The webhook re-review leg stamps provenance only after a local `if not _is_bot_authored(pr): return` check (`products/stamphog/backend/tasks/tasks.py`, diff line 887) plus fork-safety and task-linkage checks; the receiver leg fires only for a signals implementation run's own bot-authored draft PR by construction. This finding inherits that same unreachable precondition from companion finding 1-3-1.+- **Impact:** The flagged text is a natural-language nudge in the LLM prompt, not a control — the real approve/refuse/draft decisions are the deterministic gates in `review_pr.py` (bot-author refusal at line 225, draft gate at line 590), which are unaffected by prompt wording. Even reached erroneously, the block is deliberately scrutiny-preserving: it says the provenance is "not an endorsement of the diff," to "judge the diff strictly on its own merits," and to treat the PR body "as untrusted author text"; only the single "draft state is not a caution signal" line is scrutiny-reducing, and only conditioned on the same upstream bug that the stamping paths rule out.+- **Impact:** This is a speculative what-if layered on an already-speculative precondition, one step further removed (soft prompt framing rather than a hard gate). Per the criteria — speculative/defensive-paranoia, already handled upstream, no nameable reachable trigger — it is a drop under precision-over-recall.++### [❌ dismissed] should_fix · documentation — products/review_hog/backend/receivers.py:17-24,114-139,144-160++**Stamphog toggle is gated by one resolved acting reviewer, not "at least one of the assigned users" as described**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The PR states Stamphog should review an Inbox PR when "at least one of the assigned users has `stamphog_review_inbox_prs` enabled," and Case 3 describes multiple opted-in people needing to switch it off ("the people who opted in switch it off") before review stops. The implementation doesn't do that OR-across-reviewers check: both the inline check in `handle_task_run_saved` (settings loaded for the single `acting_user_id`) and the new `resolve_stamphog_acting_reviewer` call `_resolve_assigned_reviewer`, which collapses the full set of resolved reviewers down to exactly one "acting" user (the task creator if they're among the resolved reviewers, else just the first resolved reviewer) and checks only that one person's toggle. If a report has multiple assigned reviewers and the acting one (task creator, or first-in-list) has the toggle off while a different assigned reviewer has it on, Stamphog never runs — and per Case 3, turning off just the acting reviewer's toggle silences Stamphog even while another explicitly opted-in reviewer still wants it on.+- **Suggestion:** Reconcile the code with the stated intent: either (a) update the PR description/docstrings to make explicit that only the single canonical acting reviewer's Stamphog preference is honored (matching the existing `review_inbox_prs` precedent), or (b) change the gating to OR the toggle across every resolved reviewer, e.g. `any(ReviewUserSettings.load(team_id, u.id).stamphog_review_inbox_prs for u in resolved)` in both `handle_task_run_saved` and `resolve_stamphog_acting_reviewer`, so "at least one of the assigned users" is actually what triggers/keeps the review running.+- **Validator:** - **Checked:** `_resolve_assigned_reviewer`, `resolve_stamphog_acting_reviewer`, and the two gating legs in `handle_task_run_saved`, plus their docstrings and the PR's new tests, to decide whether single-acting-reviewer gating is a defect or intended.+- **Found:** The code deterministically gates on one canonical acting reviewer — `acting = next((u for u in resolved if u.id == task_created_by_id), resolved[0])` — and this is a documented, deliberate policy: the docstring cites "maintainer decisions, 2026-07-02/03" for "the **first** resolved reviewer is canonical" and states "Their `review_inbox_prs` / `stamphog_review_inbox_prs` toggles gate the respective reviews." The new toggle intentionally mirrors the pre-existing `review_inbox_prs` single-reviewer model (same shared resolver), and the PR's tests assert exactly this single-reviewer gating — there is no OR-across-reviewers test.+- **Found:** Code, function name (`_resolve_assigned_reviewer`, singular), docstrings, and tests all agree on single-acting-reviewer; the only thing that disagrees is the imprecise PR-description prose ("at least one of the assigned users"). PR description bodies are ephemeral and not part of the maintained codebase.+- **Impact:** No code defect — behavior is intentional, documented, tested, and consistent with the established `review_inbox_prs` precedent; the "multiple divergent toggles" case is handled by deliberate policy, not mishandled. The actionable core reduces to rewording a PR blurb (the reviewer's own option (a)), which doesn't meet the correctness/contract bar. On the fence → drop (precision over recall). The reviewer even concedes the code follows a sensible existing precedent.++### [❌ dismissed] should_fix · bug — products/review_hog/backend/receivers.py:210-236++**No evidenced idempotency guard on the Stamphog dispatch against repeat TaskRun saves**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The module docstring explains repeat `TaskRun` saves with an unchanged target deliberately re-fire this receiver, and that the ReviewHog leg tolerates this because `start_review_pr_workflow` uses a deterministic workflow id + `USE_EXISTING` to collapse duplicates ("a same-head re-trigger costs one fetch"). `_start_stamphog_review` has no equivalent dedup mentioned — it's documented only as "a plain toggle-gated dispatch" that queues a Celery task via `queue_inbox_pr_review`. Since `handle_task_run_saved`'s early-exit only checks whether `output` was _included_ in `update_fields`, not whether its content changed, a TaskRun can legitimately be saved multiple times with the same `pr_url` still present, each re-entering this branch and re-queuing the Stamphog review — risking duplicate GitHub approvals/comments posted against the same commit.+- **Suggestion:** Verify that `queue_inbox_pr_review` (or the task it enqueues) dedupes on something like `(pr_url, head_sha)`/`task_run_id` before posting a review, mirroring the Temporal `USE_EXISTING` protection on the ReviewHog leg. If it doesn't already, add that guard so redundant `TaskRun` re-saves for the same commit don't produce duplicate Stamphog reviews.+- **Validator:** - **Checked:** The full dispatch chain the finding is about — `_start_stamphog_review` → `queue_inbox_pr_review` → the queued Celery task `process_inbox_pr_review` in stamphog's `tasks/tasks.py`, which the reviewer did not read (they flag it as "no equivalent dedup _mentioned_" and ask to "Verify").+- **Found:** `process_inbox_pr_review` resolves the PR's current `head_sha` from GitHub, then under `transaction.atomic()` + `select_for_update()` (row lock serializing racing fires) looks up `ReviewRun.objects.for_team(team_id).filter(pull_request=pr_obj, head_sha=head_sha).exclude(status__in=(SUPERSEDED, FAILED))`. An existing run at that head returns early (`stamphog_inbox_pr_already_reviewed`) — at most restarting a stranded `QUEUED` run's workflow (the start is idempotent), never creating a new run or re-posting. A new run is created only when none exists at the current head.+- **Found:** This is exactly the `(pull_request, head_sha)` dedup the suggestion asks for, mirroring the ReviewHog leg's `USE_EXISTING`, plus a stale-snapshot guard (`payload_updated_at`) so an older re-fire can't supersede a newer webhook-delivered review. The PR ships tests for the path (an already-reviewed run row; `test_inbox_receiver_leg_stale_fetch_does_not_supersede_a_newer_run`).+- **Impact:** Repeat TaskRun saves carrying the same `pr_url` resolve to the same head, hit the existing-run no-op, and produce no duplicate GitHub approval/comment. The premise (no idempotency guard) is mistaken and the risk is already handled — drop per precision-over-recall.++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1110-1115,1157-1163,1176-1180++**Initial inbox review never re-checks the reviewer's opt-in toggle, even though the task anticipates long execution delays**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `process_inbox_pr_review`'s docstring (and `queue_inbox_pr_review`'s, in facade/api.py) states the acting reviewer's `stamphog_review_inbox_prs` toggle was already confirmed by `review_hog`'s receiver _before_ the task was enqueued, and the task trusts that decision for the rest of its run — `acting_user_id` is stamped straight into `inbox_review` (lines 1176-1180) and used unconditionally to create the ReviewRun and kick off the sandbox review/GitHub verdict. But the same function explicitly anticipates the run being delayed well past that enqueue-time check: it retries up to 3 times, and a GitHub rate limit on the PR fetch schedules a retry with `countdown=max(e.retry_after or 0, 60)` (line 1162) — i.e. at least a full minute, potentially several retries deep. Celery broker/worker backlog can add more. If the acting reviewer flips `stamphog_review_inbox_prs` off during that window, the task still runs to completion using the stale `acting_user_id`, reviewing (and potentially posting a real GitHub APPROVE for) a bot-authored draft PR the user just opted out of reviewing. Contrast this with the later-delivery path: `_inbox_rereview_carve_out` (same file) explicitly re-resolves the toggle via `get_inbox_acting_reviewer_resolver()` on every webhook delivery specifically because preferences can change mid-PR — the initial receiver leg has no equivalent re-check despite being just as capable of running long after the decision was made.+- **Suggestion:** Before creating the ReviewRun (around line 1176), re-resolve the opt-in via the same `get_inbox_acting_reviewer_resolver()` already imported in this module (mirroring `_inbox_rereview_carve_out`'s pattern), and bail (logging + returning, same shape as the opted-out skip path) if the resolver now returns None. This needs `task_created_by_id` threaded through as an extra parameter on `queue_inbox_pr_review`/`process_inbox_pr_review` (the resolver's third argument), since it isn't currently passed to this task.+- **Validator:** - **Checked:** The design model for the toggle vs. safety, what end-state a mid-window opt-out actually produces, and whether the stale-approval invariant is touched. Read the PR's own AGENTS.md/carve-out docstrings and the opt-out skip path.+- **Found:** The toggle is explicitly a preference, not a safety gate, and safety is handled on a separate axis: diff L639-642 "Dismissal is never preference-gated. A toggle switched off mid-PR stops new runs, but the skip paths' head-changing retraction still voids the standing approval"; diff L880-883 "a ready_for_review flip alone doesn't invalidate the draft-time verdict — a head-pinned approval granted on the draft takes effect when the PR flips to ready. A toggle switched off mid-PR lands in the caller's skip path, whose head-changing retraction still dismisses the stale approval — safety is never preference-gated." The opt-out skip path dismisses via `_INBOX_OPT_OUT_DISMISS_MESSAGE` on the next head-changing delivery (diff L979).+- **Found:** The factual basis is correct — `process_inbox_pr_review` doesn't re-resolve the toggle and can run minutes late (rate-limit `countdown=max(e.retry_after or 0, 60)`, up to 3 retries), and the later-delivery carve-out does re-resolve. But the later re-check exists because those deliveries fire at arbitrary future times (days later on a push), whereas the initial leg runs immediately after enqueue.+- **Impact:** The mid-window opt-out produces an approval over a commit Stamphog actually reviewed (no stale-approval-invariant violation), which then stands on the draft until the next head-changing event and is dismissed there by the opted-out skip path — the identical end-state the design already produces and tolerates for an approval granted _before_ opt-out (draft approvals stand until the next push regardless). So the missing re-check only means the review ran on a preference read stale by seconds-to-minutes, closing a narrow race whose outcome the design intentionally accepts and whose safety is handled independently. This is a minor preference-timing consistency nuance, not a reachable correctness or security defect, and falls below the keep bar under precision-over-recall.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:1176-1180,1202-1230++**Duplicate-ReviewRun guard in process_inbox_pr_review has no protection of its own — it silently depends on an incidental side effect that can be bypassed**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The comment above the `existing = (...)` dedupe query (line ~1200) claims "the row lock serializes racing fires," but `select_for_update()` (line 1205) only locks rows that already exist — it cannot prevent two concurrent invocations of this task (which the function's own docstring says can happen, since "the receiver re-fires on every TaskRun output save") from both seeing `existing is None` and both calling `_supersede_prior_runs` + `ReviewRun.objects.create(...)` for the same head_sha, unlike the webhook path which has a `delivery_id` unique constraint (`IntegrityError`-backed) as an explicit backstop — this task always creates with `delivery_id=None`. In practice this race is usually closed by a different mechanism: `_upsert_pull_request` (called just above, line ~1177) performs a conditional `UPDATE ... WHERE payload_updated_at <= incoming`, which takes a genuine Postgres row lock on the PullRequest row for the rest of the transaction and thereby serializes concurrent callers. But that protection depends entirely on `pr.get("updated_at")` being present and parseable — `_upsert_pull_request` has an explicit early return (`if incoming_updated_at is None: return pr_obj`) that skips the UPDATE (and therefore the lock) entirely when GitHub's payload doesn't carry a usable timestamp. In that case, two concurrent fires can both fall through the (now-unlocked) `_upsert_pull_request` call, both see no `existing` ReviewRun, and both create one — duplicate sandbox runs and duplicate GitHub review posts under the bot's identity for the same commit.+- **Suggestion:** Don't rely on an unrelated function's conditional-update side effect for correctness here. Take an explicit `select_for_update()` on the `pr_obj`/PullRequest row (or an equivalent advisory lock keyed on `pull_request_id`) at the start of the transaction, before the staleness check and the `existing` dedupe query, so serialization no longer depends on whether `_upsert_pull_request`'s WHERE clause happens to match.+- **Validator:** - **Checked:** `ReviewRun` model constraints (products/stamphog/backend/models.py:140-170), `_upsert_pull_request`'s locking and its `incoming_updated_at is None` early return (tasks.py:229-248), the serialization mechanism the webhook path documents, and whether `get_pr`'s payload can lack `updated_at`.+- **Found:** The reviewer's mechanism reading is correct: `ReviewRun` has no unique constraint on `(pull_request, head_sha)` — only `delivery_id` is unique (models.py:145), and the inbox path passes `delivery_id=None`, so there's no DB backstop; `select_for_update()` locks nothing when no row exists; and serialization of concurrent same-PR fires genuinely rests on `_upsert_pull_request`'s conditional UPDATE taking the PullRequest row lock (the webhook path's own comment at tasks.py:894-898 states this explicitly). The `incoming_updated_at is None` branch (tasks.py:231-233) does skip that UPDATE and its lock.+- **Impact:** The duplicate-creation outcome is gated on `incoming_updated_at is None`, i.e. `parse_datetime(pr.get("updated_at") or "")` returning None where `pr` is a successful `get_pr` fetch. GitHub's pull-request REST object always carries a non-null ISO-8601 `updated_at`, and Django's `parse_datetime` parses it — so a real fetch never yields None. For every realistic input (`updated_at` present), the PR-row lock serializes concurrent fires exactly as the comment claims (second fire blocks on the UPDATE, then finds the first fire's committed ReviewRun in the dedupe query and returns), and the `created` path serializes via the PullRequest unique constraint. The concrete duplicate-sandbox-run / duplicate-approval consequence therefore requires a GitHub payload shape that does not occur — a practically-unreachable edge case. What remains is a maintainability observation (implicit reliance on another function's side effect), not a reachable defect, which falls below the keep bar even at `consider`.++### [❌ dismissed] must_fix · bug — tools/pr-approval-agent/review_pr.py:202-209,475-477++**Self-driving carve-out doesn't guard author-familiarity computation for bot authors, producing a misleading trust signal**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self_driving flag is designed to replace human-author trust signals with task provenance (per reviewer.py's new `_format_self_driving`, which explicitly states 'author familiarity, org membership, and merged-PR history carry no signal here'). But nothing in this chunk stops the pre-existing author-familiarity machinery from still running for a self-driving (bot-authored) PR: run() calls `_maybe_compute_familiarity()` unconditionally (unaffected by self.self_driving), which calls compute_familiarity(author_login=pr.author, ...) with pr.author being the bot's own login. familiarity.py's compute_familiarity fetches the bot's own merged-PR numbers via `gh pr list --author <bot>` and checks git-blame overlap against them. Since a self-driving automation bot plausibly merges many PRs that repeatedly touch the same directories/files (that's the nature of an Inbox task agent), blame_overlap_pct or prior_prs_in_paths can realistically cross the STRONG/MODERATE thresholds in `_band()` (familiarity.py:408-425). Two consumers then surface this bogus signal without any self_driving guard: (1) reviewer.py's `_format_familiarity` renders it into the TRUSTED prompt block immediately before the newly-added self_driving_block, so the LLM reads a concrete 'author familiarity: band STRONG...' fact followed by an instruction saying that exact kind of fact 'carries no signal here' — a direct in-prompt contradiction; (2) review_pr.py's `_render_review_body()` (unchanged, ~lines 855-860) unconditionally appends 'Author wrote X% of the modified lines and has N merged PRs in these paths (familiarity {band}).' to the actual GitHub comment posted for humans to read — this reads exactly like a positive human-competency endorsement, but for a self-driving PR it really just means 'the bot has touched this code before in other automated PRs,' which is a fundamentally different (and much weaker, arguably circular) signal than what familiarity was built to measure. This directly undermines the stated design goal of the carve-out: replacing human trust signals with task provenance, not leaving a channel where fake human-like trust data still leaks into the human-facing approval comment.+- **Suggestion:** Gate familiarity computation/consumption on self_driving. Either (a) skip computing familiarity for self-driving PRs entirely in `_maybe_compute_familiarity()` (e.g. `if self.self_driving: self.familiarity = None` instead of calling `_compute_familiarity()`), or (b) keep computing it for telemetry but never attach it to self.classification['familiarity'] when self.self_driving is True, and add the same guard to `_render_review_body()`'s bullet (`if fam is not None and fam.band in (...) and not self.self_driving`). Also apply the equivalent guard in review_local.py's `_attach_familiarity()`, which has the identical unconditional call path for the offline/sandbox entrypoint.+- **Validator:** - **Checked:** Which `run()` actually handles self-driving PRs, whether familiarity is computed there, and both consumers (`reviewer.py::_format_familiarity`, `review_pr.py::_render_review_body`).+- **Found (wrong entrypoint):** Self-driving PRs never go through `review_pr.py::Pipeline.run()`. The Action CLI builds the pipeline at `review_pr.py:984` without `self_driving` (always False there), and that `run()` refuses bot authors at line 225 (`if self.pr.author_is_bot and not self.self_driving`) _before_ `_maybe_compute_familiarity()` at line 251 — so the Action path never computes familiarity for a bot author. The self-driving path is `review_local.py`'s own module-level `run(context)` (line 314), which orchestrates manually and calls `_attach_familiarity(pipeline, context)`, not `_maybe_compute_familiarity()`.+- **Found (signal deliberately absent):** `_attach_familiarity` early-returns when `context.get("author_pr_numbers")` is empty (`review_local.py:301-303`), and the server sets exactly that: `author_pr_numbers = ... if author and not is_inbox_review else []` in `activities.py::fetch_review_context` (diff ~1215-1216), with a comment that this keeps the machine user's merged-PR history out of familiarity, and an integration test asserting `context["author_pr_numbers"] == []`. So `classification["familiarity"]` stays `None` (its `_classify` default at review_pr.py:474) for every self-driving PR.+- **Found (both consumers no-op on None):** `_format_familiarity` returns `""` when `fam is None` (reviewer.py:636-643), so no `familiarity: band STRONG` fact is ever rendered before the self_driving block — the claimed in-prompt contradiction cannot occur. `_render_review_body` guards `if fam is not None and fam.band in ("STRONG","MODERATE")` (review_pr.py:871-877), so no familiarity bullet is appended to the GitHub comment for a self-driving PR.+- **Impact:** The premise — familiarity runs for a self-driving bot author and leaks a bogus trust signal into the prompt and the human-facing comment — is mistaken; the carve-out already zeroes the signal at the server, the sandbox attach step, and both consumers. The suggested guard on `_attach_familiarity` is redundant with its existing empty-`author_pr_numbers` early return. Wrong/unreproducible under the criteria → drop, notwithstanding the must_fix label.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:144-160++**Per-push reviewer resolution re-runs an expensive, uncached multi-query lookup**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is registered as the hook stamphog's webhook path calls on every new push to a self-driving PR (per the PR description's Case 2: "someone pushes new commits... we re-check the PR is genuinely ours and that someone is still opted in"). Each invocation runs `_resolve_assigned_reviewer`, which does a `SignalReportArtefact` lookup, then `resolve_org_github_login_to_users` (a Team lookup + org-membership subqueries across `UserSocialAuth`/`UserIntegration` + a `User` query with `prefetch_related`), followed by a separate `ReviewUserSettings.load()` query. None of this is cached or memoized, so a self-driving PR that receives many pushes (common during iterative agent work) re-pays this full multi-query chain on every single push, unlike the original design where this resolution ran once per TaskRun-completion.+- **Suggestion:** Cache the resolved acting-reviewer id (e.g., keyed by `(team_id, signal_report_id)` with a short TTL, or persisted on the `Task`/report after first resolution) so repeated pushes reuse the prior resolution instead of re-querying the org membership tables and settings row every time.+- **Validator:** - **Checked:** The full chain `resolve_stamphog_acting_reviewer` → `_resolve_assigned_reviewer` → `resolve_org_github_login_to_users` (`products/signals/backend/report_generation/resolve_reviewers.py:532-601`), the resolver's call frequency at `_inbox_rereview_carve_out`, and whether the suggested cache is compatible with the feature's per-push toggle re-check.+- **Found:** `resolve_org_github_login_to_users` is fully batched, NOT N+1: one `Team` org lookup, `_candidate_user_ids_for_org_and_logins` (three `Subquery`/`id__in` candidate queries over `UserSocialAuth`/`UserIntegration`/`Integration` scoped by `OrganizationMembership`), then a single `User.objects.filter(id__in=candidate_ids).prefetch_related(...)`. With the `SignalReportArtefact` lookup (1) and `ReviewUserSettings.load` (1), it's ~a handful of indexed queries per push — O(1), no per-login loop.+- **Found:** The resolver fires only on head-changing webhook deliveries (synchronize/reopen/base-retarget) to bot-authored, fork-safe, positively-identified self-driving inbox PRs — a narrow subset on an alpha feature, not a genuinely hot path. The pre-existing `_resolve_acting_reviewer` already ran this identical chain on every TaskRun save (docstring: fires on every save of a "hot model"), so re-resolving here is not a new or heavier load pattern.+- **Found:** The resolver returns a user id only when the reviewer's toggle is currently on, so re-running it every push is exactly the mechanism implementing Case 3 (opt out mid-PR → next push does not review). Caching keyed on `(team_id, signal_report_id)` or persisting on the Task/report would cache the toggle decision and defeat the mid-PR opt-out — a correctness regression.+- **Impact:** Fails the performance bar (no N+1, no unbounded/quadratic work, no missing index, not an async-blocking path) — a few batched indexed queries per push on a low-frequency path. The suggested fix trades a real feature invariant for a marginal query saving. Drop.++### [❌ dismissed] consider · performance — products/review_hog/backend/receivers.py:210-227++**Celery task dispatched unconditionally even when the team has no Stamphog installation**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `_start_stamphog_review`'s docstring notes repo-config gating happens "inside the queued task," so every opted-in user's inbox PR unconditionally publishes a Celery task even for teams with no synced Stamphog repository at all — the settings serializer already computes this exact `stamphog_connected`/`has_reviewable_repo_config` check for the same team, but that result isn't reused here to skip the dispatch. For teams that enable the toggle without ever connecting Stamphog, every inbox PR still pays a broker publish + worker pickup that's guaranteed to no-op.+- **Suggestion:** Consider checking `has_reviewable_repo_config(team_id)` before dispatching (or exposing a cheap facade check) to skip the broker round trip entirely for teams without a Stamphog installation, rather than deferring the no-op to inside the queued task.+- **Validator:** - **Checked:** The dispatch guard in `handle_task_run_saved` (`if pr_url is not None and settings.stamphog_review_inbox_prs`), the `_start_stamphog_review`/`queue_inbox_pr_review` design intent, the safe no-op inside `process_inbox_pr_review` (`repo_config is None` → early `stamphog_inbox_pr_repo_not_reviewable` return), and whether the suggested eager check helps or hurts the common case.+- **Found:** The wasted work is one broker publish (`.delay()`) + one worker pickup that runs a single `StamphogRepoConfig` existence query and returns — only for the edge-case subset (toggle on, no synced+enabled repo config), and only on inbox-PR creation (low frequency, per self-driving implementation run). No N+1, no unbounded/quadratic work, not a hot path.+- **Found:** Deferring repo-config resolution into the task is deliberate and documented: the receiver leg is kept to "only ... the broker publish" so "the caller's save path never blocks on GitHub or the product DB." The suggested `has_reviewable_repo_config(team_id)` pre-check would add a synchronous cross-product-DB query to the `on_commit` dispatch for EVERY opted-in inbox PR — including the common connected case (returns True, dispatches anyway) — net overhead there, and precisely the cross-DB latency that finding 3-1-3 flagged, relocated onto the dispatch path.+- **Impact:** Below the performance bar — a cheap, low-frequency, already-safe no-op dispatch for an edge-case team; the proposed fix pessimizes the common path and contradicts the intended light-save-path design. Premature optimization / low-impact edge case → drop.++### [✅ VALID] should_fix (validator→consider) · performance — products/stamphog/backend/tasks/tasks.py:169-196++**Bot-authored PR events (dependabot/renovate) now trigger extra uncached cross-product DB queries on every synchronize/reopen**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Before this PR, a bot-authored PR (dependabot, renovate, any `[bot]` login) hit `_review_skip_reason` -> "bot_author" and the handler returned immediately with zero DB access. Now, because `_inbox_rereview_carve_out` runs whenever `skip_reason is not None` on a head-changing/base-retargeted action, every such delivery: (1) passes the fork-safety check at line 177 (dependabot/renovate push same-repo branches, not forks, so this does not filter them out), (2) calls `_resolve_repo_config` (a writer-pinned query, line 179), and (3) when the repo's stamphog config is enabled+synced (exactly the case you want stamphog running), calls `find_signal_implementation_run` -> `find_task_run` (lines 191-196), whose branch-only leg filters `TaskRun` by `branch=` with no dedicated index (its `Meta.indexes` only cover `output__pr_url`, `state__wizard_head_branch`, `created_at`, `task/-created_at/-id`, and `team/stage/task`) — a potential full-table scan. None of this result is cached, so a repo with routine dependency-bot churn now repeats this cost on every synchronize of every such PR, indefinitely, even though it will never resolve to a self-driving run.+- **Suggestion:** Add a short-TTL negative-result cache keyed on (installation_id, repo, pr_number) — mirroring the existing `_author_lacks_write_permission` cache pattern (lines 132-141 of the pre-PR file) — so once a bot-authored PR is confirmed not self-driving, subsequent synchronize/reopen events skip straight past the DB/tasks-facade lookups for the cache TTL. Separately, consider whether `find_task_run`'s branch-only leg needs an index on `branch` now that stamphog drives meaningfully more traffic into it.+- **Validator:** - **Checked:** The carve-out's selectivity, whether the DB work is new vs. pre-existing, `TaskRun`'s indexes, and whether any cache absorbs repeats. Traced `process_pull_request_event`'s skip block, `_inbox_rereview_carve_out`, `find_signal_implementation_run` → `find_task_run`, and `TaskRun.Meta`.+- **Found:** `_inbox_rereview_carve_out` returns immediately for non-bot PRs (`if not _is_bot_authored(pr): return`), so bot-authored PRs (dependabot/renovate) on head-changing/base-retarget actions are precisely what proceeds to `_resolve_repo_config` and, when the repo's config is enabled+synced, to `find_task_run`. That `find_task_run` call is genuinely new for bot PRs — pre-PR they hit `bot_author` skip whose head-changing branch only resolved repo config for approval retraction, never the tasks-facade lookup. `find_task_run`'s branch leg filters `branch=` with no index (TaskRun.Meta.indexes at models.py:1603-1630 index `output__pr_url`, `wizard_head_branch`, `created_at`, `[task,-created_at,-id]`, `[team,stage,task]` — never `branch`), and no negative-result cache exists, so it repeats every synchronize.+- **Impact:** Confirmed a newly-introduced, uncached per-delivery DB cost (an extra `_resolve_repo_config` plus a `find_task_run` whose branch leg has an unindexed scan component) for bot-PR head changes on Stamphog-enabled repos, growing with TaskRun size. Real and newly-introduced, so it clears the keep bar — but bounded: the pr_url leg is index-backed and short-circuits cheaply, the branch-leg query is scoped by `task__repository`/`task` (the planner can lean on `task_run_task_created_idx` rather than a full TaskRun scan), it runs on an async Celery path with no user-facing latency, and it fires only on bot-PR head-changing events (the code itself treats this branch as 'rare'). The negative-cache mitigation mirrors the existing `_author_lacks_write_permission` cache, so it's cheap to address.+- **Priority:** Down-ranking should_fix → consider: this is a legitimate but minor worker-side inefficiency (bounded frequency, async, scoped query), not a high-QPS hot path or a scale-biting regression, so it belongs on record rather than flagged as a fix-now.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1125-1159++**process_inbox_pr_review performs an unconditional live GitHub fetch with no debounce, despite its own docstring acknowledging frequent re-fires**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The docstring (lines 1125-1128) states "The receiver re-fires on every TaskRun output save carrying the PR URL," and the dedupe logic can only run after fetching the PR's current head from GitHub (line 1159, `StamphogGitHubClient(...).get_pr(...)`) — there is no cooldown or coalescing before that fetch. If a task agent saves TaskRun output multiple times while its PR is open (e.g. periodic progress updates unrelated to new commits), each save enqueues `process_inbox_pr_review`, and each execution performs a full GitHub API call regardless of whether anything actually changed. This file already has a precedent for guarding against exactly this class of re-trigger spam (`STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS` for label toggling), but no equivalent exists here, risking rate-limit pressure on the shared installation token under bursty output saves.+- **Suggestion:** Add a short-lived per-(team, pr_url) cache cooldown (same shape as `_label_cooldown_key`/`STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS`) checked at the start of `process_inbox_pr_review` (or before enqueueing in `queue_inbox_pr_review`) so a burst of receiver re-fires within a short window collapses into a single GitHub fetch.+- **Validator:** - **Checked:** The receiver's firing guards (products/review_hog/backend/receivers.py:56-109), its docstring on repeat saves, and `process_inbox_pr_review`'s rate-limit handling plus its fetch-before-dedupe rationale.+- **Found:** The receiver already filters what re-fires: `created` saves return (receivers.py:66-68), saves whose `update_fields` don't include `output` return without a DB hit (receivers.py:69-73), and FAILED/CANCELLED runs return (receivers.py:74-75) — so 'periodic progress updates' that write `state`/`stage` rather than `output` never reach `queue_inbox_pr_review`. The receiver docstring (receivers.py:59-63) states the re-fire is deliberate: 'Repeat saves with an unchanged target re-fire it deliberately … a same-head re-trigger costs one fetch (early-exit).' `process_inbox_pr_review` catches `GitHubRateLimitError` and reschedules with `countdown=max(e.retry_after or 0, 60)`, so token pressure is handled by backoff, and it fetches before the dedupe by necessity because the head-keyed dedupe needs GitHub's current head — a value only GitHub knows.+- **Impact:** The `get_pr` calls are bounded per PR (only `output`-touching saves during the run's tail re-fire, and each re-fire is one fetch that then early-exits on the head-keyed dedupe), and rate limits degrade gracefully via retry+countdown rather than hammering the installation token. The proposed pre-fetch (team, pr_url) cooldown would collapse those bounded, non-adversarial bursts at the cost of possibly dropping a legitimate re-review that lands just after a progress save — which is exactly why the design dedupes post-fetch instead. The cited `STAMPHOG_LABEL_REREVIEW_COOLDOWN_SECONDS` precedent guards adversarial human label-toggle spam, a different abusable shape; agent output saves are lifecycle-bounded. This is a deliberate, already-handled design choice with bounded cost, not a scale-biting performance defect, so it falls below the keep bar.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:179-179++**`_resolve_repo_config` is re-queried redundantly within a single webhook delivery once the inbox carve-out is evaluated**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `_resolve_repo_config(installation_id, repo)` is called once inside `_inbox_rereview_carve_out` (line 179) to check enabled/synced status. If the carve-out matches (self-driving, opted-in), control falls through the skip-return and the main handler calls `_resolve_repo_config` again moments later for the same (installation_id, repo) pair — a call that, pre-PR, bot-authored PRs never reached at all since the function returned before it. If the PR is identified as self-driving but the acting reviewer is opted out, the handler instead re-enters the skip branch and calls `_resolve_repo_config` a further time as `skip_repo_config`. Both extra calls are writer-pinned reads of a row already fetched a few lines earlier in the same request.+- **Suggestion:** Thread the already-resolved `StamphogRepoConfig` out of `_inbox_rereview_carve_out` (e.g. add a `repo_config` field to `_InboxCarveOut`) so the caller reuses it instead of re-querying in both the main-path and skip-path branches.+- **Validator:** - **Checked:** Every `_resolve_repo_config` call site across `process_pull_request_event` and `_inbox_rereview_carve_out`, which branches reach each, and the size/cost of the resolved table.+- **Found:** The double-resolve is real: `_inbox_rereview_carve_out` calls `_resolve_repo_config` internally (once per bot-authored PR that clears the fork check), and then the outer handler resolves again — the main-path `repo_config = _resolve_repo_config` when the carve-out matched (`inbox_review` set), or the skip-path `skip_repo_config = _resolve_repo_config` when opted-out or not-self-driving. So affected deliveries issue 2 point lookups for the same (installation_id, repo).+- **Impact:** Each `_resolve_repo_config` is a single-row lookup against `StamphogRepoConfig`, which holds at most one row per (team, repository) — enforced by the `unique_stamphog_repo_per_team` constraint (models.py:58) — so the table is tiny and the extra call is a sub-millisecond, constant-cost read that never compounds with data growth. It runs on the same bounded-frequency async webhook path as the other carve-out work, not a hot request path. This is a DRY micro-optimization (thread the resolved config out of `_InboxCarveOut`) with negligible runtime impact — below the surfacing bar even at `consider`, unlike a compounding unindexed scan. Precision-over-recall drops it.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:1235-1237++**Inconsistent exception logging drops the error detail in process_inbox_pr_review's final catch block**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `logger.exception("stamphog_inbox_pr_create_run_failed", repository=repository, pr_number=pr_number)` omits the `error=str(e)` structured field that every other new `logger.exception`/`logger.warning` call in this same function includes (`stamphog_inbox_pr_config_resolution_failed`, `stamphog_inbox_pr_fetch_rate_limited`, `stamphog_inbox_pr_fetch_failed`). This makes the run-creation failure mode harder to filter/aggregate on in structured log search compared to every other failure path in the same task.+- **Suggestion:** Add `error=str(e)` to the `stamphog_inbox_pr_create_run_failed` log call for consistency with the rest of the function's error logging.+- **Validator:** - **Checked:** The final catch block (diff L1166-1167) against the sibling error logs in the same function (`stamphog_inbox_pr_config_resolution_failed` at L1080, `stamphog_inbox_pr_fetch_failed` at L1095), and what `logger.exception` records.+- **Found:** The inconsistency is real — `logger.exception("stamphog_inbox_pr_create_run_failed", repository=..., pr_number=...)` omits the `error=str(e)` field the two sibling `logger.exception` calls include. But it uses `logger.exception`, which attaches `exc_info` automatically, so the full traceback and exception message are recorded regardless — the title's 'drops the error detail' is inaccurate; nothing is dropped. The `error=str(e)` field is a redundant convenience. Notably, other `logger.exception` calls across these files (`review_hog_inbox_trigger_failed`, `review_hog_stamphog_inbox_review_queue_failed`, `review_hog_stamphog_connected_check_failed`) also omit it, so `error=str(e)` isn't even a codebase-wide convention.+- **Impact:** No behavioral difference and no lost information — the exception is fully logged either way; at most one event's structured `error` field is absent for dashboard filtering, while the same detail sits in the captured traceback. This is a pure style/consistency nit, which the criteria explicitly exclude, so it doesn't meet the surfacing bar even at `consider`.++### [✅ VALID] must_fix · bug — tools/pr-approval-agent/reviewer.py:271-271,683-703++**Self-driving TRUSTED prompt block contradicts the standing 'bot author always needs human review' showstopper baked into REVIEWER_SYSTEM**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** REVIEWER_SYSTEM (reviewer.py:271) is `_load_review_guidance() + _REVIEWER_SCAFFOLD_TAIL` — the literal system prompt handed to the LLM for every review, sourced verbatim from `.stamphog/review-guidance.md`, a file this chunk does not touch. That file's showstopper list states unconditionally: 'Bot author (dependabot, renovate) — always needs human review' (REFUSE or ESCALATE). This chunk's new `_format_self_driving` (reviewer.py:683-703) injects a TRUSTED user-turn block that tells the same model the opposite for self-driving PRs: 'author familiarity, org membership, and merged-PR history carry no signal here — judge the diff strictly on its own merits.' Nothing in this chunk reconciles the two: the system prompt's categorical bot-author showstopper is never carved out or referenced by the new self-driving block, `_REVIEWER_SCAFFOLD_TAIL`, or anywhere else in this diff. Since system-prompt instructions typically take priority for a well-aligned model, a self-driving Inbox PR is very likely to trip the standing 'bot author ... always needs human review' showstopper and get REFUSEd/ESCALATEd on every single run — directly defeating this PR's stated goal of having Stamphog actually review these PRs as a first-pass gate. At minimum this produces contradictory instructions the model must arbitrate on its own, with no stated tie-breaker.+- **Suggestion:** Reconcile the two instruction sources in this same chunk: either (a) update `.stamphog/review-guidance.md`'s showstopper line to carve out verified self-driving/task-linked provenance (e.g. 'Bot author — always needs human review, except a verified self-driving Inbox PR, where task-linkage substitutes for human authorship'), or (b) have `_format_self_driving` explicitly state that it supersedes the standing bot-author showstopper for this run so the model isn't left resolving a direct contradiction between its system and user prompts on its own.+- **Validator:** - **Checked:** How `REVIEWER_SYSTEM` is composed (reviewer.py:271 = `_load_review_guidance()` + scaffold tail), the full text of `.stamphog/review-guidance.md`, whether the diff reconciles the bot-author showstopper anywhere, and whether any test exercises the real reviewer prompt.+- **Found (real, unreconciled contradiction):** The system prompt lists a categorical showstopper — `.stamphog/review-guidance.md:23` "Bot author (dependabot, renovate) — always needs human review" under "Showstoppers (REFUSE or ESCALATE)". The new `_format_self_driving` block (reviewer.py:683-701) neutralizes the _familiarity_ and _draft_ signals but never mentions or waives the bot-author showstopper, and it affirmatively tells the model "the author is a machine user" — matching the showstopper's own trigger. The diff touches neither the guidance file nor the system-prompt loader (grep of the PR diff for `review-guidance`/`REVIEWER_SYSTEM`/`showstopper` is empty).+- **Found (the design's own meta-rule cuts against the block):** guidance line 66 states trusted inputs are "judgment input, never a gate — never overrides a deny rule or a refusal criterion." The self_driving block is exactly such a trusted user-turn input, so by the guidance's own framing it cannot override the bot-author refusal criterion — making systematic ESCALATE/REFUSE the likely outcome, not the intended review.+- **Found (no validating test):** `test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end` asserts APPROVED, but it runs against a fake sandbox hardcoded to emit `approved_engine_output()` (fakes.py:441-455, wired in conftest.py:183) — the real reviewer LLM is never invoked, so nothing verifies the prompt resolves the contradiction toward reviewing.+- **Impact:** Every self-driving review is a bot-authored PR hitting a standing categorical showstopper that the new provenance block never carves out, with the guidance explicitly telling the model trusted context can't override refusal criteria. That plausibly makes the feature systematically ESCALATE/REFUSE the very PRs it was built to review — a concrete trigger (every self-driving run) with a concrete, feature-defeating consequence, and a cheap fix (carve out the showstopper in the guidance or have the block explicitly supersede it). This clears the keep bar; it is not style or speculation.+- **Priority:** Keeping the reviewer's must_fix — the impact is potentially feature-breaking on the change's core path and unmitigated by tests; the LLM-behavior uncertainty ("every single run" is not provable) is offset by the guidance's line-66 meta-rule pushing the model toward the showstopper.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/reviewer.py:683-703++**`_format_self_driving` hardcodes 'it is a draft on purpose' without checking pr.draft, so it can assert a false fact once the same self-driving PR leaves draft**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The TRUSTED provenance block unconditionally states 'It is a draft on purpose (the verdict is wanted at Inbox triage time); draft state is not a caution signal for this PR' whenever `cl.get("self_driving")` is true — it never reads `pr.draft`. Per the PR's own Case 2 ('new commits land on that PR'), a self-driving PR can be re-reviewed after it has already left draft (task linkage, not draft state, is what keeps `self_driving` true on subsequent pushes), and 'Draft becomes ready: no review, and the approval stays' confirms ready-state transitions are tracked independently of re-review triggers. When that happens, this block still tells the model the PR 'is a draft on purpose' and that draft state 'is not a caution signal for this PR' — a categorically false claim about the PR's actual current state. Nothing else in the prompt surfaces the real draft/ready status for the model to catch the discrepancy (the `_check_prerequisites` gate itself only flags drafts when `not self.self_driving`, so it stays silent either way), so the model has no way to detect it's being told something false about the PR it's reviewing.+- **Suggestion:** Condition the draft-specific sentence on the actual `pr.draft` value, e.g. only render 'It is a draft on purpose...' when `pr.draft` is true, and drop or reword that clause when the self-driving PR is no longer a draft at review time — the rest of the provenance block (machine-authorship, task-linkage) remains valid regardless of draft state and can stay unconditional.+- **Validator:** - **Checked:** Whether a self-driving review can actually run on a non-draft PR, and whether draft/ready status is an LLM scrutiny lever anywhere the reviewer prompt would act on it.+- **Found (premise is technically reachable):** The webhook re-review carve-out `_inbox_rereview_carve_out` (products/stamphog/backend/tasks/tasks.py) fires on head-changing actions for any bot-authored self-driving PR and never re-checks `pr.draft` — so a self-driving PR that flipped to ready and then receives a `synchronize` is re-reviewed with `self_driving=True` while `pr.draft=False`, and `_format_self_driving` (reviewer.py:699) would then assert "it is a draft on purpose" falsely. The finding's mechanism is real, not mistaken.+- **Found (but the consequence is inert):** Draft/ready is not a scrutiny lever for the LLM. `.stamphog/review-guidance.md` never ties the model's verdict to draft/ready status — draft is enforced only by the deterministic `_check_prerequisites` gate (review_pr.py:590), not the reviewer prompt. So the clause "draft state is not a caution signal for this PR" is a no-op when there is no draft to discount, and the stale "it is a draft" wording maps to no documented change in the model's judgment. The only prompt token about draft is the block itself; `stamphog_draft` at reviewer.py:363 sits in the PostHog event-capture properties dict (next to `$ai_trace_name`, `stamphog_version`), not the prompt — so there isn't even a visible contradiction that could destabilize the trusted block.+- **Impact:** I can name the trigger (re-review of a now-ready self-driving PR) but not a concrete consequence — no wrong verdict, data loss, or user-facing harm follows, because nothing in the review guidance calibrates scrutiny on draft vs ready. It is a technically-accurate butimmaterial prompt-accuracy nit confined to a secondary edge case (push after the PR left draft). Under precision-over-recall — can't name both trigger and consequence, on the fence → drop — this is below the keep bar.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:94-96,110-112++**"Relaxes exactly two gates" is contradicted two bullets later by two more bypassed gates**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** Line 94-96 states the engine flag "relaxes exactly two gates — the bot-author refusal and the draft prerequisite", but the final bullet (lines 110-112) documents that these same runs "bypass the review-mode and author-write-permission gates" as well — two additional gates not counted in the "exactly two" tally. Both claims sit in the same bullet list under the heading "Rules that keep the exception narrow", so a reader summing up how narrow the exception actually is will undercount by two. Even if "exactly two" is technically scoped only to the `Pipeline(self_driving=...)` flag versus a separate orchestration-layer bypass, the doc doesn't say so explicitly, so the two statements read as contradictory.+- **Suggestion:** Either scope the "exactly two" claim explicitly (e.g. "the engine-level Pipeline flag relaxes exactly two gates; two further orchestration-level gates — review-mode and author-write-permission — are bypassed separately, see below") or fold all four bypassed checks into one authoritative list so the total scope of the carve-out is unambiguous.+- **Validator:** - **Checked:** Every `self_driving` engine-flag usage vs. where review-mode/write-permission are bypassed, via `gh pr diff 75215` — engine `Pipeline` checks at lines 1941/1977 (`author_is_bot and not self.self_driving`) and 1999 (`pr.draft and not self.self_driving`), and the orchestration-layer skips at lines 1004 (`_review_mode_skip_reason(...) if inbox_review is None else None`) and 1019 (`False if inbox_review is not None else _author_lacks_write_permission(...)`).+- **Found:** The two "exactly two" gates are the only ones the `self_driving` flag relaxes — bot-author refusal + draft prerequisite (plus a prompt-provenance swap). The review-mode and write-permission bypasses are triggered by a different condition (`inbox_review is not None`) at a different layer, and the AGENTS.md sentence is explicitly scoped: its subject is "The engine flag (`self_driving_review` … → `Pipeline(self_driving=...)`) … It relaxes exactly two gates." The final bullet then separately names the other two bypasses with their own rationale ("the App's machine user is not a collaborator").+- **Impact:** No real contradiction — the two statements accurately describe two distinct layers with distinct trigger conditions, and the same bulleted "Rules that keep the exception narrow" list transparently enumerates all four bypasses, so a reader of the full section cannot undercount. This is a documentation-wording/taste nit in an internal invariant doc with no correctness, security, or behavioral consequence; the reviewer's own hedge concedes the "exactly two" scoping is technically correct. Under precision-over-recall (on the fence → drop), it does not meet the bar.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:89-112++**Doc never states whether the repo's own review on/off toggle (`StamphogRepoConfig.enabled`) still gates self-driving inbox reviews**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `StamphogRepoConfig.enabled` (products/stamphog/backend/models.py:31) is the per-repo review on/off switch, documented in README.md's Configuration section as distinct from `review_mode` (auto vs trigger label). The new carve-out section explicitly lists which gates are bypassed (bot-author refusal, draft prerequisite, review-mode, author-write-permission) but never mentions whether the fundamental repo-level `enabled` flag — or the existence of a `StamphogRepoConfig` row at all — is still checked for self-driving inbox PRs. README.md's own opening line states "Repos opt in per-repo; everything else stays untouched" (README.md:3), so silently leaving this unaddressed is a meaningful gap: it's ambiguous whether a self-driving inbox PR could be reviewed/approved on a repo where Stamphog review was never enabled (or never installed at all).+- **Suggestion:** Add an explicit line confirming (or denying) that `StamphogRepoConfig.enabled` (and repo/installation existence) is still required for the self-driving inbox carve-out, so the "repos opt in per-repo" invariant's interaction with this new bypass is documented rather than left implicit.+- **Validator:** - **Checked:** Whether the `enabled`/repo-config gate is actually enforced and documented for the carve-out — traced `queue_inbox_pr_review`/`has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`, the receiver/task docstrings, the `stamphog_connected` serializer field, and the added tests, plus the AGENTS.md carve-out bullet list.+- **Found:** The gate is enforced in code and is NOT relaxed by the carve-out: `has_reviewable_repo_config` filters `enabled=True, connected_by_user_id__isnull=False` and excludes blank `installation_id`; `queue_inbox_pr_review`'s docstring states review requires "resolving a synced+enabled repo config for the PR's repository (silent no-op without one)"; the receiver/task docstring repeats "Repo-config gating (a synced+enabled StamphogRepoConfig ...) happens inside the queued task — teams without the Stamphog App get a silent no-op there"; and tests assert `never_synced_blank_installation → False`. So there is no real ambiguity — a repo where Stamphog was never enabled/installed yields a silent no-op.+- **Found:** The AGENTS.md section the reviewer cites is titled "Rules that keep the exception narrow" and enumerates only the gates the carve-out _relaxes_ (bot-author refusal, draft, review-mode, write-permission). `enabled` is not relaxed, so the correct reading is that it stays in force; its bullet-3 pointer to `queue_inbox_pr_review` leads directly to the facade docstring that documents the repo-config gating.+- **Impact:** This is a documentation-completeness preference (restate a non-relaxed gate in an invariant list) where the invariant is already enforced in code and documented in the same PR (facade docstring, task docstring, user-facing copy, `stamphog_connected` help text) — "already handled" plus doc-taste, not a code correctness/security defect. Under precision-over-recall it falls below the bar.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-1.mdnew file mode 100644index 000000000000..a38f09e02f06--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-1.md@@ -0,0 +1,322 @@+# Reviewer-quality run — `B-glm52-max-1`++- **Dumped:** 2026-07-23T17:38:10+00:00+- **Report id:** `019f8fd0-f331-7081-924a-64491f20bc8a` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 4013s (66.9 min)++## Config snapshot++- runtime / model / effort: `claude` / `@cf/zai-org/glm-5.2` / `max`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 21 | 17 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| ------------------- | --------------------------- | ------- | -------------- | ----------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 104 | 96,631 | 730,072 | 11,019,231 | 111,053 | 7 | $13.33 | $13.33 |+| claude-sonnet-5 | dedup | 1 | 12,811 | 0 | 0 | 2,721 | 0 | $0.05 | $0.05 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,783 | 0 | $0.04 | $0.04 |+| @cf/zai-org/glm-5.2 | review | 265 | 16,671,891 | 0 | 0 | 70,545 | 0 | — | $0.00 |+| @cf/zai-org/glm-5.2 | blind-spot | 207 | 12,679,189 | 0 | 0 | 49,826 | 0 | — | $0.00 |+| **total** | | **578** | **29,469,551** | **730,072** | **11,019,231** | **235,928** | **7** | **$13.42** | **$13.42** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `@cf/zai-org/glm-5.2` (472 gen(s), gw $0.00).+- naive method (all prompt tokens at input price): $62.09 — 4.6× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $33.7750 over 578 gen(s) (true $10.5994, Δ +218.7%)+ - · of which cache read: $5.5096 over 99 gen(s) (true $5.5096, Δ +0.0%)+ - · of which cache write: $4.5629 over 104 gen(s) (true $4.5629, Δ +0.0%)+ - · of which fresh (derived): $23.7024 over 578 gen(s) (true $0.5268, Δ +4399.0%)+ - output: $3.1201 over 578 gen(s) (true $2.8214, Δ +10.6%)+- 7 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------- |+| …af1c3ea6 | issues-review-p1-c2 | 16:35:24 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …1df24bd8 | issues-review-p1-c3 | 16:35:24 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …77bb522b | issues-review-p3-c2 | 16:35:29 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …750cb4dd | issues-review-p2-c1 | 16:35:30 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …4c22404a | issues-review-p3-c1 | 16:35:35 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …d99f64d0 | issues-review-p2-c2 | 16:35:39 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …a24cd97e | issues-review-p1-c1 | 16:35:43 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …14418ebd | issues-review-p2-c3 | 16:35:43 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …25a4b49d | blind-spots-c3 | 16:50:43 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …45d32a97 | blind-spots-c4 | 16:50:45 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …f27d13c8 | blind-spots-c2 | 16:50:56 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …87a03650 | blind-spots-c1 | 16:50:57 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …127b8837 | blind-spots-c1 | 17:01:35 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …ae10e18d | validation-c3 | 17:17:43 | 0 | 39,127 | claude-opus-4-8 |+| …be8d5e0e | validation-c2 | 17:17:44 | 0 | 39,632 | claude-opus-4-8 |+| …82b2ae5b | validation-c1 | 17:17:45 | 0 | 39,660 | claude-opus-4-8 |+| …6f8259c1 | validation-c4 | 17:17:45 | 0 | 38,915 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **0/17** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 2m 27s |+| review wave (perspectives) | 16m 17s |+| blind-spot sweep | 26m 24s |+| dedup (incl. combine/clean) | 29s |+| validation | 20m 08s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 42m 41s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 3 |+| 1 | 3 | review-hog-perspective-contracts-security | 3 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 1 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 4 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 1 |+| 1000 | 4 | review-hog-blind-spots-general | 1 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider — products/review_hog/backend/api/settings.py:27-32++**stamphog_review_inbox_prs is writable without a server-side connected precondition, diverging from the UI contract**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The new `stamphog_review_inbox_prs` field is a plain `serializers.BooleanField(required=False)` with no `validate_stamphog_review_inbox_prs` validator. The UI (CodeReviewScene.tsx) renders it disabled with a reason when `stamphog_connected` is false, but the PATCH endpoint accepts and persists `stamphog_review_inbox_prs: true` regardless of whether the project has a synced+enabled StamphogRepoConfig. A caller hitting the API directly (or via the generated MCP tool, which now exposes this field) can store `true` in a state the UI blocks, leaving a persisted preference that silently no-ops in the facade until a repo is connected. The help_text documents the precondition, so this is a contract-clarity gap rather than a data-integrity bug, but the writable API contract and the disabled-UI contract do not match.+- **Suggestion:** Mirror the connected precondition in the serializer so the server and UI agree. Either add a `validate_stamphog_review_inbox_prs` (or object-level `validate`) that rejects enabling when `has_reviewable_repo_config(self.context[...].team_id)` is false, returning a 400 with the same 'connect a repository first' message the UI shows; or, if silently persisting `true` for later activation is the intended design (the receiver/facade already no-op until connected), document that explicitly and keep it. If the latter is intended, no code change is needed — flagging so the deliberate choice is recorded. Verify `has_reviewable_repo_config` team-scopes by the same team_id used for `instance.team_id` to avoid a cross-team connected-state leak.+- **Validator:** - **Checked:** The serializer field + `stamphog_connected` method (`products/review_hog/backend/api/settings.py`), the facade `has_reviewable_repo_config` and `queue_inbox_pr_review` (`products/stamphog/backend/facade/api.py`), and the receiver dispatch path (`products/review_hog/backend/receivers.py::_start_stamphog_review`), all read from the PR diff.+- **Found (design is deliberate persist-then-gate, and documented):** `queue_inbox_pr_review`'s docstring states repo-config gating (synced+enabled `StamphogRepoConfig` for the PR's repo) happens inside the Celery task and is a "silent no-op without one"; `_start_stamphog_review`'s docstring repeats this ("teams without the Stamphog App get a silent no-op there, so this stays a plain toggle-gated dispatch"). The field `help_text` already documents the precondition: "Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)." So persisting `true` while disconnected stores a harmless preference that activates once a repo connects — no wrong result, no corruption.+- **Found (the security sub-concern is resolved, not open):** `has_reviewable_repo_config` uses `StamphogRepoConfig.objects.for_team(team_id)` and the serializer calls it with `instance.team_id` — the same effective root team used everywhere else in the viewset. There is no cross-team connected-state leak to fix.+- **Impact:** This is a UI-disables-vs-API-accepts divergence with no user-facing harm — not a correctness bug, data-loss, or API contract break (no broken caller, no backwards-incompatible signature). The finding's own text concedes it is "a contract-clarity gap rather than a data-integrity bug" and that "no code change is needed" if the persist-for-later design is intended, which the docstrings and help_text confirm it is. Under precision-over-recall it falls in the drop buckets (already-handled / contract-clarity, on-the-fence → drop).++### [❌ dismissed] consider · security — products/stamphog/backend/temporal/activities.py:448-451++**self_driving_review engine flag keys solely off run.output['inbox_review'] presence with no provenance-shape validation**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The engine's `self_driving_review` carve-out (which relaxes the bot-author and draft gates) is derived as `bool(output.get("inbox_review"))`. The security of the carve-out therefore rests entirely on the invariant that `inbox_review` is only ever stamped onto a run's `output` by the two positively-identifying trigger paths (webhook carve-out and receiver leg). There is no shape check that the provenance dict carries the required `trigger`/`signal_report_id`/`task_run_id`/`acting_user_id` fields, nor that `trigger` is one of the two allowed values. Any future code path that stamps a truthy `inbox_review` (even an empty dict) onto a human PR's run output would silently enable the relaxed gates on a human PR. The contract is implicit, not enforced.+- **Suggestion:** Tighten the contract: derive `self_driving_review` from a validated provenance object (e.g. require `isinstance(output.get("inbox_review"), dict)` and a known `trigger` value) rather than bare truthiness, and/or centralize the provenance construction in one helper used by both trigger paths so the field set cannot drift. A short comment at the read site naming the two permitted writers would also make the implicit invariant auditable.+- **Validator:** - **Checked:** All production writers and readers of `output["inbox_review"]` in the PR diff (`products/stamphog/backend/tasks/tasks.py`, `temporal/activities.py`) plus the receiver-leg entry (`review_hog` receiver → `queue_inbox_pr_review` facade → `process_inbox_pr_review`).+- **Found:** Exactly two writers exist, both positively-identifying. Webhook path (`tasks.py`, `output={"inbox_review": inbox_review} if inbox_review is not None else {}`) is reached only after repo-native head + synced/enabled config + team-scoped `find_signal_implementation_run` match (re-checked) + resolver + acting-reviewer toggle; it writes a full 4-key provenance dict. Receiver leg (`process_inbox_pr_review`) is dispatched only from `queue_inbox_pr_review`, which `review_hog` calls behind `settings.stamphog_review_inbox_prs`, and it too writes a full 4-key dict. No third writer exists.+- **Found:** The non-carve-out branch stamps `{}` (no `inbox_review` key), so `output.get("inbox_review")` is `None`/falsy on every human PR; the later `run.output` merge (`reviewer_raw`/`reviewer_exit_code`) never adds the key. The reviewer's "even an empty dict" premise is wrong — `bool({})` is `False`, so an empty dict would NOT enable the carve-out.+- **Found:** The auditability half of the suggestion is already done: the read site (`temporal/activities.py`, `self_driving_review=bool(output.get("inbox_review"))`) carries a comment stating it "keys off this and ONLY this ... both trigger paths stamp only after positively linking the PR to a signals implementation run," and the PR adds a dedicated invariant section to `products/stamphog/AGENTS.md`.+- **Impact:** As written and as actually reached, no code path stamps a truthy `inbox_review` onto a human PR, so there is no current correctness or security defect. The finding is a hypothetical about a _future_ writer violating the invariant — squarely the speculative-what-if / defensive-paranoia / overengineering ("centralize provenance construction", "validated provenance object") categories the criteria drop. The reviewer cannot name a concrete current trigger, only a possible future one; per the precision-over-recall bar, this is dropped.++### [❌ dismissed] consider · best_practice — tools/pr-approval-agent/reviewer.py:683-703++**Provenance block asserts server-side verification the engine itself does not perform**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The `_format_self_driving` block tells the LLM 'verified by task linkage, not author identity' as a TRUSTED fact. The engine, however, does not perform any task-linkage verification — it renders this text solely because `cl.get("self_driving")` is truthy, which in turn comes from a single `self_driving_review` field in the context JSON. The actual verification lives in the stamphog server (another chunk). If that trust boundary is ever weakened, the prompt would still assert verification the engine cannot back up, biasing the reviewer toward approval of a bot-authored draft. The contract claim ('verified by task linkage') is stronger than what this code can vouch for.+- **Suggestion:** Soften the provenance wording to attribute the verification to the runtime that set the flag rather than stating it as an engine-verified fact, e.g. 'the review runtime positively linked this PR to a PostHog Code implementation task' — so the prompt's trust claim matches what the engine actually knows, and a future server-side regression doesn't leave the prompt over-claiming. The trust boundary itself is enforced elsewhere; this is about keeping the prompt's assertion honest about where verification happens.+- **Validator:** - **Checked:** `_format_self_driving` (reviewer.py, added at diff hunk `@@ -679,6 +680,27`) and how its gating flag is produced — `review_local.py`'s `run()` sets `Pipeline(..., self_driving=bool(context.get("self_driving_review")))`, with an inline comment that the flag is stamped by the hosted server from persisted inbox provenance.+- **Found:** The premise is correct that the engine renders the block solely on `cl.get("self_driving")` and performs no task-linkage check itself. But the block is accurate for every input that actually reaches it: the flag is server-stamped from inbox provenance and cannot be set by untrusted PR content, so when the block renders, task linkage genuinely was verified upstream. The prompt states a true fact today.+- **Impact:** No live defect. The finding explicitly concedes "the trust boundary itself is enforced elsewhere," so there is no current security/correctness bug — the asserted harm (prompt over-claiming and biasing toward approval) only occurs _if a future server-side regression_ weakens the boundary. That is a speculative "what if" contingent on a hypothetical change to another component, which the validation bar says to drop. The proposed remedy is a fine-grained rewording of a prompt string with no behavioral difference — prompt-wording taste plus defensive documentation, below the surfacing bar (precision over recall).++### [❌ dismissed] consider · best_practice — products/review_hog/frontend/CodeReviewScene.tsx:1067-1073++**Fail-soft stamphog_connected=False is indistinguishable from genuinely-disconnected, producing misleading disabled copy**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `get_stamphog_connected` deliberately fails soft to `False` when the cross-product Stamphog DB read raises (settings.py: get_stamphog_reviewer wraps has_reviewable_repo_config in try/except returning False on any error). The UI treats that `False` identically to a project that genuinely has no synced/enabled Stamphog config: when `!stamphog_connected && !stamphog_review_inbox_prs`, the switch is disabled with the message 'Connect a repository to Stamphog first. Stamphog is not set up for this project yet.' During a transient Stamphog-DB outage (or circuit-breaker trip), a user who has not yet opted in sees that 'not set up' message even though the repo IS configured — the copy asserts a setup state the code did not actually verify, because the same `False` covers both 'no config' and 'read failed'. This is a correctness gap in the user-facing state, not just styling: the disabled reason misleads about why the action is unavailable.+- **Suggestion:** Distinguish the two False conditions. Either surface a third state from the serializer (e.g. `stamphog_connected: 'connected' | 'disconnected' | 'unavailable'`, or a parallel `stamphog_connected_check_failed` boolean) so the UI can render a transient-error message ('Stamphog status couldn't be checked — try again') instead of asserting 'not set up', or at minimum soften the disabled copy to not claim setup state when the read may have failed (e.g. 'Stamphog isn't available for this project right now. Connect a repository to Stamphog, or try again.'). The fail-soft returning False is fine for gating; the gap is only in the UI's claim about the underlying state.+- **Validator:** - **Checked:** The added Stamphog switch block in `products/review_hog/frontend/CodeReviewScene.tsx` (the `disabledReason` ternary in the PR diff, ~L1064-1071) and the serializer's fail-soft source `get_stamphog_connected` in `products/review_hog/backend/api/settings.py` (try/except returning `False`, from the chunk-1 diff).+- **Found:** The premise is accurate — `get_stamphog_connected` collapses both "no config" and "DB read raised" into `False`, and the disabled copy hard-asserts "Stamphog is not set up for this project yet." So during a Stamphog-DB outage the copy can misstate the reason. But the serializer comment marks this fail-soft-to-False as deliberate ("False is the safe degradation — the toggle renders disabled until the read recovers").+- **Impact (why it does not meet the bar):** The only defect is disabled-reason wording in a rare, compound degraded state: the Stamphog product DB must be down/circuit-broken _at the moment_ a not-yet-opted-in user opens the settings _and_ a repo is actually connected. The functional behavior — disabling the opt-in — is correct in that window: Stamphog reviews mint credentials and resolve the repo config against that same DB, so they would fail closed anyway (the PR's own test frames enabling-while-disconnected as the regression to prevent). No wrong result, data, logic, security, or contract effect — just imprecise copy that self-corrects when the read recovers. This is a rare, low-impact edge case, and the primary suggested remedy (a new tri-state `stamphog_connected` API field) is disproportionate to it. Under precision-over-recall, drop.++### [✅ VALID] must_fix · bug — products/tasks/backend/facade/api.py:484-518++**find_signal_implementation_run excludes the very signals tasks it must identify (internal=True), breaking the webhook carve-out leg**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** find_signal_implementation_run returns None when `task.internal` is True. But signals implementation tasks — the self-driving PRs this whole feature is built to identify — are ALWAYS created with internal=True (products/signals/backend/auto_start.py:261 passes `internal=True` to create_and_run_task, and products/tasks/backend/tests/test_api.py:274 asserts "Signal-report tasks are always created with internal=True"). So for every real self-driving inbox PR, `task.signal_report_id` is set AND `task.internal` is True, which makes `if task.signal_report_id is None or task.internal: return None` evaluate to True on the `task.internal` branch and return None. The webhook-leg carve-out (`_inbox_rereview_carve_out`) then gets run=None from the facade and fails closed, so Leg 2 (later pushes via synchronize/reopen/base retarget) NEVER re-reviews a self-driving PR. The entire second leg of the feature is non-functional in production. The docstring's stated shape ("a non-internal task carrying a signal report") directly contradicts the production data model. The `internal` flag does not separate self-driving from non-self-driving: review_hog spawns and loops are also internal but already excluded by the `signal_report_id is None` check, so `task.internal` is both redundant for the intended exclusions and fatal for the intended match.+- **Suggestion:** Drop the `task.internal` predicate and rely on `signal_report_id` alone to identify the self-driving shape — only signals-origin tasks set signal_report_id. E.g.:++ run = find_task_run(pr_url=pr_url, branch=head_branch, repository=repository)+ if run is None or run.team_id != team_id:+ return None+ task = run.task+ if task.signal_report_id is None:+ return None+ return contracts.SignalImplementationRunDTO(...)++If there is a genuine need to exclude some other internal-but-signal-report-bearing shape, encode that precisely (e.g. an origin_product allowlist of SIGNAL_REPORT) rather than the broad `internal` flag, which the implementation path sets on every self-driving task. Add a test that creates the task with internal=True (as auto_start does) and asserts the facade still returns the DTO, to lock the production shape in.++- **Validator:** - **Checked:** The production creation path for self-driving implementation tasks (`products/signals/backend/auto_start.py`), the facade passthrough (`products/tasks/backend/facade/api.py::create_and_run_task`), the flagged guard in `find_signal_implementation_run`, and the PR's own tasks-side tests in `test_webhooks.py`.+- **Found:** `auto_start.py:244-261` creates the task that opens the draft PR (`interaction_origin="signal_report"`, commented "Makes the agent auto-push and open a draft PR") with BOTH `signal_report_id=report_id` (line 254) and `internal=True` (line 261, commented "Internal so the run stays out of the default task list"). `create_and_run_task` (`facade/api.py:827,849`) forwards `internal` verbatim to `Task.create_and_run`, so the stored `Task.internal` is `True` for every real signals implementation task.+- **Found:** The flagged guard `if task.signal_report_id is None or task.internal: return None` (diff `facade/api.py:1718`) therefore hits the `task.internal` branch and returns `None` for every production self-driving task. The docstring's claimed shape ("a non-internal task carrying a signal report") is contradicted by the data model — no such row is ever produced by `auto_start`.+- **Found:** The webhook carve-out `_inbox_rereview_carve_out` (diff `tasks.py:909-918`) does `if run is None ...: return _InboxCarveOut()` (no provenance), so a `None` return collapses Leg 2 to the ordinary bot-author/draft skip — later pushes (synchronize/reopen/base retarget) are never re-reviewed, and the head-change skip path dismisses the draft-time approval with no replacement.+- **Found (false-confidence trap):** The PR's tests mask this — `_make_run` defaults to `internal=False` for the two _matching_ assertions, while the parameterized `("internal_pipeline_task", {"internal": True}, {})` case asserts `internal=True` → `None` (diff `test_webhooks.py`). So the suite is green while production is broken; no test creates the run the way `auto_start` actually does (`internal=True` + `signal_report_id` set → expect a DTO).+- **Impact:** Confirmed correctness bug. The second leg of the feature — the whole point of the webhook carve-out — is non-functional for every real self-driving inbox PR. `signal_report_id is None` already excludes review_hog spawns/loops, making `task.internal` redundant for the intended exclusions and fatal for the intended match. Meets the keep bar (concrete trigger: any production signals implementation task; concrete consequence: Leg 2 never re-reviews). `must_fix` is warranted — it ships broken and the tests give false green.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected cross-product DB read added to the hot settings GET/PATCH path**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` is a SerializerMethodField that calls `has_reviewable_repo_config(instance.team_id)` on the stamphog product DB — a separate database behind a fail-fast circuit breaker — and it is re-serialized on every settings response. The settings GET is documented (line ~107) as the Code review tab's 'always-called endpoint', and the PATCH branch (line ~105) returns `serializer.data` after save, so even an unrelated PATCH (e.g. changing urgency_threshold) now triggers a synchronous cross-database query to stamphog. The fail-soft `except Exception` handles a hard failure well, but a slow/partially-degraded stamphog DB (circuit breaker warming up, connection pool contention) adds latency to every tab load and every settings save in review_hog, coupling a previously review_hog-only endpoint's tail latency to another product's database health.+- **Suggestion:** Consider scoping the cost: either skip computing `stamphog_connected` on PATCH (the value is informational for the GET-driven UI, and the receiver re-checks repo config server-side anyway), or cache the per-team result with a short TTL (e.g. django's cache framework, keyed by team_id) so repeated tab loads within that window don't each cross the product DB boundary. At minimum, compute it only when `request.method == 'GET'` to avoid the redundant re-query on the PATCH response.+- **Validator:** - **Checked:** How the settings endpoint is driven (`products/review_hog/frontend/reviewHogSettingsLogic.ts`), the query shape of `has_reviewable_repo_config` (`products/stamphog/backend/facade/api.py`), and the fail-soft wrapper `get_stamphog_connected` (`settings.py`).+- **Found (frequency):** `loadSettings` → `reviewHogSettingsRetrieve` fires once per scene mount (`reviewHogSettingsLogic.ts:954` `afterMount`→`loadAll`→`loadSettings`) and again only on an update _failure_ (`:809`). It is NOT polled — the 10s `setInterval` (`:758`) drives the recent-reviews list, not settings. PATCH is user-initiated (a switch toggle / urgency change), so it is rare, not a hot path.+- **Found (cost & mitigation):** the added work is exactly one indexed existence check — `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()`. It is behind the fail-fast circuit breaker the issue itself acknowledges (bounding latency during degradation) and wrapped in `try/except → False` so a hard failure degrades gracefully.+- **Impact (why it does not meet the bar):** the keep bar for performance is problems that "bite at real scale" — N+1, unbounded loops, missing indexes on hot paths, quadratic behavior. A single `.exists()` on a per-user, per-scene-mount settings endpoint (further limited by ReviewHog's alpha team gate) is none of those. The reliability-coupling concern is real in principle but already mitigated by the fail-fast breaker + fail-soft handling the design intentionally added. The PATCH redundancy saves one cheap query per rare save — a micro-optimization, and the TTL-cache remedy is disproportionate. On the fence → drop (precision over recall); the `should_fix` severity is also overstated for a single existence query on a cold endpoint.++### [❌ dismissed] consider · best_practice — products/review_hog/backend/receivers.py:114-138++**Second synchronous broker publish added to the on_commit request path**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The receiver now registers two `transaction.on_commit` callbacks that each do synchronous work after the TaskRun save commits: the existing Temporal workflow start and the new `_start_stamphog_review`, which performs a Celery broker publish (`queue_inbox_pr_review`). `on_commit` callbacks run synchronously within the originating request/response cycle, so a second broker publish doubles the synchronous post-commit work on the tasks save path. The `except Exception` in `_start_stamphog_review` covers a broker that is _down_ (connection refused) but not one that _hangs_ (no socket timeout on the publish), which would stall the request that triggered the save. The existing `_start_review` has the same shape, so this is an incremental widening of a pre-existing reliability edge rather than a new class of bug.+- **Suggestion:** Confirm `queue_inbox_pr_review`'s underlying Celery `apply_async`/`delay` call is configured with a bounded connect/send timeout so a hung broker cannot stall the on_commit callback (and thus the tasks save request). If the broker publish is expected to be cheap, a short `broker_timeout`/`BROKER_CONNECTION_RETRY` setting or an explicit `connect_timeout` on the Celery connection is the operational safeguard; otherwise document that the publish is fire-and-forget-with-timeout.+- **Validator:** - **Checked:** The new on_commit dispatch and `_start_stamphog_review` (receivers.py diff), `queue_inbox_pr_review` (`products/stamphog/backend/facade/api.py`), and the pre-existing `_start_review` sibling for comparison.+- **Found (same shape as existing code):** the finding itself concedes this is "an incremental widening of a pre-existing reliability edge rather than a new class of bug" — `_start_review` already does synchronous network I/O (a Temporal workflow start) on `on_commit` with the identical `except Exception` down-not-hang shape. The PR follows the established pattern rather than introducing a new one; both callbacks only fire when both toggles are on.+- **Found (the added work is a bare `.delay()`):** `queue_inbox_pr_review` is `process_inbox_pr_review.delay(...)` — an ordinary Celery broker publish, the same primitive used across the entire codebase for task dispatch. Everything heavy (PR fetch, run creation, workflow start) runs inside the Celery task, not synchronously.+- **Impact (why it does not meet the bar):** the trigger is speculative — a broker that _hangs_ (accepts the connection but stalls on publish) rather than being down. That is a rare tail condition that applies to every `.delay()` in every Django request path in PostHog; if it were a real must-fix, it would be a codebase-wide broker-config concern, not a defect in this receiver. The suggestion ("confirm Celery has a bounded connect/send timeout") is a verify-the-framework-config ask, not a concrete reachable defect this PR introduces. Falls in the speculative-what-if / defensive-paranoia drop buckets; on the fence → drop.++### [✅ VALID] should_fix · bug — products/stamphog/backend/tasks/tasks.py:871-881++**Carve-out failure can block the stale-approval safety dismissal for bot-authored PRs**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Before this PR, when `_review_skip_reason` returned a reason (draft/bot/untrusted author), the code went straight to the head-changing stale-approval dismissal (`_retract_stale_approvals_on_skip`). The PR inserts `_inbox_rereview_carve_out` — wrapped in `try/except: retry` — between the skip detection and that dismissal. The carve-out now performs a DB query (`find_signal_implementation_run` → `find_task_run`) and an external hook call (`get_inbox_acting_reviewer_resolver()` resolver, owned by review_hog) on the critical path of EVERY head-changing bot-authored PR. If either raises (a tasks-facade DB timeout, a review_hog resolver bug, a transient blip that doesn't clear within 3 retries), `process_pull_request_event` retries up to `max_retries=3` and then fails permanently. The dismissal block below it never runs, the delivery is never marked processed, and — critically for the invariant this PR claims is 'never preference-gated' — a standing approval from an earlier head is left satisfying required reviews over unreviewed commits. The blast radius is repo-wide: a single persistent failure in the new carve-out resolution silently disables the stale-approval retraction for all bot-authored pushes, the exact case (dependabot/renovate/self-driving) the dismissal is meant to protect.+- **Suggestion:** Decouple the carve-out from the safety dismissal so a carve-out failure can't strand a stale approval. Compute the carve-out best-effort: on exception, log and fall back to an empty `_InboxCarveOut()` (byte-for-byte old behavior) and let the dismissal proceed, rather than retrying the whole event. If re-review reliability is the concern, retry only the carve-out resolution itself (or queue it separately), but never gate the head-changing dismissal behind it. Alternatively, move the dismissal to run before the carve-out for the `skip_reason is not None` branch. At minimum, the carve-out's `find_signal_implementation_run` + resolver errors should be caught locally and downgraded so dismissal safety is uninterrupted.+- **Validator:** - **Checked:** The full new control flow in `process_pull_request_event` (diff `tasks.py` @@ +864/+891), the `_inbox_rereview_carve_out` body and its guards, the pre-existing dismissal block, and what each side calls.+- **Found (mechanism is real):** When `skip_reason is not None`, the carve-out is computed first inside `try/except: raise ...retry(exc=e)`. On a persistent exception the whole event retries and, after `max_retries`, fails permanently — control never reaches the `if skip_reason is not None and inbox_review is None:` dismissal, and `_mark_pr_event_processed` is never called. So a standing approval from an earlier head is left satisfying required reviews over unreviewed commits, on exactly the bot-authored head-changing pushes the skip-path dismissal exists to protect.+- **Found (genuinely new coupling):** `_inbox_rereview_carve_out` reaches `find_signal_implementation_run` (a tasks-facade DB read via deferred import) and the review_hog resolver for every repo-native, bot-authored, head-changing PR on a synced+enabled Stamphog repo. Neither subsystem was on the skip→dismissal path before this PR. A tasks-DB blip (or a resolver bug) that doesn't clear within 3 retries now blocks the dismissal in cases where pre-PR it would have run. This contradicts the PR's own stated design — the carve-out's non-exception "unidentified" branch already `return _InboxCarveOut()` to keep "today's behavior byte-for-byte," but the exception branch does not honor that fallback for the safety dismissal.+- **Found (finding partly overstates impact):** The dominant failure source `_resolve_repo_config` is shared with the dismissal block, which itself retries-then-fails, so product-DB/GitHub outages already left stale approvals standing pre-PR — no delta there. The resolver is reached only after a self-driving run is positively matched, so it is NOT on "every bot PR" path (dependabot/renovate return None at `find_signal_implementation_run` before the resolver). The true new exposure is a tasks-DB-only partial outage (product DB healthy) or a resolver bug, and it self-heals on the next successful head-changing delivery. Narrower than "repo-wide for all bot pushes," but still a real weakening.+- **Impact:** Meets the reliability bar — a product-critical, explicitly-guarded invariant (stale-approval retraction, "safety is never preference-gated") is coupled to a newly-added, independently-failing subsystem via a retry-then-permanent-fail path, with a concrete trigger (carve-out DB/resolver raises persistently) and concrete consequence (stale approval stands over unreviewed commits). The suggested fix (compute the carve-out best-effort, fall back to empty on exception so the dismissal always proceeds; retry only the re-review resolution separately) is low-risk and aligns the exception path with the already-documented fallback. `should_fix` is appropriate: real but incident-scoped and self-healing, not a routine-path defect.++### [❌ dismissed] consider · documentation — products/stamphog/AGENTS.md:80-113++**New carve-out section doesn't fit the file's "every invariant earned through a real review finding" framing**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The file's preamble (lines 3-5) states the invariants below "were each earned through a real review finding — do not relax one without understanding what it closes." The new "The self-driving inbox carve-out" section is a feature description of a deliberately introduced relaxation, not a finding-earned invariant. A future reader taking the preamble literally could (a) treat the carve-out's narrowing rules as battle-tested-earned when they are brand-new and unproven, or (b) be confused about the file's organizing principle (invariants vs. feature carve-outs). The doc is otherwise accurate and well-cross-referenced.+- **Suggestion:** Either add a one-line lead-in under the new header noting it is a deliberate carve-out (a sanctioned exception) rather than a finding-earned invariant — e.g. "This is a sanctioned exception to the refusal above, not a finding-earned invariant; its narrowing rules are load-bearing and must be held" — or relax the preamble's absolute claim ("were each earned through a real review finding") to allow sanctioned exceptions. This keeps the contract file's epistemic framing honest.+- **Validator:** - **Checked:** The local checkout sits at a master commit (`9922ccab`), not the PR head (`1341596e`), and contains no carve-out text — so I fetched the real diff via `gh pr diff 72680` and read the actual added AGENTS.md section (`@@ -77,6 +77,40 @@`), the preamble (lines 3-5), and the README companion line.+- **Found:** The added header is `## The self-driving inbox carve-out (the one exception to the bot-author refusal)` — it self-labels as a carve-out and "the one exception" in the title itself, and the body opens with "Rules that keep the exception narrow:". This already signals to any reader that the section is a deliberate exception, not a battle-tested invariant, which defuses the finding's core worry (misreading it as finding-earned, or confusion about the file's organizing principle).+- **Found:** Even in the reviewer's worst case, the preamble instruction is "do not relax one without understanding what it closes" / "hold new code to all of them." The carve-out's narrowing rules (don't weaken `is_bot_author`, flag defaults closed, fail-closed resolver, dismissal never preference-gated) genuinely are constraints that must be held; a reader treating them as strict invariants acts conservatively and correctly — there is no wrong action the framing could induce.+- **Impact:** This is a documentation-framing/wording concern with zero behavioral effect, mapping squarely to the "pure style / taste (doc wording, 'I'd write it differently')" drop category. The reviewer concedes the doc is "otherwise accurate and well-cross-referenced," and the proposed fix is a one-line editorial disclaimer. It does not meet the correctness/security/contract/data-loss/performance bar, and under precision-over-recall ("on the fence → drop") it should not be surfaced.++### [❌ dismissed] consider · security — products/stamphog/backend/tasks/tasks.py:113-121++**`_parse_pr_url` regex is not host-anchored, so lookalike domains parse as github.com**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` is matched with `.search()` and is not anchored to the host. A `pr_url` whose host merely contains the substring `github.com` — e.g. `https://evil-github.com/owner/repo/pull/1` — yields `('owner/repo', 1)` exactly as the real GitHub URL would (verified: both produce identical parse output). The parsed `owner/repo` is then matched against the team's `StamphogRepoConfig` set via `repository__iexact`, so a non-github URL that happens to embed a real `owner/repo` path is accepted as a GitHub PR reference rather than being rejected as unparseable. `pr_url` here flows from `review_hog`'s TaskRun `output.pr_url` (internal, written by the agent server), so the direct attacker-controlled surface is small, but the function is the programmatic entry's only validation that the target is actually a GitHub PR, and it silently normalizes lookalike hosts.+- **Suggestion:** Anchor the host so only `github.com` (and optionally the scheme) matches, e.g. `_PR_URL_RE = re.compile(r"^https?://github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` and use `.match()`/`fullmatch` against the URL, or parse with `urllib.parse.urlparse` and assert `parsed.netloc == 'github.com'` before extracting owner/repo/number. Either rejects `evil-github.com` while keeping `github.com/owner/repo/pull/123/files` working.+- **Validator:** - **Checked:** The `_parse_pr_url` definition (diff `tasks.py:831-838`), its sole call site (`process_inbox_pr_review`, diff L1061), how the parsed values flow downstream, and where the raw `pr_url` host could reach a network call.+- **Found (input can't occur):** `_parse_pr_url` is called only on `pr_url`, which originates from review_hog's TaskRun `output.pr_url` — written by the agent server when a self-driving PR is opened, always a canonical `https://github.com/...` URL. The lookalike host (`evil-github.com/...`) is not a real input on this path; the finding itself concedes the attacker-controlled surface is nil. The webhook leg does not use `_parse_pr_url` at all — it consumes the GitHub-payload `html_url` (`find_signal_implementation_run`), a trusted source.+- **Found (no impact even if reached):** The raw `pr_url` host is never used for any request. Downstream, only `repository` and `pr_number` are used: the config lookup is `StamphogRepoConfig.objects.for_team(team_id).filter(repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False)` and the fetch is `StamphogGitHubClient(repo_config.installation_id).get_pr(repo_config.repository, pr_number)` — talking to github.com via the trusted DB config value and installation credentials. So a lookalike host produces no SSRF (no request to the lookalike host), no cross-tenant access (team-scoped `for_team`), and no credential exposure. The worst case is that a malformed URL embedding a real `owner/repo` the team already has a Stamphog config for triggers a review of that team's own real PR — the exact set Stamphog reviews anyway.+- **Impact (why it does not meet the bar):** This is a speculative / never-gonna-happen edge case guarded by defensive-parser paranoia — the triggering input can't arise from the internal call site, and if it did the downstream config lookup + team scoping + trusted-credential fetch neutralize it with no user-affecting consequence. Per precision-over-recall (on the fence → drop), it does not clear the keep bar. The suggested host anchor is a reasonable low-cost hardening but not a real defect worth surfacing.++### [❌ dismissed] consider · best_practice — products/stamphog/backend/tasks/tasks.py:1107-1245++**Receiver leg does not re-validate the stamphog toggle at execution time, unlike the webhook leg**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `queue_inbox_pr_review` is called after `review_hog`'s receiver confirms the acting reviewer's `stamphog_review_inbox_prs` toggle is on, and `process_inbox_pr_review` then fetches the PR and creates the run without re-checking that toggle. The webhook leg (`_inbox_rereview_carve_out`) re-resolves the toggle through the registered resolver on every delivery, but the receiver leg trusts the queue-time decision for the entire (possibly delayed, retried up to `max_retries=3`) lifetime of the task. If the acting reviewer turns the toggle off between queue and execute, or the acting reviewer is reassigned/removed, a review still lands. The PR description frames the off-mid-PR case as landing in the 'existing skip paths' with dismissal safety preserved, but for the _initial_ leg there is no skip path that re-evaluates the toggle — the run proceeds and posts a verdict. This is an asymmetry in the gate between the two legs.+- **Suggestion:** Consider re-resolving the acting reviewer's current toggle inside `process_inbox_pr_review` (via the same `get_inbox_acting_reviewer_resolver()` hook) before creating the run, treating a now-off toggle as a silent no-op (mirroring the webhook leg's `opted_out` behavior). If the queue-time trust is intentional for latency reasons, document that asymmetry explicitly in the task docstring so the contract difference between the two legs is clear to future readers.+- **Validator:** - **Checked:** The queue-time gate in review_hog (`receivers.py` diff L198 `if pr_url is not None and settings.stamphog_review_inbox_prs:` → `transaction.on_commit` → `_start_stamphog_review` → `queue_inbox_pr_review` → `process_inbox_pr_review.delay(...)`), the webhook-leg re-check (`resolve_stamphog_acting_reviewer`, diff L219-229, re-reads `ReviewUserSettings.load(...).stamphog_review_inbox_prs`), and the receiver-leg body (`process_inbox_pr_review`, diff L1041-1170) which re-resolves the repo config and fetches the PR but does not re-call the resolver/toggle.+- **Found (premise true but window is seconds):** The initial leg is a fire-and-forget `.delay()` dispatched from `on_commit`, so the queue→execute gap is normally seconds (a few tens of seconds only if transient failures trigger the `default_retry_delay=5` retries). For a review to land after opt-out, the acting reviewer would have to flip `stamphog_review_inbox_prs` off within that window right as their self-driving PR is opened.+- **Found (asymmetry is justified, not a defect):** The webhook leg re-checks because it fires on LATER deliveries (synchronize/reopen/retarget) that can arrive minutes-to-days after the queue decision, where the toggle genuinely may have changed. The initial leg acts seconds after the queue-time check, so a second re-resolution is near-redundant belt-and-braces — the kind of defensive re-check the criteria down-rank.+- **Found (impact is benign and self-healing):** The toggle is a per-user preference, not a tenant/auth boundary; the receiver leg still enforces the real security boundaries (team-scoped `for_team`, synced+enabled `StamphogRepoConfig`, positive signal-linkage provenance). A verdict landing in the race window is on a bot-authored draft, and the next head-changing webhook delivery re-checks the toggle and dismisses the stale approval via the skip path. No cross-tenant escape, no unreviewed-commit exposure that isn't retracted on the next push.+- **Impact (why it does not meet the bar):** A seconds-wide race with negligible, self-healing consequence on a preference (not a security) gate, plus a suggestion that is half documentation. This is a never-gonna-happen / low-impact edge case and a doc nicety — per precision-over-recall it drops. The security-relevant invariants of the leg are intact.++### [❌ dismissed] consider · best_practice — tools/pr-approval-agent/review_local.py:316-321++**self_driving flag read with bool(context.get(...)) is fragile against non-bool JSON values**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self_driving=bool(context.get("self_driving_review"))` correctly defaults closed for an absent key (`bool(None) == False`), but it coerces any truthy value to True. If the hosted server ever serializes the provenance as a string (e.g. `"true"`/`"false"`, a 0/1 int, or a list), `bool("false")` is `True` and `bool([0])` is `True`, silently widening the carve-out to bot-authored draft PRs that were not positively linked to an inbox task. The flag is the sole gate relaxing the bot-author refusal and the draft prerequisite, so its interpretation should be exact rather than truthy-coercing.+- **Suggestion:** Pin the flag to an explicit True check so a malformed/serialized value can't accidentally enable it: `self_driving=context.get("self_driving_review") is True`. This keeps the absent and explicit-False cases closed and rejects any non-bool the server might emit.+- **Validator:** - **Checked:** the full producer→consumer path of `self_driving_review`: the server call site in `products/stamphog/backend/tasks/tasks.py` (`self_driving_review=bool(output.get("inbox_review"))`), the builder `products/stamphog/backend/logic/reviewer.py::build_reviewer_invocation` (param typed `self_driving_review: bool = False`, stored into the context dict), the JSON hop into the sandbox, and the read-back `bool(context.get("self_driving_review"))` in `review_local.py`.+- **Found:** the value is a genuine Python `bool` at every stage — coerced with `bool(...)` at the source, declared `bool` on the builder parameter, and JSON preserves bool type across the sandbox boundary. So `context.get("self_driving_review")` is only ever `True`, `False`, or `None` (absent). Tests confirm the strict-bool contract (`context["self_driving_review"] is True`). For all three real values, `bool(...)` and the suggested `is True` produce identical results.+- **Impact:** the described widening (`bool("false") == True`) cannot be reached without an upstream contract change that the typed `bool` parameter and source-side `bool(...)` coercion already exclude; PR-controlled untrusted content never sets this key either. That makes it a speculative "what if" / defensive-coding hardening against a value upstream types rule out — below the surfacing bar (precision over recall).++### [❌ dismissed] should_fix · bug — products/stamphog/backend/tasks/tasks.py:1107-1245++**QUEUED-run restart in the inbox leg swallows workflow-start failures, stranding the run**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** In `process_inbox_pr_review`, when the dedupe finds an existing QUEUED run (an earlier attempt committed the row but its post-commit workflow start failed, e.g. Temporal briefly down), the restart is scheduled via `transaction.on_commit(lambda: _start_review_workflow(existing_run_id, team_id), using=run_write_db)` and the task then returns successfully. `_start_review_workflow` only swallows `WorkflowAlreadyStartedError`; any other failure (Temporal unreachable) raised inside an `on_commit` callback after the task returns success is not retried — the run is left QUEUED with no workflow. This is weaker than the webhook path's equivalent: `_resume_existing_delivery_run` calls `_start_review_workflow` synchronously so an error propagates and the Celery task retries (with the dedupe then re-entering to restart the still-QUEUED run). The PR's own docstring frames the QUEUED restart as the durable recovery for a committed-but-unstarted run; making it fire-and-forget on `on_commit` undermines that recovery, since the only thing that re-triggers it is a future TaskRun output save (which may never come).+- **Suggestion:** Restart the QUEUED run synchronously inside the transaction's scope so a start failure propagates to the task's `except Exception` and triggers a retry — mirroring `_resume_existing_delivery_run`. For example, call `_start_review_workflow(existing_run_id, team_id)` directly (it is already idempotent) and let the surrounding `try/except` retry, instead of deferring to `on_commit`. This keeps the inbox leg's recovery at parity with the webhook leg's.+- **Validator:** - **Checked:** The inbox-leg QUEUED-restart and new-run `transaction.on_commit(...)` calls (diff `tasks.py:1145` and `:1165`), the enclosing `with transaction.atomic(using=run_write_db):` inside `try/except ...retry(exc=e)` (diff `:1170-1172`), `_start_review_workflow` (base `:251-266`), `_resume_existing_delivery_run` (base `:268-297`), and the webhook path's new-run start (base `:912-943`).+- **Found (premise is wrong):** Django runs `on_commit` hooks registered inside the outermost `atomic()` block synchronously during `Atomic.__exit__` (after `connection.commit()`, via `run_and_clear_commit_hooks`), NOT after the Celery task returns. A `process_inbox_pr_review` is a top-level Celery task with no ATOMIC_REQUESTS/outer transaction, so its `with transaction.atomic(using=run_write_db)` IS the outermost block. The `return` in the QUEUED branch triggers `__exit__` before the function actually returns; if `_start_review_workflow` raises there (Temporal unreachable — `_start_review_workflow` only swallows `WorkflowAlreadyStartedError`, base `:264`), the exception propagates out of `__exit__`, is caught by the surrounding `except Exception as e:` (diff `:1170`), and hits `raise ...retry(exc=e)`. The run is committed QUEUED before the hook runs, so the retry re-enters the dedupe (`select_for_update` on `(pull_request, head_sha)`) and re-schedules the restart. This is the documented durable recovery, and it works.+- **Found (no asymmetry in the claimed direction):** The webhook path's own NEW-run start uses the identical `transaction.on_commit(lambda: _start_review_workflow(...))` pattern (base `:926`) with an explicit comment: "Let a post-commit start failure propagate: it lands in the `except Exception` below and retries the Celery task." So the author relies on exactly this Django semantics, and the inbox leg mirrors it. `_resume_existing_delivery_run` is synchronous only because it runs OUTSIDE any transaction (a post-commit recovery keyed on `delivery_id` in a later delivery); the inbox leg has no `delivery_id` and instead does its recovery in-transaction via the head-keyed dedupe + on_commit — functionally equivalent, both propagate-and-retry.+- **Impact (why it does not meet the bar):** The finding is Wrong/unreproducible — it assumes on_commit fires after the task returns success and is unretried, but the hook runs inside the atomic `__exit__` within the retry-protected `try`, so a start failure does retry and the QUEUED run is not stranded. No reliability defect exists; parity with the webhook leg holds.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:113-217++**`_resolve_repo_config` runs twice for positively identified self-driving PRs**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** For a webhook delivery that the carve-out positively identifies as self-driving, `_inbox_rereview_carve_out` calls `_resolve_repo_config(installation_id, repo)` (an unscoped, writer-pinned `StamphogRepoConfig` query). When the carve-out succeeds, control returns to the main path, which calls `_resolve_repo_config(installation_id, repo)` again unconditionally (the existing line ~781) before creating the run. So every carved-out re-review resolves the same repo config twice. It's a single indexed query so the cost is modest, but it's pure duplication on the rare path the PR explicitly optimizes for, and the carve-out already validated `enabled`, `installation_id`, and `connected_by_user_id`.+- **Suggestion:** Have `_inbox_rereview_carve_out` (or `_InboxCarveOut`) carry the resolved `repo_config` it already validated, and reuse it on the main path instead of re-resolving. This removes the duplicate query for carved-out runs while leaving the non-carve-out path (the common case) untouched.+- **Validator:** - **Checked:** All `_resolve_repo_config` call sites (base `tasks.py:174` def; `:781` main-path; carve-out internal call), and the carve-out control flow (a carved-out delivery has `inbox_review is not None`, so the skip block does not `return` and falls through to `:781`).+- **Found (premise is factually true):** For a positively-identified self-driving re-review, `_inbox_rereview_carve_out` calls `_resolve_repo_config(installation_id, repo)` once, then the main path re-calls it unconditionally at `:781` before creating the run — two identical `unscoped().using(db_for_write).filter(...).order_by(...).first()` queries per carved-out delivery.+- **Impact (why it does not meet the bar):** It is a single indexed lookup (the finding concedes "the cost is modest") on a rare path — later pushes to self-driving inbox PRs whose acting reviewer opted in, a small subset of webhook deliveries. It is not N+1, not unbounded, not on a hot path, not blocking I/O — none of the performance shapes the criteria keep ("bites at real scale"). No correctness, contract, or security dimension: both reads are writer-pinned and equivalent, and re-resolving on the main path is if anything more current. The suggested fix (thread the resolved `repo_config` through `_InboxCarveOut`) adds coupling to shave one negligible query — a micro-optimization / minor duplication cleanup, which per precision-over-recall (on the fence → drop) does not clear the keep bar.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:113-217++**Carve-out runs a tasks-facade lookup plus a review_hog resolver hook on every bot-authored head-changing webhook**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Once a delivery clears the `_is_bot_authored` pre-filter, `_inbox_rereview_carve_out` unconditionally issues a `find_signal_implementation_run` DB lookup (the pr_url leg is backed by a partial index, so cheap, but the branch leg is not) and then calls the registered `InboxActingReviewerResolver` (a review_hog-side DB read of the acting reviewer's current toggle) for every bot-authored `synchronize`/`reopened`/base-retarget — including dependabot, renovate, and posthog-bot pushes that will always resolve to an empty carve-out. The resolver can't be trivially cached because it depends on the live toggle state. On a burst of bot pushes across many teams this is extra per-event DB load on the webhook Celery worker for the common no-op case.+- **Suggestion:** Short-circuit earlier where possible: the carve-out already requires a synced+enabled config, so most unconfigured-bot pushes already exit at `_resolve_repo_config`. Consider also checking `find_signal_implementation_run`'s result before invoking the resolver (it already does), which avoids the resolver call for PRs with no matching task run — the dominant case. If the resolver is the remaining cost, confirm whether review_hog's resolver can read the toggle cheaply (e.g., a cached settings row) and document that expectation, since this hook now runs on the hot webhook path.+- **Validator:** - **Checked:** The full `_inbox_rereview_carve_out` guard ordering (diff `tasks.py`), `find_task_run` (`products/tasks/backend/webhooks.py:30`), and when the resolver is actually invoked.+- **Found (resolver claim is factually wrong):** The registered resolver is called only AFTER `find_signal_implementation_run` returns a non-None team-matched run; `if run is None or run.team_id != repo_config.team_id: return _InboxCarveOut()` sits before it. Dependabot/renovate/posthog-bot pushes carry no signal-report linkage, so they return None at that check and the resolver never runs for them. The finding's headline ("calls the resolver ... for every bot-authored") contradicts its own suggestion ("checking find_signal_implementation_run's result before invoking the resolver — it already does"). So the alarming part of the cost claim does not exist. (Separately, per the internal-flag bug, `find_signal_implementation_run` currently always returns None, so the resolver is unreachable regardless.)+- **Found (real cost is marginal):** The one genuinely-new per-event query is `find_signal_implementation_run`, and only for bot-authored, head-changing, repo-native pushes on a synced+enabled Stamphog config. Its primary `find_task_run` leg filters on `output__pr_url` (index-backed, per the finding); the branch leg is a fallback reached only when the PR has no recorded pr_url — self-driving PRs record one, so the cheap leg dominates. It is a single query per event, not N+1, not unbounded, not quadratic, and the primary leg is indexed — none of the performance shapes the criteria keep.+- **Found (dwarfed by existing work):** That same skip path, for head-changing bot pushes, already calls `_resolve_repo_config` and `_retract_stale_approvals_on_skip`, which makes GitHub API calls to list/dismiss approvals. One extra indexed DB lookup is negligible relative to the network I/O the path already performs per event.+- **Impact (why it does not meet the bar):** A micro-optimization on a niche subset of webhook events, with its most-serious sub-claim (resolver on every bot push) factually incorrect and its main suggestion already implemented in the code. Does not clear the "bites at real scale" bar; per precision-over-recall, drop.++### [❌ dismissed] must_fix · bug — products/stamphog/backend/tasks/tasks.py:113-121++**`_parse_pr_url` regex typo (`\\s` vs `\s`) makes the receiver leg silently no-op for any repo whose slug contains the letter 's'**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The added regex is `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\\s]+)/pull/(\d+)")`. The two character classes are NOT equivalent. The first, `[^/\s]`, correctly excludes `/` and whitespace (the `\s` shorthand). The second, `[^/\\s]`, is inside a raw string, so the regex engine sees `[^/\\s]` = an escaped backslash (`\\` -> literal `\`) followed by a literal `s`. That class excludes `/`, `\`, and the letter **s** — not whitespace. Consequently the repo half of `owner/repo` cannot contain the letter `s`. `_parse_pr_url('https://github.com/posthog/posthog/pull/123')` returns None, as does any PR whose repo slug contains an `s` (posthog, analytics, widgets, ...). Verified directly: posthog/posthog, PostHog/posthog, acme/widgets, and posthog/analytics all fail to match, while acme/widget and foo/bar match. `process_inbox_pr_review` then logs `stamphog_inbox_pr_unparseable_url` and returns without creating a run — so Leg 1 (the initial receiver review, the entire point of this PR) silently does nothing for the common case, including the PostHog/posthog repo itself. The existing host-anchoring finding examined only generic owner/repo strings and so missed this: the typo doesn't widen the match, it narrows it to near-uselessness.+- **Suggestion:** Make the two classes identical. Use the whitespace shorthand in both halves, e.g. `r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)"`, or better, anchor and capture cleanly: `r"github\.com/([^/]+?)/([^/]+)/pull/(\d+)"` (then validate owner/repo shape). Add a unit test that parses `https://github.com/posthog/posthog/pull/123` and a repo name containing 's' to lock the fix. Also consider anchoring to the host (per the existing finding) so lookalike domains don't parse as github.com.+- **Validator:** - **Checked:** The exact bytes of the added `_PR_URL_RE` line via byte-accurate `repr()` of the diff, and empirically ran the real regex against `s`-containing slugs.+- **Found (premise is false):** The actual source is `_PR_URL_RE = re.compile(r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)")` (diff `tasks.py:831`). Byte-accurate `repr` returns `'...([^/\\s]+/[^/\\s]+)...'` — repr doubles each single backslash, so BOTH character classes are `[^/\s]` (single backslash + `s`, the whitespace shorthand), identical. There is no `[^/\\s]` (literal-backslash-then-`s`) typo in the second class; the finding misquotes the regex.+- **Found (empirically disproven):** Running the real regex, `posthog/posthog` → `('posthog/posthog', 123)`, `PostHog/posthog` → matched, `posthog/analytics` → matched, `acme/widgets` → matched. Slugs containing `s` parse correctly, directly contradicting the finding's "verified" claim that they return None.+- **Impact (why it does not meet the bar):** Wrong / unreproducible — the defect does not exist in the code. Leg 1 does not silently no-op on `s`-containing repos. No change is warranted; a `must_fix` on a fabricated typo is a false positive.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_local.py:292-311,316-321++**Familiarity computation is not gated on self_driving, so the provenance block's 'familiarity carries no signal' claim is enforced only by the server, not the engine**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The provenance block added in reviewer.py::`_format_self_driving` (683-703) tells the LLM 'The author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here.' But the engine never enforces that claim itself. In review_local.run, after the bot-author refusal is skipped for a self-driving run, `_attach_familiarity` (292-311) still reads context['author_pr_numbers'] and, for a T1-agent tier, populates classification['familiarity'] via `_familiarity_offline` — unconditionally, with no `self_driving` guard. `_format_familiarity` (reviewer.py 635-680) then renders a full 'Author familiarity ... band STRONG / author last-touched X% of the lines' block immediately before the self_driving_block (line 568: `{constraint}{familiarity_block}{self_driving_block}`). The prompt therefore contradicts itself: one paragraph says familiarity carries no signal, the preceding paragraph presents the machine user's familiarity as a trusted fact. The contradiction is only avoided because the stamphog server (a different chunk) omits author_pr_numbers for self-driving runs — an external convention the engine does not verify. If that server-side omission ever regresses, the engine would silently bias the reviewer toward approving a bot-authored draft using the machine user's own merged-PR/blame history, which is exactly the signal the carve-out is meant to exclude. The same regression also surfaces in the public verdict comment: `_render_review_body` (review_pr.py 855-860) emits a 'Author wrote X% of the modified lines and has Y merged PRs in these paths (familiarity STRONG).' bullet whenever familiarity.band is STRONG/MODERATE, so a self-driving approval could be posted to GitHub citing the machine user's familiarity as the basis — the opposite of the carve-out's intent.+- **Suggestion:** Gate familiarity on the carve-out flag at the engine boundary, mirroring how every other relaxed gate is guarded by self_driving. In `_attach_familiarity` (review_local.py ~299), return early when pipeline.self_driving is set, e.g. `if pipeline.self_driving or pipeline.classification.get('tier') != 'T1-agent': return`. For full parity, also short-circuit `_maybe_compute_familiarity` in review_pr.py when self.self_driving (the Action never sets it, so this is defense-in-depth). This makes 'familiarity carries no signal here' a property the engine guarantees from its own state, not one it asserts on the server's behalf — and it keeps the prompt and the public comment from ever presenting the machine user's familiarity as an approval basis, even if the server-side omission later weakens.+- **Validator:** - **Checked:** the engine familiarity path (`review_local.py` `_attach_familiarity` L292-311 and its consumer `_familiarity_offline`), the prompt assembly (`reviewer.py` `_format_familiarity`/`_format_self_driving`), and the server that populates the context — `products/stamphog/backend/tasks/tasks.py` around the `author_pr_numbers` / `self_driving_review` assignment, plus the end-to-end test.+- **Found:** the server sets `author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []` (diff L1216) and `self_driving_review=bool(output.get("inbox_review"))` (diff L1227) — both derived from the _same_ `run.output["inbox_review"]` value in adjacent lines, not two independent conventions. Engine-side, `_attach_familiarity` returns early when `author_pr_numbers` is falsy (`review_local.py:302`), so for every self-driving run familiarity is `None`, `_format_familiarity` renders `""`, and `_render_review_body` emits no familiarity bullet. The e2e test asserts `context["author_pr_numbers"] == []` for the self-driving case (diff L1289).+- **Impact:** no defect as written or as reached — there is no self-contradicting prompt and no machine-user familiarity in the public comment today. The claimed harm requires a future regression that changes L1216 to fetch author PRs for inbox reviews while leaving the flag on; that regression would also break the existing `author_pr_numbers == []` test. This is 'already handled elsewhere' (confirmed by reading the server) plus a speculative defense-in-depth 'what if', which the bar drops. The `should_fix` priority overstates a hardening suggestion against a non-occurring, test-guarded condition.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-2.mdnew file mode 100644index 000000000000..d163ca99ffc6--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/B-glm52-max-2.md@@ -0,0 +1,338 @@+# Reviewer-quality run — `B-glm52-max-2`++- **Dumped:** 2026-07-23T20:54:40+00:00+- **Report id:** `019f906f-a157-7254-914f-9fbfb7853c5b` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 5425s (90.4 min)++## Config snapshot++- runtime / model / effort: `claude` / `@cf/zai-org/glm-5.2` / `max`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 24 | 19 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| ------------------- | --------------------------- | ------- | -------------- | ----------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 116 | 105,675 | 701,932 | 12,056,236 | 133,754 | 4 | $14.29 | $14.29 |+| claude-sonnet-5 | dedup | 1 | 17,799 | 0 | 0 | 6,852 | 0 | $0.10 | $0.10 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 533 | 0 | $0.02 | $0.02 |+| @cf/zai-org/glm-5.2 | review | 376 | 23,502,173 | 0 | 0 | 97,266 | 0 | — | $0.00 |+| @cf/zai-org/glm-5.2 | blind-spot | 204 | 11,350,268 | 0 | 0 | 66,045 | 0 | — | $0.00 |+| **total** | | **698** | **34,984,944** | **701,932** | **12,056,236** | **304,450** | **4** | **$14.41** | **$14.41** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `@cf/zai-org/glm-5.2` (580 gen(s), gw $0.00).+- naive method (all prompt tokens at input price): $67.79 — 4.7× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $38.5167 over 698 gen(s) (true $10.9972, Δ +250.2%)+ - · of which cache read: $6.0281 over 114 gen(s) (true $6.0281, Δ +0.0%)+ - · of which cache write: $4.3871 over 116 gen(s) (true $4.3871, Δ +0.0%)+ - · of which fresh (derived): $28.1015 over 698 gen(s) (true $0.5820, Δ +4728.2%)+ - output: $3.8230 over 698 gen(s) (true $3.4177, Δ +11.9%)+- 4 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | ------------------- |+| …24e3b1fd | issues-review-p1-c2 | 19:25:31 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …cbeb20c2 | issues-review-p1-c1 | 19:25:32 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …fb26932f | issues-review-p3-c1 | 19:25:33 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …12dee680 | issues-review-p2-c2 | 19:25:33 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …49a9588f | issues-review-p1-c3 | 19:25:34 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …4403dbec | issues-review-p3-c2 | 19:25:38 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …495bcc94 | issues-review-p2-c3 | 19:25:39 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …c8e39413 | issues-review-p3-c3 | 19:25:48 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …3509a075 | issues-review-p2-c1 | 19:25:54 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …5e2d35bb | blind-spots-c3 | 19:44:33 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …73ad98d8 | blind-spots-c1 | 19:44:33 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …e5694db8 | blind-spots-c2 | 19:44:35 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …0ff4b059 | blind-spots-c4 | 19:44:42 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …cdea44bb | blind-spots-c4 | 19:47:28 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …8c056f46 | blind-spots-c2 | 20:12:11 | 0 | 0 | @cf/zai-org/glm-5.2 |+| …f67e3703 | validation-c4 | 20:32:03 | 17,141 | 21,791 | claude-opus-4-8 |+| …40f92c17 | validation-c3 | 20:32:03 | 0 | 39,545 | claude-opus-4-8 |+| …aabf9d20 | validation-c1 | 20:32:10 | 17,141 | 22,425 | claude-opus-4-8 |+| …afa77452 | validation-c2 | 20:32:35 | 17,141 | 22,719 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **3/19** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 8s |+| review wave (perspectives) | 19m 17s |+| blind-spot sweep | 46m 22s |+| dedup (incl. combine/clean) | 1m 10s |+| validation | 21m 41s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 65m 39s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 3 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | review-hog-perspective-performance-reliability | 2 |+| 1000 | 1 | review-hog-blind-spots-general | 2 |+| 1000 | 2 | review-hog-blind-spots-general | 3 |+| 1000 | 3 | review-hog-blind-spots-general | 1 |+| 1000 | 4 | review-hog-blind-spots-general | 2 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:1-17++**max_migration.txt not bumped to the new 0019 migration**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The PR adds a new Postgres migration `0019_reviewusersettings_stamphog_review_inbox_prs.py` to the `review_hog` product, but the companion marker file `products/review_hog/backend/migrations/max_migration.txt` is not updated and still reads `0018_backfill_urgency_threshold_to_consider`. This marker is a repo convention kept in sync with the latest migration by every product app (e.g. `products/signals/backend/migrations/max_migration.txt` points at its latest `0071_signalscoutnote`). `max_migration.txt` is consumed as the 'latest migration' marker by the sandbox DB-cache staleness check (`bin/sandbox::check_migration_staleness`, which compares the cached schema version against the branch's `max_migration.txt`) and by the hogli rollback tooling (`temporary_max_migration` operates against this marker). The stamphog migration-risk consumer explicitly documents that 'the bumped marker file is part of the same logical change' as the migration (`tools/pr-approval-agent/migration_risk.py`). Leaving it stale means rollback tooling and cache-staleness checks reason about `0018` as the head of the `review_hog` migration sequence while `0019` exists in the tree.+- **Suggestion:** Update `products/review_hog/backend/migrations/max_migration.txt` to `0019_reviewusersettings_stamphog_review_inbox_prs` in the same change as the new migration, matching the convention used by other product apps (signals, posthog, ee).+- **Validator:** - **Checked:** `products/review_hog/backend/migrations/max_migration.txt` and the `0019` migration on the actual PR head (`1341596e`), plus which commit last touched the marker.+- **Found:** On the PR head the marker reads exactly `0019_reviewusersettings_stamphog_review_inbox_prs` — byte-identical to the new migration's name (verified via `diff`). `git log -- max_migration.txt` shows it was last changed by the PR's own base commit `bd6d4288` ("feat(stamphog): review self-driving inbox PRs behind a per-user toggle"), and `git show bd6d4288` on the file shows the `0018 → 0019` bump landing in the same commit as the migration.+- **Found:** The finding's `0018` reading only reproduces against a stale checkout that predates the PR (where neither the `0019` file nor the `stamphog_review_inbox_prs` field exist at all); once the PR head is checked out, the marker is already correct.+- **Impact:** The premise ("marker not updated, still reads `0018`") is factually false for this PR, so none of the claimed consequences (stale rollback/cache-staleness reasoning, migration-risk drift) occur. Under the criteria this is a wrong/unreproducible finding and must be dropped.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/reviewer.py:683-703,568++**Self-driving provenance block asserts familiarity carries no signal, but the engine never suppresses the familiarity block**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new `_format_self_driving` provenance block (rendered inside the == TRUSTED CONTEXT == region, appended at reviewer.py:568) tells the reviewer: "The author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here." But nothing in the engine suppresses the competing familiarity block when self_driving is set. `_format_familiarity` still renders whenever classification["familiarity"] is non-None (reviewer.py:635-645), and `Pipeline._maybe_compute_familiarity` / `review_local._attach_familiarity` still run unconditionally on the T1-agent path. The contradiction is only avoided by an out-of-engine contract: the hosted server must omit author_pr_numbers so the offline signal stays None, and the Action runtime must never set self_driving (so its gh-based `_compute_familiarity` never fires for a carve-out run). If a future caller or a server regression sets self_driving=True while also supplying author history, the trusted prompt would carry both "author familiarity carries no signal here" AND a concrete familiarity block (e.g. "author last-touched X% of the lines, Y merged PRs in these paths") — mutually contradictory trusted context for the very judgment the reviewer is asked to make. The PR claims a parity invariant ("both runtimes share one implementation of the relaxed gates"), but the familiarity suppression that the provenance block promises is not part of that shared implementation; it is left entirely to the server contract.+- **Suggestion:** Make the engine enforce the invariant the prompt asserts. When self_driving is set, skip familiarity computation and force the block empty, e.g. in `_maybe_compute_familiarity` / `_attach_familiarity`: `if self.self_driving: self.familiarity = None; return` (and equivalently early-return in `review_local._attach_familiarity`), plus have `_format_familiarity` return "" when cl.get("self_driving") is truthy. That guarantees the provenance block's claim holds regardless of what any caller passes in, and keeps the carve-out's trust semantics in one place rather than split across the engine prompt and the server's data-supply contract. Add a test that self_driving + author_pr_numbers present still yields an empty familiarity block (the current test suite only covers the absent-author_pr_numbers path).+- **Validator:** - **Checked:** the actual PR diff (head `1341596e`) for `_format_self_driving` (reviewer.py), the familiarity attach paths (`review_pr.Pipeline._maybe_compute_familiarity`, `review_local._attach_familiarity`), and every producer of the engine context — `fetch_review_context` / `run_review_in_sandbox` in the stamphog server.+- **Found:** the finding's mechanical premise is correct — reviewer.py appends `{familiarity_block}{self_driving_block}` and the engine never suppresses `_format_familiarity` when `self_driving` is set. But the contradictory state cannot be reached. Hosted path: `_attach_familiarity` early-returns unless `context["author_pr_numbers"]` is truthy, and in `fetch_review_context` both signals derive from the _same_ `run.output["inbox_review"]` on adjacent lines — `is_inbox_review` forces `author_pr_numbers = []` while `self_driving_review=bool(output.get("inbox_review"))`. So `self_driving=True` ⇒ `author_pr_numbers=[]` ⇒ familiarity stays `None` ⇒ the block renders empty. Action path: `Pipeline.self_driving` defaults `False` and nothing in the Action ever sets it, so `_format_self_driving` returns `""` there regardless of familiarity. The PR's own e2e test asserts `self_driving_review is True` and `author_pr_numbers == []` together.+- **Impact:** this is a defense-in-depth request to re-enforce in the engine what the server already guarantees at a single, two-line source of truth. It requires a hypothetical future server regression that decouples the two — a speculative what-if, not a state real inputs hit. Even if triggered, the consequence is a mildly contradictory LLM _prompt_ (soft quality degradation), not a correctness/security/data-loss/contract defect. Under the criteria (speculative what-if + already-handled + precision-over-recall), this is noise to surface to the author.++### [❌ dismissed] consider · best_practice — products/review_hog/backend/receivers.py:114-138++**Receiver fires two on_commit callbacks that each do their own deferred import; verify broker-down on the stamphog leg never blocks the ReviewHog leg**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** When both toggles are on, two independent `transaction.on_commit` lambdas are registered: one for `_start_review` and one for `_start_stamphog_review`. Each defers its own heavy import to call time (temporal client vs the stamphog facade). They run sequentially on the commit callback. `_start_stamphog_review` is wrapped in try/except so a broker/publish failure is swallowed (good — matches the 'broker being down must never surface into the saver' invariant), but the import of `queue_inbox_pr_review` itself happens inside the try, so an import-time failure (e.g. the facade module raising on import due to a misconfigured stamphog product DB) is also swallowed and only logged. That is acceptable, but it means a stamphog-side import regression silently no-ops the stamphog leg with no obvious signal beyond a logged exception, while the ReviewHog leg proceeds normally — a silent partial-failure that's easy to miss operationally.+- **Suggestion:** Confirm the deferred import sits inside the try block intentionally (it does) and that the 'review_hog_stamphog_inbox_review_queue_failed' log is wired into monitoring. Consider a metric/counter on the queue-failed path so a persistent stamphog-leg failure (import or publish) is observable as a rate, not just a log line, since the two legs now fail independently and a dead stamphog leg is invisible to users whose ReviewHog leg still works.+- **Validator:** - **Checked:** `_start_stamphog_review` at `products/review_hog/backend/receivers.py:210-234`, the two `on_commit` registrations at 116 and 131, and the failure-logging path.+- **Found:** The finding's core premise is factually wrong. The deferred import `from products.stamphog.backend.facade.api import queue_inbox_pr_review` is at line 222 — **outside** the `try:` that begins at line 224 (which wraps only the `queue_inbox_pr_review(...)` call). So an import-time failure is _not_ swallowed by the try/except; only a publish/broker failure is, and that path emits a distinct `logger.exception("review_hog_stamphog_inbox_review_queue_failed")` (line 234) — a failure signal, not a silent no-op.+- **Found:** The 'broker-down must not block the ReviewHog leg' invariant the title asks to verify already holds two ways: the ReviewHog `on_commit` (line 116) is registered before the stamphog one (line 131) so it runs first and independently, and the stamphog publish is itself wrapped in try/except. There is no defect to fix here — the finding says as much ("That is acceptable", "Confirm... (it does)").+- **Impact:** What remains is a monitoring nice-to-have — 'add a metric/counter so the queue-failed path is observable as a rate, not just a log line.' The failure is already logged with a greppable, distinct message; there is no correctness, data-loss, security, contract, or performance defect. Under precision-over-recall this is a `consider`-level observability suggestion that does not meet the keep bar, and its concrete premise (import swallowed inside the try) is mistaken.++### [❌ dismissed] consider · best_practice — tools/pr-approval-agent/review_pr.py:937-938++**Engine stamphog_review_completed analytics lack a self-driving marker while to_dict() carries the audit trail**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** This chunk adds `"self_driving": self.self_driving` to the `to_dict()` classification block (the persisted verdict JSON, line 937-938), giving the output contract a self-driving audit trail. But the engine's own `stamphog_review_completed` analytics event (`_capture_review_completed`, lines 790-854) emits no `stamphog_self_driving_review` (or equivalent) property. The version bump's stated purpose is to let verdict quality and reviewer behavior be segmented by version in LLM analytics; for self-driving runs the engine now behaves differently (bot author allowed, draft prerequisite relaxed, provenance block in the prompt), yet an engine-emitted event for such a run is indistinguishable from a normal human-PR event on every property the engine sets. The PR intent attributes the analytics stamp to a follow-up commit and notes the hosted server stamps it via its analytics-extra hook, so this is a deliberate split rather than an oversight — but it leaves the Action runtime path with no engine-side self-driving signal at all (the server hook never runs there), and any engine-only telemetry consumer loses the ability to trend self-driving verdict quality separately until the follow-up lands.+- **Suggestion:** Add `"stamphog_self_driving_review": self.self_driving` to the `properties` dict in `_capture_review_completed` (next to `stamphog_version`/`stamphog_commit_type`), so every engine-emitted `stamphog_review_completed` event — Action and hosted alike — carries the carve-out marker independently of the server hook. This makes the version-bump's segmentation goal hold for self-driving runs at the engine layer (where the behavior change actually lives) rather than depending on a separate server-side stamp, and it costs nothing for normal runs (the prop is just False).+- **Validator:** - **Checked:** `_capture_review_completed` (review_pr.py:806-855) and how its `properties` dict is built; `analytics_extra_properties()` (gateway.py); the offline entrypoint's call chain (`review_local.run` → `_llm_review` → `_capture_review_completed`, review_pr.py:804); and the server's context/env stamping.+- **Found:** the event's `properties` begins with `**analytics_extra_properties()` (review_pr.py:822), which reads the `STAMPHOG_EXTRA_PROPERTIES` env JSON. The hosted server sets `extra_properties["stamphog_self_driving_review"] = True` for inbox runs (keyed off `run.output["inbox_review"]`, the same source that sets `self_driving_review`) and serializes it into that env var. So a hosted self-driving `stamphog_review_completed` event **already carries** `stamphog_self_driving_review: True` — the premise that it is 'indistinguishable on every property the engine sets' is false for the hosted path.+- **Found:** `self.self_driving` is only ever `True` on the hosted path (`review_local` sets it from context); `review_pr.Pipeline` never sets it. The Action runtime therefore performs **no** self-driving runs, so 'the Action path has no engine-side self-driving signal' is vacuous — the suggested `"stamphog_self_driving_review": self.self_driving` would be a constant `False` there, adding no segmentation value.+- **Impact:** dismissal — this is a pure telemetry-redundancy nicety (duplicate an already-present marker on the only meaningful path, add a constant-False elsewhere), guarding against a hypothetical future decoupling of two signals that today derive from one source. No correctness/security/data-loss/contract/performance/reliability consequence; the durable audit trail already lives in `to_dict()`. Under precision-over-recall (overengineering + partly-mistaken premise), drop.++### [✅ VALID] must_fix · bug — products/tasks/backend/facade/api.py:505-510++**find_signal_implementation_run rejects internal tasks, but signals implementation tasks are created internal=True — the webhook-leg carve-out is dead in production**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** find_signal_implementation_run returns None whenever `task.signal_report_id is None or task.internal`. But the self-driving implementation run it exists to identify is created with `internal=True`: `products/signals/backend/auto_start.py` calls `tasks_facade.create_and_run_task(..., signal_report_id=report_id, interaction_origin="signal_report", internal=True)` — the comment there even says 'Internal so the run stays out of the default task list', and `interaction_origin="signal_report"` is what 'Makes the agent auto-push and open a draft PR'. Every signals-origin task (auto_start, research, select_repo, custom_agent) is `internal=True`; only the test seeders (seed_inbox_data.py / seed_refund_test_data.py) use `internal=False`. So in production, find_task_run matches the run but the `task.internal` guard immediately rejects it, find_signal_implementation_run returns None, and `_inbox_rereview_carve_out` resolves empty for every genuine self-driving PR — the entire webhook-leg (leg 2) re-review never fires. Worse, the PR's claimed 'tasks-side tests' for the facade almost certainly build fixtures with `internal=False` (the seeder convention), so the carve-out tests pass against fixtures that don't match production reality, giving false confidence that the feature works.+- **Suggestion:** Drop the `task.internal` term from the guard (the positive-identification signal is `signal_report_id` set on a SIGNAL_REPORT-origin run, not non-internals). If internal tasks must be excluded for some other reason, reconcile that with the production creator: either change `auto_start.py` to create implementation tasks with `internal=False`, or flip the guard to require what production actually sets. Critically, add a test that creates the run through the real `tasks_facade.create_and_run_task(..., internal=True)` path (or asserts on `auto_start.create_implementation_task`'s actual `internal` value) so the fixture matches production and a regression here fails CI instead of silently shipping a dead carve-out.+- **Validator:** - **Checked:** the added `find_signal_implementation_run` guard, the production creator of self-driving implementation tasks, the `create_and_run_task` → `Task.internal` mapping, `find_task_run` matching semantics, the actual caller (`_inbox_rereview_carve_out`), and the PR's tasks-side test fixtures.+- **Found (guard):** the new function (products/tasks/backend/facade/api.py, added ~L1718 in the diff) does `if task.signal_report_id is None or task.internal: return None`, and its docstring insists on "a non-internal task carrying a signal report."+- **Found (production reality):** `products/signals/backend/auto_start.py:254-261` creates the PR-opening implementation task via `create_and_run_task(..., signal_report_id=report_id, interaction_origin="signal_report", internal=True)` — the `interaction_origin` comment is literally "Makes the agent auto-push and open a draft PR," and `internal=True` is passed. `create_and_run_task` forwards `internal` straight to `Task.internal` (products/tasks/backend/facade/api.py:850). The PR does **not** modify `auto_start.py`, so master's `internal=True` stands.+- **Found (match lands on that exact run):** `webhooks.find_task_run` matches `output__pr_url=pr_url` (repo-scoped), so it returns the very `internal=True` auto_start run that opened the PR; the guard then rejects it.+- **Found (tests mask it):** the facade test's `_make_run` defaults `internal=False`, its positive cases rely on that default, and `test_non_qualifying_runs_return_none` includes `("internal_pipeline_task", {"internal": True}, {})` asserting internal→None — i.e. the suite locks in rejection of the exact shape production emits.+- **Impact:** for every genuine self-driving PR, leg-2's `_inbox_rereview_carve_out` gets `find_signal_implementation_run(...) is None` → returns an empty `_InboxCarveOut()` → no webhook re-review ever fires. A documented leg of the shipped feature is dead in production, and the tests give false green. Concrete trigger + consequence are both nameable, so it clears the correctness-bug bar; must_fix is appropriate given it's the 100% common production case, not an edge case.++### [❌ dismissed] consider · documentation — products/stamphog/AGENTS.md:92-95++**Provenance field name in carve-out contract may not match implementation**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new carve-out section asserts the engine flag is set "exclusively from the run's persisted inbox provenance (`ReviewRun.output[\"inbox_review\"]`)". The PR description's follow-up commit describes the run provenance differently: a `trigger` field ("webhook" | "inbox") plus a `stamphog_self_driving_review` stamp on engine analytics. These name different fields for what reads like the same provenance concept. If the actual persisted key is not `inbox_review`, the contract doc points future engineers at a nonexistent key — any query/audit they write against `output["inbox_review"]` silently returns nothing, and a future "do not relax" edit could key off the wrong field.+- **Suggestion:** Confirm the exact key(s) stamped on `ReviewRun.output` for inbox provenance against the implementation (the receiver-leg stamp in `process_inbox_pr_review` and the webhook-leg stamp). If the key is `trigger` or a nested `inbox_review` object containing `trigger`, align the doc to match — name the precise field and its value set so the contract is quotable. If `inbox_review` is correct, confirm `trigger` lives elsewhere and clarify both.+- **Validator:** - **Checked:** The added AGENTS.md line against the actual stamping/derivation sites in the PR diff — the two `ReviewRun.output` writes, the engine-flag derivation, and the analytics stamp.+- **Found:** The documented key is exactly what the code uses. Both legs persist `output={"inbox_review": inbox_review}` (receiver leg at diff L1160; webhook leg at diff L1030), and the server derives the engine flag exclusively from it: `self_driving_review=bool(output.get("inbox_review"))` (diff L1227). An added code comment at the same call site restates the doc verbatim ("set exclusively from the run's inbox provenance").+- **Found:** The `trigger` field the finding worries about is a _nested_ key inside the `inbox_review` dict (`{"trigger": "webhook", ...}` at diff L928/L1108), a webhook-vs-receiver leg discriminator — not a competing top-level provenance key. `stamphog_self_driving_review` (diff L1201) is an analytics extra-property name, itself gated on `output.get("inbox_review")`. Neither renames the documented key; both coexist with it.+- **Impact:** The premise (that `ReviewRun.output["inbox_review"]` may not exist, or that `trigger`/`stamphog_self_driving_review` are the same provenance concept under a different name) is refuted by the implementation. A future audit querying `output["inbox_review"]` returns exactly the provenance dict, as documented. No contract drift, so the finding does not meet the keep bar (wrong/unreproducible premise).++### [❌ dismissed] consider · documentation — products/stamphog/AGENTS.md:80-80++**Carve-out invariant section splits the egress→trust-boundaries flow**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new "self-driving inbox carve-out" section is inserted between "Sandbox credentials and egress" (ends L78) and "Trust boundaries" (now L114), wedging a refusal/trust invariant into the middle of the egress discussion. The carve-out is conceptually a trust-boundary invariant (it defines when the bot-author refusal — itself a trust boundary — is relaxed), so its current position reads as a detour between two adjacent sandbox/egress and trust-boundary sections.+- **Suggestion:** Consider moving the carve-out section to sit adjacent to (or as a subsection of) "Trust boundaries", or directly after the stale-approval/supersession invariants where the refusal lives, so the egress → trust-boundaries flow stays contiguous and the carve-out reads as a scoped exception to an existing invariant rather than a standalone interjection.+- **Validator:** - **Checked:** The AGENTS.md diff hunk placement — the new `## The self-driving inbox carve-out` section is inserted at the `@@ -77,6 +77,40 @@` hunk, after the "Sandbox credentials and egress" bullets and before "## Trust boundaries". The finding's factual claim about section ordering is accurate.+- **Found:** The entire concern is where a prose section sits relative to its neighbors in a docs file. There is no behavioral, correctness, security, contract, performance, or reliability consequence — the section's content is identical wherever it lands, and section order does not affect any code or reader-reachable contract.+- **Impact:** This is pure documentation-organization taste ("reads as a detour", "flow stays contiguous"). The validation bar explicitly drops "Pure style / taste ... with no behavioral difference"; placement of a self-contained invariant section is defensible either way (a major carve-out earning its own prominent heading is reasonable), so it does not meet the keep bar.++### [❌ dismissed] should_fix · bug — products/review_hog/backend/receivers.py:144-158++**Webhook-leg resolver re-resolves the latest suggested_reviewers artefact, so reviewer reassignment can shift whose stamphog toggle gates a re-review away from the user who authorized the initial review**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The receiver leg (initial review) and the webhook leg (later pushes) both call `_resolve_assigned_reviewer`, which keys the acting reviewer off the report's **latest** `suggested_reviewers` artefact. The initial stamphog review is queued because acting reviewer R1's `stamphog_review_inbox_prs` is on. On a later push, `resolve_stamphog_acting_reviewer` re-resolves against the _current_ latest artefact — if the report's reviewers were reassigned in the meantime, the acting reviewer is now R2, and the re-review is gated against R2's toggle, not R1's. If R2 hasn't opted in, the resolver returns None and the webhook leg skips the re-review. The PR's stated invariant is that a toggle switched off mid-PR still dismisses the stale approval, but that dismissal behavior lives in the stamphog webhook path (another chunk) and is gated on the resolver returning the user; if R2's opt-out makes the resolver return None, whether R1's stale approval from the initial (draft-time) review gets dismissed on the pushed head depends entirely on that other chunk's skip path. The review authorization for a given PR can thus drift from the user who actually authorized it, which is a subtler failure mode than the toggle-value drift the PR description addresses (it only discusses the same acting reviewer flipping their toggle).+- **Suggestion:** Confirm in the stamphog webhook-leg chunk that a None return from the registered resolver still triggers `dismiss_stale_approvals` for a head-changing push (so a reassignment-induced opt-out retracts R1's stale approval rather than leaving it pinned to an old head). If the dismissal is tied to entering the workflow, consider keying the webhook-leg acting reviewer on the persisted run provenance (the reviewer who authorized the initial review) rather than re-resolving the latest artefact, so the same user's toggle governs the whole PR lifecycle unless they explicitly reassign ownership.+- **Validator:** - **Checked:** `_resolve_assigned_reviewer` (receivers.py:159-207), the webhook carve-out `_inbox_rereview_carve_out` (tasks.py:201-215), and the caller's head-changing skip path (tasks.py:870-912), tracing what happens when a later push re-resolves to a different / opted-out acting reviewer.+- **Found:** The reviewer-drift premise is real (receivers.py:180-188 orders `suggested_reviewers` by `-created_at`), but the claimed _consequence_ is not. Any `None` from the resolver — reviewer reassigned to an opted-out R2, or no reviewer resolving at all — becomes `_InboxCarveOut(opted_out=True)` (tasks.py:205-207), and the caller then, for `action in _HEAD_CHANGING_ACTIONS`, calls `_retract_stale_approvals_on_skip(..., _INBOX_OPT_OUT_DISMISS_MESSAGE if carve_out.opted_out ...)` (tasks.py:887-898) under a retry guard. There is even a dedicated opt-out dismissal message for exactly this case.+- **Found:** The dismissal operates on the _App's_ standing approval keyed on head moves (`dismiss_stale_approvals_for_head`), independent of which user the resolver returned — so R1's draft-time approval is retracted on the pushed head regardless of the R1→R2 drift. The stale-approval invariant is preserved on this path.+- **Impact:** The finding's actionable ask ('confirm a None return still triggers dismissal for a head-changing push') is already satisfied in the code, so its safety concern is unreproducible. The residual point — that the _current_ assignee's toggle governs the re-review rather than the original authorizer's — is intentional, documented behavior (`_resolve_assigned_reviewer` docstring: assignment = the latest artefact, matching the Inbox 'For you' filter) that leaves no unsafe state. Neither half clears the keep bar.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_local.py:316-321++**self_driving carve-out flag uses fragile truthiness on a context JSON value that bypasses two safety gates**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The carve-out is enabled with `self_driving=bool(context.get("self_driving_review"))`. `self_driving` relaxes exactly two safety gates — the bot-author refusal and the draft prerequisite — so it is the single contract that decides whether a bot-authored draft PR is reviewed. `bool()` on a JSON value is only correct when the server emits a JSON boolean: `bool(True)`/`bool(False)` behave, but `bool("false")`, `bool("0")`, or any non-empty string yields `True`, silently enabling the carve-out for a PR the server did not intend to carve out. The PR description says the server 'derives it only from the run's persisted inbox provenance,' so today it serializes a real boolean, but the entrypoint takes the value at face value with no type guard, so a future server change (a string field, an env-var leak into the JSON) would bypass the bot-author and draft gates rather than fail closed.+- **Suggestion:** Treat the flag strictly so the contract fails closed on anything but an explicit boolean. For example: `self_driving=context.get("self_driving_review") is True`, or a small helper that coerces only `True`/`False` and ignores strings. This keeps the default-off invariant robust against a server that ever serializes the flag as a string, and makes it obvious at the trust boundary that only a verified boolean enables the carve-out.+- **Validator:** - **Checked:** the consumer `bool(context.get("self_driving_review"))` (review_local.py:321) and every producer of that context key — the server context-builder signature/body and its call site, plus the tests that set it.+- **Found:** the producing side always emits a genuine JSON boolean: the builder param is typed `self_driving_review: bool = False` and inserted verbatim as `"self_driving_review": self_driving_review`, and the only call site sets it via `bool(output.get("inbox_review"))`. The PR's integration test asserts `context["self_driving_review"] is True` (identity check) — which only passes for a real boolean, proving the serialized value is never a string. No producer stringifies it.+- **Found:** given a boolean input, `bool()` is already correct and fails closed: `True`→True, `False`→False, key-absent→`None`→False. The described failure (`bool("false")` → True) requires the server to serialize a truthy _string_, which no current code path does.+- **Impact:** dismissal — the trigger is unreachable given the call sites; it depends on a hypothetical future server regression that would itself be the actual bug. This is defensive-coding hardening at a server→engine boundary the producer already types as `bool`, not a defect any real input hits. The suggested `is True` alters no current behavior. Speculative-what-if + defensive-paranoia → drop under precision-over-recall.++### [❌ dismissed] consider · documentation — products/review_hog/backend/api/settings.py:72-81++**stamphog_connected enables the toggle for any stamphog repo, not the inbox PR's repo**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `get_stamphog_connected` calls `has_reviewable_repo_config(team_id)`, which returns True if the team has at least one synced+enabled StamphogRepoConfig for ANY repository. The inbox trigger, however, reviews a PR for a specific repository, and `queue_inbox_pr_review`'s downstream gating no-ops when that PR's repo has no matching config. So a user who has Stamphog connected for repo A can enable the inbox-Stamphog toggle, then have an inbox PR opened against repo B (no Stamphog config): the toggle shows enabled/active, the receiver queues a Celery task, and the task silently does nothing. The UI promises a review that never lands. This is by design per the PR description ('at least one synced, enabled Stamphog repository'), so it is not a hard bug, but the help_text ('Only takes effect when the project has a synced, enabled Stamphog repository') overstates the guarantee — it is per-repository, not per-project.+- **Suggestion:** Clarify the help_text on `stamphog_connected` / `stamphog_review_inbox_prs` to say the review only runs when the PR's own repository has a synced+enabled Stamphog config, so users understand the toggle being enabled does not guarantee every inbox PR is reviewed. No code-path change needed.+- **Validator:** - **Checked:** `has_reviewable_repo_config` (`products/stamphog/backend/facade/api.py:112-125`), `queue_inbox_pr_review` (`api.py:128-155`), and the two help_text strings at `products/review_hog/backend/api/settings.py:29-32` and `:51-53`.+- **Found:** The finding's mechanics are factually correct: `has_reviewable_repo_config` does `.filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` with no `repository=` filter (any repo), while `queue_inbox_pr_review`'s docstring confirms the PR's-repo config resolution is a 'silent no-op without one' inside the Celery task — so gating is genuinely per-repo downstream.+- **Found:** But the existing copy is not actually overstated. `stamphog_review_inbox_prs` says 'Only takes effect when the project has a synced, enabled Stamphog repository' — a necessary-condition ('only … when') framing, not an every-PR guarantee — and `stamphog_connected` explicitly says 'at least one synced, enabled Stamphog repository', which is precisely the project-level semantics. Neither promises that every inbox PR is reviewed.+- **Impact:** The finding self-identifies as 'not a hard bug' (behavior is by design) and asks only for a help_text wording refinement with no code-path change. That is a `consider`-level documentation-copy nuance on text that is already accurate — it is not a correctness/security/data/contract/performance/reliability defect. Under precision-over-recall this does not clear the keep bar.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:191-217,871-881++**Carve-out path resolves the repo config twice**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** On a delivery that trips a skip filter, `_inbox_rereview_carve_out` calls `_resolve_repo_config(installation_id, repo)` (and validates enabled/connected) to resolve the carve-out. If the carve-out succeeds, the skip path is bypassed and the main path calls `_resolve_repo_config(installation_id, repo)` again immediately afterward at line ~781 to get the same config. For the opted_out case, the skip path's `if action in _HEAD_CHANGING_ACTIONS:` block resolves the config a second time via `_resolve_repo_config` for the dismissal. So every carve-out delivery pays two identical config lookups against the writer DB. Because `StamphogRepoConfig` has a unique constraint on (provider, installation_id, repository), both calls are guaranteed to return the same row, so the redundancy is purely a wasted query, not a correctness hazard.+- **Suggestion:** Thread the already-resolved config out of the carve-out. Either extend `_InboxCarveOut` to carry the resolved `repo_config` (set only when provenance/opted_out is set) and reuse it on the main path and skip-dismiss path, or have `_inbox_rereview_carve_out` return the config alongside provenance so the caller can skip the second `_resolve_repo_config`. This keeps the rare bot-authored-PR branch to one config lookup per delivery.+- **Validator:** - **Checked:** `_inbox_rereview_carve_out` (diff L862-935), the `_InboxCarveOut` dataclass (diff L848-859), the main-path and skip-dismiss config resolution, and the cost/shape of `_resolve_repo_config` (tasks.py:174-189).+- **Found (premise is accurate):** the carve-out calls `_resolve_repo_config` (diff L897); `_InboxCarveOut` carries only `provenance`/`opted_out` — not the config — so the main path re-resolves at the pre-existing `repo_config = _resolve_repo_config(...)` (tasks.py:781), and the opted-out branch re-resolves at `skip_repo_config = _resolve_repo_config(...)` (tasks.py:763). Two identical lookups on the carve-out path, as claimed.+- **Found (cost is trivial):** `_resolve_repo_config` (tasks.py:183-188) is a single-row lookup on `(provider, installation_id, repository)` — the issue itself notes this is uniquely constrained — pinned to the writer DB. It's constant per delivery, not per-row, not in a loop, not N+1, and only runs on the rare branch reached by a bot-authored, repo-native, head-changing/base-retarget self-driving PR (every human/fork/non-inbox delivery returns before it).+- **Impact (below the bar):** the finding is one duplicate cheap indexed query on a rare path; the issue itself concedes it is "purely a wasted query, not a correctness hazard." That is a micro-optimization, not a performance problem that bites at real scale (no N+1, hot-path index miss, quadratic, or blocking async I/O). The proposed fix trades a negligible query for added coupling (threading the resolved config through the DTO). Under precision-over-recall this is noise to drop, not surface.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:68-75,894-909++**Opt-out dismissal copy/log inconsistent on a base retarget**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** When a self-driving PR is positively identified but its acting reviewer is opted out (`carve_out.opted_out=True`) on a `base_retargeted` delivery (action == "edited"), the carve-out returns opted_out with no provenance. The skip path then logs `reason="inbox_opt_out"`, but the dismissal itself is NOT the `_INBOX_OPT_OUT_DISMISS_MESSAGE` — the retraction block is gated on `if action in _HEAD_CHANGING_ACTIONS` (which excludes "edited"), so the earlier base-retarget retraction at lines ~738-748 already ran with the generic `_BASE_RETARGET_DISMISS_MESSAGE`. So a reviewer reading the GitHub dismissal sees 'The PR was retargeted to a different base branch...' while the internal log says `inbox_opt_out`, which can be confusing when correlating why an approval was dismissed on an opted-out self-driving PR. The retarget copy is technically accurate (the PR was retargeted), so this is a clarity issue, not a correctness bug.+- **Suggestion:** Either extend the opt-out dismissal to the base-retarget path (e.g. pass `carve_out.opted_out` into `_retract_approvals_on_base_retarget` so it uses `_INBOX_OPT_OUT_DISMISS_MESSAGE` when opted out), or document in a comment that base retargets intentionally use the retarget copy regardless of opt-out. The latter is fine if intentional; just make the log reason consistent with the dismissal copy a reader will actually see on the PR.+- **Validator:** - **Checked:** `_HEAD_CHANGING_ACTIONS` (tasks.py:46 = `{"synchronize","reopened"}`), the `base_retargeted` derivation (tasks.py:720, `action == "edited"`), the unconditional base-retarget retraction (tasks.py:738-748 → `_retract_approvals_on_base_retarget` with `_BASE_RETARGET_DISMISS_MESSAGE` at tasks.py:745/356), and the PR's skip-path/opt-out changes (diff L971-995).+- **Found:** the mechanics are exactly as described — on a base retarget the standing approval is dismissed first at tasks.py:738 with the retarget copy, independent of the carve-out; the opt-out dismissal is gated on `action in _HEAD_CHANGING_ACTIONS` (diff, mirroring tasks.py:759) which excludes `"edited"`, so `_INBOX_OPT_OUT_DISMISS_MESSAGE` never posts on a retarget; the skip log records `reason="inbox_opt_out"` (diff L991). Premise is accurate.+- **Impact (below the bar):** no correctness, safety, or behavioral consequence — the stale-approval invariant holds (the approval IS retracted via the retarget path), the retarget copy is accurate (the PR really was retargeted), and the `inbox_opt_out` log reason is also accurate (the review really was skipped for opt-out). The two messages describe two different sub-events, both true; there is no contradiction that changes any outcome. This is a wording/clarity nuance on an extremely narrow path (self-driving bot draft + opted-out reviewer + base-retarget `edited` delivery + a pre-existing standing approval), which the issue itself concedes is "a clarity issue, not a correctness bug." Pure style/log-copy taste with no behavioral difference falls in the drop set under precision-over-recall.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected cross-DB read runs on every settings PATCH, coupling the write path to the stamphog product DB**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** stamphog_connected is a SerializerMethodField, so it is computed on every serialize — including the PATCH response (`return Response(serializer.data)` at the settings action). This endpoint is the Code review tab's always-called settings endpoint, and the field reads from the stamphog product database (a separate DB behind the fail-fast circuit breaker). On the write path the UI only needs confirmation of the saved scalar fields (the toggles, urgency_threshold), not a fresh repo-config lookup, so each settings save now does an extra cross-product DB round-trip. The fail-fast circuit breaker (connect_timeout=3s, cooldown) and the broad `except Exception` → False keep an outage from taking the endpoint down, but on the happy path every save pays the latency of a stamphog DB query it doesn't need, and a slow-but-not-failing stamphog DB adds wall-clock to every settings PATCH.+- **Suggestion:** Either drop stamphog_connected from the PATCH response (return only the persisted scalar fields, or a serializer variant without the method field on writes), or memoize the repo-config check per request so a single settings GET/PATCH pays for it at most once. If the parity of the PATCH response shape matters to the frontend, at least confirm the frontend ignores stamphog_connected on the PATCH round-trip so the extra read is genuinely safe to skip. The GET path legitimately needs it (it gates the UI); the PATCH path does not.+- **Validator:** - **Checked:** the PATCH branch at `products/review_hog/backend/api/settings.py:133-137`, the `get_stamphog_connected` method (`:71-81`), and the underlying query in `has_reviewable_repo_config` (`products/stamphog/backend/facade/api.py:120-124`).+- **Found:** The extra work per PATCH is a single `.exists()` existence check (`StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()`) on a small per-repo config table — not an N+1, unbounded, quadratic, or index-missing query. It is already wrapped in a fail-soft `try/except` behind the documented fail-fast circuit breaker (3s connect timeout + cooldown), so a stamphog-DB outage fails fast to `False` rather than adding latency.+- **Found:** The endpoint (`user_settings`, `:130-143`) is a human-triggered settings save fired when a user toggles a switch in the Code review tab — a low-frequency action, not a per-event/per-row hot path. The GET side of the same action already does heavier work (`seed_canonicals_tolerantly` at `:142`), so one lightweight existence query on the write side is not the endpoint's cost driver.+- **Impact:** This is a micro-optimization / `consider`-level perf-reliability nit that does not 'bite at real scale' — the criteria's performance keep bar. The proposed fixes (drop the field on writes / a write-only serializer variant / per-request memoization) add complexity to preserve GET/PATCH response-shape parity in exchange for saving one cheap, already-guarded query on a cold path. Under precision-over-recall this should be dropped.++### [❌ dismissed] consider · best_practice — products/review_hog/backend/api/settings.py:71-82++**Broad except Exception in get_stamphog_connected swallows the failure category; consider distinguishing transient vs permanent for observability**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The fail-soft `except Exception: logger.exception(...); return False` is the right safety posture (an informational UI flag must not 500 the settings endpoint), and `logger.exception` preserves the stack trace. But every failure mode — circuit-breaker open (transient, expected during a stamphog outage), a genuine programming error in has_reviewable_repo_config, a connectivity blip — collapses into the same `stamphog_connected=False` + a single exception log. Under a stamphog outage this logs an exception on every settings GET (the tab's always-called endpoint), which can be noisy and makes it hard to separate 'stamphog is down, degrade gracefully' (expected) from 'the repo-config query is broken' (a real bug).+- **Suggestion:** Catch the circuit-breaker / operational error classes separately and log them at info/debug level as an expected degradation (e.g. 'review_hog_stamphog_connected_unavailable'), while keeping a narrower `except Exception` at error level for genuinely unexpected failures. This keeps the fail-soft behavior but lets on-call tell a transient outage from a regression, and avoids exception-spam during a stamphog DB incident.+- **Validator:** - **Checked:** the `except Exception` handler at `products/review_hog/backend/api/settings.py:77-81` and what it currently does on failure.+- **Found:** The error is not swallowed or hidden — `logger.exception("review_hog_stamphog_connected_check_failed")` records the full stack trace at error level, and the finding explicitly concedes this is 'the right safety posture' and that the trace is preserved. The only ask is to split the single `except` into transient (circuit-breaker-open → info/debug) vs unexpected (error) classes for log-level hygiene.+- **Found:** Implementing it requires review_hog to import and match stamphog's internal circuit-breaker/operational exception taxonomy across the facade boundary, adding coupling to shave log verbosity on a low-frequency, human-triggered settings endpoint — the 'exception-spam' scenario scales with settings-tab loads, not event/row throughput.+- **Impact:** This is a `consider`-level observability/log-level refinement on error handling that is already correct and fully observable — no correctness, security, data-loss, contract, performance-at-scale, or swallowed-failure defect. It falls in the overengineering/taste drop bucket; under precision-over-recall it should be dropped.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:113-217++**Carve-out pays a cross-DB tasks lookup before checking the toggle resolver is registered**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** In `_inbox_rereview_carve_out`, the `get_inbox_acting_reviewer_resolver() is None` check runs _after_ two database reads: `_resolve_repo_config` (a stamphog product-DB query) and `find_signal_implementation_run` (which calls `find_task_run` against the separate tasks product DB via the indexed `output__pr_url` lookup, plus a `task` join). When review_hog is absent from INSTALLED_APPS (resolver is None) the gate fails closed either way, but every bot-authored head-changing PR on a synced+enabled repo still pays the cross-DB tasks lookup for nothing before discovering there is no resolver to answer the toggle question. Bot-authored PRs are rare on this path so the absolute cost is low, but the resolver check is a cheap module-global read and could short-circuit the expensive leg entirely.+- **Suggestion:** Hoist the `resolver = get_inbox_acting_reviewer_resolver()` / `if resolver is None: return _InboxCarveOut()` check to just after the fork-safety guard (before `_resolve_repo_config`), so deployments without `review_hog` never issue the tasks-DB query. Keep the resolver _call_ (and the `opted_out` distinction) where it is now — only the None short-circuit moves. This keeps the fail-closed semantics identical while cutting the wasted cross-DB read on the no-resolver path.+- **Validator:** - **Checked:** the ordering inside `_inbox_rereview_carve_out` (diff L862-935: `_resolve_repo_config` ~L897, `find_signal_implementation_run` ~L909, then `resolver = get_inbox_acting_reviewer_resolver()` / `if resolver is None` ~L919-921), and where the resolver is registered (diff L149-166: review_hog's `connect()`, called from `AppConfig.ready()`, runs `register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer)`).+- **Found:** the premise is accurate — the None short-circuit does sit after both DB reads. But `get_inbox_acting_reviewer_resolver()` returns None only if review_hog's `AppConfig.ready()` never registered the hook, i.e. review_hog is absent from INSTALLED_APPS. stamphog and review_hog ship together in the monorepo deployment, so on every real webhook delivery the resolver is already registered and non-None.+- **Impact (below the bar):** the proposed hoist saves nothing on any production delivery, because the resolver is always present there; it only trims work in a stamphog-without-review_hog configuration that doesn't exist in the real deployment — and even then only on the already-rare bot-authored, head-changing, repo-native branch, saving two indexed single-row lookups (`_resolve_repo_config` and the `output__pr_url` task lookup). That is neither an N+1, a hot-path index miss, quadratic behavior, nor blocking async I/O, so it fails the "performance problems that bite at real scale" test; the finding itself concedes "the absolute cost is low." A speculative micro-optimization for a non-existent-in-production config is noise to drop under precision-over-recall.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:1107-1245++**Receiver-leg dedupe requires a GitHub PR fetch on every refire, including no-op refires**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `process_inbox_pr_review` fetches the PR from GitHub before the head-keyed dedupe because the dedupe keys on the PR's _current_ head, which only GitHub knows. The receiver re-fires on every `TaskRun` output save carrying `pr_url`, so a same-head refire (the common case during a live run) still costs one `get_pr` GitHub API call before it no-ops. The code comment and the review_hog receiver both acknowledge this ('a same-head re-trigger costs one fetch'), so it is by design and precedented — but from a reliability standpoint it concentrates GitHub API budget on the receiver leg: under bursty output saves (e.g. the agent server persisting progress) each save fires a `get_pr`, and on rate-limiting the task retries with `countdown=max(retry_after or 0, 60)` up to `max_retries=3`. After exhaustion the initial review is dropped, and per the PR intent this leg has 'no webhook redelivery behind it', so a sustained rate-limit window can silently lose the toggle-gated review the leg exists to guarantee.+- **Suggestion:** Two options worth weighing: (1) cache the last-seen head per (team, pr_url) in the Django cache with a short TTL and skip the fetch entirely when a live-or-delivered run already exists at that head — only the first refire and post-push refires would fetch; or (2) if accepting the per-refire fetch, consider raising `max_retries` for this task specifically (or a longer base delay) since, unlike the webhook task, there is no redelivery backstop. At minimum, confirm the expected TaskRun output-save frequency is low enough that the per-refire `get_pr` cost stays inside GitHub's secondary rate limit.+- **Validator:** - **Checked:** `process_inbox_pr_review` (diff L1042-1175) — the `get_pr`-before-dedupe ordering, the rate-limit branch, and the retry config; plus the review_hog receiver `handle_task_run_saved` / `_start_stamphog_review` (diff L170-260) to gauge how often the task is enqueued and under what gate.+- **Found (premise holds):** `get_pr` (diff ~L1085) does run before the head-keyed `select_for_update` dedupe (diff ~L1128-1140), and `_start_stamphog_review` enqueues on every TaskRun save carrying a `pr_url` when `stamphog_review_inbox_prs` is on — so a same-head refire costs one fetch before it no-ops.+- **Found (failure mode already handled):** the fetch's rate-limit path is explicit, not swallowed — `except GitHubRateLimitError: retry(countdown=max(e.retry_after or 0, 60))`, with `max_retries=3` and a `stamphog_inbox_pr_fetch_rate_limited` warning log (diff ~L1088-1093). The path is opt-in (`stamphog_review_inbox_prs` defaults off) and scoped to one self-driving PR at a time, so fetch volume is one `get_pr` per output save for a single PR — bounded, not N+1 or unbounded.+- **Impact (below the bar):** the claimed "silent loss" requires a sustained GitHub secondary-rate-limit window lasting across all three ≥60s-spaced retries during one PR's refires — a speculative compound condition — and even then the consequence is a delayed/dropped best-effort draft-time initial review that is logged, not data loss or a correctness break. The per-refire fetch is a consciously accepted design tradeoff (the task and receiver comments state it), and the finding's own suggestion is partly "confirm the output-save frequency" — a request to verify an assumption rather than a named defect with a trigger+consequence that will actually occur. Handled failure mode + speculative trigger + bounded low-severity outcome → drop under precision-over-recall.++### [❌ dismissed] consider · performance — products/review_hog/backend/receivers.py:144-160++**Webhook-leg toggle re-check runs the full reviewer resolution (artefact query + multi-table org-identity lookups) on every synchronize/reopened webhook for self-driving PRs**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `resolve_stamphog_acting_reviewer` is called by stamphog's webhook path before every re-review of a self-driving PR on a later push. It calls `_resolve_assigned_reviewer`, which does a `SignalReportArtefact.objects.filter(...).order_by('-created_at').first()` query (signals DB) plus `resolve_org_github_login_to_users`, which in turn runs several main-DB queries (`Team`, `UserSocialAuth`, `UserIntegration`, `Integration`, `User` with prefetches) to map GitHub logins to org members. Unlike the receiver leg — which already did this work once and is gated behind a TaskRun save — this re-runs on every `synchronize`/`reopened`/retarget webhook delivery for the PR, even when the acting reviewer and their toggle have not changed since the initial review. The acting reviewer's identity and toggle are stable across most pushes, so this is repeated redundant resolution work on a webhook path. (This is distinct from the settings-GET `stamphog_connected` cross-DB read the performance perspective covered; this is the per-push webhook resolver cost, on a different trigger.)+- **Suggestion:** Consider caching the resolved acting reviewer + toggle decision per (team, signal_report, head) with a short TTL, or have the webhook leg pass the already-known signal_report_id / acting reviewer from the persisted run provenance so the resolver can short-circuit when the report's suggested_reviewers artefact hasn't changed (e.g., compare artefact id/updated_at rather than re-resolving logins each time). At minimum, document that every self-driving PR push costs a signals artefact query plus the org-identity resolution fan-out.+- **Validator:** - **Checked:** the resolver chain — `resolve_stamphog_acting_reviewer` → `_resolve_assigned_reviewer` (receivers.py:144-207) → `resolve_org_github_login_to_users` (products/signals/backend/report_generation/resolve_reviewers.py:304-331), and the carve-out gating that decides when the resolver even runs (tasks.py:167-205).+- **Found:** The per-call cost is bounded, not pathological: one `SignalReportArtefact` `.order_by('-created_at').first()`, one `Team` org lookup, a candidate-id narrowing, and a single batched `User.objects.filter(id__in=candidate_ids).prefetch_related(...)` (explicitly 'restricts DB work to users that plausibly match the requested logins') — a handful of indexed queries over a report's small reviewer set, not N+1-per-login, unbounded, or quadratic.+- **Found:** The resolver is reached only after the carve-out passes every cheap gate first (tasks.py:167-200): head-changing action, bot-authored, repo-native (non-fork), synced+enabled config, and a `find_signal_implementation_run` task match. So it fires only for machine-generated self-driving inbox PRs on a new push — a low-volume slice, not a hot path.+- **Found:** Fresh re-resolution on each push is required by design: the webhook leg 're-checks this toggle before every re-review' so a mid-PR opt-out stops new runs (receivers.py:148-149, stamphog carve-out invariant). The suggested per-(team,report,head) TTL cache would risk serving a stale toggle decision, trading a documented safety property for negligible gain.+- **Impact:** A `consider`-level perf micro-optimization on a narrowly-gated, low-frequency webhook branch — it does not 'bite at real scale' (the performance keep bar), and the proposed caching is overengineering that conflicts with a safety invariant. Drop under precision-over-recall.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1245++**Receiver leg stamps self_driving_review=True with no positive run-linkage check, so an agent-supplied pr_url can redirect a real approval onto any PR in a configured repo**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `process_inbox_pr_review` takes `pr_url` from the caller (`review_hog`'s receiver, which reads it from the TaskRun's `output.pr_url` — agent-controlled, not externally validated), parses repo+number, resolves a synced+enabled StamphogRepoConfig for the _parsed_ repository, fetches that PR, and stamps `output={"inbox_review": {...}}` from the caller-supplied signal_report_id/task_run_id/acting_user_id — without ever verifying the fetched PR corresponds to that signals run (no find_signal_implementation_run, no branch/repo linkage check like the webhook carve-out performs). The activities then derive `self_driving_review=bool(output.get("inbox_review"))` purely from that stamp. The engine's self_driving carve-out relaxes the bot-author refusal, the draft prerequisite, AND — on the hosted path — the per-repo review_mode gate and the author-write-permission lookup. So unlike the webhook leg, which positively identifies the PR via find_signal_implementation_run before any gate is bypassed, the receiver leg trusts the URL entirely: a prompt-injected or buggy signals agent that writes an `output.pr_url` pointing at any open PR in any repo the team has a synced Stamphog config for (including a human-authored, ready-for-review PR) causes Stamphog to fetch it, bypass bot/draft/review_mode/write-permission, and post a real head-pinned GitHub approval there. The blast radius is 'any PR in any of the team's configured repos', and the leg's stated purpose is exactly to post approvals, so this is an unintended-approval path, not a theoretical one.+- **Suggestion:** Before creating the run, positively link the fetched PR to the originating signals run the same way the webhook leg does: call find_signal_implementation_run(team_id, repository=parsed_repo, pr_url=pr_url, head_branch=`pr['head']['ref']`) (or a variant keyed on task_run_id) and require a match whose signal_report_id equals the caller-supplied signal_report_id; bail to a no-op (do not stamp inbox_review) on mismatch. At minimum, assert the fetched PR is bot-authored and draft (the self-driving shape) before stamping self_driving_review — today the receiver leg never checks either, so even the engine's relaxed gates are entered on a human PR solely because the caller said so.+- **Validator:** - **Checked:** the full `process_inbox_pr_review` body (diff L1042-1175), the webhook carve-out `_inbox_rereview_carve_out` (diff L862-935), the engine's `self_driving` derivation and gate relaxation (diff L1227/1941/1999), and the write path for `output.pr_url` (`set_output` action → `set_task_run_output`).+- **Found (no positive linkage on the receiver leg):** `process_inbox_pr_review` parses the caller-supplied `pr_url`, resolves a team-scoped enabled `StamphogRepoConfig` for the _parsed_ repo, fetches that PR, and stamps `output={"inbox_review": ...}` (diff L1160) after only URL-parse, `state == open`, and `head_sha` checks — it never calls `find_signal_implementation_run`, never checks `_is_bot_authored`, and never checks `draft`.+- **Found (the webhook leg does guard):** the carve-out is consulted only when `skip_reason is not None` (bot/draft PRs) and hard-requires `if not _is_bot_authored(pr): return _InboxCarveOut()` (diff L886-890). So a human, ready PR can never receive the webhook carve-out — but the receiver leg applies `inbox_review` to whatever `pr_url` resolves to. This asymmetry is real, not framing.+- **Found (the stamp is the only key to real gate relaxation):** activities set `self_driving_review=bool(output.get("inbox_review"))` (diff L1227), which the engine uses to skip the bot-author refusal (`if self.pr.author_is_bot and not self.self_driving`, diff L1941) and the draft prerequisite (`if pr.draft and not self.self_driving`, diff L1999), ending in a real head-pinned APPROVE.+- **Found (trust boundary is real):** `output.pr_url` is caller-supplied via the `task:write` `set_output` endpoint (presentation/views/api.py:1106-1123 → `set_task_run_output`, api.py:2144-2158), validated only against the task's `json_schema`, not against the PR the agent actually opened; auto_start grants `posthog_mcp_scopes="full"` and the seeding signal-report content is untrusted, so a prompt-injected or buggy implementation agent can write an arbitrary `pr_url`. The in-code comment at diff L446-448 asserts "both trigger paths stamp only after positively linking the PR to a signals implementation run" — which is false for the receiver leg.+- **Impact:** a poisoned/buggy `output.pr_url` pointing at any open human PR in any repo the team has a synced+enabled Stamphog config for → the receiver leg stamps `inbox_review`, the engine bypasses the bot-author and draft refusals, and posts a real GitHub approval (capable of satisfying required reviews) on a PR no human asked it to review. This is an authorization gap that the feature's own positive-identification invariant (enforced on the webhook leg) is meant to prevent; the fix (mirror `find_signal_implementation_run`, or at minimum assert bot-authored+draft before stamping) is cheap and aligns the legs. Reachability is partly contingent on the receiver actually firing (it gates on a non-internal signal-report task, which interacts with the internal-flag mismatch), but it is a real latent security hole in an approval-posting path, so must_fix stands.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/tasks/tasks.py:68-75,894-898++**Opt-out dismissal copy says 'New commits were pushed' on a reopened self-driving PR, where no commits were pushed**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `_INBOX_OPT_OUT_DISMISS_MESSAGE` leads with 'New commits were pushed — dismissing the stamphog approval from an earlier head.' The skip path posts it whenever `action in _HEAD_CHANGING_ACTIONS` and `carve_out.opted_out`. `_HEAD_CHANGING_ACTIONS` includes `reopened`, which does not move the head or push commits. So a self-driving PR that is closed and reopened while its acting reviewer is opted out gets a GitHub dismissal comment claiming new commits were pushed, which is false. (Distinct from the already-covered base-retarget case, which is about the wrong message being selected; here the opt-out message itself is selected but is factually wrong for the reopen action.)+- **Suggestion:** Either narrow `_HEAD_CHANGING_ACTIONS` so the opt-out dismissal only fires on actual head moves (synchronize), or branch the dismissal copy on the action: for `reopened` use wording that does not claim commits were pushed (e.g. 'The PR was reopened — dismissing the stamphog approval. No reviewer currently has stamphog inbox reviews enabled for this self-driving PR, so stamphog will not re-review.').+- **Validator:** - **Checked:** `_HEAD_CHANGING_ACTIONS` (tasks.py:46 = `{"synchronize","reopened"}`), the new `_INBOX_OPT_OUT_DISMISS_MESSAGE` text (diff L818-822), the three pre-existing sibling dismissal messages (`_LABEL_SKIP_DISMISS_MESSAGE` / `_AUTHOR_SKIP_DISMISS_MESSAGE` / `_UNTRUSTED_SKIP_DISMISS_MESSAGE`, tasks.py:49-63), and the skip-path posting gate.+- **Found (premise holds):** `reopened` is in `_HEAD_CHANGING_ACTIONS` and does not push commits, so the opt-out message's leading "New commits were pushed" is inaccurate on a reopen.+- **Found (it's a pre-existing house convention, not new):** all three existing skip messages open with the byte-identical "New commits were pushed — dismissing the stamphog approval from an earlier head." and are posted under the same `action in _HEAD_CHANGING_ACTIONS` gate — so a reopened human PR already gets "New commits were pushed" from `_UNTRUSTED_SKIP_DISMISS_MESSAGE` today. The new opt-out message merely matches its siblings; the PR introduces no novel class of inaccuracy.+- **Impact (below the bar):** this is cosmetic user-facing-copy imprecision in a GitHub dismissal comment on a very narrow path (self-driving bot draft + opted-out reviewer + `reopened` action + an actual standing approval to dismiss). There is no behavioral, correctness, or safety consequence — the dismissal action itself is correct and the remainder of the message conveys the real takeaway (no reviewer opted in, stamphog won't re-review). Fixing it properly would mean rewording all four messages, not this one in isolation. Pure copy-wording taste with no behavioral difference, consistent with existing convention → drop under precision-over-recall.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-1.mdnew file mode 100644index 000000000000..53d154c761b9--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-1.md@@ -0,0 +1,192 @@+# Reviewer-quality run — `C-gpt55-xhigh-1`++- **Dumped:** 2026-07-23T23:54:56+00:00+- **Report id:** `019f9122-1671-7715-b230-7d4b3c188cf5` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 4548s (75.8 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 7 | 10 | 7 | 0 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ----------- | ---------- | --------- | ---------- |+| gpt-5.5 | review | 125 | 6,704,951 | 0 | 0 | 37,337 | 0 | — | $10.24 |+| claude-opus-4-8 | validation | 72 | 65,094 | 461,606 | 6,680,772 | 62,010 | 0 | $8.10 | $8.10 |+| gpt-5.5 | blind-spot | 42 | 2,323,297 | 0 | 0 | 16,361 | 0 | — | $3.04 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,317 | 0 | $0.03 | $0.03 |+| claude-sonnet-5 | dedup | 1 | 8,947 | 0 | 0 | 576 | 0 | $0.02 | $0.02 |+| **total** | | **241** | **9,111,318** | **461,606** | **6,680,772** | **117,601** | **0** | **$8.16** | **$21.44** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.5` (167 gen(s), gw $13.28).+- naive method (all prompt tokens at input price): $37.64 — 4.6× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $18.2573 over 241 gen(s) (true $6.5868, Δ +177.2%)+ - · of which cache read: $7.0594 over 224 gen(s) (true $3.3404, Δ +111.3%)+ - · of which cache write: $2.8850 over 72 gen(s) (true $2.8850, Δ +0.0%)+ - · of which fresh (derived): $8.3129 over 241 gen(s) (true $0.3614, Δ +2200.1%)+ - output: $3.1801 over 241 gen(s) (true $1.5692, Δ +102.7%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …43b87b49 | issues-review-p3-c3 | 22:40:16 | 0 | 0 | gpt-5.5 |+| …85a94951 | issues-review-p1-c1 | 22:40:17 | 0 | 0 | gpt-5.5 |+| …29877be3 | issues-review-p3-c2 | 22:40:18 | 0 | 0 | gpt-5.5 |+| …86111420 | issues-review-p3-c1 | 22:40:19 | 0 | 0 | gpt-5.5 |+| …8e8becec | issues-review-p1-c3 | 22:40:24 | 0 | 0 | gpt-5.5 |+| …17e59cb8 | issues-review-p1-c2 | 22:40:28 | 0 | 0 | gpt-5.5 |+| …f92da0d8 | issues-review-p2-c1 | 22:40:30 | 0 | 0 | gpt-5.5 |+| …44e43599 | issues-review-p2-c2 | 22:40:31 | 0 | 0 | gpt-5.5 |+| …d2302dc5 | issues-review-p2-c3 | 22:40:33 | 0 | 0 | gpt-5.5 |+| …b62698aa | issues-review-p1-c2 | 23:10:42 | 0 | 0 | gpt-5.5 |+| …b1eab0e9 | issues-review-p2-c1 | 23:10:43 | 0 | 0 | gpt-5.5 |+| …e0680321 | issues-review-p2-c2 | 23:10:43 | 0 | 0 | gpt-5.5 |+| …ecab5814 | issues-review-p3-c2 | 23:10:43 | 0 | 0 | gpt-5.5 |+| …65558c84 | issues-review-p1-c1 | 23:10:43 | 0 | 0 | gpt-5.5 |+| …df20f692 | issues-review-p1-c3 | 23:10:44 | 0 | 0 | gpt-5.5 |+| …59d3f610 | issues-review-p2-c3 | 23:10:45 | 0 | 0 | gpt-5.5 |+| …9f350965 | issues-review-p3-c1 | 23:10:46 | 0 | 0 | gpt-5.5 |+| …fd0b1da6 | blind-spots-c2 | 23:40:55 | 0 | 0 | gpt-5.5 |+| …9ba65e09 | blind-spots-c3 | 23:40:56 | 0 | 0 | gpt-5.5 |+| …c83195e0 | blind-spots-c1 | 23:40:57 | 0 | 0 | gpt-5.5 |+| …c260c574 | blind-spots-c4 | 23:41:53 | 0 | 0 | gpt-5.5 |+| …059f3f68 | validation-c1 | 23:44:00 | 0 | 39,279 | claude-opus-4-8 |+| …c3afbb10 | validation-c2 | 23:44:00 | 0 | 39,928 | claude-opus-4-8 |+| …3f4d16dc | validation-c3 | 23:44:05 | 17,141 | 21,904 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **1/24** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 16s |+| review wave (perspectives) | 33m 32s |+| blind-spot sweep | 30m 03s |+| dedup (incl. combine/clean) | 7s |+| validation | 10m 58s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 63m 35s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 3 |+| 3 | 3 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 3 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/review_pr.py:937-938++**Self-driving audit flag is added to the result payload but not to analytics**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The added audit flag is placed under `to_dict()["classification"]["self_driving"]`, but the review-completed analytics payload in `_capture_review_completed` is unchanged. The PR intent calls out a `stamphog_self_driving_review` stamp on the engine analytics; without adding it to the captured properties, downstream analytics cannot segment relaxed-gate runs from normal reviews.+- **Suggestion:** Add an explicit analytics property in `_capture_review_completed`, e.g. `"stamphog_self_driving_review": self.self_driving`, and keep the existing `to_dict` classification flag if the run output also needs the audit trail.+- **Validator:** - **Checked:** the full PR diff (fetched via `gh pr diff 72680`, since this checkout is pinned at master and the PR head `1341596e` isn't fetchable). Traced how the `self_driving` flag reaches analytics: `_capture_review_completed` (review_pr.py:790-839), `analytics_extra_properties()` (gateway.py:17-32), and the hosted server's env injection in `products/stamphog/backend/temporal/activities.py`.+- **Found:** the stamp is not missing. The PR adds it at `products/stamphog/backend/temporal/activities.py` (`_reviewer_environment`): `extra_properties["stamphog_self_driving_review"] = True` when `run.output["inbox_review"]` is set, serialized into `STAMPHOG_EXTRA_PROPERTIES`. That env var is read by `analytics_extra_properties()` (gateway.py:25) and spread via `**analytics_extra_properties()` into the `stamphog_review_completed` event at review_pr.py:806 (and into the LLM-trace events at reviewer.py:328,354). The PR's own code comment says this is 'so the engine's completed events and LLM traces segment cleanly in analytics,' and `test_integration.py` asserts `STAMPHOG_EXTRA_PROPERTIES["stamphog_self_driving_review"] is True`.+- **Found:** the finding is right that review_pr.py's `_capture_review_completed` was not edited and that `to_dict()["classification"]["self_driving"]` (review_pr.py:934-935 in the diff) is the audit-trail flag — but it wrongly concludes analytics can't segment. Because `stamphog_self_driving_review` is not among the hardcoded base props (which win on collision), it survives the merge and lands on the event.+- **Impact:** none — downstream analytics can already segment relaxed-gate runs from normal reviews. The suggested fix (`"stamphog_self_driving_review": self.self_driving` in `_capture_review_completed`) would be strictly worse: it stamps only the completed event and would miss the LLM-trace events that the current single injection point covers. This is a 'wrong/unreproducible' and 'already handled elsewhere' drop under the criteria.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:1-17++**New migration needs the review_hog max migration marker bumped**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This adds a new Django migration for the `review_hog` product, but the chunk does not update `products/review_hog/backend/migrations/max_migration.txt` from `0018_backfill_urgency_threshold_to_consider` to this new `0019_...` migration. Product migration directories in this repo carry that marker for migration numbering/conflict tooling, so leaving it stale can trip preflight/conflict checks and makes the migration directory metadata inconsistent with the actual latest migration.+- **Suggestion:** Update `products/review_hog/backend/migrations/max_migration.txt` to contain `0019_reviewusersettings_stamphog_review_inbox_prs` in the same change as the migration.+- **Validator:** - **Checked:** The PR's full changed-file list (`gh pr view 72680 --json files`) and the actual diff of `products/review_hog/backend/migrations/max_migration.txt`, plus the local migrations directory to establish the pre-PR baseline.+- **Found:** `max_migration.txt` IS in the PR's changed files, and its diff bumps the marker exactly as the suggestion asks: `-0018_backfill_urgency_threshold_to_consider` / `+0019_reviewusersettings_stamphog_review_inbox_prs`. That value matches the new migration filename `0019_reviewusersettings_stamphog_review_inbox_prs.py` precisely.+- **Impact:** The finding's premise is false — the marker is not stale. It only appeared missing because the reviewer saw a partial chunk whose file set (models.py, the 0019 migration, api/settings.py, receivers.py, CodeReviewScene.tsx, generated types) excluded `max_migration.txt`; the file is bumped elsewhere in the same PR. No preflight/conflict-tooling breakage exists. This is a 'wrong / unreproducible' drop under the validation bar.++### [❌ dismissed] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1173++**Inbox review task trusts caller-supplied provenance without revalidating the TaskRun**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `process_inbox_pr_review` accepts `team_id`, `pr_url`, `signal_report_id`, `task_run_id`, and `acting_user_id` from the caller, then stamps `output.inbox_review` and starts a self-driving review after only checking that the PR belongs to a synced Stamphog repo. Unlike the webhook carve-out, this path does not independently verify that the task run exists for the same team, is non-internal, carries the supplied signal report, and actually produced this PR URL. If the receiver is ever called with stale or incorrect task output, or another internal caller uses the facade incorrectly, Stamphog can bypass the normal bot/draft/review-mode/write-permission gates for an arbitrary PR in a configured repo.+- **Suggestion:** Before creating the `ReviewRun`, resolve the task through the tasks facade by `task_run_id` and `team_id` and verify the run is the expected self-driving shape: same team, non-internal task, matching `signal_report_id`, and matching PR URL/repository/head branch. Alternatively add a dedicated tasks facade method for this exact receiver-leg validation and fail closed if it returns `None`. Only stamp `output["inbox_review"]` after that check passes.+- **Validator:** - **Checked:** Traced every caller of `process_inbox_pr_review` and `queue_inbox_pr_review` across the PR diff, plus `handle_task_run_saved` (products/review_hog/backend/receivers.py) and `find_signal_implementation_run` (products/tasks/backend/facade/api.py).+- **Found:** The task is only reachable via `queue_inbox_pr_review.delay()` (diff L708), whose only caller is review_hog's `_start_stamphog_review` (diff L279), invoked solely from `handle_task_run_saved`. That receiver derives all five params directly from the just-saved `TaskRun` instance — `pr_url = instance.output['pr_url']`, `task_run_id = str(instance.id)`, `signal_report_id = str(task.signal_report_id)`, `team_id = instance.team_id` (diff L127-146) — after already enforcing `task.signal_report_id is not None`, `not task.internal`, and status ∉ {FAILED, CANCELLED} (receivers.py L84-90). The linkage the finding wants re-verified is established by construction at the call site.+- **Found:** The webhook↔receiver asymmetry is deliberate, not an oversight. The webhook leg calls `find_signal_implementation_run` because GitHub delivers events for arbitrary PRs and has no trustworthy linkage — it resolves the run _from_ the PR URL. The receiver leg is driven by the TaskRun itself, so it already holds a verified, in-hand run. Re-running `find_signal_implementation_run(team_id, pr_url=...)` would resolve the same run from the same pr_url and pass trivially, adding no protection against the real caller — and it would not catch a hypothetically wrong-but-self-consistent pr_url either.+- **Impact:** The named triggers don't meet the bar. 'Stale output' is already handled (fresh GitHub fetch, open-state check, stale-snapshot guard under row lock, head-keyed dedupe — diff L1078-1140). 'Incorrect output' requires the internal agent-server/webhook-backstop to write a wrong pr_url — an upstream concern shared with the pre-existing ReviewHog `_start_review` leg and unfixed by the suggestion. 'Another internal caller misusing the facade' is a speculative future bug, not a reachable condition given the sole call site. This is defense-in-depth / redundant re-validation a trusted parent caller already performs, so per precision-over-recall it is dropped.++### [❌ dismissed] should_fix — products/tasks/backend/facade/api.py:503-511++**Team scoping is applied after an unscoped task lookup, causing false negatives**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `find_signal_implementation_run` delegates to `find_task_run` without passing `team_id`, then discards the result if it belongs to another team. Because `find_task_run` returns only the first matching run for a PR URL or repository/branch, a matching run from another team can mask the correct same-team run and make the Stamphog webhook carve-out fail closed. This is especially likely for repository/branch fallback, where branch names can collide across teams working in the same repository.+- **Suggestion:** Make the lookup team-scoped before selecting a row. For example, add a team-scoped variant of `find_task_run`, or implement this facade query directly with `TaskRun.objects.filter(team_id=team_id, ...)` for both the PR URL and repository/branch legs before applying the signal/internal checks.+- **Validator:** - **Checked:** `find_task_run` (products/tasks/backend/webhooks.py:30-99), the carve-out call site `_inbox_rereview_carve_out` (diff L862-914), and how `pr_url` reaches the lookup; also whether signals implementation tasks are wizard runs.+- **Found:** The carve-out always passes `pr_url=pr.get("html_url")` from a `pull_request` webhook (diff L909-914). `find_task_run` runs the pr_url leg first and returns on match (webhooks.py:37-58); the branch fallback (webhooks.py:61+) is only consulted when the pr_url leg yields nothing. So the issue's headline case — cross-team branch-name collision — is behind a leg that the always-present pr_url normally skips.+- **Found:** A GitHub PR URL is globally unique to one PR/repo, and each self-driving PR is opened by exactly one run; the only same-pr_url collisions are same-team resumes (documented at webhooks.py:38-40). No other-team run carries the same pr_url, so the pr_url leg resolves the correct same-team run — cross-team masking there is unreachable, not merely rare.+- **Found:** Reaching the branch fallback requires the opening run to not yet have recorded `output.pr_url`. But recording pr_url is what triggers the initial receiver-leg review, and the carve-out scope is later deliveries only (synchronize/reopen/retarget), by which point pr_url is recorded. On top of that, masking would need two teams running tasks with identical generated (`posthog-code/…`) branch names in one shared repo.+- **Impact:** Even in that theoretical race the outcome is a skipped re-review (fail-closed), not a tenant-isolation violation — the team check returns None on mismatch and never binds a PR to another team's run (diff L917-918), and the initial draft-time verdict already posted. A practically-unreachable edge case with a low, safe consequence does not meet the bar; per precision-over-recall, drop.++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/facade/api.py:151-157++**Fire-and-forget facade can still raise broker errors into the caller**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `queue_inbox_pr_review` is documented as fire-and-forget so the caller's save path never blocks on the Stamphog leg, but `process_inbox_pr_review.delay(...)` can raise when the Celery broker is unavailable or serialization fails. If the review_hog receiver does not catch this at every call site, a transient queueing failure can bubble into the TaskRun save path and break the primary self-driving task flow.+- **Suggestion:** Wrap the `.delay(...)` call in a broad exception handler, log enough context to debug the missed Stamphog enqueue, and return without raising. If callers should own that behavior instead, narrow the facade docstring and ensure every caller catches broker failures explicitly.+- **Validator:** - **Checked:** The facade `queue_inbox_pr_review` (products/stamphog/backend/facade/api.py, diff L687-713), its only production caller in review_hog, and the broker-failure test coverage; grepped all call sites of `queue_inbox_pr_review`.+- **Found:** The facade does not wrap `.delay()` (diff L708-713), but the sole production caller `_start_stamphog_review` (products/review_hog/backend/receivers.py, diff L206-228) already wraps the call in `try/except Exception` + `logger.exception('review_hog_stamphog_inbox_review_queue_failed')`; its docstring states 'the broker being down must never surface into the saver.' Grep shows exactly one production call site (diff L279) — 'every call site' is that one guarded site.+- **Found:** `test_stamphog_queue_failure_never_raises_into_the_save_path` (diff L365-376) patches the facade with `side_effect=RuntimeError('broker down')` and asserts the TaskRun output save 'must not raise' — the precise failure mode the finding hypothesizes is already regression-tested.+- **Found:** The caller is dispatched via `transaction.on_commit(...)` in `handle_task_run_saved` (diff L138-146), so it runs after the TaskRun commit; even an unhandled raise could not roll back the save or break the primary task flow.+- **Impact:** The premise ('if the receiver does not catch this') is false — it does, at its only call site, with a test, and post-commit. The suggestion is a redundant try/except (defensive paranoia) and a docstring nit for behavior that is already correct and owned by the caller. Does not meet the bar; drop.++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:316-321++**Privileged self-driving flag is parsed with loose truthiness**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The hosted sandbox entrypoint enables the bot/draft gate carve-out with `bool(context.get("self_driving_review"))`. That treats any non-empty value as privileged, including strings like `"false"`, `"0"`, or other malformed JSON values. Because this flag relaxes security-sensitive gates, the contract should fail closed unless the server provided the exact boolean `true`.+- **Suggestion:** Parse the flag strictly, for example `self_driving = context.get("self_driving_review") is True`, and optionally reject/log non-boolean values so malformed context cannot accidentally enable the carve-out.+- **Validator:** - **Checked:** the end-to-end flow of `self_driving_review`. Engine side, `review_local.py:391` loads the context via `json.loads(Path(args.context).read_text())`, then `run()` (diff line 1937) does `Pipeline(..., self_driving=bool(context.get("self_driving_review")))`. Producer side, the context file is written only by trusted server code.+- **Found:** the value is always a JSON boolean or absent — never a string. `products/stamphog/backend/logic/reviewer.py::build_reviewer_invocation` declares `self_driving_review: bool = False` (typed `bool`) and writes `context["self_driving_review"] = self_driving_review`; its caller `products/stamphog/backend/temporal/activities.py` passes `bool(output.get("inbox_review"))`. A Python `bool` serializes to JSON `true`/`false` and deserializes back to a `bool`, so `context.get("self_driving_review")` is only ever `True`, `False`, or `None` — for all of which `bool(x)` equals `x is True`.+- **Found:** no untrusted input reaches this field. It derives from `run.output["inbox_review"]` (server-stamped inbox provenance), not from the reviewed PR's author/diff/metadata; the Action runtime never sets it (absent → `False`). The hypothesized `"false"`/`"0"` string would require the trusted server to violate its own `bool` contract, or a developer to hand-author a malformed `--context` file — manual misuse, not a security boundary.+- **Impact:** none reachable. The loose-vs-strict truthiness distinction is unobservable given the upstream `bool` type and server-controlled context source. This is a speculative 'what if' / defensive-coding-paranoia drop under the criteria, and the `must_fix` security severity is unwarranted because there is no untrusted-input path and no user-affecting consequence.++### [❌ dismissed] must_fix · bug — tools/pr-approval-agent/reviewer.py:568-568,683-703++**Self-driving prompt can still include author familiarity context**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new provenance block is appended after the existing familiarity block, but nothing in this chunk guarantees familiarity is absent for `self_driving` runs. If `classification["familiarity"]` is populated by `Pipeline._maybe_compute_familiarity()` or by the offline context path, the prompt will contain both human-author familiarity and the new machine-author provenance guidance, contradicting the stated invariant that provenance replaces human-author trust signals for self-driving PRs.+- **Suggestion:** Make the invariant explicit in code: skip familiarity computation/attachment when `pipeline.self_driving` is true in both `review_pr.py` and `review_local.py`, or have `_format_familiarity` return `""` when `cl.get("self_driving")` is true. Add a regression test where `self_driving` and a populated familiarity object are both present and the prompt contains only the provenance block.+- **Validator:** - **Checked:** which entrypoint ever sets `self_driving`, and whether familiarity can be populated on the same run. Only `review_local.py` (hosted sandbox) reads `self_driving` from context; `review_pr.py`/Action leaves it `False` by default. Traced `review_local.py::_attach_familiarity`, `reviewer.py::_format_familiarity`, and the server source of `author_pr_numbers`.+- **Found:** for a self-driving run the familiarity block is guaranteed empty, so the two blocks cannot coexist. `_attach_familiarity` (`review_local.py:299-303`) early-returns unless tier is `T1-agent` AND `context["author_pr_numbers"]` is truthy; on that path `classification["familiarity"]` stays `None`, and `_format_familiarity` returns `""` when `fam is None` (`reviewer.py:644-645`), so no familiarity text is appended.+- **Found:** the hosted server couples both signals to one provenance flag so they cannot diverge. In `products/stamphog/backend/temporal/activities.py`, `fetch_review_context` sets `author_pr_numbers = []` when `is_inbox_review` (diff 1215-1216) and `run_review_in_sandbox` passes `self_driving_review=bool(output.get("inbox_review"))` (diff 1227) — both from `run.output["inbox_review"]`. Hence `self_driving=True ⟺ inbox review ⟺ author_pr_numbers=[]`, forcing familiarity absent; `test_integration.py` asserts no author merged-PR history is fetched for the inbox leg.+- **Impact:** none reachable — the predicted prompt contradiction (both familiarity and provenance) cannot occur in current code. The invariant is enforced by the coupled server logic plus the engine's tier/PR-numbers gate, so this is an 'already handled elsewhere' / 'speculative what-if ruled out by the call sites' drop, and the suggested extra guard is defensive paranoia. `must_fix` is unwarranted absent any reachable defect.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-2.mdnew file mode 100644index 000000000000..36c9c1ecede3--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/C-gpt55-xhigh-2.md@@ -0,0 +1,238 @@+# Reviewer-quality run — `C-gpt55-xhigh-2`++- **Dumped:** 2026-07-24T01:35:44+00:00+- **Report id:** `019f9175-4420-7da6-9d5d-f7a00484ce0c` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 5143s (85.7 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.5` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 14 | 10 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | -------------- | ----------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| gpt-5.5 | review | 220 | 15,166,343 | 0 | 0 | 83,677 | 0 | — | $19.40 |+| claude-opus-4-8 | validation | 95 | 68,498 | 569,386 | 10,251,436 | 109,522 | 0 | $11.76 | $11.76 |+| gpt-5.5 | blind-spot | 62 | 4,676,254 | 0 | 0 | 25,223 | 0 | — | $4.86 |+| claude-sonnet-5 | dedup | 1 | 11,100 | 0 | 0 | 1,717 | 0 | $0.04 | $0.04 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,347 | 0 | $0.03 | $0.03 |+| **total** | | **379** | **19,931,224** | **569,386** | **10,251,436** | **221,486** | **0** | **$11.84** | **$36.10** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.5` (282 gen(s), gw $24.27).+- naive method (all prompt tokens at input price): $57.26 — 4.8× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $30.0656 over 379 gen(s) (true $9.0671, Δ +231.6%)+ - · of which cache read: $13.8162 over 355 gen(s) (true $5.1257, Δ +169.5%)+ - · of which cache write: $3.5587 over 95 gen(s) (true $3.5587, Δ +0.0%)+ - · of which fresh (derived): $12.6908 over 379 gen(s) (true $0.3827, Δ +3215.7%)+ - output: $6.0357 over 379 gen(s) (true $2.7687, Δ +118.0%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …c2c2e871 | issues-review-p1-c3 | 00:11:27 | 0 | 0 | gpt-5.5 |+| …2f08f65b | issues-review-p1-c2 | 00:11:30 | 0 | 0 | gpt-5.5 |+| …ca16feaa | issues-review-p2-c1 | 00:11:31 | 0 | 0 | gpt-5.5 |+| …6d48f10e | issues-review-p1-c1 | 00:11:34 | 0 | 0 | gpt-5.5 |+| …10d422d1 | issues-review-p2-c2 | 00:11:34 | 0 | 0 | gpt-5.5 |+| …459a594f | issues-review-p3-c1 | 00:11:35 | 0 | 0 | gpt-5.5 |+| …fff06a85 | issues-review-p3-c2 | 00:11:36 | 0 | 0 | gpt-5.5 |+| …539614a9 | issues-review-p2-c3 | 00:11:51 | 0 | 0 | gpt-5.5 |+| …d642de68 | issues-review-p1-c2 | 00:41:28 | 0 | 0 | gpt-5.5 |+| …3ecc2cc1 | issues-review-p2-c3 | 00:41:29 | 0 | 0 | gpt-5.5 |+| …7e3c03d1 | issues-review-p1-c3 | 00:41:29 | 0 | 0 | gpt-5.5 |+| …f003d7e2 | issues-review-p2-c1 | 00:41:29 | 0 | 0 | gpt-5.5 |+| …f1ab0919 | issues-review-p1-c1 | 00:41:29 | 0 | 0 | gpt-5.5 |+| …73ee600a | issues-review-p3-c2 | 00:41:30 | 0 | 0 | gpt-5.5 |+| …3aea3e9c | issues-review-p2-c2 | 00:41:31 | 0 | 0 | gpt-5.5 |+| …ada829a3 | issues-review-p3-c1 | 00:41:32 | 0 | 0 | gpt-5.5 |+| …61fb57eb | issues-review-p1-c2 | 01:11:50 | 0 | 0 | gpt-5.5 |+| …a7e30ef1 | issues-review-p2-c2 | 01:11:51 | 0 | 0 | gpt-5.5 |+| …e2904cf2 | issues-review-p2-c1 | 01:11:51 | 0 | 0 | gpt-5.5 |+| …09328549 | issues-review-p3-c2 | 01:11:51 | 0 | 0 | gpt-5.5 |+| …af03869d | issues-review-p1-c1 | 01:11:52 | 0 | 0 | gpt-5.5 |+| …4f6a9db7 | issues-review-p3-c1 | 01:11:52 | 0 | 0 | gpt-5.5 |+| …d7cd9e98 | blind-spots-c1 | 01:15:54 | 0 | 0 | gpt-5.5 |+| …4bc6dff4 | blind-spots-c3 | 01:15:58 | 0 | 0 | gpt-5.5 |+| …55a2c03d | blind-spots-c2 | 01:16:02 | 0 | 0 | gpt-5.5 |+| …f340858f | blind-spots-c4 | 01:16:07 | 0 | 0 | gpt-5.5 |+| …e8680eaa | validation-c3 | 01:20:31 | 0 | 38,984 | claude-opus-4-8 |+| …c551de7f | validation-c1 | 01:20:34 | 0 | 39,374 | claude-opus-4-8 |+| …62c5aa5d | validation-c2 | 01:20:37 | 17,141 | 22,941 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **1/29** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 17s |+| review wave (perspectives) | 64m 40s |+| blind-spot sweep | 4m 21s |+| dedup (incl. combine/clean) | 17s |+| validation | 15m 23s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 69m 01s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 1 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] must_fix — products/review_hog/backend/api/settings.py:16-16,52-54,222-222++**Declare the new ReviewHog to Stamphog product dependency**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This chunk adds imports from `products.stamphog.backend.facade.*` in ReviewHog, but `tach.toml` currently does not list `products.stamphog` in the `products.review_hog` module's `depends_on`. Even though these imports use Stamphog's exposed facade, the product dependency itself still has to be declared; otherwise the architecture/dependency check will reject the new cross-product edge.+- **Suggestion:** Add `products.stamphog` to the `depends_on` list for `products.review_hog` in `tach.toml` if this dependency is intentional. If ReviewHog should not depend on Stamphog directly, move the connection check and hook registration behind an existing allowed boundary instead.+- **Validator:** - **Checked:** Whether the PR actually leaves `products.review_hog`'s `depends_on` without `products.stamphog`. The reviewer only saw the `settings.py` chunk (chunk 1); I pulled the full PR diff (`gh pr diff 72680`) to see every file it touches, including `tach.toml`.+- **Found:** The PR's own `tach.toml` diff adds the exact entry the finding says is missing — inside the `products.review_hog` module block: `+ # Facade-only (enforced by stamphog's [[interfaces]] block) ...` `+ "products.stamphog",` (tach.toml, review_hog `depends_on`). So the premise "tach.toml currently does not list products.stamphog" is mistaken for the merged state.+- **Found:** All three production `review_hog → stamphog` imports go through the exposed facade surface: `products/review_hog/backend/api/settings.py` imports `products.stamphog.backend.facade.api.has_reviewable_repo_config`; `products/review_hog/backend/receivers.py` imports `products.stamphog.backend.facade.inbox_hooks.register_inbox_acting_reviewer_resolver` and `products.stamphog.backend.facade.api.queue_inbox_pr_review`. Stamphog's existing `[[interfaces]]` block (tach.toml:1101-1108) exposes `backend\.facade.*`, so the interface check also passes. The only non-facade stamphog import in review_hog (`from products.stamphog.backend.models import StamphogRepoConfig`) is in `test_settings_api.py`, and `tests` is excluded in tach.toml's top-level `exclude`.+- **Impact:** Both `tach check --dependencies` and `--interfaces` are satisfied by the PR as written (consistent with the PR body stating that command was run). The suggested fix — add `products.stamphog` to `review_hog`'s `depends_on` — is already done in the diff, so the finding is wrong/unreproducible against the actual change and would be pure noise if surfaced.++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:316-321++**Self-driving flag accepts any truthy context value**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The hosted context flag controls a security-sensitive carve-out that relaxes the bot-author and draft gates, but it is parsed with `bool(context.get("self_driving_review"))`. That treats non-empty strings like `"false"`, `"0"`, or any non-empty object as enabled. If the context producer ever serializes this as a string, or a malformed context reaches this entrypoint, the engine will grant the carve-out instead of failing closed.+- **Suggestion:** Require an explicit JSON boolean true before enabling the carve-out, for example `self_driving = context.get("self_driving_review") is True`, and consider rejecting/logging non-boolean values so contract drift is visible. Add a regression test with `self_driving_review: "false"` that still refuses a bot-authored draft.+- **Validator:** - **Checked:** The single producer of the `--context` JSON that `review_local.py::run` consumes: `build_reviewer_invocation` (products/stamphog/backend/logic/reviewer.py:98) and its only caller `run_review_in_sandbox` (products/stamphog/backend/temporal/activities.py:428–445), plus how the payload is serialized and re-parsed.+- **Found:** The value is a genuine `bool` at every hop. activities.py:445 passes `self_driving_review=bool(output.get("inbox_review"))` (already coerced); reviewer.py:98 types the parameter `self_driving_review: bool = False` and puts it in the `context` dict; reviewer.py:130 serializes with `json.dumps(context, ...)` → JSON `true`/`false`; review_local.py:391 reads it back via `json.loads` → a Python `bool`; only then does review_local.py:316 apply `bool(...)`. A JSON boolean round-trips losslessly, so at the flagged line the value is provably `True`, `False`, or absent (`bool(None)` → `False`, i.e. fails closed).+- **Found:** The finding is self-describedly hypothetical — "_if_ the context producer _ever_ serializes this as a string, or a malformed context reaches this entrypoint." There is exactly one producer (grep for `build_reviewer_invocation` / `--context` shows a single non-test call site) and it is server-assembled; the PR head cannot write the context file (the server holds the token and overwrites trusted paths), so there is no attacker-controllable or string-typed path to this key.+- **Impact:** The string-`"false"` carve-out grant cannot occur given the typed, `bool()`-coerced producer and the JSON round-trip. Switching to `is True` guards a condition the upstream types already rule out — the criteria's "speculative what-if" and "defensive-coding paranoia" drop categories. No concrete trigger can be named against the real code, so precision-over-recall says drop.++### [❌ dismissed] should_fix — products/review_hog/backend/receivers.py:144-154++**Webhook re-review can switch acting reviewers after Inbox assignments change**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new Stamphog webhook resolver recomputes the acting reviewer from the report's latest suggested_reviewers artefact on every later push. Those artefacts are append-only/latest-wins and can be edited after the PR was originally opened, so a self-driving PR's later Stamphog reviews can become governed by a different user's toggle than the one resolved by the initial TaskRun receiver. That breaks the intended per-user gate: the original acting reviewer can opt out mid-PR, but a later assignment change to another opted-in reviewer would allow reviews to continue; the inverse can also stop reviews even though the original actor remains opted in.+- **Suggestion:** Make the webhook leg re-check the toggle for the same acting reviewer chosen by the initial receiver. Persist that acting_user_id with the self-driving PR provenance, or expose a stable acting_user_id through the tasks/Stamphog facade, then have resolve_stamphog_acting_reviewer load that user's ReviewUserSettings directly. If no stable actor is available for an old/incomplete run, fail closed rather than recomputing from the current suggested_reviewers set.+- **Validator:** - **Checked:** How `resolve_stamphog_acting_reviewer` (`products/review_hog/backend/receivers.py:~217`) and the webhook carve-out (`_inbox_rereview_carve_out`, products/stamphog/backend/tasks/tasks.py) resolve the reviewer; how the _initial_ receiver leg resolves it; whether `suggested_reviewers` artefacts can change post-PR-open; and what `acting_user_id` is actually used for.+- **Found:** Both legs call the identical `_resolve_assigned_reviewer(team_id, signal_report_id, task.created_by_id)` — the webhook leg passes the stable `run.task_created_by_id` and re-derives the reviewer set from the latest artefact, exactly as the receiver leg does. The receiver leg is NOT a one-time pin: `handle_task_run_saved` fires on _every_ TaskRun output save (every agent turn) and re-resolves each time. So there is no fixed "initial acting reviewer" for the webhook leg to diverge from — the whole system is latest-wins by construction.+- **Found:** This is the explicitly documented contract, not an oversight. `_resolve_assigned_reviewer`'s docstring defines assignment as "the report's **latest** `suggested_reviewers` artefact — the exact set the Inbox 'For you' filter matches and Slack notifications fan out to," and the new AGENTS.md invariant states the webhook leg deliberately "re-check[s] the toggle through the resolver." Assignment follows the current artefact everywhere in the product; the carve-out mirrors ReviewHog's own inbox-trigger semantics on purpose (PR decision 6).+- **Found:** No safety impact. The stale-approval dismissal is unconditional and never preference-gated (tasks.py skip path retracts on any head change regardless of toggle/assignee; documented + code-confirmed). And `acting_user_id` feeds only the toggle gate + a provenance/attribution stamp (`output.inbox_review`, engine `self_driving` flag) — stamphog posts via the team's GitHub App machine user, so a reviewer switch causes no impersonation.+- **Impact:** The reviewer's premise — that this "breaks the intended per-user gate" — is mistaken: the intended gate IS the _current_ assignee's toggle, consistent across both legs and the Inbox surfaces, so following an assignment change is the contract, not a break. The only observable effect is whether an advisory review verdict is produced for whoever is now assigned, under a narrow scenario (a human edits `suggested_reviewers` via the artefact API after the draft PR is already open, to a different opted-in/out member, while pushes continue). No correctness, data-loss, or security consequence. Per precision-over-recall this is a drop; the suggested fix (pin acting_user_id + fail-closed for old runs) would itself diverge from the documented latest-wins model and add defensive handling the design intentionally omits.++### [❌ dismissed] should_fix — products/review_hog/backend/receivers.py:114-138++**Stamphog enqueue is blocked behind the ReviewHog Temporal start**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** When both inbox toggles are enabled, the code registers the ReviewHog `on_commit` callback first and the Stamphog callback second. Django executes `on_commit` callbacks serially in registration order, and `_start_review` synchronously connects to Temporal before returning. If the ReviewHog Temporal start is slow or hung during an outage, the independent Stamphog review may be delayed or never queued even though its own toggle was enabled.+- **Suggestion:** Make the two dispatches operationally independent. The smallest change is to register the Stamphog `on_commit` callback before the ReviewHog callback, or use one `on_commit` callback that queues Stamphog first and then starts ReviewHog. A more robust option is to put both trigger requests behind durable async queue/outbox records so one backend's outage cannot block the other trigger.+- **Validator:** - **Checked:** `_start_review` (products/review_hog/backend/receivers.py:164-200), `_start_stamphog_review` (PR diff), the two `on_commit` registrations, and Django's serial on_commit execution model, plus the Temporal entry point `start_review_pr_workflow` (temporal/client.py).+- **Found:** `_start_review` wraps the entire Temporal `sync_connect()` + `start_workflow` in `try/except Exception` and only logs (receivers.py:188-200) — it never re-raises. `_start_stamphog_review` is identically guarded ("the broker being down must never surface into the saver", try/except around `queue_inbox_pr_review`). So a Temporal _failure_ in the first callback cannot stop the second from running. The finding's severe outcome — Stamphog "never queued" — is unreachable.+- **Found:** The suggested "smallest change" (register Stamphog first, or one callback that queues Stamphog before ReviewHog) does NOT make the two dispatches "operationally independent." Django runs all `on_commit` callbacks serially in the same thread; ordering only decides which trigger waits behind the other's blocking network call. Reordering merely moves the risk to the other trigger — it does not decouple them, so the finding's core remedy misreads the mechanism.+- **Impact:** The only genuine residual is a _bounded delay_ (not loss) of the Stamphog Celery enqueue if the ReviewHog Temporal connect is slow during a Temporal outage. Both are best-effort, fire-and-forget advisory reviews dispatched post-commit on a background TaskRun-save path — the save has already committed, nothing user-facing or data-carrying is blocked, and during a Temporal outage ReviewHog's own review is failing regardless. The Stamphog leg is itself just a broker publish. This is a marginal, infra-outage-only reliability edge, and the only fix that would actually decouple them (a durable async outbox) is a heavyweight architectural addition — overengineering for this path. Fails the bar (severe claim is wrong, simple fix is a no-op, residual impact is low).++### [❌ dismissed] consider — products/review_hog/backend/api/settings.py:77-82++**Fail-soft Stamphog connection check can create noisy error logs**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `get_stamphog_connected` intentionally fails soft, but it logs every failure with `logger.exception` on a settings endpoint that the Code review page calls routinely. If the Stamphog product DB or its circuit breaker is unavailable, every page load can emit a full stack trace, creating log noise that makes the underlying outage harder to diagnose.+- **Suggestion:** Keep returning `False`, but throttle or cache the failure log for a short TTL per team, and include `team_id` in the log context. For expected circuit-open/read-unavailable cases, consider a warning with `exc_info=True` only when the throttle permits, reserving unthrottled `logger.exception` for unexpected errors.+- **Validator:** - **Checked:** `get_stamphog_connected` (products/review_hog/backend/api/settings.py:58-65 in the diff), when its `except` path fires, how the endpoint is invoked from the frontend (`reviewHogSettingsLogic.ts:446` `loadSettings` on mount), and the alpha-gating (`get_can_trigger_reviews` limits the UI to `settings.REVIEWHOG_TEAM_ID`).+- **Found:** The `logger.exception` only executes when `has_reviewable_repo_config(team_id)` raises — i.e. during an actual Stamphog product-DB / circuit-breaker outage. In steady state the except path never runs, so there is zero baseline noise. The settings read is fetched on scene mount (`await reviewHogSettingsRetrieve(currentProjectId())`), not a high-frequency poll, and the Code review page is alpha-gated to the designated ReviewHog team — so even during an outage the emission rate is bounded by occasional page loads, not request volume.+- **Impact:** This is a logging-hygiene / observability preference, not one of the keep categories (no correctness, security, data-loss, contract, or real-scale performance defect). It is the opposite of a "swallowed error that hides failures" — the error is logged loudly and the value fails soft to `False` as intended. The claim that stack traces "make the outage harder to diagnose" is weak: a handful of traces from a low-traffic settings endpoint during a dependency outage aids diagnosis rather than obscuring it, and Stamphog emits its own outage logs. The proposed remedy — per-team TTL-throttled failure logging plus expected-vs-unexpected tiering (`warning`/`exc_info`) — is observability infrastructure disproportionate to an informational UI flag, i.e. mild overengineering. Per precision-over-recall this does not clear the bar; the one trivially-valid sub-point (add `team_id` to the log) is too minor to surface on its own.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_pr.py:225-225,587-590++**Self-driving mode is not bound to bot-authored PRs before relaxing the draft gate**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new self_driving flag is used directly to skip both the bot-author refusal and the draft prerequisite. That means any caller that passes self_driving=True for a human-authored draft PR will bypass the draft gate even though the carve-out is only intended for bot-authored self-driving implementation PRs. This is separate from parsing truthy values: even an exact boolean true on the wrong PR shape makes the engine review a human draft and gives the reviewer prompt machine-user provenance that does not apply.+- **Suggestion:** Fail closed by deriving an effective self-driving mode only after PR data is available, for example self.self_driving = self.self_driving and self.pr.author_is_bot before classification/gates run, and use that derived value for the draft relaxation, prompt classification, and output. In review_local.py, build PRData first, then apply the same author_is_bot check before the bot-author gate. If self_driving was requested for a non-bot author, either ignore the carve-out or return a refusal/escalation so malformed hosted context cannot weaken normal draft behavior.+- **Validator:** - **Checked:** Every call site that can set `self_driving` on the engine (`Pipeline`), and the server-side chain that derives the flag: `review_pr.py` Action entrypoint, `review_local.py`, `products/stamphog/backend/temporal/activities.py::run_review_in_sandbox`, and the two provenance-stamping legs in `tasks/webhooks.py` / `tasks.py`.+- **Found:** The Action runtime never sets the flag — `review_pr.py:966` calls `Pipeline(args.pr_number, args.repo, dry_run=..., verbose=...)` with no `self_driving` kwarg (defaults `False`). The only non-default setter is the hosted path: `activities.py` passes `self_driving_review=bool(output.get("inbox_review"))` into `build_reviewer_invocation`, which round-trips through the context JSON to `review_local.py`'s `Pipeline(..., self_driving=bool(context.get("self_driving_review")))`.+- **Found:** `inbox_review` provenance is stamped only for positively-identified bot authors. The webhook leg `_inbox_rereview_carve_out` returns an empty `_InboxCarveOut()` for any non-bot author via an explicit `if not _is_bot_authored(pr): return _InboxCarveOut()` guard (before any DB work), then further requires repo-native head, synced+enabled config, a team-scoped tasks-facade match, and the acting reviewer's toggle. The receiver leg `process_inbox_pr_review` is bot-authored by construction — its PR URL comes from a signals-implementation TaskRun whose PR is opened by the team's GitHub App machine user.+- **Impact:** `self_driving=True` cannot reach a human-authored draft through the actual call sites; producing it would require an upstream bug (the webhook `_is_bot_authored` gate failing, or a signals-implementation run carrying a human's PR URL). The proposed engine-level `author_is_bot` bind is therefore redundant with the parent caller's existing `_is_bot_authored` gate and guards a state the call sites already rule out — the criteria's "already handled by a parent caller" and "defensive-coding paranoia / speculative what-if" drop categories. The design intentionally centralizes positive identification at the server (the sandboxed engine has no DB access to re-verify task linkage), so a partial local check would not complete the validation it implies. Does not meet the bar.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1183,1215-1223++**Receiver-leg reviews trust caller-supplied provenance before enabling the self-driving approval bypass**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `process_inbox_pr_review` is a new approval-capable entry point, but it treats `team_id`, `pr_url`, `signal_report_id`, and `task_run_id` as already-attested facts and immediately stamps `output={"inbox_review": ...}` on the `ReviewRun`. Downstream, `activities.py` turns any `inbox_review` provenance into `self_driving_review=True`, which relaxes the bot/draft gates and changes the trust context. Unlike the webhook leg, this path does not re-check that the supplied task run is the non-internal signal implementation run for this team, that its signal report id matches, that the PR URL belongs to the run/task repository, or that the fetched PR is the repo-native bot-authored self-driving shape. Since task-run output is a caller/agent-controlled contract elsewhere in the tasks product, a bad or compromised caller can point this path at another PR in an enabled repo and get it reviewed under the self-driving carve-out.+- **Suggestion:** Make `process_inbox_pr_review` fail closed unless it can independently re-attest the provenance before creating the `ReviewRun`. For example, after parsing/fetching the PR, call or extend the tasks facade to verify `team_id`, `task_run_id`, `signal_report_id`, repository, and `pr_url` all describe the same non-internal signal implementation run, and mirror the webhook carve-out's PR-shape checks (`head.repo.full_name` equals the base repo and author is a bot) before setting `inbox_review`. If any check fails, log and return without stamping self-driving provenance.+- **Validator:** - **Checked:** Traced the four provenance fields from review_hog's TaskRun receiver → `queue_inbox_pr_review` facade → `process_inbox_pr_review`, and compared against the webhook leg (`_inbox_rereview_carve_out`) and `find_signal_implementation_run`.+- **Found (partial correction to the finding):** Three of the four fields are actually server-attested, not caller-supplied — `team_id`/`signal_report_id`/`task_run_id`/`acting_user_id` come from the fired `TaskRun`/`Task` rows and the server-side reviewer resolver (`receivers.py` ~L108–216). The one genuinely caller-controlled field is `pr_url`: it is `output.get("pr_url")` (receivers.py:78), the tasks product itself annotates it `"originates from task-run output APIs, so it is caller-controlled"` (products/tasks/backend/facade/api.py:5342), and it is written through the `set_output` PATCH endpoint gated by `task:write` (products/tasks/backend/presentation/views/api.py:1110) — a scope the sandbox agent holds (`INTERNAL_SCOPES` includes `task:write`, posthog/temporal/oauth.py:37-38). So the self-driving agent, which runs an LLM over untrusted PR/signal content, can set `pr_url` to any value.+- **Found (the real gap):** `process_inbox_pr_review` (diff L1041-1166) parses the repo _from_ the agent-supplied `pr_url`, resolves any enabled `StamphogRepoConfig` for that repo, fetches whatever PR the URL names, and stamps `output={"inbox_review": ...}` with no re-attestation — it never calls `find_signal_implementation_run`, never checks bot-authorship/draft/fork-safety, and never verifies the `pr_url` belongs to `task_run_id`'s run. The webhook leg does all of this (diff L862-936) and its own comment calls it `"belt and braces for the boundary a compromised or refactored facade would otherwise silently widen."` The receiver even has `task.repository` in hand (receivers.py:88) but doesn't use it to constrain the URL.+- **Impact:** `activities.py` sets `self_driving_review=bool(output.get("inbox_review"))` (diff L1227), which relaxes the bot-author refusal, draft gate, per-repo `review_mode`, and author-write-permission gate, and the workflow posts a real head-pinned GitHub APPROVE. A prompt-injected/compromised self-driving agent can therefore point `pr_url` at an arbitrary PR in a team-enabled repo (same-repo, different PR number suffices — e.g. a dependabot PR or a LABEL-mode-excluded human PR) and obtain an unearned Stamphog approval that satisfies required reviews with zero human in the loop — exactly the hazard tasks.py:73-75 documents the bot-author refusal exists to prevent. This is a trigger-side bypass, which the PR's own design explicitly set out to avoid ("a positively identified carve-out rather than a trigger-side bypass"), so it also breaks a stated invariant. Meets the security / auth-gap keep bar with a concrete trigger and concrete consequence; the elevated precondition (needs a compromised agent + opted-in reviewer + enabled repo) is real but does not neutralize the exposure.++### [❌ dismissed] should_fix · code_quality — products/tasks/backend/facade/api.py:501-503++**Team scoping is applied after an unscoped task-run match**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `find_signal_implementation_run` calls the unscoped `find_task_run` first and only then checks `run.team_id != team_id`. If another team has a matching PR URL or repository/head branch and is selected first, this facade returns `None` even when the requested team has a valid matching implementation run. That makes the self-driving webhook carve-out fail nondeterministically for valid runs instead of enforcing team scope in the lookup itself.+- **Suggestion:** Apply the team filter before selecting a run. Either extend `find_task_run` to accept an optional `team_id` and include it in both the PR URL and branch querysets, or implement the equivalent team-scoped lookup directly in this facade so the selected candidate is drawn only from the requested team.+- **Validator:** - **Checked:** Read `find_task_run` (products/tasks/backend/webhooks.py:29-96) and the only caller of `find_signal_implementation_run`, the webhook carve-out `_inbox_rereview_carve_out` (diff L862-936), plus how `team_id` is derived there.+- **Found (premise is technically accurate but the trigger is unreachable):** `find_task_run` matches on `output__pr_url=pr_url` scoped to `task__repository__iexact=repository` (webhooks.py:41-42), else on `branch` + `repository` (webhooks.py:66-73) — neither leg is team-filtered, and `find_signal_implementation_run` applies `run.team_id != team_id` afterward (diff L1714). For a _valid requested-team run to be shadowed_, two different PostHog teams must both hold a run matching the **same** `pr_url` (+repo) or the **same** `branch` (+repo). A real GitHub PR URL is unique to the single run that opened it, so natural pr_url duplication across teams does not occur; the branch leg is only consulted when no run has recorded that pr_url, and self-driving head branches are task-specific `posthog-code/<slug>` names that don't collide across teams. The collision is a contrived multi-tenant coincidence, not something real inputs hit.+- **Found (isolation is not actually broken):** The post-match `run.team_id != team_id → None` check correctly _rejects_ a foreign-team run — there is no cross-tenant binding or data leak. In the plausible variant the reviewer's own scenario implies (config-team ≠ run-team, e.g. `_resolve_repo_config` picks the oldest config's team while another team actually opened the PR), returning `None` is the intended fail-closed outcome; the suggested team-scoped query would return `None` there too, so the fix changes nothing in that case.+- **Impact:** The only genuinely distinct consequence — a valid same-team run missed because a second team matched first — is fail-closed (a later-push re-review is skipped; the stale-approval dismissal path is unconditional and unaffected, and the initial draft review already ran via the receiver leg). Rare trigger + fail-closed + no isolation violation puts this under the skill's 'never-gonna-happen edge case / speculative what-if' drop bar rather than a correctness bug worth surfacing.++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/reviewer.py:568-568,683-703++**Self-driving prompt still includes author familiarity when present**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self-driving block is appended after `familiarity_block`, but nothing suppresses the existing author-familiarity trust signal when `cl["self_driving"]` is true. That contradicts the intended behavior described in the chunk: self-driving reviews should replace human-author trust context with verified task provenance. If the sandbox context ever contains `author_pr_numbers`, or if `Pipeline(..., self_driving=True)` is used outside the tokenless sandbox path, the prompt can contain both a positive author-familiarity block and a later warning that machine-user familiarity carries no signal. That gives the reviewer conflicting trusted context and can bias approval for bot-authored PRs based on the machine user's history.+- **Suggestion:** Make the suppression explicit in the engine, not only in the server context producer. For example, skip familiarity for self-driving runs before the prompt is built (`if self.self_driving: return` in `Pipeline._maybe_compute_familiarity` and `_attach_familiarity`), or have `_build_review_prompt` render `familiarity_block = ""` whenever `cl.get("self_driving")` is true. Also ensure `_render_review_body` does not add the author-familiarity bullet for self-driving runs.+- **Validator:** - **Checked:** Whether `familiarity` can be non-`None` while `self_driving` is `True` at prompt-build time — traced `_build_review_prompt`/`_format_familiarity`/`_format_self_driving` (reviewer.py), the familiarity populator `_attach_familiarity` (review_local.py), and the server producer `fetch_review_context` (activities.py), plus both engine entrypoints.+- **Found:** `_attach_familiarity` only sets `classification["familiarity"]` when `context.get("author_pr_numbers")` is truthy — review_local.py:302-304 `raw_prs = context.get("author_pr_numbers"); if not raw_prs: return`. With no numbers, familiarity stays `None` and `_format_familiarity(cl)` returns `""`.+- **Found:** The server sets `author_pr_numbers = []` for every inbox/self-driving review — `activities.py::fetch_review_context`: `is_inbox_review = bool((run.output or {}).get("inbox_review")); author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []`. The PR's own integration test asserts `context["author_pr_numbers"] == []` for a self-driving run. So on the hosted path (the only path that sets `self_driving=True`) familiarity is `None` by construction and the two blocks never coexist.+- **Found:** The Action entrypoint never enables the flag (`review_pr.py:966` instantiates `Pipeline` without `self_driving`), so the finding's second hedge — `self_driving=True` outside the sandbox — does not occur in production.+- **Impact:** The conflicting-trust-signal prompt the finding describes is unreachable in the current code; producing it requires an upstream change (server populating `author_pr_numbers` on an inbox review, or a new non-sandbox caller enabling the flag). The suppression is already handled at the context producer, documented, and test-asserted, so the proposed engine-level suppression is defense-in-depth against a state the parent caller rules out — a speculative-what-if / already-handled drop, not a live bug. Does not meet the bar.++### [✅ VALID] must_fix · bug — products/tasks/backend/facade/api.py:503-506++**Implementation PR lookup filters out the Signals tasks it is meant to identify**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `find_signal_implementation_run` returns `None` when `task.internal` is true, but the Signals auto-start implementation path currently creates its implementation task with `internal=True` (`products/signals/backend/auto_start.py` passes `internal=True`, and tasks tests document that signal-report tasks are hidden by default this way). That means the webhook carve-out cannot positively identify the self-driving Inbox PRs this PR is trying to support, so later pushes will continue to be skipped as bot/draft PRs instead of being re-reviewed.+- **Suggestion:** Do not use `task.internal` as the discriminator here. Match the actual implementation-run shape used by Signals, for example `origin_product == SIGNAL_REPORT` plus the implementation run marker (`run.state["ai_stage"] == "implementation"`) or the existing Signals implementation association/artefact if that boundary is acceptable. Keep excluding unrelated internal plumbing tasks, but allow the internal implementation task that opens the PR.+- **Validator:** - **Checked:** The self-driving implementation task creation in `products/signals/backend/auto_start.py`, how `create_and_run_task` propagates `internal`, the discriminator in `find_signal_implementation_run` (diff L1717-1718), and the assumption encoded in review_hog's receiver + both test suites.+- **Found (premise confirmed):** `auto_start.py:258-261` creates the task that opens the draft PR — `interaction_origin="signal_report"` (comment: "Makes the agent auto-push and open a draft PR"), `ai_stage="implementation"` — with `internal=True` and a deliberate comment ("Internal so the run stays out of the default task list"). `create_and_run_task` forwards it unchanged (products/tasks/backend/facade/api.py:828 default, :850 `internal=internal`) into `Task.create_and_run` → `Task.internal`; no remap. `find_signal_implementation_run` then does `if task.signal_report_id is None or task.internal: return None` (diff L1718), so it rejects exactly the task shape it exists to identify.+- **Found (corroboration):** Every production signal-report task is `internal=True` — implementation (auto_start.py:261), research (report_generation/research.py:715), custom agents (custom_agent/base.py:683); the only `internal=False` is `management/commands/seed_inbox_data.py:279`, a dev seed. So `not task.internal` selects no real signal-report task. The PR's own test masks this: `_make_run` defaults `internal=False` (diff L1798), and review_hog's receiver test treats its `internal=True` case (`internal_pipeline_task`) as a skip — so green tests never exercise the real `internal=True` shape.+- **Impact:** The webhook carve-out (leg 2) gets `None` for every genuine self-driving PR, so `synchronize`/`reopen`/retarget pushes fall through to the bot/draft skip and are never re-reviewed — the carve-out is inert against production data. The same wrong assumption also sits on the pre-existing `if task.internal: return` in `receivers.py` that gates leg 1 (the initial review dispatch), so the feature is likely broadly non-functional, not just leg 2. Concrete trigger + concrete feature-breaking consequence, verified against the actual task-creation code; `must_fix` is warranted.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-1.mdnew file mode 100644index 000000000000..e4f0d7144a9f--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-1.md@@ -0,0 +1,278 @@+# Reviewer-quality run — `D-opus48-xhigh-1`++- **Dumped:** 2026-07-24T02:24:47+00:00+- **Report id:** `019f91c6-f61c-7f78-b31a-ddbd6a76f556` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 2724s (45.4 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-opus-4-8` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 14 | 14 | 1 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | review | 198 | 225,134 | 1,901,923 | 22,808,441 | 277,743 | 3 | $31.36 | $31.36 |+| claude-opus-4-8 | validation | 103 | 79,530 | 614,115 | 12,038,044 | 112,873 | 2 | $13.08 | $13.08 |+| claude-opus-4-8 | blind-spot | 85 | 95,637 | 796,437 | 8,882,636 | 124,611 | 0 | $13.01 | $13.01 |+| claude-sonnet-5 | dedup | 1 | 9,759 | 0 | 0 | 1,504 | 0 | $0.03 | $0.03 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,573 | 0 | $0.03 | $0.03 |+| **total** | | **388** | **419,089** | **3,312,475** | **43,729,121** | **518,304** | **5** | **$57.52** | **$57.52** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- naive method (all prompt tokens at input price): $250.16 — 4.3× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $44.6066 over 388 gen(s) (true $44.6066, Δ +0.0%)+ - · of which cache read: $21.8646 over 374 gen(s) (true $21.8646, Δ +0.0%)+ - · of which cache write: $20.7030 over 386 gen(s) (true $20.7030, Δ -0.0%)+ - · of which fresh (derived): $2.0391 over 388 gen(s) (true $2.0391, Δ +0.0%)+ - output: $12.9114 over 388 gen(s) (true $12.9114, Δ -0.0%)+- 5 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …6e580bf3 | issues-review-p3-c3 | 01:40:26 | 0 | 46,915 | claude-opus-4-8 |+| …ffa0103b | issues-review-p2-c3 | 01:40:27 | 0 | 46,914 | claude-opus-4-8 |+| …d027bad0 | issues-review-p2-c2 | 01:40:28 | 0 | 60,993 | claude-opus-4-8 |+| …2dba1b1d | issues-review-p1-c3 | 01:40:29 | 0 | 46,916 | claude-opus-4-8 |+| …fcf984de | issues-review-p3-c1 | 01:40:29 | 17,141 | 41,587 | claude-opus-4-8 |+| …480f3a49 | issues-review-p3-c2 | 01:40:30 | 17,141 | 43,853 | claude-opus-4-8 |+| …58b95f34 | issues-review-p2-c1 | 01:40:31 | 17,141 | 41,583 | claude-opus-4-8 |+| …3236e305 | issues-review-p1-c1 | 01:40:31 | 17,141 | 41,584 | claude-opus-4-8 |+| …a1566830 | issues-review-p1-c2 | 01:40:31 | 17,141 | 43,853 | claude-opus-4-8 |+| …317d7b86 | blind-spots-c2 | 01:55:58 | 0 | 63,953 | claude-opus-4-8 |+| …b31ab1e0 | blind-spots-c4 | 01:55:58 | 0 | 43,363 | claude-opus-4-8 |+| …d65a66ed | blind-spots-c3 | 01:55:59 | 0 | 49,165 | claude-opus-4-8 |+| …e19927db | blind-spots-c1 | 01:55:59 | 0 | 60,589 | claude-opus-4-8 |+| …7a623e92 | validation-c1 | 02:07:12 | 0 | 39,729 | claude-opus-4-8 |+| …6a945bab | validation-c3 | 02:07:15 | 0 | 39,374 | claude-opus-4-8 |+| …ef8ca86a | validation-c2 | 02:07:35 | 17,141 | 23,194 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **6/16** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 18s |+| review wave (perspectives) | 15m 29s |+| blind-spot sweep | 10m 52s |+| dedup (incl. combine/clean) | 18s |+| validation | 17m 57s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 26m 22s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | ? | 0 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | ? | 0 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider · security — products/review_hog/backend/api/settings.py:27-32++**Enable path for stamphog_review_inbox_prs has no server-side precondition, only a client-side one**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `stamphog_review_inbox_prs` is a freely-writable serializer field with no server-side validation tying it to `stamphog_connected`. The precondition ('only takes effect when the project has a synced, enabled Stamphog repository') is enforced only in the frontend (CodeReviewScene.tsx renders the switch disabled when `!stamphog_connected`). A direct PATCH to the settings endpoint — or the generated MCP client, which exposes this field as a plain optional boolean — can set the toggle true on a team with no reviewable Stamphog repo. This matters because when true the toggle ultimately authorizes hosted Stamphog to post a real GitHub approval on a bot-authored draft PR (a security-relevant, approve-first action). The only thing between 'toggle set via API' and a posted approval is the gating re-checked downstream in the queued Celery task and the webhook-leg positive-identification carve-out; the API layer itself asserts no precondition. The current behavior is a documented no-op when no repo config exists, so this is defense-in-depth rather than an active vulnerability, but the API contract does not reflect the precondition the product relies on.+- **Suggestion:** Consider validating the enable path server-side to mirror the UI guard and make the contract self-consistent: in the serializer's `validate_stamphog_review_inbox_prs` (or `validate`), reject enabling the toggle when `has_reviewable_repo_config(self.context['get_team']()...team_id)` is False, so the only defense against an accidental real approval isn't solely the downstream task's checks. If keeping the permissive-write-plus-downstream-no-op design is deliberate (as the receiver comment states), document on the field's `help_text` that enabling without a connected repo is accepted and silently no-ops, so API/MCP consumers understand the toggle can be set in a state the UI forbids.+- **Validator:** - **Checked:** The serializer field (`products/review_hog/backend/api/settings.py:27-32`, `stamphog_review_inbox_prs` — a writable `BooleanField(required=False)` in `Meta.fields`), the receiver dispatch (`products/review_hog/backend/receivers.py` `handle_task_run_saved` / `_start_stamphog_review`), the facade (`products/stamphog/backend/facade/api.py` `queue_inbox_pr_review` + `has_reviewable_repo_config`), and the downstream Celery task `process_inbox_pr_review` (`products/stamphog/backend/tasks/tasks.py:1110-1250`).+- **Found (premise is accurate but self-conceded as non-active):** The field is indeed freely writable with no `validate_*`. But the finding's own text says this is "defense-in-depth rather than an active vulnerability" and "a documented no-op when no repo config exists."+- **Found (already handled downstream):** `process_inbox_pr_review` (tasks.py:1138-1150) independently resolves a `StamphogRepoConfig` with the exact same gating as `has_reviewable_repo_config` (`enabled=True, connected_by_user_id__isnull=False`, non-empty `installation_id`, team-scoped via `for_team`) and returns early (`stamphog_inbox_pr_repo_not_reviewable`) when none exists. Enabling the toggle without a connected repo produces no `ReviewRun`, no workflow, and therefore no GitHub approval. The supposed consequence is prevented by existing validation — a drop criterion.+- **Found (contract fallback already satisfied):** The finding's alternative suggestion — document that enabling without a connected repo is accepted and no-ops — is already done: the field's `help_text` reads "Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)." API/MCP consumers already see this.+- **Found (no tenant/security hole):** The row is per-user, per-team and self-scoped; setting your own toggle crosses no boundary, and the approval only ever fires for the team's own positively-identified self-driving inbox PRs. There is no IDOR/auth gap; with a connected repo the toggle working is the intended behavior.+- **Impact:** The only thing server-side validation would add is rejecting a `True` that already no-ops until a repo is connected (a reasonable pre-set-preference pattern the UI itself allows once connected). That is defense-in-depth against an already-guarded, already-documented no-op — precisely the "already handled" / defensive-paranoia class the criteria say to drop, and the author already scoped it to the lowest priority (`consider`). Under precision-over-recall, drop.++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:1109-1112,1178-1183++**Receiver leg stamps self-driving provenance without positive re-identification**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `process_inbox_pr_review` (leg 1) accepts `pr_url`, `acting_user_id`, `signal_report_id`, and `task_run_id` from the `queue_inbox_pr_review` facade and stamps them straight into `output["inbox_review"]`, which is the sole thing that flips `self_driving_review=True` in the engine and bypasses the bot-author refusal, draft prerequisite, review-mode, and author-write-permission gates. Unlike the webhook leg (`_inbox_rereview_carve_out`), leg 1 performs no positive identification: it never confirms the PR at `pr_url` is actually a non-internal signals-implementation run for `team_id` (no `find_signal_implementation_run` call), never checks the PR is bot-authored/draft/repo-native, and never validates that `acting_user_id`/`signal_report_id` belong to the team. It simply fetches whatever PR sits at `pr_url` within a synced+enabled config for the team and posts a real, head-pinned GitHub APPROVE on it as self-driving. The webhook leg deliberately hardens this exact boundary — its team re-check is commented as 'belt and braces for the boundary a compromised or refactored facade would otherwise silently widen' — but leg 1 has no equivalent, so a bug or future refactor in review_hog's TaskRun receiver (e.g. firing with a pr_url from a non-signal task, or a task in another team) would silently widen the carve-out into auto-approving an arbitrary PR with no human in the loop. The inputs are internal today, but a real GitHub approval that can satisfy required reviews is a high-value action to leave protected only by an upstream caller's correctness.+- **Suggestion:** Give leg 1 the same positive identification the webhook leg has: before stamping `inbox_review` provenance, call `find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url, head_branch=<pr head ref>)` and bail (no-op) if it returns None or its `run_id`/`signal_report_id` don't match the caller-supplied values. At minimum, re-verify the fetched PR is bot-authored (reuse `_is_bot_authored(pr)`) and that the resolved run is a non-internal signal task for `team_id`, so leg 1 fails closed rather than trusting the facade caller for the entire self-driving carve-out.+- **Validator:** - **Checked:** Leg 1 `process_inbox_pr_review` (stamphog `tasks/tasks.py:1109-1245`), its full caller chain, the webhook leg `_inbox_rereview_carve_out` (`tasks/tasks.py:144-215`), the `queue_inbox_pr_review` facade (`facade/api.py:128-155`), review_hog's `handle_task_run_saved` receiver (`receivers.py:72-141`), and `find_signal_implementation_run` (tasks `facade/api.py:484`).+- **Found:** The premise "leg 1 performs no positive identification" is true of leg 1 _in isolation_, but the identification is done by its sole production caller. The only caller of `queue_inbox_pr_review` is `_start_stamphog_review`, reached from `handle_task_run_saved`, which fires only when `task.signal_report_id is not None` (receivers.py:98) and `not task.internal` (receivers.py:104), with `pr_url` taken from _that same task run's_ own `output` (receivers.py:93), scoped to `instance.team_id`, and the `stamphog_review_inbox_prs` toggle checked (receivers.py:126). That is verbatim the "non-internal task carrying a signal report in the given team" shape `find_signal_implementation_run` asserts — the exact check the issue wants leg 1 to duplicate. All other symbol references in the PR are the facade definition, docs, and tests; no endpoint or command feeds an external `pr_url`.+- **Found:** Leg 1 is team-scoped throughout — repo config `for_team(team_id).filter(repository__iexact=…, enabled=True, connected_by_user_id__isnull=False)` (tasks.py:1140), PR fetched via that team's installation, and `ReviewRun.objects.for_team(team_id)`. A wrong `pr_url` can only ever resolve inside a repo the team already has a synced+enabled Stamphog config for, or it no-ops (tasks.py:1151). So there is no tenant-isolation hole.+- **Found:** The webhook leg needs inline `find_signal_implementation_run` because its entry point is an untrusted external GitHub payload with no prior identification (the lookup is its _primary_ ID; the team re-check is the belt-and-braces layer on top). Leg 1's entry point is a trusted internal `TaskRun` post_save where identification is intrinsic to the trigger conditions. The asymmetry is justified by entry-point trust, not an omission.+- **Impact:** The issue itself concedes "the inputs are internal today"; its harm scenario is explicitly conditioned on "a bug or future refactor in review_hog's TaskRun receiver." That is defense-in-depth against a hypothetical future regression — a speculative what-if that cannot occur given the current call sites, and a case already handled by the parent caller. Under the validation criteria (precision over recall; drop speculative and already-handled findings; on the fence → drop), it does not meet the keep bar. The suggestion is a reasonable hardening, but not a currently-reachable defect.++### [❌ dismissed] consider · code_quality — products/stamphog/backend/facade/api.py:120-124++**has_reviewable_repo_config omits the provider filter its sibling queries apply**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** has_reviewable_repo_config filters on enabled + connected_by_user_id + non-blank installation_id, but unlike its two sibling resolvers it does not filter provider="github". The receiver leg (process_inbox_pr_review, which filters `provider="github", repository__iexact=..., enabled=True, connected_by_user_id__isnull=False`) and `_resolve_repo_config` both scope to provider="github". This function drives the UI's `stamphog_connected` flag / the inbox toggle's enabled state. Today GitHub is the only provider so the result is identical, but the divergence is latent: if any non-GitHub provider config is ever added, has_reviewable_repo_config would report the toggle as actionable while every actual review path (which is provider-scoped) fails to find a matching config — the exact silent-no-op the docstring says this check exists to prevent.+- **Suggestion:** Add `provider="github"` to the filter so it matches the reviewability predicate the review paths actually use: `.filter(provider="github", enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="")`. This keeps the UI's connected signal in lockstep with what reviews can run on.+- **Validator:** - **Checked:** `has_reviewable_repo_config` (stamphog `facade/api.py:120-124`) against the review-path queries it's compared to, plus the `StamphogRepoConfig.provider` field (`models.py:26-29`), the write paths (`presentation/serializers.py` field config, `presentation/views.py:201`/`:308`), and every `provider=` filter in the backend.+- **Found:** The omission is real — `has_reviewable_repo_config` filters `.filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="")` with no `provider="github"`, whereas `process_inbox_pr_review` (`tasks.py:1140`) and `_resolve_repo_config` (`tasks.py:186`) scope to `provider="github"`. (Note the sibling `get_repo_config` at `facade/api.py:108` also omits it, so the "all siblings filter provider" framing is partial.)+- **Found:** The harm is unreachable today and stays unreachable via the API. `has_reviewable_repo_config` already requires a non-blank `installation_id` and a non-null `connected_by_user_id`; a non-blank `installation_id` is only ever set by the verified `sync_installation` flow, and that flow hardcodes `provider="github"` (`views.py:308` `get_or_create(provider="github", …)`). Manual creates can set a different `provider` but leave `installation_id` blank (read-only on the serializer), so they're excluded by `.exclude(installation_id="")`. Every row that can satisfy the predicate is therefore `provider="github"`. The model comment confirms "GitHub is the only implemented provider today" (`models.py:26`).+- **Impact:** Zero behavioral difference today, and no current input path can create a non-GitHub config that counts as reviewable. The issue itself concedes "Today GitHub is the only provider so the result is identical"; its harm is conditioned on future work adding a non-GitHub provider — future-proofing for a case not in scope. Per the criteria (drop speculative what-ifs that can't occur given the call sites/validation already in place, drop future-proofing, on the fence → drop), it does not meet the keep bar.++### [❌ dismissed] consider · code_quality — products/tasks/backend/facade/api.py:501-505++**find_signal_implementation_run's branch fallback resolves non-deterministically**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** find_signal_implementation_run delegates to find_task_run(pr_url, branch, repository). The pr_url leg is reliable (globally unique), but when pr_url is None/unmatched it falls back to the branch+repository leg, which returns `.first()` with no deterministic ordering. When multiple TaskRuns share (branch, repository) — e.g. across teams that both configured the same repo, or repeated runs on a common branch name — the picked run is arbitrary. find_signal_implementation_run then hard-filters on team_id and the signal-report/non-internal predicate, so an arbitrary pick of the 'wrong' run returns None (fail-closed) even when a valid self-driving run for the correct team exists, silently skipping a legitimate re-review for that delivery. Impact is low for the current caller because the carve-out only fires on synchronize/reopen/base-retarget (by which time the self-driving PR has been opened and its pr_url is populated on the run, so the reliable pr_url leg matches), but the facade is written for reuse and the branch fallback's flakiness is not signalled to future callers.+- **Suggestion:** Either document on find_signal_implementation_run that callers must guarantee a stored pr_url for reliable identification (and that the branch fallback is best-effort), or make the branch match deterministic (e.g. add an explicit `.order_by("-created_at")` in find_task_run's branch leg) so the same (branch, repository) always resolves the same run rather than depending on default DB ordering.+- **Validator:** - **Checked:** The new `find_signal_implementation_run` (`products/tasks/backend/facade/api.py`, PR head) and the `find_task_run` helper it delegates to (`products/tasks/backend/webhooks.py:29-98`), plus whether the PR modifies `find_task_run`, plus the sole caller (`_inbox_rereview_carve_out` in stamphog `tasks.py`).+- **Found:** The branch leg's non-determinism is genuine — `find_task_run` line 68-76 does `.filter(branch=…, task__repository__iexact=…, state__wizard_head_branch__isnull=True).first()` with no `order_by`, whereas the pr_url leg orders by `terminal_rank, -created_at` (line 54). But `find_task_run` is **pre-existing, unmodified code**: it is byte-identical in master (same branch-leg `.first()` with no ordering), and the PR diff touches only a new delegating caller (`from products.tasks.backend.webhooks import find_task_run` + `find_task_run(pr_url=…, branch=…, repository=…)`) and a test file — not `find_task_run` itself. The normal webhook handler `process_pull_request` (webhooks.py:159) already calls it identically, so any flakiness predates this PR.+- **Found:** The new caller cannot reach the branch fallback. `_inbox_rereview_carve_out` passes `pr_url=pr.get('html_url')` and only fires on synchronize/reopen/base-retarget, by which time the PR is open and the run's `output.pr_url` is stored, so `find_task_run`'s deterministic pr_url leg matches first. The issue itself concedes this.+- **Impact:** No currently-reachable defect. The harm scenario needs the branch fallback exercised AND multiple TaskRuns colliding on exact `(branch, repository)` (already repo-scoped), and even then the outcome is a fail-closed _missed_ re-review, not a wrong approval / data loss / contract break. The stated motivation is explicitly reuse and signalling to "future callers" — future-proofing / documentation for callers that don't exist. Per the criteria (drop speculative what-ifs that can't occur given the call site, drop future-proofing, on the fence → drop), it does not meet the keep bar.++### [❌ dismissed] consider · bug — tools/pr-approval-agent/review_pr.py:587-593++**Merge-conflict prerequisite gate goes inert for self-driving draft PRs**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** Relaxing the draft prerequisite for `self_driving` runs means `_check_prerequisites` now proceeds past the draft check for these PRs, leaving `pr.mergeable_state == "dirty"` (new line ~592) as the only merge-conflict guard. GitHub's REST API reports `mergeable_state == "draft"` for draft PRs — the draft state takes precedence over `dirty`/`clean`/`behind`, and mergeability is not computed while a PR is draft. Both runtimes pass GitHub's value straight through (`review_pr` github.py:592, `review_local.py:198`). So for a self-driving _draft_ PR the `"dirty"` branch can never fire, and the prerequisites gate provides no merge-conflict protection at all for exactly the class of PR this carve-out was created to review. A self-driving draft that has diverged from base can therefore clear prerequisites and receive a head-pinned approval, whereas before the change every draft was blocked outright so the conflict gate's blind spot was harmless.+- **Suggestion:** Decide explicitly whether conflict detection should cover self-driving draft reviews. If yes, don't rely on `mergeable_state == "dirty"` for drafts — either resolve mergeability server-side and pass the resolved value in the context, or when `self_driving and pr.draft` treat an inability to confirm clean mergeability as blocking. If skipping conflict checks on drafts is intentional (leaning on the head-changing dismissal when conflicts are later resolved), add a one-line comment noting the `dirty` check is deliberately inert for self-driving drafts so a future reader doesn't assume it protects them.+- **Validator:** - **Checked:** `review_pr.py::_check_prerequisites` (the reworked draft/`dirty` gate), how `mergeable_state` is populated in both runtimes (`github.py:592`, `review_local.py:198`), the `PRData` fields, and the merge/dismissal invariants described for the carve-out.+- **Found:** The premise is technically correct. `review_pr.py:587` now reads `if pr.draft and not self.self_driving:`, and the only remaining conflict guard is `if pr.mergeable_state == "dirty":`. Both runtimes forward GitHub's raw `mergeable_state` (`github.py:592`, `review_local.py:198`) and neither captures the separate `mergeable` boolean — so for a draft PR, where GitHub returns `mergeable_state == "draft"`, the `== "dirty"` branch cannot fire. The guard is genuinely inert for self-driving drafts.+- **Impact:** The named consequence — a head-pinned approval posted on a conflicted draft — does not translate into user-facing harm, so it fails the "concrete consequence = real harm" test. (1) A `dirty` PR cannot be merged by GitHub regardless of approvals, and a draft cannot be merged either — merge safety is enforced independently of any reviewer verdict. (2) Resolving a real merge conflict always changes the head SHA (merge-in or rebase), which triggers the head-pinned-approval dismissal this PR explicitly preserves, so a stale approval on a formerly-conflicted PR is dismissed before it could ever merge. (3) The reviewed diff is computed `base_sha..head_sha` via git and is well-defined regardless of mergeability, so the conflict does not corrupt or mislead the review itself. The protection the gate would provide is fully redundant with GitHub's own draft/dirty merge-blocking plus the design's head-change dismissal (which the finding's own suggestion acknowledges). The only remaining value is a clarifying comment noting the check is deliberately inert — a documentation nicety below the ReviewHog bar. On the fence → drop, per precision-over-recall.++### [❌ dismissed] consider · best_practice — tools/pr-approval-agent/reviewer.py:683-703++**self-driving familiarity invariant relies on server context, not the engine flag**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new provenance block asserts to the reviewer that for self-driving runs "author familiarity, org membership, and merged-PR history carry no signal here." However, nothing in the engine ties familiarity suppression to the `self_driving` flag it now holds. `review_local._attach_familiarity` (review_local.py:292-311) and `Pipeline._maybe_compute_familiarity` only skip when tier != T1-agent or when `author_pr_numbers` is absent from the context — the invariant depends entirely on the hosted server choosing not to include `author_pr_numbers`. If a self-driving run is classified T1-agent and the context ever carries `author_pr_numbers` (a server-side change, a leaked/reused field, or a future refactor), familiarity would be computed on the machine user's git history and rendered in the same TRUSTED region via `_format_familiarity`, directly contradicting this block's claim that familiarity carries no signal and feeding the LLM two conflicting trust signals in one prompt.+- **Suggestion:** Enforce the documented invariant with the flag the engine already has rather than only via context omission: return early from `_attach_familiarity` (and `Pipeline._maybe_compute_familiarity`) when the run is self-driving, e.g. `if pipeline.self_driving or pipeline.classification.get("tier") != "T1-agent": return`. That guarantees `familiarity is None` for self-driving runs regardless of what the context carries, keeping `_format_familiarity` empty and consistent with the provenance block.+- **Validator:** - **Checked:** `_attach_familiarity` (review_local.py:292-311) and `_maybe_compute_familiarity` (review_pr.py:510-521) gating; the server-side context builder `fetch_review_context` and sandbox launcher `run_review_in_sandbox` in `products/stamphog/backend/temporal/activities.py`; and how `self_driving_review` vs `author_pr_numbers` are derived.+- **Found:** No current contradiction exists. The self-driving path sets `author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []`, where `is_inbox_review = bool((run.output or {}).get("inbox_review"))` (activities.py ~235-238). The engine flag is set from the _same_ value: `self_driving_review=bool(output.get("inbox_review"))` (activities.py ~449). Both the empty PR list and the `self_driving` flag derive from one source of truth (`run.output["inbox_review"]`) in the same file, so they cannot diverge under current code. With `author_pr_numbers` empty, `_attach_familiarity` hits `if not raw_prs: return` (review_local.py:302-303), `familiarity` stays `None`, and `_format_familiarity` (reviewer.py) renders empty — matching the provenance block's 'familiarity carries no signal' claim. There are no two conflicting trust signals today.+- **Impact:** The described failure (familiarity computed on the machine user and rendered in the TRUSTED region) is unreachable in the current codebase. The reviewer's own trigger is explicitly hypothetical — 'a server-side change, a leaked/reused field, or a future refactor.' That is the definition of a speculative what-if / defensive-coding hardening, which the validation bar drops. Guarding the engine's early-return on `self_driving` would be a reasonable belt-and-braces addition, but it defends against a condition that cannot occur given the single-value coupling already in place, so it does not meet the keep bar. Precision over recall → drop.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected runs a synchronous cross-DB query on every settings read and write**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** get_stamphog_connected() calls has_reviewable_repo_config(instance.team_id), a synchronous query into the separate Stamphog product DB, and this field is serialized on every response the endpoint produces. The GET is described in this file as "the Code review tab's always-called endpoint" (line 107), and because stamphog_connected is in Meta.fields it is also recomputed on every PATCH response — so each of the four toggles (review_inbox_prs, stamphog_review_inbox_prs, review_labeled_prs, urgency_threshold) incurs an extra cross-DB round trip on save, on top of the page-load read. There is no caching, so a value that only changes when a repo is connected/disconnected is re-fetched on every request. The fail-soft try/except protects against errors but not against the added latency on a hot endpoint.+- **Suggestion:** Avoid recomputing this on every request. Cheapest options: (a) only populate stamphog_connected for the GET (e.g. drop it from the PATCH response via a to_representation branch or a read-specific serializer) since the client already holds the connection state after load; and/or (b) memoize has_reviewable_repo_config(team_id) behind a short-TTL cache keyed by team_id, since the answer changes rarely. Either removes the write-path amplification and the repeated cross-DB reads.+- **Validator:** - **Checked:** `has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`, the serializer method field `get_stamphog_connected` (`settings.py:71-82`), and the call frequency via the DRF viewset (`user_settings` GET/PATCH action) and the frontend `reviewHogSettingsLogic` usage in `CodeReviewScene.tsx`.+- **Found (query is a single cheap indexed check, not N+1/unbounded):** `has_reviewable_repo_config` is one `.exists()` — `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()`. No loop, no per-row amplification, team-scoped (indexed). It runs at most once per settings request.+- **Found (endpoint is cold, human-paced, not high-frequency):** "always-called" means once per Code review tab page load (GET), and PATCH fires only on a user toggling one of four switches (`updateSettings(...)` in `CodeReviewScene.tsx:1044/1062/1097/1130`). These are human-initiated, low-volume events, not a per-event/per-row hot path. The product is alpha and UI-gated to the ReviewHog team, so real traffic is tiny.+- **Found (not the async-blocking case):** this is a synchronous DRF view, so a synchronous DB read is the normal execution model — not "blocking I/O on an async path." Reliability is already covered by the fail-soft try/except.+- **Impact:** The added cost is a single indexed existence query (a few ms, even cross-DB) on a settings endpoint hit occasionally per user. That does not meet the performance bar ("problems that bite at real scale" — N+1, unbounded, quadratic, missing indexes on genuinely hot paths). The proposed short-TTL cache / read-vs-write serializer split is a micro-optimization + caching infrastructure for a cold path — the overengineering/speculative class the criteria say to drop. On the fence → drop.++### [❌ dismissed] consider · performance — products/review_hog/backend/receivers.py:126-138++**Stamphog review is re-dispatched on every output save with no pre-dispatch guard**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** handle_task_run_saved fires on every TaskRun output save (the module docstring notes repeat saves with an unchanged target re-fire deliberately, since output is re-written "at the end of every agent turn whose current branch changed"). The new stamphog leg dispatches queue_inbox_pr_review whenever pr_url is not None and settings.stamphog_review_inbox_prs, with no guard on whether the PR/head actually changed since the last dispatch and no check that the team has a reviewable Stamphog repo config (that check is deferred into the queued task, and the UI keeps an already-on toggle interactive after Stamphog is disconnected). ReviewHog's own leg collapses duplicates cheaply at the Temporal layer (deterministic workflow id + USE_EXISTING), but per the PR description the stamphog leg dedupes on the PR's current head — which requires the queued task to fetch the PR from GitHub before it can no-op. So repeated output saves with an unchanged pr_url each cost a broker publish plus a GitHub PR fetch, and a team that left the toggle on after disconnecting Stamphog pays that on every inbox PR for nothing.+- **Suggestion:** Gate the re-dispatch so unchanged targets don't repeatedly enqueue work: track the last-dispatched PR head/target (e.g. on the run's output or a lightweight marker) and only call `_start_stamphog_review` when it actually changed, mirroring the intent of the head-keyed dedupe described in the PR. If keeping the dispatch unconditional, document that each firing costs a broker publish + a downstream GitHub fetch so the cost of the hot-path re-fires is explicit. (Adding has_reviewable_repo_config to the receiver itself is not recommended — it would put a cross-DB query on this hot save path.)+- **Validator:** - **Checked:** the stamphog dispatch branch (`receivers.py:126-139`), the `handle_task_run_saved` docstring and pre-dispatch guards (`receivers.py:85-110`), `_start_stamphog_review`'s docstring, and the downstream ordering in `products/stamphog/backend/tasks/tasks.py` `process_inbox_pr_review` (repo-config resolution vs GitHub fetch).+- **Found (the disconnected-team cost claim is factually wrong):** `process_inbox_pr_review` (tasks.py:1138-1150) resolves the repo config first and `return`s at `stamphog_inbox_pr_repo_not_reviewable` when none exists — this is _before_ the `StamphogGitHubClient(...).get_pr(...)` call (tasks.py:1157+). So a team that left the toggle on after disconnecting pays a broker publish + one cheap indexed `.exists()`, NOT the GitHub fetch the finding asserts. The GitHub fetch only happens for connected teams (the intended path).+- **Found (re-fire is deliberate and already documented):** the `handle_task_run_saved` docstring states repeat saves "re-fire it deliberately" and that "a same-head re-trigger costs one fetch (early-exit)" — the finding's fallback suggestion (b), documenting the cost, is already satisfied in-code. The cheapest-first guards (`update_fields` without `output` → return; internal/no-target → return, `receivers.py:85-110`) already suppress the bulk of hot saves.+- **Found (suggestion (a) conflicts with intended design):** the head-keyed dedupe is intentionally downstream because the receiver only has `output.pr_url`, not the current GitHub head — the fetch is what reveals it, and that is precisely how the design recovers a "lost synchronize" delivery (per the run docstring). A receiver-side last-dispatched marker would defeat that recovery property.+- **Impact:** the real cost (connected case) is a bounded, small number of single GitHub PR fetches per PR — with explicit rate-limit handling (`GitHubRateLimitError` retry/backoff) — on a low-volume, alpha, human-triaged flow. That is not N+1, unbounded, quadratic, or otherwise a problem that "bites at real scale." Combined with an inaccurate central cost claim, an already-satisfied doc suggestion, and a primary fix that contradicts the deliberate recovery design, this does not meet the bar — drop.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1124-1165++**Inbox review task hits GitHub on every dispatch with no cheap dedup, eroding shared rate-limit budget**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** process_inbox_pr_review is re-dispatched by review_hog's TaskRun receiver on every TaskRun output save that carries the PR URL (stated in the docstring, L1124-1128), and every Celery retry re-enters here too. Each invocation runs a StamphogRepoConfig query and then a full GitHub get_pr REST call (L1158-1165) BEFORE the head-keyed DB dedup can decide it's a no-op. Unlike the webhook path — which short-circuits redeliveries cheaply via the delivery-id idempotency cache (`_is_duplicate_pr_event` / `_mark_pr_event_processed`) before touching GitHub or the DB, and uses asymmetric cache TTLs plus a label cooldown specifically to 'absorb synchronize bursts' — the inbox leg has no burst-absorbing early-out: the head-keyed dedup fundamentally needs the current head SHA, which only the fetch supplies. So a burst of output saves for one self-driving PR (and each retry) each consumes a get_pr against the installation's shared GitHub rate-limit budget. Under many concurrent self-driving runs this can degrade the very budget that ALL stamphog reviews for that installation depend on — a reliability coupling the rest of this file goes out of its way to guard.+- **Suggestion:** Add a cheap burst-absorbing short-circuit before the config/fetch work, consistent with the webhook path's idempotency+cooldown pattern: e.g. a short-TTL cache keyed on (team_id, pr_url) set after a successful queue/no-op so rapid refires collapse without a GitHub call, or record the last-fetched head per PR and skip when unchanged within the window. Keep the TTL short (and lean on the webhook leg) so a genuinely new head / lost-synchronize is still eventually reviewed. This preserves the recovery intent while bounding get_pr amplification and Celery-retry re-fetches.+- **Validator:** - **Checked:** `process_inbox_pr_review` (stamphog `tasks.py:1130-1174`: config query at 1140, `get_pr` at 1159, head-keyed dedup at 1198-1221), the webhook path's cheap early-out (`_is_duplicate_pr_event`/`_mark_pr_event_processed` in `process_pull_request_event`), review_hog's `handle_task_run_saved` receiver, and the tasks-side output writers.+- **Found:** The premise is correct — the receiver dispatches via `queue_inbox_pr_review().delay()` with no review_hog-side dedup, and leg 1 hits `get_pr` before the DB dedup, whereas the webhook path short-circuits redeliveries on `delivery_id` before touching GitHub.+- **Found:** But amplification is bounded and modest. The receiver early-outs when `update_fields` is set and excludes `"output"` (receivers.py:86), and the frequent status writes `update_task_run_status` save `update_fields=["status","error_message","completed_at","updated_at"]` — no `"output"` — so they never re-fire. Only genuine output writes (`set_task_run_output` api.py:2160, webhook backstop webhooks.py:337) re-fire, and `pr_url` is written once; retries are capped at `max_retries=3`. Per-run `get_pr` amplification is realistically single-digit, not N+1/unbounded.+- **Found:** The cheap early-out is inherently unavailable to this leg: it has no `delivery_id` (not a webhook), and the head-keyed dedup needs the current head SHA that only the fetch supplies — the docstring acknowledges the refire and treats it as intended lost-synchronize recovery. The webhook guards exist because webhooks burst; the receiver's trigger (a few output saves per opt-in, low-frequency inbox run) does not.+- **Impact:** No realistic scale where this bites — the feature is per-user opt-in (default off), each `get_pr` is one REST call against a generous per-installation budget dwarfed by the review's own GitHub calls, and the "many concurrent runs degrade the budget" claim is speculative. The suggested `(team_id, pr_url)` TTL cache would also suppress the explicit lost-synchronize recovery. Per the criteria (performance must bite at real scale; drop rare/low-impact scale concerns; on the fence → drop), it does not meet the keep bar.++### [❌ dismissed] consider · best_practice — products/review_hog/backend/receivers.py:144-156++**Registered hook resolve_stamphog_acting_reviewer is not exception-safe, breaking this module's documented "never raise into the caller" invariant**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This module is deliberately exception-proof relative to its callers: handle_task_run_saved wraps its whole body in try/except because it "executes inside tasks' save path and must never raise into it", and both `_start_review` and `_start_stamphog_review` carry their own try/except so a broker/Temporal outage "must never surface into the saver". The newly-added resolve_stamphog_acting_reviewer breaks that discipline. review_hog registers it into stamphog's inbox hook registry (connect() -> register_inbox_acting_reviewer_resolver) and stamphog's webhook path calls it before every self-driving re-review, yet the function has no guard around work that can raise: the SignalReportArtefact query, the deferred posthog.schema-heavy resolve_org_github_login_to_users(...) import/call, and ReviewUserSettings.load(...). `_resolve_assigned_reviewer` only catches JSON decode errors (lines 143-146); a transient DB error, an org-resolution failure, or an import error propagates straight out of the resolver. Trigger: a DB hiccup or resolver failure during a synchronize/reopened/retarget webhook. Consequence: the exception escapes into stamphog's webhook re-review handler — a cross-product blast radius that this module's own convention exists specifically to prevent, and that review_hog (as the owner and registrant of the hook) is responsible for containing. Because it fires on later pushes rather than the initial save path the perspectives focused on, this failure mode is easy to miss.+- **Suggestion:** Make the registered hook fail-closed the same way the rest of the module does: wrap the body in try/except, log via logger.exception (e.g. "review_hog_stamphog_acting_reviewer_resolve_failed"), and return None so a resolution failure cleanly skips the re-review instead of surfacing into stamphog's webhook path. A resolver that returns None on error preserves the existing skip-path semantics (the webhook leg already treats a missing/None resolver as "do not re-review"), rather than turning a transient error into a failed webhook.+- **Validator:** - **Checked:** every consumer of the registered resolver — `get_inbox_acting_reviewer_resolver` is imported and called only inside `_inbox_rereview_carve_out` (`products/stamphog/backend/tasks/tasks.py:201/205`), which itself has exactly one call site: `process_pull_request_event` at tasks.py:876. Grepped the repo-wide FETCH_HEAD tree to confirm no other callers.+- **Found (the escape the finding claims cannot happen — caller already guards it):** the sole call site wraps it: `try: carve_out = _inbox_rereview_carve_out(...) except Exception as e: logger.exception("stamphog_pr_event_inbox_carve_out_failed", ...); raise process_pull_request_event.retry(exc=e)` (tasks.py:875-879). A DB hiccup, heavy-import failure, or org-resolution error raised by `resolve_stamphog_acting_reviewer` is caught on the stamphog side, logged, and turned into a Celery delivery retry. There is no unguarded propagation into the webhook handler; the premised cross-product blast radius does not exist.+- **Found (the suggested fix would introduce a real bug):** the caller distinguishes resolver-not-registered (`resolver is None` → skip, tasks.py:202-204) from resolver-returned-None (`acting_user_id is None` → `_InboxCarveOut(opted_out=True)`, tasks.py:206-207), and the opted-out branch runs `_retract_stale_approvals_on_skip(...)` (tasks.py:894-898) — it DISMISSES the standing GitHub approval. So making the resolver swallow exceptions and return None would turn a transient DB blip into a silent approval dismissal, exactly the destructive outcome the caller's retry ("Retry (don't drop) ... must not silently drop a legitimate re-review", tasks.py:873-874) is designed to avoid. The current raise→catch→retry is the correct handling for transient errors.+- **Impact:** the concern is already handled at the call site, and the recommended change would regress behavior. Under the criteria this is both "already handled" (prevented by the parent caller) and "wrong premise" — drop.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:321++**Security-gate carve-out uses truthy coercion instead of a fail-closed exact check**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `self_driving=bool(context.get("self_driving_review"))` enables the carve-out with a truthiness test. The `self_driving` flag disables two security controls — the bot-author refusal (`_refuse_bot_author`, whose docstring calls it "the defense-in-depth layer for any manual or out-of-band invocation") and the draft prerequisite — so that Stamphog will post a real GitHub approval on a bot-authored draft. Because `self_driving_review` crosses a JSON boundary, `bool()` makes this control fail OPEN for any non-boolean truthy value: the strings "false", "0", or any non-empty string all coerce to True and silently enable the bypass. The rest of the design is explicitly "fail closed," but this coercion is the one place a malformed/unexpected type flips the gate on rather than off.+- **Suggestion:** Honor only a genuine boolean true so anything else fails closed: `self_driving=context.get("self_driving_review") is True`. This keeps the intended default-off behavior for an absent key, None, or False, while ensuring a malformed or unexpected value can never relax the bot-author/draft gates.+- **Validator:** - **Checked:** the full producer→consumer path for `context["self_driving_review"]` — the sole producer `build_reviewer_invocation` (products/stamphog/backend/logic/reviewer.py:86-131), its single caller `run_review_in_sandbox` (products/stamphog/backend/temporal/activities.py:428-450), the JSON serialization boundary, and the consumer in review_local.py:321. Also checked the CLI `--context <path>` entry.+- **Found:** The value can never be a non-boolean truthy type given the call site and type. The parameter is annotated `self_driving_review: bool = False` (logic/reviewer.py:101) and the only caller passes `self_driving_review=bool(output.get("inbox_review"))` (activities.py:449) — a genuine Python bool. It is placed in the context dict (`"self_driving_review": self_driving_review`, ~line 131) and serialized with `json.dumps(context, ...)` (~line 130). JSON preserves boolean type across `dumps`/`loads`, so `context.get("self_driving_review")` on the engine side is always `True`, `False`, or absent (`None`). For every one of those reachable values, `bool(...)` and `is True` produce identical results. The truthy-string scenario ('false', '0', any non-empty string) would require the trusted server to serialize a string into a field it always fills with `bool(...)` — that path does not exist.+- **Impact:** The described fail-open cannot be triggered: no untrusted party controls this field (PR content flows into `pr`/`files`/`discussion`, never `self_driving_review`), and the producer emits only booleans. This is exactly the 'speculative what-if / defensive-coding' class the criteria drop — a guard against a value that upstream types and the `bool(...)` call already rule out. The one residual case, an operator hand-crafting a `--context` file with a truthy-string typo, is a trusted operator who could set `true` directly anyway, making it a never-gonna-happen, zero-impact edge. The suggested `is True` is a harmless one-liner but defends against an unreachable input, so it does not meet the security keep bar (no reachable vulnerability, no affected user).++### [❌ dismissed] consider · security — tools/pr-approval-agent/review_local.py:316-321++**Bot-author and draft gates relaxed on an unverified context flag with no engine-side check**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The self-driving carve-out disables two defense-in-depth authorization controls — the bot-author refusal and the draft prerequisite (review_pr.py:225 and :590 both gate on `not self.self_driving`) — based solely on `context["self_driving_review"]`. The engine performs no independent verification that the PR is genuinely an inbox-linked implementation task; it fully trusts a single boolean that arrives in the same context JSON that also carries untrusted GitHub-sourced fields (pr.title, pr.body, reviews, discussion). This chunk also expands the LLM's untrusted-content attack surface: bot-authored draft PRs that were previously refused before any prompt was built now reach `_llm_review`, so their diff/body/comments are processed by the reviewer. If any current or future caller sets this flag for a non-inbox bot PR, or the trusted flag is ever populated from GitHub-controlled data, Stamphog would post a real GitHub approval on arbitrary bot-authored code — precisely what the bot-author refusal exists to prevent.+- **Suggestion:** Keep `self_driving_review` the exclusive responsibility of server-side inbox-provenance derivation and make it structurally impossible to source from GitHub-controlled data — e.g. carry server-trusted control fields in a separate sub-object of the context from the GitHub-sourced payload, so a future refactor can't merge untrusted data into the control flag. The existing anti-injection notice and `_sanitize_untrusted` cover the expanded untrusted surface; the gap is that the gate relaxation itself has no engine-side positive signal. This is defense-in-depth around a deliberate design decision, not a claim the current server derivation is wrong.+- **Validator:** - **Checked:** every setter of the flag (`self_driving_review`/`inbox_review`), the engine gates it relaxes (review_pr.py:225, review_pr.py:590, review_local.py:324), and the server-side authorization chain that stamps `ReviewRun.output["inbox_review"]`.+- **Found:** No reachable vulnerability exists today. The flag is set in exactly one place — `run_review_in_sandbox` → `self_driving_review=bool(output.get("inbox_review"))` (activities.py:449) — and `inbox_review` provenance is stamped only by the two linkage-verified trigger paths. The webhook leg (facade tasks in the diff, ~lines 897-923) requires a repo-native branch (never a fork), a synced+enabled repo config (`repo_config.enabled`, `installation_id`, `connected_by_user_id is not None`), a `find_signal_implementation_run` match with an explicit `run.team_id == repo_config.team_id` check, and the acting reviewer's toggle re-resolved. No code path derives the flag from any GitHub-controlled field (pr.title/body/reviews/discussion flow into separate context keys, never into `self_driving_review`). So 'a caller sets this for a non-inbox bot PR' or 'the flag populated from GitHub data' cannot occur under current code.+- **Found:** The two concerns are self-mitigated or by-design. The reviewer states the untrusted-surface expansion is already covered by 'the existing anti-injection notice and `_sanitize_untrusted`', and PR content is untrusted everywhere already (a bot diff is no more dangerous to the LLM than a human diff). 'No engine-side independent verification' is intrinsic to the architecture: the sandbox is tokenless by design (CLAUDE.md: 'The sandbox holds NO long-lived secret') and cannot re-verify task linkage — the server is the trust authority, exactly as documented.+- **Impact:** The finding explicitly frames itself as 'defense-in-depth around a deliberate design decision, not a claim the current server derivation is wrong,' and conditions the risk on a 'current or future caller' / the flag being 'ever populated from GitHub-controlled data.' That is the speculative-what-if + overengineering pattern the criteria drop: the suggestion is to add an architectural abstraction (a separate server-trusted sub-object) to future-proof against a refactor not in scope, guarding a condition ruled out by the current single, provenance-keyed setter. No concrete current trigger→consequence, so it does not meet the security keep bar. Precision over recall → drop.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:873-881++**Redundant writer-pinned repo-config resolution on every carved-out inbox re-review**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** On the webhook path, when a delivery is a carved-out self-driving re-review (skip_reason set and provenance returned), `_inbox_rereview_carve_out` has already resolved the repo config via `_resolve_repo_config`. After the skip check falls through for inbox_review, the main body then calls `_resolve_repo_config(installation_id, repo)` again. Both calls are writer-pinned (.using(router.db_for_write(...))) queries. As a result, every synchronize/reopen/base-retarget on a self-driving PR issues two identical config-resolution queries against the write DB instead of one. (base-retarget deliveries resolve it a third time via `_retract_approvals_on_base_retarget`.)+- **Suggestion:** Have `_inbox_rereview_carve_out` return the resolved StamphogRepoConfig alongside the provenance/opted_out result (e.g. on the `_InboxCarveOut` dataclass) and reuse it in the main body, so the carved-out path resolves the config once. Minor, but it removes a duplicate writer-pinned query from every self-driving re-review.+- **Validator:** - **Checked:** The webhook-path config-resolution flow in `process_pull_request_event` (stamphog `tasks.py:853-924`), the carve-out helper's internal resolution (`_inbox_rereview_carve_out` at tasks.py:179), `_resolve_repo_config` itself (tasks.py:174-189), and the `StamphogRepoConfig` unique index (`models.py:68`).+- **Found:** The double-resolution claim is accurate: for a carved-out re-review (`skip_reason` set, provenance returned), the carve-out resolves once at tasks.py:179, the `inbox_review is not None` case skips the 881-912 block, and the main body resolves again at tasks.py:918 → 2 identical calls; a `base_retargeted` delivery adds a third at tasks.py:858.+- **Found:** But each call is a single unique-index lookup — `_resolve_repo_config` filters on `(provider, installation_id, repository)` (tasks.py:186), the exact model unique index (models.py:68). So the redundancy is one (or two) extra sub-millisecond indexed reads, not a scan, not N+1 (constant count, not per-row), not unbounded.+- **Impact:** Below the performance bar. The path is a cold, opt-in (default-off), low-frequency carve-out (only synchronize/reopen/base-retarget on self-driving PRs), and the same handler already runs a full sandbox review with many GitHub calls — one extra indexed query is negligible. It is not a hot path, N+1, or missing-index problem. The suggested fix (thread the config through `_InboxCarveOut`) also couples the carve-out helper to the main body, whose disabled/non-carve-out branches (tasks.py:925, 891) use the config differently. The reviewer's own "consider"/"Minor" reflects this. Per the criteria (drop low-impact micro-optimizations that don't bite at real scale; precision over recall; on the fence → drop), it does not meet the keep bar.++### [✅ VALID] should_fix · bug — products/stamphog/backend/tasks/tasks.py:872-898++**Carve-out resolution runs before the skip dismissal, so a tasks-facade failure can leave a stale approval standing**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** On a head-changing delivery (synchronize / reopened / base-retarget) that trips a skip reason, process_pull_request_event now resolves the inbox carve-out via `_inbox_rereview_carve_out(...)` BEFORE the existing stale-approval dismissal, and re-raises as a Celery retry if that resolution throws (L873-879). `_inbox_rereview_carve_out` calls into the tasks product (`find_signal_implementation_run` -> `find_task_run`, which queries the tasks DB) and the review_hog-registered resolver hook — cross-product code whose availability stamphog does not control. Only a bot-authored PR reaches that fallible branch (human PRs return early inside the carve-out via `_is_bot_authored`), and a self-driving PR is exactly the shape this PR newly grants a head-pinned approval to. If the carve-out resolution fails persistently (the tasks DB is unavailable while stamphog's own DB is up, or a deterministic query error on this PR's inputs), the task exhausts its 3 retries WITHOUT ever reaching the `if skip_reason is not None and inbox_review is None:` block that calls `_retract_stale_approvals_on_skip`. The prior approval then keeps satisfying required reviews over the newly pushed, unreviewed commits until some later head change re-attempts dismissal. This defeats the guarantee `_retract_stale_approvals_on_skip`'s own docstring states ('Raises on failure so the caller can retry — a dropped dismissal would leave the stale approval standing') and the stamphog CLAUDE.md stale-approval invariant, by gating an invariant-critical dismissal on a cross-product call's success. The base code attempted the head-changing skip dismissal for every skipped delivery independently of any tasks-facade health.+- **Suggestion:** Do not let the carve-out resolution gate the stale-approval dismissal. Restructure so the head-changing skip dismissal (`_retract_stale_approvals_on_skip`, with its own independent retry) is reached even when `_inbox_rereview_carve_out` cannot be resolved — e.g. on a carve-out exception, still run the dismissal (treating the delivery as not-carved-out for dismissal purposes) before retrying for the re-review; or, since carved-out runs re-enter the workflow through `dismiss_stale_approvals` anyway, perform the head-changing dismissal ahead of / independently of the carve-out outcome. The safety retraction must never become unreachable because the tasks facade is momentarily unavailable.+- **Validator:** - **Checked:** The PR-head skip flow in `process_pull_request_event` (stamphog `tasks.py:870-912`), the master baseline of the same function, `_inbox_rereview_carve_out`'s cross-product calls, `_retract_stale_approvals_on_skip`'s docstring, the task's retry decorator, and tasks-vs-stamphog DB separation.+- **Found (regression):** Master reached the head-changing skip dismissal unconditionally when `skip_reason is not None`, gated only on stamphog-owned `_resolve_repo_config` + `_retract_stale_approvals_on_skip`. The PR inserts `_inbox_rereview_carve_out(...)` before that block and `raise …retry(exc=e)` on any exception (tasks.py:875-879), so the dismissal at tasks.py:894 is only reached if the carve-out did NOT throw. Both dismissal routes — the re-review path (whose workflow runs `dismiss_stale_approvals` first) and the skip block — require the carve-out to succeed; a throw blocks both.+- **Found (fallible dependency):** `_inbox_rereview_carve_out` calls `find_signal_implementation_run`→`find_task_run` (queries `TaskRun`, a plain `models.Model` on a different DB from stamphog's `ProductTeamModel` product DB) and the review_hog resolver hook (`ReviewUserSettings.load`/`resolve_reviewers`), none wrapped in try/except. Only bot-authored PRs reach these (human PRs return early via `_is_bot_authored`), so the finding is correctly scoped. The PR's own comment at tasks.py:873 concedes this resolution can fail.+- **Found (guarantee broken):** `_retract_stale_approvals_on_skip`'s docstring: "Raises on failure so the caller can retry — a dropped dismissal would leave the stale approval standing." With `@shared_task(max_retries=3, default_retry_delay=5)` (~15s budget) and the webhook already ACKed (no GitHub redelivery), a tasks-side outage exceeding ~15s exhausts retries with no dismissal — the stale APPROVE keeps satisfying required reviews over unreviewed commits until the next head change.+- **Found (new exposure):** In master, stamphog never approved bot-authored PRs, so their skip-dismissal was vacuous. This PR makes bot-authored self-driving PRs approvable (head-pinned APPROVE) while gating their dismissal behind the fallible carve-out — the exact shape now at risk. So the hole is introduced by this change.+- **Impact:** Reachable violation of the product's central stale-approval invariant (CLAUDE.md "the big one") under a realistic cross-product partial outage. Concrete trigger and consequence both nameable → meets the keep bar; not defensive paranoia (the codebase treats these dismissals as invariant-critical and retries on failure everywhere else). `should_fix` fits: the trigger is a multi-condition conjunction with eventual self-recovery on the next push, so not `must_fix`.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-2.mdnew file mode 100644index 000000000000..43e288d290e4--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/D-opus48-xhigh-2.md@@ -0,0 +1,301 @@+# Reviewer-quality run — `D-opus48-xhigh-2`++- **Dumped:** 2026-07-24T03:09:43+00:00+- **Report id:** `019f91f1-617b-7b31-a7d3-b295c38728d4` · **PR:** https://github.com/PostHog/posthog/pull/72680+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 2645s (44.1 min)++## Config snapshot++- runtime / model / effort: `claude` / `claude-opus-4-8` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 16 | 16 | 1 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ----------- | ------------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | review | 172 | 205,449 | 1,731,687 | 20,206,260 | 252,950 | 2 | $28.28 | $28.28 |+| claude-opus-4-8 | blind-spot | 69 | 94,888 | 787,278 | 7,016,712 | 128,702 | 0 | $12.12 | $12.12 |+| claude-opus-4-8 | validation | 93 | 71,855 | 530,522 | 9,700,602 | 129,937 | 2 | $11.77 | $11.77 |+| claude-sonnet-5 | dedup | 1 | 13,317 | 0 | 0 | 2,922 | 0 | $0.06 | $0.06 |+| claude-sonnet-5 | other:perspective_selection | 1 | 9,029 | 0 | 0 | 1,672 | 0 | $0.03 | $0.03 |+| **total** | | **336** | **394,538** | **3,049,487** | **36,923,574** | **516,183** | **4** | **$52.26** | **$52.26** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- naive method (all prompt tokens at input price): $214.61 — 4.1× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $39.4267 over 336 gen(s) (true $39.4267, Δ -0.0%)+ - · of which cache read: $18.4618 over 324 gen(s) (true $18.4618, Δ +0.0%)+ - · of which cache write: $19.0593 over 334 gen(s) (true $19.0593, Δ +0.0%)+ - · of which fresh (derived): $1.9057 over 336 gen(s) (true $1.9057, Δ -0.0%)+ - output: $12.8357 over 336 gen(s) (true $12.8357, Δ +0.0%)+- 4 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …ed369456 | issues-review-p1-c3 | 02:26:57 | 0 | 46,915 | claude-opus-4-8 |+| …7bb8523c | issues-review-p2-c3 | 02:26:57 | 0 | 46,917 | claude-opus-4-8 |+| …3b72783c | issues-review-p2-c2 | 02:26:57 | 0 | 60,995 | claude-opus-4-8 |+| …05b52675 | issues-review-p1-c2 | 02:26:57 | 0 | 60,994 | claude-opus-4-8 |+| …024c57b4 | issues-review-p1-c1 | 02:26:58 | 17,141 | 41,587 | claude-opus-4-8 |+| …004bb7f2 | issues-review-p2-c1 | 02:27:00 | 17,141 | 41,581 | claude-opus-4-8 |+| …2fc53ef9 | issues-review-p3-c2 | 02:27:01 | 0 | 60,993 | claude-opus-4-8 |+| …d5c1e007 | issues-review-p3-c1 | 02:27:04 | 17,141 | 41,583 | claude-opus-4-8 |+| …d47a1e3f | blind-spots-c4 | 02:38:33 | 0 | 43,362 | claude-opus-4-8 |+| …f8a4f21a | blind-spots-c2 | 02:38:33 | 0 | 63,821 | claude-opus-4-8 |+| …d6030790 | blind-spots-c1 | 02:38:33 | 0 | 61,431 | claude-opus-4-8 |+| …26d92285 | blind-spots-c3 | 02:38:37 | 17,141 | 31,592 | claude-opus-4-8 |+| …addfe77d | validation-c1 | 02:51:41 | 0 | 39,978 | claude-opus-4-8 |+| …56d2c68d | validation-c2 | 02:51:43 | 17,141 | 22,953 | claude-opus-4-8 |+| …f484386c | validation-c3 | 02:51:44 | 0 | 38,995 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **5/15** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 19s |+| review wave (perspectives) | 11m 38s |+| blind-spot sweep | 12m 38s |+| dedup (incl. combine/clean) | 32s |+| validation | 18m 28s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 24m 16s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | review-hog-perspective-logic-correctness | 2 |+| 2 | 2 | review-hog-perspective-logic-correctness | 1 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 2 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider · code_quality — products/stamphog/backend/facade/api.py:120-124++**has_reviewable_repo_config omits provider filter, diverging from the receiver leg's reviewability predicate**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** has_reviewable_repo_config drives the UI's stamphog_connected flag, whose stated purpose is to render the inbox toggle disabled whenever there is nothing hosted reviews can actually run on (so the switch never enables a review that fails closed later). Its query filters enabled=True, `connected_by_user_id__isnull=False`, and excludes installation_id="", but it does NOT filter provider="github". Every other StamphogRepoConfig read in the product filters provider="github" — including the receiver leg process_inbox_pr_review's own config resolution (tasks.py: .filter(provider="github", `repository__iexact`=..., enabled=True, `connected_by_user_id__isnull=False`).exclude(installation_id="")), which is exactly the reviewability condition this flag is meant to mirror. The two definitions of "reviewable" therefore differ by the provider column. StamphogRepoConfig.provider defaults to "github" and only github exists today, so this is latent rather than an active bug; but the moment a non-github provider row is introduced, has_reviewable_repo_config would count it as reviewable and enable the toggle, while process_inbox_pr_review would resolve no config for it and silently no-op — the precise regression class the flag was added to prevent.+- **Suggestion:** Add provider="github" to the has_reviewable_repo_config filter so its reviewability predicate stays byte-for-byte aligned with the receiver-leg resolution in process_inbox_pr_review (and with the rest of the product's config reads). For example: StamphogRepoConfig.objects.for_team(team_id).filter(provider="github", enabled=True, `connected_by_user_id__isnull=False`).exclude(installation_id="").exists().+- **Validator:** - **Checked:** `has_reviewable_repo_config`'s filter (facade/api.py added lines: `enabled=True, connected_by_user_id__isnull=False`, `.exclude(installation_id="")`, no `provider`), `process_inbox_pr_review`'s resolution and every other `StamphogRepoConfig` read (tasks.py:186/509/534/593, views.py:88/212/308), and the `provider` model field.+- **Found:** the premise is factually accurate — the flag's predicate omits `provider="github"` that the receiver-leg resolution includes. But `provider = models.CharField(max_length=32, default="github")` (models.py:29) with the code comment "GitHub is the only implemented provider today," and every creation path hardcodes `provider="github"` (views.py:308, tasks.py:553). No path creates a non-github row, so for 100% of existing rows `enabled + connected + non-blank installation` already entails `provider="github"`; the two predicates return identical results today.+- **Impact (dismissal):** the divergence has zero behavioral effect given current data and can only bite if a whole new SCM provider is implemented and its rows created — a case not in scope, which the reviewer explicitly labels "latent rather than an active bug." Even then the consequence is a toggle rendering enabled instead of disabled plus a silent no-op (minor UX), not a correctness/security/data-loss defect. This is future-proofing for an out-of-scope case and a speculative what-if that current types/data rule out — below the precision-over-recall bar. A one-line consistency tidy-up with no behavioral difference doesn't clear the surfacing threshold. Drop.++### [❌ dismissed] should_fix · security — products/review_hog/backend/receivers.py:144-156++**Webhook-leg opt-out gate resolve_stamphog_acting_reviewer is not fail-closed on error**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** resolve_stamphog_acting_reviewer is registered as the cross-product hook that stamphog's webhook path calls before re-reviewing a self-driving PR (leg 2). Its return value is the security gate: a user id authorizes stamphog to post a real GitHub approval on a bot-authored draft (a carve-out that relaxes the bot-author refusal); None must stop the review. Unlike handle_task_run_saved — which the module docstring/comments deliberately wrap in a blanket try/except so it 'must never raise' — this resolver calls `_resolve_assigned_reviewer` (which hits the DB via SignalReportArtefact query and resolve_org_github_login_to_users) and ReviewUserSettings.load (another DB read) with no exception handling. On a transient DB/resolution error the function raises instead of returning None. The design's stated invariant is that every scope check 'fails closed' (per the PR, 'missing resolver all fail closed'), but that was validated for an absent resolver, not a resolver that raises. If stamphog's webhook caller treats a raising hook as anything other than 'skip the review', a transient error becomes fail-open: stamphog approves a PR whose acting reviewer may have toggled the opt-in off — exactly the outcome the toggle exists to prevent. The gate should not depend on the caller's error handling to preserve the opt-out contract.+- **Suggestion:** Make the gate fail closed independently of the caller: wrap the body in try/except and return None on any exception (logging it), mirroring handle_task_run_saved's exception-proofing. For example:++ def resolve_stamphog_acting_reviewer(team_id, signal_report_id, task_created_by_id):+ try:+ acting_user_id = `_resolve_assigned_reviewer`(team_id, signal_report_id, task_created_by_id)+ if acting_user_id is None:+ return None+ if not ReviewUserSettings.load(team_id, acting_user_id).stamphog_review_inbox_prs:+ return None+ return acting_user_id+ except Exception:+ logger.exception("review_hog_stamphog_resolver_failed")+ return None++This guarantees that a transient failure suppresses the carve-out (no approval posted) rather than risking an approval on a PR whose reviewer opted out.++- **Validator:** - **Checked:** All runtime callers of the registered hook. Grepped the PR diff for `get_inbox_acting_reviewer_resolver` / `resolver(` — the resolver is invoked in exactly one production site, `_inbox_rereview_carve_out` (`products/stamphog/backend/tasks/tasks.py`, `acting_user_id = resolver(...)`), which is itself called from one place in `process_pull_request_event`. The initial leg `process_inbox_pr_review` does not call the resolver at all (the toggle was already checked in review_hog's receiver before queueing).+- **Found:** The sole caller already fails closed on a _raising_ resolver, not just an absent one. In `process_pull_request_event`: `carve_out = _InboxCarveOut()` then `try: carve_out = _inbox_rereview_carve_out(...) except Exception as e: logger.exception(...); raise process_pull_request_event.retry(exc=e)`. A resolver exception propagates out of `_inbox_rereview_carve_out`, is caught here, and re-raised as a Celery retry — `carve_out` stays default (`provenance=None`), and the `raise` halts execution before run creation. On persistent failure past `max_retries`, the task simply fails and no review is queued. At no point does a raised resolver exception cause an approval.+- **Impact:** The finding's fail-open scenario cannot occur — the premise ('if the caller treats a raising hook as anything other than skip the review') is a conditional that the actual caller does not satisfy. Per the validation criteria this is 'already handled' (prevented at the parent caller, confirmed by reading it) and 'wrong/unreproducible'. Additionally, the proposed fix would be a net regression: swallowing the exception to return `None` makes `_inbox_rereview_carve_out` return `opted_out=True`, which dismisses the standing approval and permanently skips the re-review on a merely transient DB blip, whereas the current retry path recovers correctly and preserves the opt-out contract. Not worth surfacing.++### [❌ dismissed] consider · security — products/stamphog/backend/tasks/tasks.py:1176-1181++**Leg-1 inbox review stamps the security-relaxing self-driving flag from unverified caller input**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** process_inbox_pr_review unconditionally stamps output.inbox_review (trigger/signal_report_id/task_run_id/acting_user_id) directly from its Celery task parameters. That provenance is exactly what temporal/activities.py later reads to set self_driving_review=True, which relaxes the engine's bot-author refusal and draft prerequisite (documented core invariants in products/stamphog/CLAUDE.md) and suppresses the author merged-PR familiarity fetch. Unlike leg 2 (`_inbox_rereview_carve_out`), leg 1 performs NO positive identification of its own — it only confirms the team has a synced+enabled repo config for the PR's repository. So the bot-author refusal is disabled for whatever PR review_hog's receiver hands over; if that receiver ever queues a PR that is not actually a signals implementation run (a receiver bug, a future refactor that loosens the trigger, or any non-self-driving bot PR), stamphog will disable the bot-author refusal for it. The trust boundary for a core security invariant rests entirely on a cross-product caller.+- **Suggestion:** Mirror leg 2's positive identification inside process_inbox_pr_review: after fetching the PR, call find_signal_implementation_run(team_id=team_id, repository=repository, pr_url=pr_url, head_branch=<pr head ref>) and only stamp inbox_review when it returns a match whose team_id/signal_report_id/task_run_id agree with the parameters. Fail closed (skip the self-driving review) otherwise. This keeps the bot-author/draft refusal robust regardless of caller correctness, at the cost of one extra scoped DB read that leg 2 already performs.+- **Validator:** - **Checked:** every caller of `queue_inbox_pr_review` in the diff, the receiver that dispatches leg 1 (`products/review_hog/backend/receivers.py::handle_task_run_saved`), and `find_signal_implementation_run` (leg 2's positive-ID helper in `products/tasks/backend/facade/api.py`).+- **Found:** leg 1 _does_ perform positive identification — it just lives in the sole caller, not inside the Celery task. The receiver reaches `_start_stamphog_review`/`queue_inbox_pr_review` only after `task.signal_report_id is not None`, `not task.internal`, and a present `pr_url` taken from the TaskRun's own `output.pr_url` (receivers.py: the `signal_report_id`/`internal`/`pr_url` guards), then the acting-reviewer toggle. That is the _same_ predicate `find_signal_implementation_run` enforces (`run.team_id != team_id → None`, `task.signal_report_id is None or task.internal → None`).+- **Found:** the two legs are asymmetric by necessity, not by oversight. Leg 2 arrives from a GitHub webhook with no task context, so it must reverse-look-up the run via `find_task_run(pr_url=..., branch=...)`. Leg 1 already holds the authoritative TaskRun (the very instance that fired the receiver) and passes that task's own recorded `pr_url`/`signal_report_id`/`run_id` through — a more direct linkage than the reverse lookup, not a weaker one. The suggested `find_signal_implementation_run(pr_url=...)` call inside `process_inbox_pr_review` would reverse-resolve back to the identical originating task, confirming what the caller already knows (and could introduce false-negative drops on replica lag).+- **Impact:** the `self_driving_review` relaxation is stamped only for runs created through this one gated path; human PRs and other bots (dependabot/renovate) still hit `_review_skip_reason`'s bot refusal on the webhook path, so the core invariant is not weakened for anything else. The finding's own trigger is explicitly hypothetical — "if that receiver _ever_ queues a PR that is not actually a signals implementation run (a receiver bug, a future refactor that loosens the trigger)" — i.e. guarding against a future defect in the sole, currently-correct caller. Under the precision-over-recall bar this is speculative "what if" plus defense-in-depth against a redundant, parent-caller-already-performed check; it names no reachable defect in the code as written. Drop.++### [❌ dismissed] consider · security — products/tasks/backend/facade/api.py:507-509++**Self-driving identification admits soft-deleted signals tasks, authorizing gate bypass**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** find_signal_implementation_run positively identifies a self-driving run via find_task_run (matched by pr_url, or by branch+repository) and only rejects the match when task.signal_report_id is None or task.internal is true. It does not exclude soft-deleted tasks (Task inherits DeletedMetaFields with a `deleted` flag), and find_task_run's pr_url and non-wizard branch legs don't filter `task__deleted` either (only the wizard leg does). Because a match here is what authorizes stamphog's carve-out to bypass the write-permission and review-mode security gates for the PR, a PR linked to a task the user has since deleted can still authorize that gate bypass. Exploitability is limited (the carve-out also requires a bot-authored, repo-native head), but a deleted task should not remain a valid credential for disabling security gates.+- **Suggestion:** Exclude soft-deleted tasks from the identity check — e.g. add `if task.deleted: return None` alongside the existing signal_report_id/internal guard (or filter `task__deleted=False`), so a deleted task can't authorize the gate-bypassing carve-out. Consider whether the webhook backstop's other consumers want the same exclusion.+- **Validator:** - **Checked:** `find_task_run` filter legs (products/tasks/backend/webhooks.py:30-100), `find_signal_implementation_run` (facade/api.py, added by PR) and its team-scope guard, `_inbox_rereview_carve_out`'s re-checks, the `Task` soft-delete model (`DeletedMetaFields.deleted` bool at posthog/models/utils.py:54; `soft_delete()` at models.py:471; default manager NOT auto-filtered, proven by the explicit `deleted=False` at models.py:300), and `find_task_run`'s primary consumer.+- **Found:** the premise is factually accurate — the `pr_url` and non-wizard branch legs of `find_task_run` omit `task__deleted=False` (only the wizard-head leg has it), so a soft-deleted task's run can match. But the identity `find_signal_implementation_run` verifies is factual provenance ("did a self-driving run open this PR?"), which stays true after the Task's `deleted` flag flips: the `TaskRun` persists, `output.pr_url` still matches, `signal_report_id`/`internal` are unchanged. Excluding deleted tasks would reject a genuinely self-driving PR, not correct a misidentification.+- **Found:** team scope is enforced twice (`find_signal_implementation_run`: `run.team_id != team_id → None`; carve-out: `run.team_id != repo_config.team_id → skip`), so there is no cross-tenant/IDOR path. The carve-out additionally requires a bot-authored (team's own GitHub App), repo-native head, an enabled repo config, and the acting reviewer's _live_ toggle — none of which soft-deleting the task alters.+- **Impact (dismissal):** no tenant boundary is crossed and no external actor gains anything — the bypassed write-permission/review-mode gates exist to stop auto-approving untrusted human PRs, whereas this only ever fires on the team's own machine-authored PR that the team opted into reviewing. The described effect (a re-review still firing after task deletion) is the same review that would run were the task live, requires a rare confluence (deleted task + later head-changing webhook on the still-open PR + reviewer still opted in), and the reviewer concedes exploitability is limited. There's no documented contract that soft-deleting a task revokes GitHub automation (the live toggle is the intended off-switch), and `find_task_run`'s primary consumer intentionally still matches deleted-task PRs for merge handling. This is defense-in-depth hygiene against a low-impact edge case — below the precision-over-recall bar (on the fence → drop).++### [❌ dismissed] consider · security — tools/pr-approval-agent/review_local.py:316-321++**Loose truthiness on self_driving_review at the approval-carve-out boundary**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The self-driving flag — the single input that unlocks a real GitHub approval on a bot-authored draft PR — is derived with `bool(context.get("self_driving_review"))`. A missing key or a JSON `false` correctly resolves to False (fail-closed), but any truthy non-boolean the server might emit — most notably the string "false" — coerces to True and silently enables the carve-out. For a value that decides whether the reviewer posts a branch-protection-counting approval, loose truthiness is a fragile contract at a security-sensitive trust boundary.+- **Suggestion:** Require the exact boolean the contract promises: `self_driving=context.get("self_driving_review") is True`. This preserves the fail-closed default for absent/false values while rejecting stringified or otherwise malformed values instead of trusting them.+- **Validator:** - **Checked:** The producer→consumer chain for `self_driving_review` across the three files that touch it in the PR head (FETCH_HEAD `1341596`): where `review_local.py` loads the context, where the server serializes it, and where the value originates.+- **Found:** `review_local.py:395` loads context via `context = json.loads(Path(args.context).read_text())` — JSON deserialization, so a JSON `false` becomes Python `False`, never the string `"false"`. The only producer is `products/stamphog/backend/logic/reviewer.py:131`, which sets the key from a parameter typed `self_driving_review: bool = False` and serializes the whole dict with `json.dumps` (a Python `bool` → the JSON tokens `true`/`false`). The value itself is coerced to a real `bool` one layer up at `products/stamphog/backend/temporal/activities.py:451`: `self_driving_review=bool(output.get("inbox_review"))`.+- **Found:** No alternate producer writes this context file — `main()` reads a single `--context` path the server provisions; the file's own docstring/comment states the flag "rides in on the hosted context JSON, stamped by the server."+- **Impact:** The reviewer's concrete trigger (a truthy non-boolean such as `"false"` coercing to `True`) is unreachable: the sole producer is trusted first-party code that emits a genuine JSON boolean, and `json.loads` never yields the string `"false"` from a JSON `false`. For the divergence to happen the server would have to emit a stringified value in violation of its own `bool` annotation and explicit `bool()` coercion — a hypothetical future regression, not a defect in the code as written. An attacker who could actually write the context file controls the sandbox and would simply write `true`, so `is True` buys no real defense. Under the criteria this is speculative/defensive-coding paranoia guarding against a value the upstream type contract already rules out, and it fails the keep-bar of naming a reachable trigger — precision-over-recall says drop.++### [❌ dismissed] consider · performance — products/review_hog/backend/receivers.py:126-139++**Stamphog review is re-queued on every output-touching TaskRun save with no dedupe in this leg; idempotency of the real GitHub approval depends entirely on downstream head-dedupe**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** handle_task_run_saved runs on every TaskRun save (the module docstring/comment calls TaskRun 'a hot model'), and this leg calls `_start_stamphog_review` -> queue_inbox_pr_review every time the run's output carries a pr_url and the toggle is on. There is no dedupe key or head snapshot computed in this chunk — unlike the review_hog leg, whose duplicate collapse is backed by a deterministic Temporal workflow id + USE_EXISTING. The stamphog leg instead relies entirely on the queued Celery task deduping on the PR's current head (asserted in the PR description but not present in this chunk). Because the follow-up/babysit loop persists output repeatedly for a single PR head, queue_inbox_pr_review can be published many times for the same head. Since the stamphog verdict is a real GitHub approval (an externally visible side effect), correctness hinges on that downstream head-dedupe being robust and early-exiting before any duplicate approval; if it dedupes only after fetching/creating a run, repeated saves fan out repeated work.+- **Suggestion:** Confirm the queued task's head-keyed dedupe early-exits before any approval-producing work for an already-reviewed head, and consider guarding the enqueue itself (e.g., only enqueue when the pr_url/head is newly observed on this run's output, mirroring the head-keyed receiver dedupe the PR description mentions) so a hot save path does not repeatedly publish to the broker for an unchanged head.+- **Validator:** - **Checked:** The downstream dedupe in `products/stamphog/backend/tasks/tasks.py::process_inbox_pr_review` (the task `queue_inbox_pr_review` enqueues) and the workflow-start it gates, `_start_review_workflow`, to test the finding's own conditional ('if it dedupes only after fetching/creating a run').+- **Found:** `process_inbox_pr_review` dedupes on `(pull_request, head_sha)` via `ReviewRun.objects...select_for_update().filter(pull_request=pr_obj, head_sha=head_sha).exclude(status__in=(SUPERSEDED, FAILED)).first()`. When an existing run at that head is found it `return`s early — no `_supersede_prior_runs`, no `ReviewRun.create`, no workflow start (the only exception being a still-QUEUED run whose workflow is restarted). The approval is produced solely inside the Temporal workflow, started by `_start_review_workflow`, whose workflow id is derived from `review_run_id` under `ALLOW_DUPLICATE_FAILED_ONLY`, so a duplicate start raises `WorkflowAlreadyStartedError` and is swallowed. The dedupe therefore early-exits before any approval-producing work, and the workflow start is itself idempotent per run.+- **Impact:** No duplicate GitHub approval can result from repeated receiver fires — the correctness concern the finding hinges on is already prevented (robust head-keyed, row-locked dedupe + idempotent workflow start), confirmed by reading the code. The only residual is a minor, bounded inefficiency: each output-touching save on an opted-in self-driving PR costs one Celery publish + one `get_pr` fetch before the cheap early-exit. That is not an at-scale performance defect (per-PR, low-volume opted-in path) and it deliberately mirrors the review_hog leg's own documented 'repeat fires cost one fetch, early-exit' design (receivers.py docstring). The finding is a hedged 'confirm X / consider guarding the enqueue' optimization, not a concrete bug — drop per precision-over-recall.++### [❌ dismissed] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1155-1165++**Receiver-leg inbox review fetches the PR from GitHub on every refire with no pre-fetch dedup**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** process_inbox_pr_review resolves the repo config and then makes an unconditional GitHub get_pr call (followed by a full DB transaction: `_upsert_pull_request`, a select_for_update dedupe, and possibly `_supersede_prior_runs`) before it can dedupe, because the head-keyed dedupe needs the current head SHA that only GitHub knows. The task and facade docstrings state the review_hog TaskRun receiver re-fires 'on every TaskRun output save carrying the PR URL'. So for an active self-driving run that saves output many times, each refire that reaches this task incurs one get_pr round trip against the installation's shared GitHub API rate budget plus a redundant write transaction, even though all but the first at a given head no-op inside the dedupe. Unlike the webhook leg — which pre-filters redeliveries cheaply via the STAMPHOG_PR_EVENT_IDEMPOTENCY cache before doing any GitHub/DB work — the inbox leg has no equivalent guard, so bursts of output saves translate directly into bursts of GitHub calls and DB writes. Under many concurrent self-driving runs this is a rate-limit / DB-write amplification risk that can degrade all of the installation's stamphog reviews.+- **Suggestion:** Add a short-lived cache debounce mirroring the webhook leg's idempotency guard — e.g. a cache key on (team_id, pr_url) with a small TTL (tens of seconds) that collapses a burst of refires into a single get_pr — accepting that a genuinely new head is instead picked up by the webhook synchronize leg (or the next refire after the TTL). Alternatively, have queue_inbox_pr_review's caller pass the run's known head/revision so a cheap cache/DB check can short-circuit before the GitHub fetch. This preserves the lost-synchronize recovery property while cutting the redundant external calls and write transactions.+- **Validator:** - **Checked:** `process_inbox_pr_review`'s fetch/dedupe ordering (unconditional `get_pr` + `_upsert_pull_request` write before the head-keyed `select_for_update` dedupe), the webhook leg's `STAMPHOG_PR_EVENT_IDEMPOTENCY` pre-filter, ReviewHog's sibling inbox leg (`_start_review` → deterministic-workflow-id + USE_EXISTING collapse, fetch inside the workflow), and the tasks-side output-write paths (`set_task_run_output` and the caller PATCH surface in facade/api.py).+- **Found:** the mechanism is real — the inbox leg does one `get_pr` + a no-op write transaction per refire with no pre-fetch guard, so it fetches on in-flight refires that the webhook/ReviewHog paths would collapse. But the ordering is deliberate and documented: the task comment says the fetch must precede the dedupe "because the dedupe keys on the PR's current head, which only GitHub knows," and retries-not-drops to preserve lost-synchronize recovery — the exact property the suggested cache debounce trades away.+- **Found:** the cost is bounded (one `get_pr` per Celery task, linear in `pr_url`-carrying output saves) — not N+1, quadratic, or unbounded. The output-write paths are milestone-driven (`set_task_run_output` completes structured runs and posts Slack; the PATCH surface), not sub-second polling; nothing in-repo shows an output-rewrite loop that would produce the assumed "many" saves.+- **Impact (dismissal):** reviews remain functionally correct (the dedupe still no-ops) — no correctness, data-loss, lock, or leak defect, so the only claimed harm is rate-limit/DB amplification. That "degrade all of the installation's stamphog reviews" outcome requires an implausible per-installation burst of `pr_url` output saves to threaten a GitHub App's 5000+/hr (scaling) budget, and the feature is behind a default-off per-user toggle limited to non-internal signal-report runs, capping concurrency. This is a bounded, low-impact efficiency nit against a deliberate documented tradeoff, with the at-scale degradation speculative — below the precision-over-recall bar. The `should_fix` rating overstates it.++### [❌ dismissed] consider — tools/pr-approval-agent/reviewer.py:683-703++**Self-driving carve-out trusts the flag alone, not the bot-author invariant it relaxes**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_format_self_driving` emits its provenance text into the TRUSTED CONTEXT region whenever cl["self_driving"] is set, asserting as fact: "The author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here — judge the diff strictly on its own merits." The companion draft-gate relaxation in review_pr.py::`_check_prerequisites` (new line ~590: `if pr.draft and not self.self_driving`) lets a self-driving run proceed to a real, branch-protection-counting approval on a draft PR. Both are gated solely on the self_driving flag, which review_local.py takes verbatim from the server-provided context JSON. The prior_refuse_bot_author gate was explicitly documented as the "defense-in-depth layer for any manual or out-of-band invocation"; this change removes that backstop on the approval path with no engine-side re-assertion of the condition being carved out. `pipeline.pr.author_is_bot` is already populated, so if the server ever stamps the flag on a run whose PR is not actually a bot-authored inbox draft (a run/provenance mixup), the engine will relax the draft gate on a human's PR and inject a false "author is a machine user, discard familiarity/org signals" instruction into the trusted prompt — degrading review integrity and potentially yielding an approval that should never have been granted.+- **Suggestion:** Anchor the carve-out to the invariant it relaxes rather than to the flag alone. Compute an effective self-driving condition that also requires the positively-identified bot author — e.g. gate both the draft-prerequisite relaxation and the `_format_self_driving` provenance block on `self.self_driving and self.pr.author_is_bot`. Inbox PRs are bot-authored by construction, so the intended flow is unchanged, but a mis-stamped flag can no longer relax gates or inject the machine-user claim on a human-authored PR.+- **Validator:** - **Checked:** How `self_driving` reaches both relaxed gates and whether the engine could ever see `self_driving=True` alongside a human author. Traced: `review_pr.py:209` (flag stored), `:225` (bot gate `author_is_bot and not self_driving`), `:477` (`classification["self_driving"]`), `:590` (draft gate `pr.draft and not self_driving`), `reviewer.py:692` (`_format_self_driving` gated on `cl["self_driving"]`), and the server origin `activities.py:451` `self_driving_review=bool(output.get("inbox_review"))`.+- **Found:** The flag and `pr.author_is_bot` are both read from the same server-provided context JSON — not two independent trust sources. The flag is set to True exclusively from a run's persisted inbox provenance, which both trigger legs stamp only after positively linking the PR to a signals implementation task; the receiver leg keys on the implementation TaskRun's own PR URL and the webhook leg requires a `find_signal_implementation_run` task match (PR body + `review_pr.py:202-208` comment). Those PRs are opened by the PostHog Code machine user, so `self_driving=True ⟹ bot author` holds by construction. No current call site produces `self_driving=True` on a human-authored PR.+- **Impact:** The named consequence (relaxing the draft gate + injecting the "author is a machine user" claim on a human PR) requires the server to mis-stamp inbox provenance onto a run whose linked PR is human-authored — a hypothetical server regression the reviewer states conditionally ("if the server ever..."). That is a speculative what-if / defensive-paranoia hardening, not a defect reachable in the code as written: the drop categories in the criteria cover "conditions that can't actually occur given the call sites" and "guarding against errors upstream invariants already rule out." The suggested `self_driving and author_is_bot` cross-check is free and preserves the happy path (inbox PRs are bot-authored), but it fails the keep-bar of naming a concrete, reachable trigger, so precision-over-recall says drop.++### [❌ dismissed] consider · best_practice — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected is team-level but the review is gated per-repository, so the toggle can be enabled while reviews silently no-op**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** get_stamphog_connected returns has_reviewable_repo_config(instance.team_id), a team-level check for 'at least one synced, enabled Stamphog repository' (the help_text and model docstring both say so). The frontend uses this single flag to decide whether stamphog_review_inbox_prs is interactive. But the actual review only fires for the PR's specific repository — the model docstring states it 'only takes effect for teams with a synced, enabled StamphogRepoConfig covering the PR's repository', and the repo-config gate runs inside queue_inbox_pr_review per PR repo. For a team that has connected repo A but whose Inbox implementation opens a PR in repo B (or later disables A's config while the toggle stays on), stamphog_connected is True (or the toggle is already on and stays interactive), yet the review is dropped as a silent no-op. The user sees an enabled, on toggle and no verdict, with no signal that nothing ran. The enablement condition is coarser than the behavior it gates.+- **Suggestion:** Either make the connectivity signal repo-aware where the PR repository is knowable, or make the coarseness explicit in the UI copy/behavior (e.g., note that the toggle applies only to Inbox PRs opened in connected repositories, and surface when a review was skipped because the PR's repo isn't configured). At minimum, document that stamphog_connected is a team-level presence check that does not guarantee the specific Inbox PR's repo is covered, so the toggle being enabled does not imply a review will run.+- **Validator:** - **Checked:** `get_stamphog_connected` in `products/review_hog/backend/api/settings.py` and the facade it calls, `has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`, plus the per-repo gate in `products/stamphog/backend/tasks/tasks.py::process_inbox_pr_review`.+- **Found:** The mismatch is real: `has_reviewable_repo_config(team_id)` is a team-level `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()`, while the review is gated on the PR's _specific_ repo inside `process_inbox_pr_review` (repo_config `None` → early return logging `stamphog_inbox_pr_repo_not_reviewable`). So a team connected on repo A with an Inbox PR in repo B sees `stamphog_connected=True` yet no verdict.+- **Impact:** Does not meet the keep bar. (1) The no-op is the intended fail-closed behavior (facade docstring: 'silent no-op without one') — no wrong result, data loss, contract break, or leaked resource; it's a UX/observability nuance. (2) The primary suggested fix (repo-aware signal) is infeasible where flagged: `stamphog_connected` is computed in the per-user, project-level settings serializer with no PR — hence no PR repo — in context; the toggle is inherently a project-level preference, so a repo-aware signal would require per-repo toggles (scope expansion). (3) Impact is speculative/edge-case: needs connected-repo vs Inbox-PR-repo divergence (or a mid-PR disable), whereas those repos usually coincide; worst case is mild confusion, not a break. (4) The fallback 'document it' ask is largely met — the `stamphog_review_inbox_prs` help_text already says it 'Only takes effect when the project has a synced, enabled Stamphog repository (see stamphog_connected)'. On the fence → drop (precision over recall).++### [❌ dismissed] consider · bug — tools/pr-approval-agent/reviewer.py:695-702++**Provenance block asserts merged-PR/familiarity signal is absent, but the engine never enforces that for self-driving runs**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new TRUSTED provenance block tells the reviewer, as fact, that for a self-driving PR "the author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here." Nothing in the engine guarantees this assertion holds: the `self_driving` flag relaxes only the bot-author and draft gates — it does not gate familiarity computation. On the actual self-driving path (`review_local.py::run()`), `_attach_familiarity()` still computes and attaches an author-familiarity block whenever `context["author_pr_numbers"]` is present and the tier is T1-agent (and `Pipeline._maybe_compute_familiarity` behaves the same). The invariant is enforced only upstream, by the server choosing to omit `author_pr_numbers`. If a self-driving run ever arrives with those PR numbers (server misconfiguration, a future change, or a hand-built context), the familiarity block and this provenance block both render, and the LLM receives two contradictory pieces of trusted guidance in the same prompt: a concrete author-familiarity summary alongside a statement that merged-PR history carries no signal. That directly undercuts the PR's stated "by construction" guarantee and could skew the verdict for a real approval.+- **Suggestion:** Make the engine self-consistent instead of relying solely on the server: when `self.self_driving` is True, force `classification["familiarity"]` to None (or short-circuit `_maybe_compute_familiarity` / `_attach_familiarity`) so the familiarity block can never render alongside the provenance block. This keeps the two trusted blocks mutually exclusive regardless of what the context JSON contains, matching the provenance text's own claim.+- **Validator:** - **Checked:** Whether a self-driving run can present `self_driving=True` together with a non-empty `author_pr_numbers` (the only way the familiarity block and the provenance block co-render). Traced the server activity that populates both fields and the engine's familiarity gate.+- **Found:** Both values are derived from the _same_ field in the _same_ activity: `activities.py:237` sets `is_inbox_review = bool((run.output or {}).get("inbox_review"))`, `:238` sets `author_pr_numbers = ... if author and not is_inbox_review else []`, and `:451` sets `self_driving_review=bool(output.get("inbox_review"))`. So `inbox_review` truthy forces `self_driving=True` AND `author_pr_numbers=[]` in lockstep. On the engine side, `review_local.py::_attach_familiarity` early-returns at `if not raw_prs: return` (line 302) with an empty list, so no familiarity block is attached — the provenance block's claim ("merged-PR history carries no signal") holds.+- **Found:** The Action path (`Pipeline._maybe_compute_familiarity`) never sets `self_driving` and refuses bot authors at the `_refuse_bot_author` gate before familiarity is ever computed, so it cannot produce the contradiction either.+- **Impact:** The contradictory-prompt scenario is unreachable in the current design — the reviewer's own trigger list ("server misconfiguration, a future change, or a hand-built context") is entirely hypothetical, and the finding concedes the invariant "is enforced only upstream" (i.e. it _is_ enforced). Under the criteria this is a speculative what-if / already-handled case: the problem is prevented by the server's single-source derivation, and the suggested `force familiarity=None when self_driving` is a defense-in-depth re-assertion of an invariant that holds by construction. Precision-over-recall → drop.++### [❌ dismissed] consider · performance — products/review_hog/backend/api/settings.py:71-82++**stamphog_connected adds a cross-database query to the always-called settings endpoint on every GET and PATCH**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The new stamphog_connected SerializerMethodField calls has_reviewable_repo_config(instance.team_id) every time ReviewUserSettingsSerializer is serialized. The viewset serializes on every GET — which the code itself notes at settings.py:108 is "the Code review tab's always-called endpoint" — and on the response of every PATCH (toggling any unrelated setting like urgency_threshold or review_labeled_prs re-runs it). Each call is a synchronous query against the stamphog product DB, a separate database. This couples the latency and load of ReviewHog's core settings endpoint to a second database's availability and round-trip time, and the connection state it reports (whether a synced+enabled StamphogRepoConfig exists) changes very rarely, so the query is almost always recomputing an unchanged answer.+- **Suggestion:** Cache the per-team result with a short TTL (e.g. Django cache keyed on team_id for ~60s), since repo-config connection state changes rarely, so most settings reads and writes avoid the cross-DB round trip. Alternatively, if the alpha-stage cost is acceptable, at least avoid recomputing it on PATCH responses where connection state is irrelevant to the mutation. This keeps the fail-soft behavior intact while removing the repeated cross-database dependency from the hot path.+- **Validator:** - **Checked:** `get_stamphog_connected` in `products/review_hog/backend/api/settings.py` (the `try/except → return False` fail-soft wrapper), the query it runs (`has_reviewable_repo_config` in `products/stamphog/backend/facade/api.py`), and the viewset shape (serializes a single `ReviewUserSettings` instance, not a list).+- **Found:** The added cost is exactly one query per response: `StamphogRepoConfig.objects.for_team(team_id).filter(enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="").exists()` — a team-scoped (indexed) `SELECT 1 … LIMIT 1`, no loop or per-row fan-out. The endpoint is the Code review settings/config page (per-user, per-page-load), and the product is alpha-gated (UI limited to `REVIEWHOG_TEAM_ID`), so call volume is low. The cross-DB availability coupling the finding raises is already mitigated by the PR's own fail-soft `except Exception: return False` — a stamphog-DB outage degrades the flag, it cannot take the settings endpoint down.+- **Impact:** Does not meet the keep bar for 'performance problems that bite at real scale' — it is a single cheap indexed existence check (not N+1, no missing index, not blocking I/O on an async path) on a low-frequency config endpoint whose reliability risk is already handled. The suggested TTL cache / skip-on-PATCH is a premature micro-optimization; the reviewer themselves hedges that the alpha-stage cost may be acceptable. On the fence → drop (precision over recall).++### [❌ dismissed] consider · best_practice — products/review_hog/backend/api/settings.py:79-81++**Expected, benign stamphog DB failures are logged at exception level (full traceback) on an always-called endpoint**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** get_stamphog_connected catches all exceptions and calls logger.exception(...), which emits a full stack trace. The surrounding comment states this failure is expected and benign (a separate DB behind a fail-fast circuit breaker, with False as the intended safe degradation). Because this runs on the Code review tab's always-called settings endpoint, a sustained stamphog DB outage or an open circuit breaker will emit one full traceback per settings read per user — observability noise that inflates logging volume/cost and can bury genuine errors, for a condition the code already treats as normal.+- **Suggestion:** Log the expected degradation at a lower level without a stack trace, e.g. logger.warning("review_hog_stamphog_connected_check_failed: %s", exc) (optionally sampled/rate-limited), reserving logger.exception for genuinely unexpected failures. This preserves the fail-soft return of False while keeping logs signal-rich under a stamphog DB outage.+- **Validator:** - **Checked:** The `get_stamphog_connected` handler in `products/review_hog/backend/api/settings.py` — the `try: return has_reviewable_repo_config(...) except Exception: logger.exception(...); return False` block — and the endpoint's traffic profile (single-instance settings serializer on the alpha-gated Code review config page).+- **Found:** The finding is purely about log level/format: `logger.exception` (ERROR + traceback) vs `logger.warning` for a handled, expected failure. The fail-soft behavior (`return False`) is correct and identical either way — there is no behavioral or user-facing difference.+- **Impact:** Below the keep bar. It is not a correctness/security/data-loss/contract defect, not a scale performance problem, and not the kind of reliability defect the bar names (that list is _swallowed_ errors hiding failures — this is the inverse, over-logging a handled condition). The claimed harm (log volume/cost, burying real errors) is conditional on a sustained second-DB outage AND meaningful traffic on what is a per-user, per-page-load, alpha-gated config endpoint — speculative, not demonstrated, and during a real outage ERROR-level visibility is arguably wanted. This is an observability/log-hygiene preference adjacent to style/taste; the reviewer's own priority is the lowest. Precision over recall → drop.++### [❌ dismissed] consider · performance — products/stamphog/backend/tasks/tasks.py:873-894++**Bot-authored head-changing skip path resolves the repo config twice**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** On a head-changing (or base-retarget) delivery whose PR is skipped, `_inbox_rereview_carve_out` is invoked and internally calls `_resolve_repo_config` (a writer-pinned primary-DB read) plus the find_signal_implementation_run tasks-facade backstop. When the carve-out resolves empty (the common case for genuine bot PRs like dependabot/renovate, which are bot-authored and repo-native so they pass the early short-circuits), control falls into the retraction branch which calls `_resolve_repo_config(installation_id, repo)` a second time for the same (installation, repo). Bot dependency PRs synchronize frequently, so this doubles the primary-DB config lookups on the webhook hot path and layers the find_task_run backstop (whose branch-only leg on TaskRun.branch is not index-backed) on top for every such event.+- **Suggestion:** Return the resolved StamphogRepoConfig from `_inbox_rereview_carve_out` (e.g. on the `_InboxCarveOut` dataclass) and reuse it in the retraction branch instead of calling `_resolve_repo_config` again, so a skipped bot PR event resolves the config once. This removes the duplicate writer-pinned query while keeping the retraction behavior identical.+- **Validator:** - **Checked:** the skip-path flow in `process_pull_request_event` (diff: `carve_out = _inbox_rereview_carve_out(...)` then the retraction branch's `skip_repo_config = _resolve_repo_config(installation_id, repo)`), `_inbox_rereview_carve_out`'s internal `_resolve_repo_config` + `find_signal_implementation_run` calls, `_resolve_repo_config`'s query (single-row read on the unique `(provider, installation_id, repository)` index, models.py:67-71), and `TaskRun` indexes (models.py:1332 — `branch` has no `db_index` and is absent from `indexes`; only `output.pr_url`/`wizard_head_branch` partial indexes exist).+- **Found:** the double `_resolve_repo_config` is real for a bot-authored, repo-native, head-changing skipped PR (dependabot/renovate synchronize). But it is the _only_ duplicated work: `find_task_run` is the carve-out's inherent one-time identification cost, not a duplication, and the suggested fix (return the config on `_InboxCarveOut`) removes just the one extra config lookup, leaving `find_task_run` untouched. So the branch-index remark is tangential to what the fix addresses.+- **Impact (dismissal):** the actionable delta is a single extra O(1) index-backed primary-DB lookup per skipped bot-PR event — 2 constant queries instead of 1, not N+1/quadratic/unbounded and not a missing-index-on-hot-path (the config lookup IS indexed). It runs on an async, already-ACKed webhook path that on this same branch already does the carve-out resolve + `find_task_run` (incl. the pre-existing unindexed branch scan) + retraction + approval-dismissal queries, so the duplicate is a small fraction of total work and sub-millisecond in absolute terms. There is no correctness or reliability consequence (behavior identical). This is a valid but negligible micro-optimization that does not bite at real scale — below the precision-over-recall bar. Drop.++### [❌ dismissed] should_fix · bug — products/stamphog/backend/tasks/tasks.py:872-898++**Tasks-facade lookup now gates the stale-approval retraction for bot PRs, coupling a core stamphog invariant to a second datastore**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** On the webhook path, `_inbox_rereview_carve_out` is now invoked inside the `if skip_reason is not None:` block (L873-881) and, on any exception, re-raises `process_pull_request_event.retry(...)` — before control can reach the head-changing stale-approval retraction at L891-898 (`_retract_stale_approvals_on_skip`). For a bot-authored, repo-native head-changing delivery (dependabot/renovate `synchronize` on a stamphog-enabled repo), the carve-out passes its early short-circuits (bot author + repo-native head + synced/enabled config) and reaches `find_signal_implementation_run`, which queries the tasks datastore (`find_task_run` -> `TaskRun.objects.filter(output__pr_url=...)` / branch match). Before this change, retracting a standing stamphog approval on such a skip depended only on stamphog's own DB. Now a fault isolated to the tasks lookup (e.g. the tasks DB degraded while stamphog's product DB is healthy, or a query-layer error) makes the whole delivery retry; with `max_retries=3` on the task, a persistent tasks-side fault within the retry budget abandons the delivery WITHOUT ever running the retraction — leaving a prior stamphog APPROVE standing over the newly pushed commits. That is the exact 'no approval may remain standing over commits it didn't review' invariant the product treats as sacrosanct, and the failure mode is new: the retraction's dependency surface has silently expanded to a cross-product datastore. The author's inline rationale ('a transient DB blip ... must not silently drop a legitimate re-review') reasons only about preserving re-reviews and misses this collateral effect on the retraction of non-self-driving bot PRs.+- **Suggestion:** Decouple the stale-approval retraction from the carve-out lookup so a tasks-side fault cannot strand a standing approval. Options: (a) for a bot-authored, head-changing skip, run `_retract_stale_approvals_on_skip` first (it is safe/idempotent and fail-closed — the workflow re-dismisses anyway if this later turns out to be a genuine re-review), then attempt the carve-out re-review; or (b) catch the exception from `find_signal_implementation_run` inside `_inbox_rereview_carve_out`, log it, and return an empty `_InboxCarveOut()` (treat 'lookup failed' as 'not carved out') so this delivery still retracts — relying on the inbox-refire backstop to recover a re-review that was genuinely lost. Reserve the `retry(...)` for the run-creation leg, not for the branch that also owns the retraction.+- **Validator:** - **Checked:** the skip-path flow in `process_pull_request_event` (`@shared_task(max_retries=3, default_retry_delay=5)`, diff line 1040): carve-out invoked under `if skip_reason is not None:` with `except → process_pull_request_event.retry(...)` before the head-changing retraction; `_review_skip_reason` (returns `"bot_author"` via `_is_bot_authored`); `_retract_stale_approvals_on_skip` (tasks.py:368) and `dismiss_stale_approvals_for_head`.+- **Found:** the code-flow observation is correct — a persistent tasks-DB fault in `find_signal_implementation_run` can exhaust retries without the retraction running. But the asserted harm cannot occur for the named class: dependabot/renovate are refused as `bot_author` and never receive a stamphog APPROVE, and `_retract_stale_approvals_on_skip` only dismisses this App's standing approvals for the PR (no prior review → no-op: no PR row returns early, a row with no standing APPROVE dismisses nothing). So skipping it strands nothing for non-self-driving bot PRs — the finding's core premise ("prior stamphog APPROVE standing over the newly pushed commits" for dependabot/renovate) is mistaken.+- **Found:** the only bot-authored PRs stamphog can approve are self-driving carve-out PRs — the class the reviewer explicitly excludes ("non-self-driving bot PRs"). For that class the exposure needs an isolated, persistent tasks-DB outage (tasks DB down while stamphog's DB is healthy) across all 3 retries, and it self-heals: the next synchronize delivery or the leg-1 inbox refire re-reviews once the tasks DB recovers, and the workflow runs `dismiss_stale_approvals` first.+- **Impact (dismissal):** the concrete trigger→consequence chain does not connect (the named victim class has no approval to lose) — the "premise is mistaken" drop condition. The residual valid case is a rare, transient, self-healing cross-datastore infrastructure edge that the reviewer did not analyze and that is milder than the assigned `should_fix`; it is not a failure mode that will occur on realistic inputs. Below the precision-over-recall bar. Drop.++### [✅ VALID] should_fix (validator→consider) · bug — tools/pr-approval-agent/review_pr.py:587-593++**Draft-gate relaxation silently disables the merge-conflict gate for self-driving PRs**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** Before this change a draft PR was always blocked by the `if pr.draft:` branch in `_check_prerequisites`, so execution never depended on the follow-on `if pr.mergeable_state == "dirty":` check for any draft. Relaxing that branch to `if pr.draft and not self.self_driving:` now lets a self-driving _draft_ PR fall through to the conflict check — but GitHub reports `mergeable_state` as `"draft"` (or `"unknown"`) for draft PRs, never `"dirty"`, so `pr.mergeable_state == "dirty"` cannot fire on this newly-allowed path. `PRData` exposes no other conflict signal (there is no `mergeable` boolean field). Net effect: a self-driving draft PR that actually has merge conflicts passes the "merge conflicts present" gate and can receive a real head-pinned APPROVE, whereas the same conflict on a human (non-draft) PR would DENY. Relaxing the draft gate thus unintentionally removed a separate safety gate for exactly the path this PR opens up, and it is untested (the tests exercise LABEL-mode/read-only-author drafts, not a conflicted draft).+- **Suggestion:** Give the self-driving path a conflict signal that GitHub actually populates for drafts. Capture the boolean `mergeable` field on `PRData` and treat `mergeable is False` as "merge conflicts present" in addition to `mergeable_state == "dirty"`, or explicitly handle the `"draft"`/`"unknown"` mergeable states so the conflict gate still protects self-driving drafts. Add a test with a draft PR whose mergeable state is `"draft"` and conflicted to lock the behavior.+- **Validator:** - **Checked:** Whether the self-driving path reaches the conflict gate, whether `mergeable_state == "dirty"` can fire for a draft, and whether any other conflict signal exists on `PRData`.+- **Found:** The offline/self-driving path runs `_check_prerequisites` (`review_local.py:233` in `_run_gates_offline`), so `self_driving=True` skips the draft branch (`review_pr.py:590`) and falls through to `if pr.mergeable_state == "dirty"` (`:592`). `PRData` (`github.py:17-38`) exposes only `mergeable_state: str`, no `mergeable` boolean, and it is populated verbatim from GitHub (`github.py:592`, `review_local.py:198`). GitHub reports `mergeable_state="draft"` for drafts and `"unknown"` for not-yet-computed (leg 1 reviews the PR immediately at open time) — never `"dirty"` — so the conflict gate cannot fire on the exact path this PR opens. The premise is verified.+- **Impact:** Real but mild. An approval on a conflicted PR cannot cause a bad merge: GitHub blocks merging a `dirty` PR regardless of approvals, and the approval is head-pinned — resolving conflicts changes the head SHA, which the PR's dismiss-stale-approvals invariant retracts and re-reviews. So the concrete consequence is a transient, dismissable APPROVE verdict on an unmergeable draft (a minor verdict-integrity/UX gap at Inbox triage), not the merge-of-conflicted-code the finding implies.+- **Priority:** Downgrading should_fix → consider. The gate gap is genuine and directly introduced by the changed lines, but the downstream harm is neutralized by GitHub's merge-block on `dirty` plus the head-pinned/dismiss-on-push invariant, so it does not warrant should_fix; it's worth keeping on record as a low-priority robustness note.++### [❌ dismissed] consider · best_practice — tools/pr-approval-agent/review_pr.py:587-590++**Verdict comment doesn't disclose the carve-out and reports the relaxed draft gate as "all clear"**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** When a self-driving run is APPROVED, the GitHub verdict comment posted by `_render_review_body` shows the gate-mechanics table built from `self.gate_results`, in which the prerequisites gate now renders `prerequisites | ✓ | all clear` even though the PR is a draft — the draft condition was skipped, not satisfied. The bot-author refusal is not a `GateResult` at all, so it never appears either. A human auditing a real head-pinned approval sitting on a bot-authored draft therefore gets no signal in the comment that two normally-hard gates (bot-author, draft) were relaxed, and "prerequisites: all clear" is affirmatively misleading for a draft. The `self_driving` flag is recorded only in the machine-readable `to_dict()` audit trail, not in the human-facing comment.+- **Suggestion:** When `self.self_driving` is set, disclose the carve-out in the verdict comment (e.g. a line stating the PR was approved under the self-driving inbox carve-out with the bot-author and draft gates relaxed by design), and/or render the prerequisites row for a relaxed draft as something like "draft (relaxed for self-driving)" instead of "all clear" so the posted approval is auditable at a glance.+- **Validator:** - **Checked:** What the prerequisites gate returns on a relaxed-draft path, how the verdict comment is assembled, and whether the carve-out is recorded anywhere.+- **Found:** The finding's facts are accurate — `_check_prerequisites` returns `(True, "all clear")` (`review_pr.py:607`) with the draft blocker skipped for self-driving, `_render_review_body` builds the gate table only from `self.gate_results` (`:900`) with no reference to `self.self_driving`, and the flag lands only in the machine-readable `to_dict()` (`:938`). So the rendered comment does show `prerequisites | ✓ | all clear` and omits carve-out disclosure.+- **Impact:** Does not meet the keep bar. This is a human-facing-copy / auditability enhancement, not a defect in a keep-category: the approval is correct by design, no value is computed wrongly, no invariant is broken. "all clear" reflects the gate's carve-out-adjusted logic (no active prerequisite blockers) rather than asserting the PR is non-draft, so it is terse, not affirmatively false. The self-driving provenance is not actually hidden — it is captured in the `to_dict()` audit record (`:938`), stamped on analytics (`stamphog_self_driving_review`), and documented in AGENTS.md; surfacing it in the rendered comment as well is a design/taste decision. Under precision-over-recall, with comment-wording/presentation explicitly de-prioritized and the substantive audit data already recorded, this is low-value polish → drop.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-1.mdnew file mode 100644index 000000000000..10e738a5633d--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-1.md@@ -0,0 +1,308 @@+# Reviewer-quality run — `G-gpt56luna-xhigh-1`++- **Dumped:** 2026-07-30T12:29:06+00:00+- **Report id:** `019fb2c4-b3da-7f27-be3b-116754d3d480` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 3865s (64.4 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-luna` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 16 | 14 | 3 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | -------------- | ----------- | ------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 98 | 91,761 | 536,281 | 8,830,882 | 140,681 | 0 | $11.74 | $11.74 |+| gpt-5.6-luna | review | 294 | 14,927,809 | 0 | 0 | 66,930 | 0 | — | $3.77 |+| gpt-5.6-luna | blind-spot | 48 | 2,515,503 | 0 | 0 | 14,111 | 0 | — | $0.61 |+| claude-sonnet-5 | dedup | 1 | 7,050 | 0 | 0 | 4,994 | 0 | $0.06 | $0.06 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 515 | 0 | $0.02 | $0.02 |+| **total** | | **442** | **17,548,104** | **536,281** | **8,830,882** | **227,231** | **0** | **$11.82** | **$16.20** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `gpt-5.6-luna` (342 gen(s), gw $4.37).+- naive method (all prompt tokens at input price): $50.89 — 4.3× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $12.1391 over 442 gen(s) (true $8.2521, Δ +47.1%)+ - · of which cache read: $5.9217 over 401 gen(s) (true $4.4154, Δ +34.1%)+ - · of which cache write: $3.3518 over 98 gen(s) (true $3.3518, Δ -0.0%)+ - · of which fresh (derived): $2.8656 over 442 gen(s) (true $0.4849, Δ +491.0%)+ - output: $4.0584 over 442 gen(s) (true $3.5721, Δ +13.6%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …8e18820a | issues-review-p2-c1 | 11:25:33 | 0 | 0 | gpt-5.6-luna |+| …f2b0afc2 | issues-review-p3-c1 | 11:25:35 | 0 | 0 | gpt-5.6-luna |+| …d0ec36a3 | issues-review-p3-c3 | 11:25:35 | 0 | 0 | gpt-5.6-luna |+| …f15ae926 | issues-review-p1-c1 | 11:25:36 | 0 | 0 | gpt-5.6-luna |+| …619f4ca9 | issues-review-p2-c2 | 11:25:37 | 0 | 0 | gpt-5.6-luna |+| …e56eee38 | issues-review-p3-c2 | 11:25:37 | 0 | 0 | gpt-5.6-luna |+| …a178c439 | issues-review-p2-c3 | 11:25:38 | 0 | 0 | gpt-5.6-luna |+| …925ccf6b | issues-review-p1-c2 | 11:25:38 | 0 | 0 | gpt-5.6-luna |+| …287d55ec | issues-review-p1-c3 | 11:25:38 | 0 | 0 | gpt-5.6-luna |+| …b7f511d2 | issues-review-p3-c2 | 11:28:37 | 0 | 0 | gpt-5.6-luna |+| …cb617c7c | issues-review-p1-c3 | 11:28:37 | 0 | 0 | gpt-5.6-luna |+| …edb1e880 | issues-review-p1-c2 | 11:28:39 | 0 | 0 | gpt-5.6-luna |+| …8db511ae | issues-review-p2-c1 | 11:28:39 | 0 | 0 | gpt-5.6-luna |+| …f5d3e848 | issues-review-p3-c1 | 11:28:44 | 0 | 0 | gpt-5.6-luna |+| …3e67a6ca | issues-review-p3-c3 | 11:28:47 | 0 | 0 | gpt-5.6-luna |+| …35ed01a3 | issues-review-p2-c2 | 11:28:50 | 0 | 0 | gpt-5.6-luna |+| …79465e07 | issues-review-p1-c1 | 11:28:56 | 0 | 0 | gpt-5.6-luna |+| …13cf0169 | issues-review-p2-c3 | 11:28:56 | 0 | 0 | gpt-5.6-luna |+| …a68e8a42 | issues-review-p2-c3 | 11:32:13 | 0 | 0 | gpt-5.6-luna |+| …4461bc08 | issues-review-p3-c2 | 11:32:13 | 0 | 0 | gpt-5.6-luna |+| …15f77917 | issues-review-p3-c3 | 11:32:14 | 0 | 0 | gpt-5.6-luna |+| …e97de4f3 | issues-review-p2-c2 | 11:32:15 | 0 | 0 | gpt-5.6-luna |+| …50c29f17 | issues-review-p3-c1 | 11:32:16 | 0 | 0 | gpt-5.6-luna |+| …b1d3ef60 | issues-review-p1-c2 | 11:32:18 | 0 | 0 | gpt-5.6-luna |+| …5aa40ed7 | issues-review-p1-c1 | 11:32:28 | 0 | 0 | gpt-5.6-luna |+| …f55b8d73 | issues-review-p2-c3 | 11:34:56 | 0 | 0 | gpt-5.6-luna |+| …374e3e4d | issues-review-p3-c1 | 11:35:00 | 0 | 0 | gpt-5.6-luna |+| …231ee8f1 | issues-review-p1-c1 | 11:35:06 | 0 | 0 | gpt-5.6-luna |+| …4a8fd08e | issues-review-p3-c2 | 11:35:12 | 0 | 0 | gpt-5.6-luna |+| …5fe2cfee | issues-review-p2-c2 | 11:35:13 | 0 | 0 | gpt-5.6-luna |+| …fed9506a | issues-review-p3-c3 | 11:35:27 | 0 | 0 | gpt-5.6-luna |+| …7c98cba5 | issues-review-p2-c1 | 12:02:16 | 0 | 0 | gpt-5.6-luna |+| …e34b7976 | blind-spots-c1 | 12:04:20 | 0 | 0 | gpt-5.6-luna |+| …5c56f6ed | blind-spots-c2 | 12:04:23 | 0 | 0 | gpt-5.6-luna |+| …dc221d7c | blind-spots-c3 | 12:04:24 | 0 | 0 | gpt-5.6-luna |+| …fc42e214 | blind-spots-c4 | 12:04:28 | 0 | 0 | gpt-5.6-luna |+| …294929fc | validation-c2 | 12:08:01 | 0 | 37,687 | claude-opus-4-8 |+| …df37a609 | validation-c3 | 12:08:03 | 0 | 36,819 | claude-opus-4-8 |+| …47fabd34 | validation-c4 | 12:08:04 | 17,141 | 19,622 | claude-opus-4-8 |+| …278954cb | validation-c1 | 12:08:06 | 17,141 | 20,147 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **2/40** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 11s |+| review wave (perspectives) | 39m 03s |+| blind-spot sweep | 2m 36s |+| dedup (incl. combine/clean) | 49s |+| validation | 21m 01s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 41m 39s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | ? | 0 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 2 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | review-hog-blind-spots-general | 1 |++## Findings (post-dedup) with validator verdict++### [✅ VALID] should_fix (validator→consider) · bug — products/review_hog/backend/receivers.py:144-158++**Honor opt-in from any assigned reviewer**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The resolver selects only one canonical assigned reviewer and then gates Stamphog on that user's toggle. This does not implement the stated contract that Stamphog should run when at least one assigned reviewer has opted in: if the first reviewer is opted out but another assigned reviewer is opted in, the PR is skipped entirely.+- **Suggestion:** Resolve the full assigned reviewer set for the Stamphog path, select an opted-in reviewer when any exists, and use that reviewer as the acting identity for the queued review. Keep the existing single-reviewer resolution for ReviewHog if that behavior is intentional.+- **Validator:** - **Checked:** the actual PR diff for `receivers.py` (working tree is at master, not the PR head, so I pulled `gh pr diff 75215`), tracing both the initial-trigger leg (`handle_task_run_saved`) and the webhook re-review leg (`resolve_stamphog_acting_reviewer`), plus `_resolve_assigned_reviewer` and the `queue_inbox_pr_review` call.+- **Found:** `_resolve_assigned_reviewer` returns exactly one identity — `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` (receivers.py, the `acting = next(...)` line). Both stamphog gates then read `stamphog_review_inbox_prs` off that single `acting_user_id` (the `if pr_url is not None and settings.stamphog_review_inbox_prs:` block, and `resolve_stamphog_acting_reviewer`). So a report with ≥2 resolved reviewers where the canonical one (task creator, else first resolved) is opted out but another opted in → stamphog is skipped. This does contradict the PR's repeated 'at least one of the assigned users' / 'any assigned reviewer' / 'nobody is opted in' contract.+- **Found (counter-evidence):** the same PR adds a docstring documenting the design as deliberate — 'The same resolved acting reviewer carries a second, independent toggle' — and the ReviewHog leg gates on the identical single acting reviewer (the finding itself accepts that as intentional). So the discrepancy is really an internal contradiction between the PR prose and the code's own documented single-acting-reviewer model, resolvable by fixing either side.+- **Impact:** a genuine, reachable behavioral gap (an opted-in non-canonical reviewer's preference is silently ignored), but narrow — it needs a multi-reviewer report with mismatched toggles, on a draft experiment branch, and the consequence is a missed review, not wrong output/data loss/security. Worth surfacing so the author reconciles code vs. description, but the documented single-reviewer design and narrow blast radius put it below should_fix.+- **Priority:** lowered to `consider` — real discrepancy on record, but plausibly a documentation mismatch rather than a code defect, and low-impact at this stage.++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:113-121++**Strictly validate inbox PR URLs**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_parse_pr_url` uses an unanchored regex that searches for `github.com/` anywhere in the input and accepts arbitrary characters in the owner/repository segment. For example, a URL hosted on a lookalike domain can be interpreted as a GitHub PR URL, and malformed paths can be accepted. Since this value originates from a task output and controls which configured repository and PR number are fetched, the parser should enforce the actual host and exact path shape.+- **Suggestion:** Parse with `urllib.parse.urlparse`, require an allowed scheme and `netloc == "github.com"` (or the configured GitHub host), and validate the path against an anchored pattern such as `^/[^/]+/[^/]+/pull/[1-9][0-9]*/?$`. Reject query/fragment variants unless explicitly supported.+- **Validator:** - **Checked:** the only caller of `_parse_pr_url`, `process_inbox_pr_review` in `products/stamphog/backend/tasks/tasks.py`, and how the parsed `(repository, pr_number)` flow into the config lookup and the GitHub fetch; also the caller chain (`queue_inbox_pr_review` facade ← review_hog receiver) that supplies `pr_url` and `team_id`.+- **Found:** the parsed `repository` is used solely as a lookup key: `StamphogRepoConfig.objects.for_team(team_id).filter(provider="github", repository__iexact=repository, enabled=True, connected_by_user_id__isnull=False).exclude(installation_id="")`. A lookalike-host or malformed URL that yields a non-configured owner/repo simply misses and returns (`stamphog_inbox_pr_repo_not_reviewable`).+- **Found:** the URL is never fetched. The actual GitHub call is `StamphogGitHubClient(repo_config.installation_id).get_pr(repo_config.repository, pr_number)` — it uses the config's **canonical** repo and the team's own installation, so only `pr_number` (always `\d+`, `int()` can't crash) comes from the parsed string. Host enforcement therefore prevents no SSRF/redirect.+- **Found:** `team_id` is an explicit task argument scoping every read/write (`for_team(team_id)`), not derived from the URL — no cross-tenant/IDOR surface.+- **Impact:** the claimed consequences (lookalike domain, malformed path) are neutralized downstream by the team-scoped enabled-config lookup and canonical-repo fetch; no concrete reachable failure can be named. The only residual concern — an arbitrary `pr_number` within an already-enabled repo — is not closed by the proposed host/path anchoring (a well-formed `github.com/<configured-repo>/pull/<N>` still parses) and is bounded to repos the team already enabled with the reviewer opted in. This is defensive hardening the surrounding validation already covers, so it does not meet the bar.++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:321-321++**Validate the self-driving flag strictly as a boolean**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This flag relaxes the bot-author and draft gates, but `bool(context.get("self_driving_review"))` treats any non-empty string as true, including values such as `"false"` or `"0"`. A malformed or incorrectly serialized hosted context could therefore authorize the privileged self-driving carve-out and allow a bot-authored draft PR through.+- **Suggestion:** Require the exact JSON boolean value, for example `self_driving=context.get("self_driving_review") is True`, and ideally reject or log malformed non-boolean values when constructing the hosted context.+- **Validator:** - **Checked:** the full producer→consumer path for `self_driving_review`: `run_review_in_sandbox` (activities.py) → `build_reviewer_invocation` (logic/reviewer.py) → JSON context file → `review_local.run` at review_local.py:321.+- **Found:** the value is stamped by `build_reviewer_invocation(self_driving_review=bool(output.get("inbox_review")))`, whose parameter is typed `bool`, and written as `context = {..., "self_driving_review": self_driving_review}` then `json.dumps`-ed. The engine reads it back with `json.load`, so `context.get("self_driving_review")` is always a genuine Python `bool` (or `None` for the Action-shaped context that omits the key). There is no code path that serializes this key as a string.+- **Found:** the context is server-generated from task provenance (`ReviewRun.output["inbox_review"]`), not from PR body / untrusted author text — so it is not attacker-controllable, and the carve-out direction is fail-closed: absent/`False`/`None` all yield `bool(...) == False`.+- **Impact:** the flagged `bool("false")`-style hazard requires a truthy non-boolean string to reach the key, which the typed `bool` construction and `json.dumps` round-trip rule out. `bool(...)` and the suggested `is True` produce identical results for every value this pipeline can actually emit. This is defensive-coding paranoia against an unreachable input — per the criteria (speculative what-if / condition that can't occur given the call sites and types), drop it.++### [❌ dismissed] should_fix · bug — tools/pr-approval-agent/review_pr.py:937-938++**Skip author-familiarity signals for self-driving reviews**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The new self_driving flag is recorded and passed to the prompt, but `_maybe_compute_familiarity` still computes and exposes the bot author's familiarity for T1 reviews. The reviewer prompt renders that signal before the self-driving provenance block, and `_render_review_body` can also publish author-familiarity bullets. This contradicts the stated behavior that machine-author familiarity and merged-PR history carry no signal, and a bot with prior activity could receive inappropriate trust weight.+- **Suggestion:** When self_driving is enabled, skip `_maybe_compute_familiarity` or leave classification["familiarity"] unset, and suppress any author-familiarity review-body bullet for that path. Add a focused regression test asserting that a self-driving review contains no familiarity signal.+- **Validator:** - **Checked:** which code path a self-driving run actually executes, and where familiarity is computed vs. suppressed — `review_pr.py::run`/`_maybe_compute_familiarity` (the Action path) versus `review_local.py::run`/`_attach_familiarity` (the hosted path), plus the server-side context builder in `activities.py::fetch_review_context`.+- **Found:** `self_driving` is only ever set by `review_local.py::run` (`Pipeline(..., self_driving=bool(context.get("self_driving_review")))`); that entrypoint drives the pipeline manually (`_classify` → `_run_gates_offline` → `_attach_familiarity` at review_local.py:348 → `_llm_review`) and never calls `_maybe_compute_familiarity`. `review_pr.py::run` (which does call `_maybe_compute_familiarity` at review_pr.py:241) is the Action entrypoint, and nothing in the Action runtime sets `self_driving`, so it always runs with `self_driving=False` and a bot author still hits `_refuse_bot_author` before familiarity.+- **Found:** `_attach_familiarity` early-returns when `author_pr_numbers` is empty (review_local.py:301-304, `if not raw_prs: return`), leaving `classification["familiarity"]` = None (set by `_classify`, review_pr.py:464) and `self.familiarity` = None. The server empties `author_pr_numbers` for every inbox/self-driving review: `activities.py::fetch_review_context` computes `is_inbox_review` and sets `author_pr_numbers = ... if author and not is_inbox_review else []`. Both `author_pr_numbers` emptying and the `self_driving_review` flag are keyed off the same `run.output["inbox_review"]` provenance, so they are coupled — a self-driving run always has empty PR numbers.+- **Found:** with `classification["familiarity"]` = None, `_format_familiarity` renders no signal into the prompt and `_render_review_body` (review_pr.py:855, `fam = self.classification.get("familiarity")`) emits no author-familiarity bullet. The requested regression coverage already exists: `test_integration.py::test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end` asserts `context["author_pr_numbers"] == []` ("the machine user's merged-PR history must not feed familiarity").+- **Impact:** the finding's premise — that a self-driving review computes and exposes the bot author's familiarity — does not hold; the stated no-machine-familiarity behavior is enforced (server-emptied `author_pr_numbers` + `_attach_familiarity` early-return), just via a different mechanism than the `review_pr.py` path the finding inspected. Wrong/unreproducible, so it does not meet the bar.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:210-236++**preserve failed initial stamphog queues for retry**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** If the Celery broker is unavailable, `queue_inbox_pr_review` raises and this handler only logs the exception. Because the initial Stamphog review is not backed by a GitHub webhook delivery, the review is permanently lost unless another TaskRun save or PR push happens. The callback also performs broker I/O synchronously in the TaskRun save path.+- **Suggestion:** Use a durable outbox or a retryable enqueue operation for the initial review, with bounded producer timeouts. Persist the pending handoff before commit and retry it asynchronously so broker failures neither block TaskRun saves nor silently discard the review.+- **Validator:** - **Checked:** `_start_stamphog_review` (receivers.py L210–236 in the PR head) and its call site, plus the sibling `_start_review` (Temporal leg) it was modeled on, and the PR's own Case 2 recovery path.+- **Found (deliberate, documented posture):** the catch-log fire-and-forget is intentional and explicitly documented — the docstring reads 'Fire-and-forget the hosted Stamphog review; the broker being down must never surface into the saver.' It is a verbatim copy of the established `_start_review`/Temporal leg in the same file, which likewise wraps a downstream dispatch in `try/except Exception: logger.exception(...)`. Neither leg was designed to be durable; the file's whole philosophy is that a TaskRun save must never break because downstream infra (Temporal, the Celery broker) is momentarily down.+- **Found (recovery exists):** the 'permanently lost' framing is overstated — the review is only dropped if the broker is down at that exact on_commit moment AND no further push ever lands. Per the PR's Case 2, later commits on a self-driving PR re-review through stamphog's webhook path (`resolve_stamphog_acting_reviewer`), so for the iterating draft PRs this feature targets, a transient broker blip on the initial queue is recovered on the next push.+- **Found (sync-I/O claim):** the callback runs via `transaction.on_commit` (after the transaction closes, not holding it open) and the docstring notes the facade only does a broker publish ('the only work on this save path is the broker publish') — a single Celery enqueue, identical in cost profile to the sibling Temporal-start already accepted on this path.+- **Impact:** the suggested fix (durable outbox, retryable enqueue, bounded producer timeouts, persist-before-commit) is a substantial reliability-infra pattern that contradicts the deliberately-chosen, documented, sibling-consistent design — textbook overengineering for an experiment-stage feature (draft PR on a frozen experiment branch). The failure mode is rare and the consequence mild and recoverable, so it does not meet the bar.++### [❌ dismissed] must_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1107-1110++**Persist or reconcile failed initial review dispatches**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The receiver queues this task as fire-and-forget, while the task gives up after only three retries. If the broker, database, or GitHub remains unavailable through those attempts, the initial inbox review is silently lost because no durable pending-review record or reconciliation path is created. A later TaskRun save is not guaranteed, so the PR can remain unreviewed indefinitely.+- **Suggestion:** Persist the requested review (for example, on the TaskRun or in a dedicated outbox row) before dispatching, and add a reconciler that resumes pending reviews. At minimum, use a longer/backoff retry policy with an observable terminal failure and a durable retry path rather than relying on another output save.+- **Validator:** - **Checked:** `process_inbox_pr_review` in `products/stamphog/backend/tasks/tasks.py` (decorator, all three retry paths), its receiver dispatch in `products/review_hog/backend/receivers.py` (`_start_stamphog_review` → `queue_inbox_pr_review` under `transaction.on_commit`), and the webhook re-review carve-out `_inbox_rereview_carve_out` that runs on later deliveries.+- **Found:** every failure branch (`stamphog_inbox_pr_config_resolution_failed`, `stamphog_inbox_pr_fetch_failed`/`_rate_limited`, `stamphog_inbox_pr_create_run_failed`) logs via `logger.exception`/`warning` and then `raise ...retry(exc=e)`; retry exhaustion raises Celery's `MaxRetriesExceededError`. The outcome is a logged terminal failure, not the code-level 'silent' loss the finding describes.+- **Found:** the task docstring states the initial leg is a convenience to have the verdict ready at draft-triage time, and that later head-changing events re-review through the webhook carve-out; the receiver re-fires on every TaskRun output save (runs typically save output more than once), and a refire after an undelivered head still reviews. So the durable/authoritative review path is the webhook leg, by design — the initial leg is deliberately best-effort.+- **Impact:** a permanently-failed initial dispatch loses only an _optional_ pre-review of a toggle-gated experimental feature; it posts no approval, so the stale-approval safety invariant is untouched, and any subsequent push or output re-save recovers it. The only genuinely stuck case is a draft that never receives another commit or save — a rare, low-impact tail whose consequence is a missing nice-to-have, not data loss or a safety hole. This does not meet the reliability bar.+- **Impact:** the proposed remedy (a persisted outbox row plus a reconciler resuming pending reviews) is disproportionate durability machinery for a best-effort leg — overengineering under the validation criteria — and the must_fix severity is unsupportable for a safe, recoverable, logged failure.++### [❌ dismissed] should_fix · code_quality — products/stamphog/backend/facade/api.py:122-126++**Filter the reviewable-config check to supported providers**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `has_reviewable_repo_config` checks enabled and synced configs but does not restrict the provider to GitHub, while both the initial task and webhook path explicitly resolve only `provider="github"`. Any synced non-GitHub config would therefore enable the inbox toggle even though the queued review can never be processed for that repository.+- **Suggestion:** Add `provider="github"` to the queryset, matching the provider filters used by the actual review paths.+- **Validator:** - **Checked:** `has_reviewable_repo_config`'s queryset in `products/stamphog/backend/facade/api.py` against how `provider`, `installation_id`, and `connected_by_user_id` are actually set — the model (`models.py:26-29`), the create serializer (`presentation/serializers.py:74-104`), both sync-create sites, and the manual-config adoption helper.+- **Found:** the helper requires BOTH `connected_by_user_id__isnull=False` AND non-blank `installation_id` (`.exclude(installation_id="")`). Both are set together only by the authenticated GitHub sync flow, which hardcodes `provider="github"` (`tasks/tasks.py:551` create; `presentation/views.py:307` `get_or_create(provider="github", ...)`).+- **Found:** the only path that lets a client set a non-github `provider` is the plain serializer create, but there `installation_id` is `read_only` ('Set only by the verified sync_installation flow; ignored on direct writes', `serializers.py:98-99`) and `connected_by_user_id` is not a serializer field (`fields` list, `serializers.py:74-85`). And `_adopt_preexisting_config` filters `provider="github"` (`views.py:66+`), so a manual non-github row is never adopted into a synced one.+- **Impact:** a config with `provider != "github"` can never simultaneously carry a non-blank installation_id and a connecting user, so it can never pass this check — the flagged scenario is unreachable. Even if it were, the helper only drives the UI toggle's enabled/disabled state; the actual review path filters `provider="github"` and no-ops, so the worst case is a cosmetic toggle mismatch, not a processing bug. Adding the filter is harmless consistency but guards a state that can't occur with the only implemented provider — speculative future-proofing, below the bar.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:88-95++**Documented carve-out does not match the current implementation**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This section documents an implemented self-driving exception using `self_driving_review`, `Pipeline(self_driving=...)`, `ReviewRun.output["inbox_review"]`, and `queue_inbox_pr_review`, but those contracts are not present in the checked-out code. The actual inbox receiver starts `start_review_pr_workflow` directly with `trigger_source="inbox"`, while `review_local.py` still unconditionally refuses bot authors and the Stamphog webhook pre-filter still rejects drafts and bot-authored PRs. This makes the security and behavior documentation materially misleading and could cause future changes to rely on nonexistent gates.+- **Suggestion:** Either update the documentation to describe the actual `trigger_source`/`signal_report_id` flow and current bot refusal behavior, including the README entry point, or land the corresponding implementation before documenting this exception. Verify every referenced symbol and gate with a regression test before retaining the carve-out contract.+- **Validator:** - **Checked:** Pulled the real PR #75215 diff (`gh pr diff`) and grepped every symbol the finding names, then read the implementing hunks in `facade/api.py`, `facade/inbox_hooks.py`, `logic/reviewer.py`, `tasks/tasks.py`, `temporal/activities.py`, and `tools/pr-approval-agent/reviewer.py`.+- **Found:** Every documented contract is implemented _in this PR_, not absent: `queue_inbox_pr_review` is a new facade fn in `products/stamphog/backend/facade/api.py`; `process_inbox_pr_review` is the receiver leg in `tasks/tasks.py`; `facade/inbox_hooks.py` is a new resolver module; the engine flag flows `ReviewRun.output["inbox_review"]` → `self_driving_review=bool(output.get("inbox_review"))` (`temporal/activities.py`) → `Pipeline(self_driving=...)` (`tools/pr-approval-agent/reviewer.py`, `review_local.py`).+- **Found:** The reviewer's claimed alternative mechanism does not exist — `trigger_source` has **0** occurrences across the 2222-line diff. The bot/draft gates are _not_ unconditional: `tasks/tasks.py` adds `_inbox_rereview_carve_out` and bypasses the pre-filter with `if skip_reason is not None and inbox_review is None:`, and the engine relaxes the refusal via `reviewer.py::_format_self_driving` keyed on `cl.get("self_driving")`.+- **Found:** The on-disk checkout is the base, not the PR head — `HEAD` is `fe6ca668` (an unrelated data-imports commit), the PR head `1341596e` is not even fetched locally, and `products/stamphog/AGENTS.md` on disk is 113 lines with no carve-out section. This is exactly the tree the finding describes as 'the checked-out code.'+- **Impact:** The premise (documentation describes contracts the code doesn't implement) is mistaken — doc and implementation are consistent _within the PR_. The finding is an artifact of validating the PR's docs against a base tree lacking the PR's code, so it meets the 'Wrong / unreproducible' drop bar and would be a false positive to the author.++### [✅ VALID] must_fix (validator→should_fix) · security — products/stamphog/backend/tasks/tasks.py:1152-1162++**Revalidate the fetched PR before enabling the self-driving carve-out**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial inbox path fetches the PR and then unconditionally stamps `inbox_review`, which causes the engine to bypass bot-author, draft, fork, author-association, and write-permission safeguards. Unlike `_inbox_rereview_carve_out`, it never verifies that the fetched PR is bot-authored, repository-native, or otherwise matches the positively identified self-driving task. A malformed or manipulated `pr_url`/TaskRun output could therefore make Stamphog approve an arbitrary PR in a configured repository, including a fork or human-authored PR.+- **Suggestion:** After fetching the PR, apply the same identity checks as the webhook carve-out: require a bot author, a draft if that is part of the self-driving contract, and `head.repo.full_name` to match the configured repository. Also resolve `task_run_id` in the supplied team and verify its signal report, repository, and PR URL/branch match the fetched PR before creating the run; otherwise return without setting `inbox_review`.+- **Validator:** - **Checked:** `process_inbox_pr_review` (initial leg) vs `_inbox_rereview_carve_out` (webhook leg) in `products/stamphog/backend/tasks/tasks.py`; the engine's `self_driving` handling in `tools/pr-approval-agent/review_pr.py`/`review_local.py`; and how `output.pr_url` is written in `products/tasks/backend/` (agent-server observation + webhook backstop `_record_run_pr_url`).+- **Found (asymmetry):** the webhook leg positively identifies a self-driving PR with three checks before granting provenance — `_is_bot_authored(pr)`, fork-safety `head_repo.lower() != repo.lower()`, and a team-scoped `find_signal_implementation_run` task match. The initial leg does NONE of these on the fetched PR: after `get_pr(repo_config.repository, pr_number)` it unconditionally stamps `output={"inbox_review": {...}}` on the run.+- **Found (bypass is real):** in the engine, `self_driving` relaxes exactly the bot-author refusal (`if self.pr.author_is_bot and not self.self_driving`) and the draft prerequisite (`if pr.draft and not self.self_driving`), with no independent fork/association re-check — the engine explicitly delegates 'positively linked' verification to the hosted runtime. So the run's `inbox_review` stamp alone lets the engine post a real GitHub APPROVE on a bot/draft/fork PR.+- **Found (why the webhook leg's checks matter):** both legs ultimately trust `output.pr_url`, but the webhook leg re-validates the actual PR object on top (bot-author + non-fork). The initial leg trusts `output.pr_url` — written by an LLM agent's observed PR creation (untrusted-content threat model per the product's own invariants) or a branch-matched backstop — without re-validating the fetched PR at all.+- **Impact:** if `output.pr_url` ever resolves to a non-self-driving PR (fork or human-authored) in a configured+enabled repo, stamphog would review and could auto-approve it, satisfying required reviews with no human — the exact catastrophe the bot/fork/association gates exist to prevent (tasks.py bot-author comment; product CLAUDE.md stale-approval/trust-boundary invariants). The fix reuses existing helpers (`_is_bot_authored`, the fork check), so parity with the webhook leg is cheap.+- **Priority:** lowering must_fix → should_fix. The gap and its severe consequence are verified, but the direct exploit requires `output.pr_url` to point at a non-bot/fork PR, and the normal write paths are server-mediated (bot-observed creation; backstop match on a randomly generated `wizard_head_branch`), so adversarial control of that value is a narrow, unconfirmed vector; the feature is also per-user-toggle-gated and requires a synced+enabled config. This is a safety-critical consistency gap to bring to parity before broad rollout, not a confirmed merge-blocking exploit.++### [✅ VALID] must_fix (validator→consider) · bug — products/review_hog/backend/receivers.py:114-138++**check all assigned reviewers for Stamphog opt-in**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The Stamphog dispatch is gated only by the canonical acting reviewer returned by `_resolve_assigned_reviewer`. If that reviewer has `stamphog_review_inbox_prs` disabled but another assigned reviewer has it enabled, the Inbox PR is never queued, contrary to the feature requirement that any assigned reviewer opting in should enable the Stamphog review.+- **Suggestion:** Resolve the assigned reviewers separately for the Stamphog path and select an opted-in reviewer, or return the full resolved assignment set and dispatch when `any(user_settings.stamphog_review_inbox_prs for user in assigned_reviewers)` is true. Apply the same selection rule in `resolve_stamphog_acting_reviewer` so later webhook re-reviews remain consistent.+- **Validator:** - **Checked:** `_resolve_assigned_reviewer` and both its consumers (the initial dispatch in `handle_task_run_saved` and the webhook-leg `resolve_stamphog_acting_reviewer`) in the PR diff, plus the added tests in `test_inbox_trigger.py`.+- **Found (premise is factually correct):** `_resolve_assigned_reviewer` returns a single identity — `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` — and the stamphog gate reads `stamphog_review_inbox_prs` off that one user in both the initial-queue and webhook paths. So a report with ≥2 resolved reviewers where the canonical one is opted out but another opted in does skip the stamphog review, contrary to the PR prose's 'any assigned reviewer'.+- **Found (deliberate, tested design cuts against must_fix):** this is a duplicate of the contracts-perspective finding on the same code. The single-acting-reviewer model is documented in the code's own added docstring ('The same resolved acting reviewer carries a second, independent toggle'), mirrors the identical ReviewHog gating, and every added test exercises exactly one reviewer (`_suggest_reviewers(["alice"])` at diff L347/370/383/401). Implementation, docstring, and tests all consistently encode single-reviewer gating — the 'any assigned reviewer' contract lives only in imprecise PR prose, so the mismatch is as likely a description bug as a code bug.+- **Impact:** a real but narrow, reachable gap (an opted-in non-canonical reviewer's preference is ignored) on an experiment-stage draft PR, recoverable on a later push per the webhook re-review path. Not a clear correctness defect that must block merge.+- **Priority:** lowered from `must_fix` to `consider` — the same reasoning as the contracts-perspective duplicate: a genuine intent-vs-implementation discrepancy worth the author reconciling (fix the code or the wording), but plausibly deliberate, narrow in blast radius, and not a must-fix bug.++### [❌ dismissed] should_fix · bug — products/tasks/backend/facade/api.py:501-514++**should_fix: avoid cross-team task-run matches shadowing the valid run**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `find_signal_implementation_run` calls the global `find_task_run` and only checks `run.team_id` after the lookup. If the same GitHub repository is connected to multiple teams, a newer matching run from another team can be selected by the URL or branch lookup, fail the team check, and cause the function to return `None` without considering the valid run belonging to the requested team. This makes inbox reviews nondeterministically disappear in multi-tenant setups.+- **Suggestion:** Apply the team constraint inside the lookup, either by adding a `team_id` parameter to `find_task_run` and filtering both URL and branch legs before ordering, or by querying candidate runs in this facade and continuing past non-matching-team/non-signal runs until the requested team's signal implementation run is found.+- **Validator:** - **Checked:** `find_signal_implementation_run` (facade, diff ~line 1694) and the `find_task_run` it delegates to (`products/tasks/backend/webhooks.py:30-99`), plus the single caller `_inbox_rereview_carve_out`, which always passes both `pr_url=pr.html_url` and `head_branch`.+- **Found:** `find_task_run`'s pr_url leg (`webhooks.py:42-60`) filters `output__pr_url=pr_url` + `task__repository__iexact=repository`. A GitHub PR html_url is globally unique and is recorded on exactly one run (the one that opened/bound it), so no second run in another team shares that `output.pr_url`. The 'newer cross-team run shadows the valid same-team run' mechanism the finding describes has no valid same-team run to shadow — there is at most one run per pr_url binding.+- **Found:** the `run.team_id != team_id` check is a deliberate fail-closed tenant guard (docstring: 'no caller can accidentally bind a PR to another tenant's run'), not a run selector. If the unique run for this PR belongs to another team, returning None is the intended safe outcome.+- **Found:** cross-team candidate collision is possible only in the branch fallback (`webhooks.py:69-79`, unordered `.first()`), which is reached solely when the pr_url leg misses — requiring the same repo connected to multiple teams AND a colliding non-wizard branch AND an unrecorded pr_url simultaneously.+- **Impact:** the primary (pr_url) path — the one always exercised here — cannot exhibit the described shadowing; the branch-fallback variant is a compound, vanishingly rare multi-tenant edge whose worst case is one missed re-review of an experimental toggle-gated feature, recoverable on the next push. This is a speculative never-gonna-happen edge, below the bar.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:111-138++**avoid repeated full resolver work on hot TaskRun saves**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Every qualifying `TaskRun` output save resolves the latest reviewer artefact and organization membership, loads settings, and can enqueue another Stamphog task. TaskRun is a hot model and the receiver intentionally re-fires on unchanged targets, so repeated saves can cause substantial database and broker work even when the PR head has not changed. The downstream task deduplicates only after it fetches GitHub state.+- **Suggestion:** Add a cheap persisted/idempotency watermark for the Stamphog handoff, such as the last queued PR URL/head or a unique pending-handoff record, and skip enqueueing when the target has not changed. Keep the webhook path responsible for new-head re-reviews.+- **Validator:** - **Checked:** the receiver's cheapest-first guard ordering (`handle_task_run_saved`), whether the flagged resolver work is net-new, and the downstream `process_inbox_pr_review` Celery task's dedup path in the PR diff.+- **Found (resolver work is shared, not net-new, and already an accepted re-fire cost):** the `_resolve_assigned_reviewer` + `ReviewUserSettings.load` calls the finding points at (L111–138) are the same resolver the pre-PR ReviewHog leg already ran on every qualifying re-fire — the stamphog leg only adds a boolean `settings.stamphog_review_inbox_prs` check on the already-loaded settings plus one `on_commit` enqueue. The receiver docstring already documents and accepts these re-fires ('Repeat saves with an unchanged target re-fire it deliberately'), and the resolver is gated behind narrow cheapest-first guards (not created, output touched, not FAILED/CANCELLED, has target, signal_report_id set, non-internal) — so it runs only for the one non-internal signal-report implementation task, a tiny slice of TaskRun saves, not the 'hot model' at large.+- **Found (the redundant downstream fetch is inherent, and the re-fire is a deliberate backstop):** the downstream task's own comments state the dedupe 'keys on the PR's current head, which only GitHub knows', so the GitHub fetch must precede dedup — the receiver holds only the PR URL and branch name, never the head SHA. The re-fire-then-fetch is an intentional reliability backstop: 'a refire after a head the webhook leg never delivered — a lost synchronize — still reviews the new commits.'+- **Impact / why it fails the bar:** the suggested receiver-side watermark ('last queued PR URL/head') is unworkable as stated — keying on PR URL would suppress the deliberately-preserved lost-synchronize recovery, and keying on head requires the very GitHub fetch it aims to avoid. The actual cost is bounded (one enqueue + one async GitHub fetch per agent-turn output save, experiment-scoped to opted-in users), runs off the save path in Celery, and correctly no-ops downstream on an unchanged head. This is a deliberate, documented design tradeoff, not an N+1 / unbounded / quadratic hot-path defect — it doesn't meet the performance bar.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:114-138++**Keep the two post-commit dispatches independent**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** These callbacks run in registration order with Django's default `robust=False`. If the ReviewHog callback raises before its internal try block, such as during a deferred import, Django stops executing later commit callbacks and the Stamphog review is never dispatched, even though its toggle is enabled.+- **Suggestion:** Register the callbacks with `robust=True`, or ensure each callback catches all exceptions including deferred imports, so a failure in one product's dispatch cannot suppress the other product's independent review.+- **Validator:** - **Checked:** the two `on_commit` registrations in `handle_task_run_saved` (review leg registered first, stamphog second), the full body of `_start_review` (L164–201, unchanged by this PR), and what can raise before its internal `try`.+- **Found (premise is technically real but has a single, narrow trigger):** the only statements outside `_start_review`'s `try` are its two deferred imports (`from ...temporal.client import start_review_pr_workflow`, `...temporal.types import TRIGGER_INBOX`) plus dict construction from already-bound locals that cannot raise. The Temporal RPC itself is inside the `try`. So the _only_ propagating failure is the deferred import of review_hog's own temporal package. That module is cached in `sys.modules` after the first successful import and can only fail under a systemic deploy/environment breakage (missing temporalio/PyGithub, an activity-registration error in the package `__init__`) — not a transient or per-PR condition.+- **Found (impact coincides with an already-dead feature):** if that import fails, `_start_review` fails for _every_ inbox review in the process — ReviewHog's inbox path is entirely non-functional in that deploy. The finding's added consequence is only 'and the stamphog leg is also suppressed', and only for a user who has _both_ toggles on. It is not an independent loss that occurs in a healthy deploy.+- **Impact / why it fails the bar:** the trigger (the product's own temporal client becoming unimportable at commit time) is practically unreachable in normal operation and, when reachable, is a deploy-wide breakage the on_commit ordering only compounds marginally. This is defensive robustness against a never-gonna-happen edge (guard type per the criteria), not a failure mode that will occur — precision-over-recall says drop. (The `robust=True` suggestion is a cheap, reasonable hardening, but cheapness doesn't lift a practically-unreachable edge over the bar.)++### [❌ dismissed] should_fix · bug — products/tasks/backend/facade/api.py:501-508++**Restrict self-driving matches to active implementation runs**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The branch fallback delegates to `find_task_run`, whose ordinary branch lookup does not exclude terminal or deleted runs. If a self-driving branch name is reused, an unrelated bot PR can match an old completed task run and be treated as a positively identified inbox PR, enabling the webhook carve-out for the wrong task.+- **Suggestion:** Use a dedicated lookup for this facade that filters out terminal and deleted runs, or require an exact PR URL match once a run has recorded one. Do not use stale historical branch runs as proof that the current PR came from a self-driving implementation.+- **Validator:** - **Checked:** `find_signal_implementation_run` → `find_task_run` (`products/tasks/backend/webhooks.py:30-99`), how signals implementation runs set their branch (`products/signals/backend/auto_start.py:269` via `create_and_run_task(..., branch=base_branch)`; `products/tasks/backend/models.py` `create_run`), and the gates in `_inbox_rereview_carve_out`.+- **Found:** signals runs store the BASE branch in the `branch` column (`auto_start.py:269`), not the PR head ref (the agent generates the head branch in-sandbox). So the ordinary branch leg (`filter(branch=head_branch, ...)`, `webhooks.py:69-79`) matches a signals run only if an incoming PR's _head_ ref equals that run's _base_ branch (e.g. a bot PR whose head ref is `master`) — there is no reusable 'self-driving branch name' this leg keys on. The premise of the finding doesn't match how branches are stored.+- **Found:** the pr_url leg (`webhooks.py:42-60`) is the primary, unique matcher; the branch leg is only a pre-URL fallback. And terminal runs are included on purpose — the pr_url leg's comment (`webhooks.py:38-41`) prefers-but-includes terminal runs for same-PR resumes.+- **Found:** the suggested fix (exclude terminal/deleted) would break the intended flow: a signals implementation run reaches COMPLETED as soon as the agent opens the draft PR, yet the still-open PR's later pushes must remain identifiable as self-driving. Excluding terminal runs would drop that common case.+- **Impact:** the described exploit (reused self-driving branch → stale completed run → wrong-task carve-out) is essentially unreachable given base-vs-head branch storage and pr_url precedence; and even a coincidental branch collision is further bounded by the carve-out's prior bot-author + fork-safety + enabled-config gates, so a misidentified PR is at worst a bot-authored, repo-native PR reviewed with stale provenance. Below the bar, and the proposed remedy would regress legitimate re-reviews.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-2.mdnew file mode 100644index 000000000000..279f1c5798ac--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/G-gpt56luna-xhigh-2.md@@ -0,0 +1,301 @@+# Reviewer-quality run — `G-gpt56luna-xhigh-2`++- **Dumped:** 2026-07-30T13:54:38+00:00+- **Report id:** `019fb32c-ae9e-7911-b66c-56f6259d79bc` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 2205s (36.8 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-luna` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 16 | 14 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | -------------- | ----------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 128 | 98,935 | 685,047 | 11,257,165 | 135,422 | 0 | $13.79 | $13.79 |+| gpt-5.6-luna | review | 262 | 12,656,685 | 0 | 0 | 54,937 | 0 | — | $3.34 |+| gpt-5.6-luna | blind-spot | 41 | 2,073,184 | 0 | 0 | 10,859 | 0 | — | $0.49 |+| claude-sonnet-5 | dedup | 1 | 6,560 | 0 | 0 | 1,916 | 0 | $0.03 | $0.03 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 552 | 0 | $0.02 | $0.02 |+| **total** | | **433** | **14,841,345** | **685,047** | **11,257,165** | **203,686** | **0** | **$13.84** | **$17.67** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `gpt-5.6-luna` (303 gen(s), gw $3.83).+- naive method (all prompt tokens at input price): $63.64 — 4.6× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $13.8691 over 433 gen(s) (true $10.4299, Δ +33.0%)+ - · of which cache read: $6.8831 over 377 gen(s) (true $5.6286, Δ +22.3%)+ - · of which cache write: $4.2815 over 116 gen(s) (true $4.2815, Δ +0.0%)+ - · of which fresh (derived): $2.7044 over 433 gen(s) (true $0.5198, Δ +420.3%)+ - output: $3.8050 over 433 gen(s) (true $3.4102, Δ +11.6%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …a0125960 | issues-review-p1-c3 | 13:19:02 | 0 | 0 | gpt-5.6-luna |+| …424a3898 | issues-review-p1-c2 | 13:19:03 | 0 | 0 | gpt-5.6-luna |+| …15f38e00 | issues-review-p1-c1 | 13:19:03 | 0 | 0 | gpt-5.6-luna |+| …cafcd1ee | issues-review-p2-c2 | 13:19:03 | 0 | 0 | gpt-5.6-luna |+| …55b8e044 | issues-review-p3-c2 | 13:19:04 | 0 | 0 | gpt-5.6-luna |+| …4436954b | issues-review-p3-c1 | 13:19:04 | 0 | 0 | gpt-5.6-luna |+| …1bb0d7af | issues-review-p3-c3 | 13:19:04 | 0 | 0 | gpt-5.6-luna |+| …5ff91f72 | issues-review-p2-c3 | 13:19:04 | 0 | 0 | gpt-5.6-luna |+| …eff28a6d | issues-review-p2-c1 | 13:19:08 | 0 | 0 | gpt-5.6-luna |+| …0747fa56 | issues-review-p3-c1 | 13:22:03 | 0 | 0 | gpt-5.6-luna |+| …ffbe675c | issues-review-p1-c1 | 13:22:03 | 0 | 0 | gpt-5.6-luna |+| …051cc66e | issues-review-p2-c1 | 13:22:21 | 0 | 0 | gpt-5.6-luna |+| …0fbcb0b0 | issues-review-p3-c2 | 13:22:22 | 0 | 0 | gpt-5.6-luna |+| …f9939922 | issues-review-p2-c2 | 13:22:22 | 0 | 0 | gpt-5.6-luna |+| …8dece515 | issues-review-p1-c2 | 13:22:22 | 0 | 0 | gpt-5.6-luna |+| …bb5a7f81 | issues-review-p3-c3 | 13:22:23 | 0 | 0 | gpt-5.6-luna |+| …8ac54491 | issues-review-p1-c3 | 13:22:24 | 0 | 0 | gpt-5.6-luna |+| …1a7e764b | issues-review-p2-c3 | 13:22:24 | 0 | 0 | gpt-5.6-luna |+| …1d443697 | issues-review-p3-c3 | 13:25:34 | 0 | 0 | gpt-5.6-luna |+| …34a13a38 | issues-review-p2-c1 | 13:25:36 | 0 | 0 | gpt-5.6-luna |+| …574d2492 | issues-review-p2-c3 | 13:25:36 | 0 | 0 | gpt-5.6-luna |+| …9119acbf | issues-review-p2-c2 | 13:25:37 | 0 | 0 | gpt-5.6-luna |+| …2a312922 | issues-review-p1-c2 | 13:25:38 | 0 | 0 | gpt-5.6-luna |+| …1598c2d7 | issues-review-p1-c3 | 13:25:38 | 0 | 0 | gpt-5.6-luna |+| …11875582 | issues-review-p3-c1 | 13:25:42 | 0 | 0 | gpt-5.6-luna |+| …de2b3850 | issues-review-p3-c2 | 13:25:53 | 0 | 0 | gpt-5.6-luna |+| …5361852b | issues-review-p3-c2 | 13:28:27 | 0 | 0 | gpt-5.6-luna |+| …14c175c2 | issues-review-p1-c3 | 13:28:28 | 0 | 0 | gpt-5.6-luna |+| …82a0212c | issues-review-p2-c2 | 13:28:36 | 0 | 0 | gpt-5.6-luna |+| …1c6c9d6b | issues-review-p1-c2 | 13:28:37 | 0 | 0 | gpt-5.6-luna |+| …b621bd00 | issues-review-p2-c1 | 13:28:37 | 0 | 0 | gpt-5.6-luna |+| …735cffd4 | issues-review-p3-c3 | 13:28:43 | 0 | 0 | gpt-5.6-luna |+| …e4daa5ea | issues-review-p3-c1 | 13:28:56 | 0 | 0 | gpt-5.6-luna |+| …9425465a | blind-spots-c3 | 13:31:37 | 0 | 0 | gpt-5.6-luna |+| …6f2b4074 | blind-spots-c2 | 13:31:38 | 0 | 0 | gpt-5.6-luna |+| …86143e54 | blind-spots-c4 | 13:31:40 | 0 | 0 | gpt-5.6-luna |+| …da2583ec | blind-spots-c1 | 13:36:45 | 0 | 0 | gpt-5.6-luna |+| …9c6b5cd8 | validation-c1 | 13:39:14 | 0 | 37,280 | claude-opus-4-8 |+| …74a9928c | validation-c4 | 13:39:18 | 0 | 36,608 | claude-opus-4-8 |+| …e5adfbfe | validation-c3 | 13:39:20 | 0 | 36,912 | claude-opus-4-8 |+| …f71a1652 | validation-c2 | 13:39:23 | 0 | 37,255 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **0/41** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 7s |+| review wave (perspectives) | 12m 56s |+| blind-spot sweep | 6m 53s |+| dedup (incl. combine/clean) | 18s |+| validation | 15m 58s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 19m 49s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 2 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 1 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 2 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | review-hog-blind-spots-general | 2 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_pr.py:587-590++**Restrict the draft bypass to bot-authored PRs**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The self_driving flag bypasses the draft prerequisite for any PR when enabled, but the intended carve-out is specifically for verified bot-authored Inbox PRs. If a trusted-context construction bug or misassociation sets this flag on a human draft PR, the engine will review and potentially approve it despite draft status.+- **Suggestion:** Derive an effective flag after fetching the PR that requires both trusted self-driving provenance and `pr.author_is_bot`, or fail closed when the flag and author type do not match. Use that effective value consistently for both gate relaxation and prompt provenance.+- **Validator:** - **Checked:** Traced every path that can set `Pipeline.self_driving`. The engine reads it in `review_local.run()` as `self_driving=bool(context.get("self_driving_review"))`, which is stamped in `products/stamphog/backend/temporal/activities.py` (`run_review_in_sandbox`) as `self_driving_review=bool(output.get("inbox_review"))`. So the flag is _only_ ever set when the `ReviewRun` carries inbox provenance, which is written on exactly two paths in `products/stamphog/backend/tasks/tasks.py`.+- **Found:** The webhook re-review path (`_inbox_rereview_carve_out`) hard-gates on author type before it will produce provenance: `if not _is_bot_authored(pr): return _InboxCarveOut()` — a human-authored PR can never receive `inbox_review` provenance there. The initial-review path (`process_inbox_pr_review`) has no explicit bot check but is only invoked via `queue_inbox_pr_review` from review_hog's TaskRun receiver, fed PR URLs from signal-implementation runs, which open PRs as the team's GitHub App machine user (bot) by construction. There is no real input by which a human draft PR reaches the engine with `self_driving=True`.+- **Impact:** The scenario the finding describes is explicitly conditioned on "a trusted-context construction bug or misassociation" — i.e. a hypothetical defect in the upstream provenance-stamping, not a reachable input. The suggested `effective = self_driving and pr.author_is_bot` recheck is a defense-in-depth belt-and-braces guard redundant with the bot-author restriction the parent callers already enforce (webhook explicitly; receiver by task-linkage invariant). Under the validation bar this is a speculative "what if"/defensive-paranoia item guarding against conditions ruled out by validation already in place — precision-over-recall says drop. Note also the bot-author-refusal half of the concern is moot for a human PR: `if self.pr.author_is_bot and not self.self_driving` is already a no-op when `author_is_bot` is False, so the only behavioral change for a hypothetical mis-flagged human PR is the draft gate, and even then a GitHub draft cannot be merged while draft.++### [❌ dismissed] must_fix · bug — products/review_hog/backend/receivers.py:144-158++**Honor the opt-in of any assigned reviewer**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The Stamphog resolver selects the canonical reviewer and checks only that user's `stamphog_review_inbox_prs` toggle. The stated behavior is to run Stamphog when at least one assigned reviewer has opted in, so a canonical reviewer who is opted out currently prevents an eligible assigned reviewer from enabling the review.+- **Suggestion:** Resolve the assigned reviewers once, then select an opted-in reviewer for the Stamphog leg, or add a separate resolver that checks the toggle across all resolved assigned users while preserving the intended acting-user selection for review configuration.+- **Validator:** - **Checked:** The real PR head (`1341596e`, fetched — the working tree was on base `d24a844e` and lacked the changes) for `products/review_hog/backend/receivers.py`, its tests (`tests/test_inbox_trigger.py`), the stamphog webhook consumer (`products/stamphog/backend/tasks/tasks.py`), and the inversion hook (`facade/inbox_hooks.py`).+- **Found:** The single-acting-reviewer model is the deliberate, documented design, not an oversight. `receivers.py` module docstring: "The same resolved acting reviewer carries a second, independent toggle: `stamphog_review_inbox_prs`". `_resolve_assigned_reviewer` returns exactly one `acting.id`, and `handle_task_run_saved` reads BOTH toggles off that one user's `ReviewUserSettings.load(team_id, acting_user_id)`. The webhook re-review path resolves the identical single acting reviewer (`tasks/tasks.py:205` via `get_inbox_acting_reviewer_resolver`), so "any assigned reviewer" is implemented nowhere.+- **Found:** Tests pin the flagged behavior as intended, not buggy. `test_opted_out_canonical_reviewer_blocks_the_review` asserts `mock_start.assert_not_called()` with the comment "a later reviewer's opt-in must not hijack whose options the review runs with" — the exact scenario the issue calls a bug. `test_the_two_toggles_gate_their_reviews_independently` is commented "the two toggles on **the one acting reviewer**." This mirrors the pre-existing `review_inbox_prs` gate (a documented maintainer decision, 2026-07-02/03).+- **Impact:** The issue's premise ("stated behavior is to run Stamphog when at least one assigned reviewer opted in") comes only from loose PR-body prose and is contradicted by the code's docstrings, the webhook leg, and explicit tests. Adopting the suggestion would break the pinned invariant that a non-canonical reviewer's opt-in must not enable a review under a different reviewer's identity. Per the criteria this is a mistaken-premise finding — drop it.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:210-236++**do not silently lose the initial review when queue publishing fails**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** If the broker is unavailable, queue_inbox_pr_review raises before Celery accepts the task, but this helper catches and only logs the exception. Because the PR is bot-authored and draft, the normal Stamphog webhook path will not reliably provide another opportunity to create the initial review, so a transient broker failure can permanently drop the requested review. The task's retry policy cannot help when the task was never enqueued.+- **Suggestion:** Use a durable handoff or outbox/retry mechanism for the initial dispatch, recording the pending review before commit and retrying publication until it is accepted. At minimum, retain a durable pending marker that a later worker can reconcile instead of swallowing the enqueue failure.+- **Validator:** - **Checked:** The real PR head (`1341596e`) `_start_stamphog_review` (`products/review_hog/backend/receivers.py`), the facade `queue_inbox_pr_review` (`facade/api.py:128` — a bare `process_inbox_pr_review.delay()`), and the Stamphog webhook/task path (`products/stamphog/backend/tasks/tasks.py`).+- **Found:** The reviewer's webhook fact is right — the inbox carve-out is deliberately later-deliveries-only (`tasks.py:160`: "the initial review is the receiver leg's job"; `_inbox_rereview_carve_out` returns empty unless action is in `_HEAD_CHANGING_ACTIONS`/base-retarget), so the webhook does not create the initial review. But the "permanent loss" conclusion misses the documented recovery: `process_inbox_pr_review`'s docstring (`tasks.py:1124-1128`) states the durability model — "The receiver re-fires on every TaskRun output save carrying the PR URL, so dedupe keys on the PR's CURRENT head" — so a dropped `.delay()` is re-attempted on the next output save once the broker recovers. The receiver re-fires from two independent `pr_url` writers (`receivers.py:18-19`: the agent server AND the `tasks/webhooks.py` backstop).+- **Found:** The failure is not silently swallowed — it logs a full traceback (`review_hog_stamphog_inbox_review_queue_failed`) — and is the same deliberate fire-and-forget pattern as the sibling `_start_review` Temporal leg (module invariant: broker/Temporal down "must never surface into the saver"), which the reviewer did not flag.+- **Impact:** Permanent loss requires a compound rare scenario: transient broker outage at the exact dispatch AND no subsequent output-save re-fire AND no later head-change webhook. Consequence is a single dropped first-pass approve-first review (still covered by ReviewHog and human review) on an explicitly experimental feature. Per the criteria this is defensive/reliability paranoia against a rare transient failure with documented recovery, and the suggested durable outbox + reconciliation worker is overengineering for the scope — drop.++### [❌ dismissed] should_fix — products/tasks/backend/facade/api.py:500-501++**Apply team scoping inside the signal-run lookup**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `find_signal_implementation_run` calls `find_task_run` without passing `team_id`, then checks the single returned row's team afterward. For branch-based matching, a newer run from another team using the same repository and branch can be returned first, causing the correct self-driving run to be missed. The lookup also scans across tenants unnecessarily, which becomes more expensive as TaskRun volume grows.+- **Suggestion:** Extend `find_task_run` to accept and filter by `team_id` in both its PR URL and branch lookup querysets, and pass the team ID from this facade. Post-filtering the first result is not equivalent to tenant-scoped selection.+- **Validator:** - **Checked:** `find_signal_implementation_run` (products/tasks/backend/facade/api.py:484-516), the delegated `find_task_run` legs (products/tasks/backend/webhooks.py:29-98), TaskRun Meta (`ordering = ["-created_at"]`, models.py), the sole caller `_inbox_rereview_carve_out` (products/stamphog/backend/tasks/tasks.py:144-215), and the tasks webhook backstop `_record_run_pr_url` (webhooks.py:184-185, 203-213).+- **Found:** The branch leg (webhooks.py:64-76) is genuinely un-team-scoped and `.first()` returns newest-first, so the ordering premise is technically accurate. But the only caller invokes this exclusively on synchronize/reopen/base-retarget (tasks.py:167) and always passes `pr_url=pr.get("html_url")` (tasks.py:194). The pr_url leg filters on a globally-unique GitHub PR URL and runs first; the tasks backstop stamps `output.pr_url` on the initial `opened` delivery (webhooks.py:184), so on the later deliveries this carve-out actually handles, the pr_url leg resolves the run and the branch leg is not reached.+- **Found:** The cross-tenant _binding_ risk is already closed — api.py:505 returns None on `run.team_id != team_id`, so no other tenant's run can ever be bound. The only residual effect is a false negative (a skipped re-review), and it requires the branch leg to be hit AND two teams configured against the same GitHub repo AND both holding a TaskRun row with the _identical_ head-branch string. Self-driving branches are unique machine-generated names and a real PR head maps to a single git branch, so this collision is practically unreachable.+- **Impact:** Speculative, practically-unreachable edge case with low blast radius (one skipped re-review delivery, no data/security exposure). The performance angle also fails the "bites at real scale" bar: the branch leg already filters on the selective `branch`+`repository__iexact`, the pr_url leg on a unique value, and both run only on infrequent PR webhook deliveries — no N+1, unbounded scan, or hot path. Per precision-over-recall, this is a drop.++### [❌ dismissed] should_fix · performance — tools/pr-approval-agent/review_pr.py:202-209++**skip familiarity computation for self-driving bot PRs**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Enabling the self-driving path now allows bot-authored PRs to reach `_maybe_compute_familiarity()`, which performs a GitHub CLI request plus multiple bounded git operations. This work is unnecessary for machine authors, and the prompt explicitly says author familiarity carries no signal. It adds avoidable latency and can consume the review job's retry/time budget on every Inbox review.+- **Suggestion:** Short-circuit familiarity for self-driving reviews, for example by returning from `_maybe_compute_familiarity()` when `self.self_driving` is true, and apply the same condition in `review_local._attach_familiarity()` so both execution paths remain consistent.+- **Validator:** - **Checked:** How self-driving inbox reviews actually execute and whether they reach `_maybe_compute_familiarity()`. Traced both engine entrypoints — `review_pr.py::Pipeline.run()` (Action path) and `review_local.py::run()` (hosted sandbox path) — plus how `author_pr_numbers` is populated for inbox runs in `products/stamphog/backend/temporal/activities.py`.+- **Found:** Self-driving reviews run in the tokenless sandbox via `review_local.run()`, which does NOT call `Pipeline.run()` and never calls `_maybe_compute_familiarity()`. It calls `_attach_familiarity(pipeline, context)` (`review_local.py:348`), which short-circuits before any git work: `raw_prs = context.get("author_pr_numbers"); if not raw_prs: return` (`review_local.py:301-303`). The PR's own activities.py change sets `author_pr_numbers = ... if author and not is_inbox_review else []` — an empty list for every inbox review — so `_attach_familiarity` returns immediately with no `git blame`/`git log`.+- **Found:** The 'GitHub CLI request' the finding cites lives in `compute_familiarity`/`_fetch_author_pr_numbers`, reachable only via `Pipeline._compute_familiarity` on the Action path. The sandbox uses `_familiarity_offline` (injected PR numbers, zero `gh` calls), and `review_pr.py::main()` builds `Pipeline(..., dry_run=..., verbose=...)` with no `self_driving` argument (`review_pr.py:966`), so `Pipeline.run()` with `self_driving=True` occurs only in tests, never in the production inbox flow.+- **Impact:** The premise is mistaken on all counts: inbox reviews never hit `_maybe_compute_familiarity()`, issue no `gh` request in the sandbox, and their bounded git operations are already skipped because the server hands in an empty `author_pr_numbers`. The suggested short-circuit duplicates work the code already avoids, so there is no avoidable latency or retry/time-budget cost — 'wrong/unreproducible' and 'already handled elsewhere' → drop.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:1-17++**Use the next unique migration number**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** ReviewHog already has a different `0019_reviewreport_author_login_and_more` migration, so adding another `0019` creates a migration-name collision. The migration checks and `max_migration.txt` will also become inconsistent, preventing reliable migration execution and CI validation.+- **Suggestion:** Rename this migration to the next available number and update its dependency and `products/review_hog/backend/migrations/max_migration.txt` to match.+- **Validator:** - **Checked:** The review_hog migrations directory on both the PR head (`FETCH_HEAD`) and `origin/master`, plus both `0019` files' `dependencies` blocks and each side's `max_migration.txt`.+- **Found:** `origin/master` already ships `0019_reviewreport_author_login_and_more.py`, dependency `0018_backfill_urgency_threshold_to_consider`, and `max_migration.txt` = `0019_reviewreport_author_login_and_more`. The PR adds `0019_reviewusersettings_stamphog_review_inbox_prs.py` (`migrations/0019_...py:7-9`), which also depends on `0018...`, with `max_migration.txt` = `0019_reviewusersettings_stamphog_review_inbox_prs`. The branch is stale — it forked at `0018` and master gained its own `0019` afterward.+- **Found:** Two migrations numbered `0019` both rooted on `0018` create two leaf nodes in the review_hog graph → Django errors 'Conflicting migrations detected; multiple leaf nodes in the migration graph' and `makemigrations --check` fails; the single-line `max_migration.txt` values collide on merge, which PostHog's migration-lint CI check catches.+- **Impact:** After merge/rebase onto master, migrations cannot run and CI migration validation fails until the file is renumbered (e.g. `0020_...`), its dependency repointed to `0019_reviewreport_author_login_and_more`, and `max_migration.txt` updated. Concrete trigger and consequence both confirmed — a real contract/build break; `must_fix` stands.++### [❌ dismissed] must_fix — products/stamphog/backend/tasks/tasks.py:25-25++**Register the inbox reviewer resolver**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The webhook carve-out calls `get_inbox_acting_reviewer_resolver()`, but the repository contains no registration of a resolver via `register_inbox_acting_reviewer_resolver`. Consequently, the resolver is always `None`, so every synchronize/reopen/base-retarget delivery fails closed and self-driving inbox PRs are never re-reviewed after their initial review.+- **Suggestion:** Register `review_hog.backend.receivers._resolve_acting_reviewer` from `ReviewHogConfig.ready()` (or expose a dedicated registration function), and add an integration test proving that a qualifying inbox PR's synchronize event queues a new review.+- **Validator:** - **Checked:** the full registration chain the issue claims is missing — `get_inbox_acting_reviewer_resolver`/`register_inbox_acting_reviewer_resolver` (products/stamphog/backend/facade/inbox_hooks.py:24-33), every caller of the registration function repo-wide, `ReviewHogConfig.ready()` (products/review_hog/backend/apps.py:9-13), `receivers.connect()` (products/review_hog/backend/receivers.py:58-69), and INSTALLED_APPS.+- **Found:** the resolver IS registered. `ReviewHogConfig` is installed (posthog/settings/web.py:76); its `ready()` calls `receivers.connect()` (apps.py:13); `connect()` calls `register_inbox_acting_reviewer_resolver(resolve_stamphog_acting_reviewer)` (receivers.py:69), and `resolve_stamphog_acting_reviewer` is defined at receivers.py:144. So by app-ready `get_inbox_acting_reviewer_resolver()` returns a real callable, not `None`. This is exactly the wiring the suggestion asks to add — it already exists (registered from `connect()` rather than inline in `ready()`, which is equivalent). The `noqa`-free import at receivers.py:53 is deliberately import-light to avoid the dependency cycle the carve-out docstring describes.+- **Found:** the premise 'self-driving inbox PRs are never re-reviewed' does not hold — the fail-closed `resolver is None` branch (tasks.py:202-204) is only taken when review_hog is absent, which is not the deployed configuration.+- **Impact:** the finding is Wrong/unreproducible per the drop criteria — investigating the actual code shows the claimed bug does not exist. The secondary 'add an integration test' ask cannot carry the finding on its own (the test file already references the resolver slot at products/stamphog/backend/tests/test_tasks.py:30), and a missing-test nit does not meet the keep bar when the alleged must_fix bug is not real.++### [❌ dismissed] should_fix · documentation — products/stamphog/AGENTS.md:85-85,106-106++**Use the actual ReviewHog setting key**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The documented toggle is `stamphog_review_inbox_prs`, but the ReviewHog model and API expose the setting as `review_inbox_prs`. This name mismatch can lead implementers to query or add a nonexistent setting and makes the carve-out contract inaccurate.+- **Suggestion:** Replace `stamphog_review_inbox_prs` with the canonical `review_inbox_prs` field/API key, optionally describing it as the Stamphog inbox-review toggle in prose.+- **Validator:** - **Checked:** The claim that `stamphog_review_inbox_prs` is a nonexistent setting and that the canonical key is `review_inbox_prs`. Traced the PR diff across the model, serializer, migration, receivers, and frontend, plus the existing `review_inbox_prs` usages on `master`.+- **Found:** This PR _introduces_ `stamphog_review_inbox_prs` as a distinct new field, coexisting with the older `review_inbox_prs`. Both are declared on the same model: `products/review_hog/backend/models.py` keeps `review_inbox_prs = models.BooleanField(...)` and adds `stamphog_review_inbox_prs = models.BooleanField(default=False, db_default=False)`. The serializer exposes both (`products/review_hog/backend/api/settings.py` fields list gains `stamphog_review_inbox_prs`), migration `0019_reviewusersettings_stamphog_review_inbox_prs.py` creates the column, and the frontend/generated types (`CodeReviewScene.tsx`, `api.schemas.ts`, `api.zod.ts`) all carry it. The Stamphog gate keys on the new field: `receivers.py` uses `ReviewUserSettings.load(...).stamphog_review_inbox_prs`.+- **Found:** The two toggles are deliberately independent, asserted by tests: `test_inbox_trigger.py` parameterizes `stamphog_only` ({stamphog_review_inbox_prs: True} → stamphog runs, review_hog doesn't), `review_hog_only` ({review_inbox_prs: True} → the reverse), and a comment states "keying on review_inbox_prs would re-review for users who never opted into stamphog." The AGENTS.md carve-out text ("opted in via ReviewHog's per-user `stamphog_review_inbox_prs` toggle") is precisely correct — it is a ReviewHog per-user setting named `stamphog_review_inbox_prs`.+- **Impact:** The finding's premise is mistaken (Wrong/unreproducible). Applying the suggested fix — replacing `stamphog_review_inbox_prs` with `review_inbox_prs` — would document the wrong gate and contradict the code and tests, turning correct documentation into a regression. Does not meet the bar.++### [❌ dismissed] should_fix · documentation — products/stamphog/README.md:15-15++**Document an entry point that exists in the repository**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The README identifies `queue_inbox_pr_review` as the facade entry point, but no such function or symbol exists in the repository; the current inbox receiver calls `start_review_pr_workflow` directly. This leaves the documented integration path unusable for maintainers trying to trace or invoke it.+- **Suggestion:** Update the documentation to reference the actual facade/function and module path introduced by the implementation, or add and export `queue_inbox_pr_review` if that facade is part of the intended contract.+- **Validator:** - **Checked:** Whether `queue_inbox_pr_review` exists as a facade symbol and whether the inbox receiver calls `start_review_pr_workflow` directly instead, as the finding claims. Traced the PR diff for the definition, the import, the call site, and both symbols.+- **Found:** `queue_inbox_pr_review` is a real function defined by this PR in `products/stamphog/backend/facade/api.py` (`def queue_inbox_pr_review(*, team_id, pr_url, acting_user_id, signal_report_id, task_run_id)`), which delegates to the `process_inbox_pr_review` Celery task. The inbox receiver `_start_stamphog_review` in `products/review_hog/backend/receivers.py` imports it (`from products.stamphog.backend.facade.api import queue_inbox_pr_review`) and calls `queue_inbox_pr_review(...)`. The README's `queue_inbox_pr_review` reference is therefore accurate and traceable.+- **Found:** The finding conflates two distinct legs. `start_review_pr_workflow` is the ReviewHog leg (`_START = "products.review_hog.backend.temporal.client.start_review_pr_workflow"`, used by `_start_review`); the Stamphog inbox leg is a separate path that goes through `queue_inbox_pr_review` (`_STAMPHOG_QUEUE = "products.stamphog.backend.facade.api.queue_inbox_pr_review"`, used by `_start_stamphog_review`). They are not substitutes for each other. Tests in `test_inbox_trigger.py` patch each target independently.+- **Impact:** Premise is mistaken (Wrong/unreproducible) — the symbol exists, is imported and invoked, and the documented integration path is usable. The likely cause is that the reviewer searched a checkout without the PR's new files (the facade and receiver additions live in files this PR creates/modifies). Does not meet the bar.++### [❌ dismissed] should_fix · bug — products/review_hog/backend/receivers.py:111-115++**Honor the any-assignee Stamphog opt-in contract**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The receiver resolves a single canonical acting reviewer and checks only that user's Stamphog toggle. This means an Inbox PR assigned to multiple reviewers is skipped when the canonical reviewer has opted out, even if another assigned reviewer has opted in, contradicting the stated behavior that Stamphog runs when at least one assigned user enables it. The later webhook recheck uses the same single-user selection, so the mismatch persists on subsequent pushes.+- **Suggestion:** Resolve the full assigned reviewer set for the report, select an opted-in reviewer for the Stamphog leg when any exists, and pass that user to the queue/recheck path. Keep the existing canonical reviewer selection for the ReviewHog leg if its semantics must remain unchanged.+- **Validator:** - **Checked:** Re-confirmed against the PR head (`1341596e`): `_resolve_assigned_reviewer` (`receivers.py` — returns one `acting.id`), the two-toggle dispatch in `handle_task_run_saved`, the module docstring, `resolve_stamphog_acting_reviewer`, the webhook consumer `_inbox_rereview_carve_out` (`products/stamphog/backend/tasks/tasks.py`), and `tests/test_inbox_trigger.py`.+- **Found:** The single-acting-reviewer model is the deliberate, documented, test-pinned design, not a contract break. `receivers.py` module docstring: "The same resolved acting reviewer carries a second, independent toggle: `stamphog_review_inbox_prs`". `test_opted_out_canonical_reviewer_blocks_the_review` asserts the review does NOT run when the canonical reviewer is opted out (comment: "a later reviewer's opt-in must not hijack whose options the review runs with") — the exact scenario this finding calls a bug is the pinned intended behavior; `test_the_two_toggles_gate_their_reviews_independently` is commented "the two toggles on the one acting reviewer."+- **Found:** The added sub-claim — the webhook recheck reuses the single-user selection — is true but by design: `resolve_stamphog_acting_reviewer` wraps `_resolve_assigned_reviewer` ("Same acting-reviewer resolution as this module's own trigger"), so the initial and re-review legs intentionally agree on one acting reviewer. No "any assigned reviewer" path exists anywhere.+- **Impact:** The "at least one assigned user" contract lives only in loose PR-body prose, contradicted by the code's docstrings, the webhook leg, and explicit tests — so there is no real security/contract defect. This is the same mistaken-premise finding as issue `2-1-1` under a different perspective; adopting the suggestion would break the pinned invariant. Drop, consistent with the prior duplicate.++### [❌ dismissed] must_fix — products/stamphog/backend/tasks/tasks.py:1107-1245++**Validate the PR is actually the linked self-driving run**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial inbox task trusts `pr_url`, `signal_report_id`, and `task_run_id` supplied by the receiver, but never verifies that the fetched PR is repo-native, bot-authored, or actually linked to that specific signals implementation run. Any task output that contains an arbitrary PR URL could therefore trigger the inbox carve-out on an existing human or fork PR and bypass the normal bot, draft, author-association, and write-permission gates, potentially posting an automatic approval.+- **Suggestion:** After fetching the PR, enforce the same positive-identification checks as the webhook carve-out: require `head.repo.full_name` to match the configured repository, require the PR author to be the expected bot, and resolve the tasks facade by `team_id`, repository, and PR URL, rejecting unless its run ID and signal report ID match the task arguments. Ideally validate the task linkage before creating the `ReviewRun`, and only stamp `inbox_review` after all checks pass.+- **Validator:** - **Checked:** the full reachability chain into `process_inbox_pr_review` — its sole trigger `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review` (products/review_hog/backend/receivers.py:98-139), every writer of `output.pr_url` in tasks (products/tasks/backend/webhooks.py:184-212), the repo-config gate inside the task (products/stamphog/backend/tasks/tasks.py:1138-1153), and the engine's self-driving flag wiring (products/stamphog/backend/temporal/activities.py:237-238,448-451).+- **Found:** the args the issue calls attacker-influenced are read off the triggering TaskRun itself. `handle_task_run_saved` only fires the stamphog leg for a run that is non-internal (receivers.py:104) and carries a signal report (receivers.py:98), and passes that run's OWN `output.pr_url` (receivers.py:93,130) with its own id/report (receivers.py:136-137). So the PR→run linkage is inherent in the trigger — the receiver leg starts from the verified run, unlike the webhook leg which must match an arbitrary inbound PR back to a run (why only the webhook leg needs `find_signal_implementation_run` + fork/bot checks).+- **Found:** `output.pr_url` is not attacker-controllable to point at a foreign PR. The webhook backstop that writes it (`_record_run_pr_url`) fires only on a repo-native match (`is_internal_branch`, webhooks.py:184), so a fork PR (head repo ≠ base) can never be recorded; the agent server records the bot's own opened PR. There is no external/untrusted write path to a signal-report run's `output`.+- **Found:** even granting a wrong URL, `process_inbox_pr_review` requires an enabled `StamphogRepoConfig` for `team_id` + the parsed repo (tasks.py:1140-1153), bounding any review to repos the team already controls; and the engine comment (activities.py:448-451) plus the receiver docstring ('bot-authored draft by construction', tasks.py:1116-1118) show the self-driving relaxation is a documented, intentional trust assumption resting on this invariant.+- **Impact:** dismissal — the 'arbitrary/fork PR bypass' is a speculative what-if that depends on a condition (attacker-set foreign `output.pr_url` on a non-internal signal-report run) the call sites and the repo-native write gate already rule out. The suggested fork/bot/facade re-checks are defensive redundancy over an upstream invariant the code upholds, which the precision-over-recall bar drops.++### [❌ dismissed] must_fix · code_quality — tools/pr-approval-agent/review_local.py:321-321++**Require a strict boolean for the self-driving flag**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `bool(context.get("self_driving_review"))` treats any non-empty value, including the string `"false"`, as `True`. A malformed or differently serialized context can therefore enable both relaxed gates and the trusted provenance prompt instead of defaulting closed as intended.+- **Suggestion:** Only enable the carve-out when the value is the JSON boolean `true`, for example `self_driving=context.get("self_driving_review") is True`; optionally reject other non-boolean values explicitly.+- **Validator:** - **Checked:** The producer of `context["self_driving_review"]` and the serialization path to `review_local.run()`. Traced `activities.py::run_review_in_sandbox` → `logic/reviewer.py::build_reviewer_invocation` → the JSON context file the engine reads via `json.loads`.+- **Found:** The value is a genuine Python `bool` at every hop: `activities.py` sets `self_driving_review=bool(output.get("inbox_review"))`; `build_reviewer_invocation(self_driving_review: bool = False)` (diff `logic/reviewer.py:767`) is typed `bool` and stores it verbatim in the context dict (`"self_driving_review": self_driving_review`, diff line 787). That dict is JSON-serialized to the context file and read back in `review_local.main()`, so `context.get("self_driving_review")` is only ever `True`, `False`, or `None` (absent). `bool(True)/bool(False)/bool(None)` are all correct.+- **Found:** The context file is written by the trusted hosted server, not the PR author — it is not attacker-controlled input. `json.dumps(False)` emits the JSON literal `false`, which `json.loads` restores to Python `False`, never the string `"false"`. No code path serializes this flag as a quoted string.+- **Impact:** The `bool("false") == True` scenario the finding relies on cannot occur given the typed-bool producer and JSON round-trip; for every input the real pipeline produces, `bool(x)` and `x is True` are identical. The suggestion is a marginal defensive hardening against a hypothetical malformed producer, not a fix for a reachable defect — speculative what-if ruled out by the types in place → drop.++### [❌ dismissed] should_fix · performance — products/review_hog/backend/receivers.py:114-138++**avoid dispatching duplicate Stamphog jobs for every output save**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Every TaskRun save that includes output can enqueue another Stamphog task, even when the PR URL has not changed. The queued task then fetches the PR from GitHub before deduplicating by its current head, so frequent agent/output saves can create redundant Celery work and GitHub API requests for the same PR.+- **Suggestion:** Coalesce dispatches before enqueueing, for example with a short-lived per-task-run/PR idempotency key or persisted last-dispatched target. Keep a bounded reconciliation path for missed synchronize webhooks rather than fetching and queueing on every unchanged output save.+- **Validator:** - **Checked:** `handle_task_run_saved`'s Stamphog dispatch guard + docstring in `receivers.py` (PR head `1341596e`) and the full `process_inbox_pr_review` body in `products/stamphog/backend/tasks/tasks.py:1110-1245` — fetch/dedupe ordering and where the sandbox workflow actually starts.+- **Found:** The reviewer's facts hold but the cost is bounded. The fetch runs before dedupe by necessity — code comment (`tasks.py:~1155`): "The fetch runs before the dedupe because the dedupe keys on the PR's current head, which only GitHub knows." But the expensive work is deduped: a head-keyed `select_for_update` lookup (`tasks.py:~1200`) returns a no-op when a live/delivered `ReviewRun` already exists at that `head_sha`; only a new head supersedes + creates + starts the workflow. So a same-head re-fire costs one `get_pr` + a couple of DB queries, not a redundant review.+- **Found:** This is deliberate and documented. `handle_task_run_saved` docstring: repeat saves "re-fire it deliberately" and "a same-head re-trigger costs one fetch (early-exit)"; `process_inbox_pr_review` docstring: "The receiver re-fires on every TaskRun output save carrying the PR URL, so dedupe keys on the PR's CURRENT head... a refire after a head the webhook leg never delivered — a lost synchronize — still reviews the new commits." The re-fire-and-fetch IS the missed-synchronize reconciliation the reviewer's suggestion says to keep.+- **Found:** The proposed pre-enqueue coalesce conflicts with the design and is largely infeasible: keying on PR URL / task_run would suppress legitimate re-reviews of new commits on the same PR, and the receiver can't cheaply know the head to dedupe on it — `TaskRun.output` carries `pr_url`/`head_branch`, not the commit SHA (the reason the fetch exists).+- **Impact:** Residual waste is a bounded `get_pr` + DB queries per same-head re-save on a low-volume, opt-in-only self-driving-PR flow — no N+1/quadratic/hot-path behavior, the costly sandbox path is already deduped, and the cheap-coalesce remedy would break the documented recovery. Does not meet the at-scale performance bar — drop.++### [✅ VALID] must_fix (validator→should_fix) · bug — products/stamphog/backend/tasks/tasks.py:1190-1207++**Prevent concurrent receiver tasks from creating duplicate reviews**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The `select_for_update()` is applied to `ReviewRun` rows after filtering by `head_sha`. When no run exists yet, the query locks nothing, so two receiver tasks fired concurrently for the same PR head can both observe no existing run, create separate queued runs, and start duplicate Temporal/LLM reviews.+- **Suggestion:** Serialize on the `PullRequest` row before checking for an existing head, or add a database uniqueness constraint on `(pull_request, head_sha)` and handle the resulting `IntegrityError` by resuming the winner. This should also prevent duplicate workflow starts under concurrent TaskRun output events.+- **Validator:** - **Checked:** the `ReviewRun` model's constraints (products/stamphog/backend/models.py:140-173), `_upsert_pull_request`'s locking (tasks.py:319-363), `_supersede_prior_runs` (tasks.py:415-432), `_start_review_workflow`'s id derivation (tasks.py:366-380), the trigger fan-out in `handle_task_run_saved` (products/review_hog/backend/receivers.py:82-139), and the `delivery_id` dedup path.+- **Found:** the flagged gap is real and nothing else closes it. `ReviewRun` has no `Meta.constraints` (models.py:140-173) — no `(pull_request, head_sha)` uniqueness — and its only unique column `delivery_id` is set to `None` on this leg (tasks.py:1227), so with Postgres allowing multiple NULLs the duplicate `create()` (tasks.py:1223) raises nothing. `_upsert_pull_request` uses `get_or_create` with no row lock (tasks.py:339), and `select_for_update().filter(pull_request=..., head_sha=...)` (tasks.py:1202) plus `_supersede_prior_runs` (tasks.py:424) lock nothing when neither run's row exists yet — the 'row lock serializes racing fires' comment (tasks.py:1198-1199) only holds once a row exists.+- **Found:** the two runs get distinct `review_run_id`s, and `_start_review_workflow` derives the Temporal workflow id from `review_run_id` (tasks.py:369), so both workflows start — no Temporal-level dedup.+- **Found:** concurrency is expected, not exotic — the receiver re-fires on every TaskRun output save carrying the PR URL (docstring tasks.py:1125; receivers.py:126-139 enqueues per save), and the slow `get_pr` sits outside the transaction (tasks.py:1158-1159), so two tasks tend to reach the short critical section together.+- **Impact:** two QUEUED runs → two sandbox/LLM reviews for the same head → wasted LLM cost and GitHub load, and possibly a duplicate non-approve comment. This meets the 'race condition / reliability defect' keep bar.+- **Priority:** lowered to should_fix — `post_verdict` adopts an existing head-pinned APPROVE rather than stacking a second (stamphog CLAUDE.md), so a double approval is prevented and the stale-approval invariant is not violated; the blast radius is duplicate work plus a possible duplicate comment, not data corruption, and the window is the short transaction.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-1.mdnew file mode 100644index 000000000000..9edf6e49a512--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-1.md@@ -0,0 +1,183 @@+# Reviewer-quality run — `H-gpt56terra-xhigh-1`++- **Dumped:** 2026-07-30T13:16:49+00:00+- **Report id:** `019fb301-3383-7655-8707-db3c6a298dec` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 2784s (46.4 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-terra` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 9 | 8 | 6 | 3 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ----------- | ---------- | --------- | ---------- |+| claude-opus-4-8 | validation | 81 | 87,071 | 493,009 | 6,824,774 | 76,279 | 0 | $8.84 | $8.84 |+| gpt-5.6-terra | review | 103 | 5,189,563 | 0 | 0 | 30,181 | 0 | — | $4.08 |+| gpt-5.6-terra | blind-spot | 35 | 1,953,506 | 0 | 0 | 12,481 | 0 | — | $1.38 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 1,234 | 0 | $0.02 | $0.02 |+| claude-sonnet-5 | dedup | 1 | 5,646 | 0 | 0 | 765 | 0 | $0.02 | $0.02 |+| gpt-5.6-terra | other | 41 | 0 | 0 | 0 | 0 | 0 | — | $0.00 |+| **total** | | **262** | **7,241,767** | **493,009** | **6,824,774** | **120,940** | **0** | **$8.88** | **$14.34** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.6-terra` (179 gen(s), gw $5.47).+- naive method (all prompt tokens at input price): $38.97 — 4.4× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $11.7777 over 262 gen(s) (true $6.9523, Δ +69.4%)+ - · of which cache read: $4.8604 over 197 gen(s) (true $3.4124, Δ +42.4%)+ - · of which cache write: $3.0813 over 81 gen(s) (true $3.0813, Δ +0.0%)+ - · of which fresh (derived): $3.8360 over 262 gen(s) (true $0.4586, Δ +736.4%)+ - output: $2.5669 over 262 gen(s) (true $1.9270, Δ +33.2%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …1112e67a | issues-review-p3-c3 | 12:31:42 | 0 | 0 | gpt-5.6-terra |+| …d805036a | issues-review-p2-c3 | 12:31:43 | 0 | 0 | gpt-5.6-terra |+| …b5f39c1d | issues-review-p2-c1 | 12:31:44 | 0 | 0 | gpt-5.6-terra |+| …fbcb0a3f | issues-review-p3-c2 | 12:31:45 | 0 | 0 | gpt-5.6-terra |+| …79cace11 | issues-review-p1-c1 | 12:31:48 | 0 | 0 | gpt-5.6-terra |+| …355c2238 | issues-review-p2-c2 | 12:31:51 | 0 | 0 | gpt-5.6-terra |+| …491fb939 | issues-review-p1-c3 | 12:31:54 | 0 | 0 | gpt-5.6-terra |+| …f6cb2e26 | issues-review-p1-c2 | 12:31:56 | 0 | 0 | gpt-5.6-terra |+| …079f41ae | issues-review-p2-c3 | 12:34:50 | 0 | 0 | gpt-5.6-terra |+| …4f219b0a | issues-review-p1-c3 | 12:34:50 | 0 | 0 | gpt-5.6-terra |+| …f491a6e3 | issues-review-p3-c2 | 12:34:52 | 0 | 0 | gpt-5.6-terra |+| …64f5746a | issues-review-p1-c2 | 12:34:52 | 0 | 0 | gpt-5.6-terra |+| …68e02878 | issues-review-p2-c2 | 12:34:57 | 0 | 0 | gpt-5.6-terra |+| …00546152 | issues-review-p2-c1 | 12:34:58 | 0 | 0 | gpt-5.6-terra |+| …04e9772e | issues-review-p3-c3 | 12:35:03 | 0 | 0 | gpt-5.6-terra |+| …39a69252 | issues-review-p1-c1 | 12:35:05 | 0 | 0 | gpt-5.6-terra |+| …588c1e67 | blind-spots-c2 | 13:02:47 | 0 | 0 | gpt-5.6-terra |+| …1678c58f | blind-spots-c3 | 13:02:49 | 0 | 0 | gpt-5.6-terra |+| …a40b2d88 | blind-spots-c1 | 13:02:50 | 0 | 0 | gpt-5.6-terra |+| …63284cfc | blind-spots-c4 | 13:02:51 | 0 | 0 | gpt-5.6-terra |+| …6a250cb6 | validation-c4 | 13:04:56 | 17,141 | 19,423 | claude-opus-4-8 |+| …5c4f7432 | validation-c3 | 13:04:56 | 0 | 36,883 | claude-opus-4-8 |+| …5ff42468 | validation-c2 | 13:04:58 | 17,141 | 20,142 | claude-opus-4-8 |+| …fda5d326 | validation-c1 | 13:05:03 | 17,141 | 20,197 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **3/24** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 15s |+| review wave (perspectives) | 6m 10s |+| blind-spot sweep | 27m 08s |+| dedup (incl. combine/clean) | 9s |+| validation | 11m 58s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 33m 19s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 1 |+| 3 | 3 | ? | 0 |+| 1000 | 1 | review-hog-blind-spots-general | 2 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | review-hog-blind-spots-general | 1 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] consider · documentation — products/stamphog/README.md:14++**Remove the em dash from user-facing documentation**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new README copy uses an em dash before `gated by`. Repository copy guidance applies to docs and explicitly disallows em dashes, so this adds text that violates the documented writing standard.+- **Suggestion:** Split this into two sentences or use a colon, for example: "ReviewHog's inbox receiver calls the `queue_inbox_pr_review` facade. The acting reviewer's per-user `stamphog_review_inbox_prs` setting gates it."+- **Validator:** - **Checked:** the review-hog-validation-criteria skill (v1), the current `products/stamphog/README.md`, and whether a documentation em dash clears the ReviewHog bar.+- **Found:** The criteria enumerate "Pure style / taste — naming, formatting, comment wording ... with no behavioral difference. (Formatting is not a ReviewHog concern.)" as an explicit drop. This finding is an em dash before `gated by` in a README — zero correctness/security/data-loss/contract/performance/reliability impact, and no concrete trigger→consequence can be named (the skill's keep test).+- **Found:** The README is already written with em dashes as its house style: `README.md:3` ("approval**— not just comments"), `:9` ("Action** — runs"), `:10` ("Hosted\*\* ... — a GitHub App"), plus `:12`/`:20`. Flagging one em dash while the whole document uses them is inconsistent style noise, and this is developer-facing docs, not user-facing product copy.+- **Impact:** No user or codebase effect; keeping it is exactly the style noise the skill's precision-over-recall rule says to suppress. Drop.++### [❌ dismissed] must_fix · security — products/stamphog/backend/tasks/tasks.py:1107-1245++**Validate the initial inbox review against the actual task run and PR**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial-review task treats its queued `team_id`, `pr_url`, `signal_report_id`, `task_run_id`, and `acting_user_id` as trusted provenance. It only resolves a configured repository and fetches an open PR; it never verifies that the supplied run is the matching non-internal signal implementation run, that its signal report matches, or that the fetched PR is bot-authored with a repo-native head. Consequently, a task output containing an arbitrary PR URL for a configured repository can create a run stamped `inbox_review`, which makes the engine bypass its normal bot/draft, review-mode, and write-permission gates. This defeats the stated positive-identification boundary, including the fork-safety protection present on the webhook path.+- **Suggestion:** Before creating the run, resolve the task through the tasks facade and require its ID, team, signal report, and repository to match the queued values. Fetch the PR first and require its head repository to equal the configured repository and its author to be the expected bot. Re-resolve the current opted-in reviewer at execution time (rather than trusting the queued user ID), and only stamp `inbox_review` after all of these checks pass.+- **Validator:** - **Checked:** the full caller chain into `process_inbox_pr_review` — `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review` (products/review_hog/backend/receivers.py), how `output.pr_url` is bound (products/tasks/backend/webhooks.py:221-227, metrics.py:344), and the webhook carve-out's checks (products/stamphog/backend/tasks/tasks.py:887-895).+- **Found:** the queued `team_id`/`signal_report_id`/`task_run_id`/`acting_user_id` are read straight off the saving `TaskRun` in `handle_task_run_saved`, which dispatches only after gating `task.signal_report_id is not None`, `not task.internal`, and an opted-in resolved reviewer. They are the identity of the very run that triggered the save, dispatched in-process by review_hog — not values a caller could forge — so 're-verify the run/signal report matches' guards nothing (the receiver leg doesn't even gate on them; they are stamped as provenance only).+- **Found:** `output.pr_url` is recorded by the trusted agent server observing the bot open its PR (webhooks.py:221-227), with a branch+repo webhook match as the only backstop. Self-driving PRs are bot-authored on repo-native branches by construction, so the fetched PR in the honest flow already satisfies `_is_bot_authored` and head-repo==base — the checks the finding wants are redundant with reality there.+- **Found:** the webhook leg re-checks bot-authorship + fork-safety because it starts from an _untrusted arbitrary PR event_ and must positively identify it; the receiver leg starts from a _trusted run save_ and reuses that run's own recorded URL. The finding conflates the two trust models.+- **Impact:** for the receiver leg to review a fork/human PR with gates bypassed, `output.pr_url` on a non-internal signal-report run would have to point at an attacker-beneficial PR. External actors cannot set that field on a victim team's run, and the observation-based binding ties it to a bot-opened repo-native PR; the remaining path is compromising PostHog's own internal implementation agent. That is a speculative internal-compromise / defense-in-depth 'what-if,' not a reachable exploit given the call sites — below the keep bar (precision over recall).++### [✅ VALID] must_fix (validator→should_fix) · security — tools/pr-approval-agent/reviewer.py:506,568++**Suppress bot familiarity instead of presenting contradictory trusted context**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** Self-driving reviews still run the normal author-familiarity calculation and include its positive result before this new provenance block. A long-lived bot can therefore be presented as a STRONG or MODERATE familiar author, and the rendered review body also advertises that signal, despite the new block saying author familiarity carries no signal. This weakens the intended trust boundary for the newly allowed bot-authored draft approvals.+- **Suggestion:** When `self_driving` is set, skip familiarity computation/attachment in both `review_pr.py` and `review_local.py` (and avoid rendering its review-body bullet), so the reviewer receives only the task-provenance trust signal for these runs.+- **Validator:** - **Checked:** `_build_review_prompt` (reviewer.py:505,567), the new `_format_self_driving` (reviewer.py:680–703), both familiarity attach paths (`review_pr.py:_maybe_compute_familiarity` 519–521 / run() 241; `review_local.py:_attach_familiarity` 299–309, called at 348), `compute_familiarity`/`_band` in familiarity.py, and gates.py.+- **Found:** The self-driving carve-out relaxes only the bot-author refusal and draft gate (review_pr.py:225, review_local.py patched run()); it does NOT gate familiarity. `familiarity_block` is computed at reviewer.py:505 and rendered at :567 immediately before `{self_driving_block}`. `_attach_familiarity` (review_local.py:299) attaches the signal for any `T1-agent` run when `author_pr_numbers` is present, with no `self_driving` check — so for a self-driving T1-agent review the prompt carries BOTH a familiarity block and a provenance block claiming familiarity 'carr[ies] no signal here.' The new docstring even states familiarity 'is deliberately absent' (reviewer.py:685), which the code does not enforce.+- **Found:** familiarity.py's module docstring says STRONG band exists 'so the ownership norms can treat strong familiarity like owning-team membership' — a posture-relaxing trust signal. `_band` (familiarity.py:407) grants STRONG on blame-overlap alone; a bot that repeatedly opens/merges PRs in the same paths (the feature's intended steady state) accrues blame overlap and prior-PR counts, yielding a positive band that contradicts the provenance instruction on exactly the machine-generated diffs the carve-out means to scrutinize.+- **Impact:** Genuine trust-boundary inconsistency in a security-sensitive carve-out that grants real GitHub approvals to bot drafts: two TRUSTED blocks assert opposite things, and the positive familiarity signal can relax the LLM's skepticism toward a bot diff. The premise ('familiarity still computed/rendered for self-driving') is confirmed true; only the magnitude (band value) is data-dependent.+- **Priority:** Downgrading must_fix → should_fix on concrete evidence of mitigation: familiarity is judgment-layer only (no reference in gates.py; `_maybe_compute_familiarity` only populates `classification`, never a gate), so it cannot deterministically force an unsafe approval; the provenance block explicitly tells the LLM familiarity 'carr[ies] no signal here — judge the diff strictly on its own merits,' giving a textual override; and a non-NONE band requires the server to inject `author_pr_numbers` plus accrued bot blame/PR overlap. Real and worth fixing (cheap: gate the attach/render on `not self_driving`), but not a hard deterministic hole that must block merge.++### [✅ VALID] must_fix (validator→should_fix) · bug — products/review_hog/backend/receivers.py:114-138,144-154++**Honor opt-in from any assigned reviewer**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The feature is intended to run when at least one assigned reviewer enables the Stamphog toggle, but `_resolve_assigned_reviewer` picks a single canonical/creator reviewer and both call sites only inspect that user's setting. If the first assignee is opted out and a later assigned reviewer is opted in, no initial review is queued and later push events are also skipped.+- **Suggestion:** Resolve the assigned reviewers as a collection for the Stamphog path and select an opted-in assignee (preserving the requester-first preference when applicable). Use that selected user as `acting_user_id` for both the initial dispatch and the webhook resolver, while retaining the existing single-reviewer behavior for ReviewHog if that is intentional.+- **Validator:** - **Checked:** The real PR diff (local checkout is stale — no stamphog code, migration 0019 is unrelated), tracing `_resolve_assigned_reviewer`, both call sites in `handle_task_run_saved`, the webhook `resolve_stamphog_acting_reviewer`, and the stamphog facade (`queue_inbox_pr_review`, `inbox_hooks.InboxActingReviewerResolver`).+- **Found:** `_resolve_assigned_reviewer` returns a single id — `acting = next((u for u in resolved if u.id == task_created_by_id), resolved[0]); return acting.id`. For self-driving inbox PRs the task creator is the GitHub-integration bot (per module docstring), so `task_created_by_id` matches no suggested reviewer → `acting = resolved[0]` (first-ordered). Both legs gate on that one user: `settings = ReviewUserSettings.load(team_id, acting_user_id); if pr_url is not None and settings.stamphog_review_inbox_prs:` for the initial dispatch, and `resolve_stamphog_acting_reviewer` re-checks the same single user's `stamphog_review_inbox_prs` on webhook re-review. The whole facade flows one `acting_user_id` (`InboxActingReviewerResolver = Callable[[int, str, int | None], int | None]`).+- **Impact:** Report suggesting `[alice, bob]` with alice (first) opted out and bob opted in → `acting = alice` → initial Stamphog dispatch skipped AND webhook re-reviews resolve to `None` → skipped. This is the normal multi-reviewer rollout case (Slack fans out to plural reviewers), and it contradicts the feature's stated gate ("at least one of the assigned users has `stamphog_review_inbox_prs` enabled"; Case 3's "nobody is opted in"). Concrete trigger and concrete consequence both nameable — a genuine logic gap, not speculative.+- **Priority:** Lowering must_fix → should_fix: the failure is a silent under-trigger in the fail-safe direction (no unwanted review published — the feature simply doesn't run), on a draft experiment branch, and the single-canonical-reviewer resolver is a deliberate, documented, shared mechanism (required for ReviewHog's per-user options). Worth surfacing so the author reconciles code vs. intent — the fix is contained (select an opted-in assignee for the stamphog path) — but it is not a blocking correctness/data-loss defect.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-8++**Rebase the migration on the existing 0019 leaf**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The repository already contains `0019_reviewreport_author_login_and_more`, also depending on `0018_backfill_urgency_threshold_to_consider` (and `max_migration.txt` names it as the current leaf). Adding another migration named `0019` with the same parent creates conflicting migration leaves, causing Django migration checks to fail.+- **Suggestion:** Rename this migration to the next available number and depend on the existing `0019_reviewreport_author_login_and_more` migration, then update `max_migration.txt` if required by the repository's migration tooling.+- **Validator:** - **Checked:** The PR's new migration (`0019_reviewusersettings_stamphog_review_inbox_prs.py`) dependency + its `max_migration.txt` diff, against the base checkout's existing `0019_reviewreport_author_login_and_more.py` and `max_migration.txt`.+- **Found:** PR migration declares `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]` (lines 7-8) and its `max_migration.txt` hunk rewrites `0018_backfill_urgency_threshold_to_consider` → `0019_reviewusersettings_stamphog_review_inbox_prs` — so the branch's merge-base leaf was still `0018`. Base/master already has `0019_reviewreport_author_login_and_more.py` whose `dependencies` (line 8) is the same `0018_backfill_urgency_threshold_to_consider`, and master's `max_migration.txt` = `0019_reviewreport_author_login_and_more`.+- **Impact:** On merge/rebase onto current master, two migrations parent on `0018` → two migration leaves for the `review_hog` app, so `makemigrations --check` / `migrate` fails, and `max_migration.txt` conflicts on its single line. PostHog uses `django-linear-migrations` (the `max_migration.txt` convention), which fails the build rather than auto-merging — a deterministic CI/merge-queue block. Concrete trigger (rebase onto a master that already landed `0019_reviewreport_...`) and concrete consequence (migration check failure) both confirmed; must_fix stands.++### [❌ dismissed] should_fix · bug — products/tasks/backend/facade/api.py:506-507++**Scope the task-run lookup before selecting a match**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** `find_task_run` searches all teams and returns only its first repository/PR match. The subsequent `run.team_id != team_id` check then returns `None` rather than continuing to a matching run in the requested team. A non-internal signal task in another team targeting the same repository and PR URL or branch can therefore prevent the legitimate team's bot draft from being recognized on later webhook deliveries, so opted-in users stop receiving re-reviews.+- **Suggestion:** Add `team_id` support to `find_task_run` (and apply it to every PR URL/branch query before ordering), or implement the lookup here with `TaskRun.objects.filter(team_id=team_id, ...)`. This ensures ordering happens only among the requesting team's candidate runs.+- **Validator:** - **Checked:** `find_signal_implementation_run` (products/tasks/backend/facade/api.py, new in this PR), the `find_task_run` it delegates to (products/tasks/backend/webhooks.py:29-95), and the sole production caller `_inbox_rereview_carve_out` (products/stamphog/backend/tasks/tasks.py, diff line 909).+- **Found:** `find_task_run` tries the `pr_url` leg first and returns before the branch leg is reached (webhooks.py:38-59). A GitHub PR `html_url` is globally unique to one physical PR, recorded by the single run that created it, so the `pr_url` leg resolves to the correct team's run — `run.team_id != team_id` cannot mismatch here. The only documented duplicate-`pr_url` case is a same-team wizard resume, disambiguated by the terminal-rank ordering (webhooks.py:39-42).+- **Found:** the only caller passes both `pr_url` and `head_branch` and is gated to `synchronize`/`reopened`/base-retarget actions only (`_HEAD_CHANGING_ACTIONS = {"synchronize","reopened"}`, tasks.py:46) — all post-creation deliveries. By then the PR exists and its URL was saved onto the task (that save wakes the initial listener), so the run's `output.pr_url` is set and the `pr_url` leg matches. The branch fallback never governs this path. The initial review is a separate receiver leg (`process_inbox_pr_review`) that does not call this function.+- **Impact:** the described failure needs either two teams' runs sharing the same globally-unique PR URL (does not occur), or the `pr_url` leg to miss _and_ two distinct tenants on the identical repository holding non-wizard runs with an identical branch string (self-driving branches carry `secrets.token_hex(3)` random suffixes). That is a stack of practically-unreachable conditions on a path that `pr_url` already resolves correctly — a speculative what-if, not a reachable defect. The facade is additionally fail-closed (explicit team check plus a caller-side belt-and-braces recheck).diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-2.mdnew file mode 100644index 000000000000..72924e591c7f--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/H-gpt56terra-xhigh-2.md@@ -0,0 +1,237 @@+# Reviewer-quality run — `H-gpt56terra-xhigh-2`++- **Dumped:** 2026-07-30T14:26:18+00:00+- **Report id:** `019fb34f-1d26-7355-b8d3-9d248a5f7382` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 1849s (30.8 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-terra` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 11 | 10 | 3 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 98 | 89,531 | 581,480 | 9,909,389 | 135,036 | 3 | $12.41 | $12.41 |+| gpt-5.6-terra | review | 99 | 5,403,492 | 0 | 0 | 33,121 | 0 | — | $4.09 |+| gpt-5.6-terra | blind-spot | 41 | 2,675,142 | 0 | 0 | 12,880 | 0 | — | $1.62 |+| claude-sonnet-5 | dedup | 1 | 6,555 | 0 | 0 | 2,346 | 0 | $0.04 | $0.04 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 506 | 0 | $0.02 | $0.02 |+| gpt-5.6-terra | other | 18 | 0 | 0 | 0 | 0 | 0 | — | $0.00 |+| **total** | | **258** | **8,180,701** | **581,480** | **9,909,389** | **183,889** | **3** | **$12.47** | **$18.17** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `gpt-5.6-terra` (158 gen(s), gw $5.71).+- naive method (all prompt tokens at input price): $56.33 — 4.5× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $14.0800 over 258 gen(s) (true $9.0617, Δ +55.4%)+ - · of which cache read: $6.6412 over 217 gen(s) (true $4.9547, Δ +34.0%)+ - · of which cache write: $3.6342 over 98 gen(s) (true $3.6342, Δ +0.0%)+ - · of which fresh (derived): $3.8046 over 258 gen(s) (true $0.4727, Δ +704.8%)+ - output: $4.0944 over 258 gen(s) (true $3.4044, Δ +20.3%)+- 3 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …e4525e54 | issues-review-p1-c1 | 13:56:28 | 0 | 0 | gpt-5.6-terra |+| …07479a57 | issues-review-p3-c1 | 13:56:29 | 0 | 0 | gpt-5.6-terra |+| …8aa2db59 | issues-review-p1-c2 | 13:56:30 | 0 | 0 | gpt-5.6-terra |+| …d473268f | issues-review-p3-c2 | 13:56:32 | 0 | 0 | gpt-5.6-terra |+| …0cfc5bae | issues-review-p1-c3 | 13:56:33 | 0 | 0 | gpt-5.6-terra |+| …1456e131 | issues-review-p3-c3 | 13:56:35 | 0 | 0 | gpt-5.6-terra |+| …2c355ad5 | issues-review-p2-c3 | 13:56:35 | 0 | 0 | gpt-5.6-terra |+| …c85e1dcc | issues-review-p2-c1 | 13:56:52 | 0 | 0 | gpt-5.6-terra |+| …b8f46018 | issues-review-p2-c2 | 13:57:14 | 0 | 0 | gpt-5.6-terra |+| …aaa56694 | issues-review-p2-c2 | 13:59:13 | 0 | 0 | gpt-5.6-terra |+| …d90c8e13 | issues-review-p3-c2 | 13:59:15 | 0 | 0 | gpt-5.6-terra |+| …4ec205eb | issues-review-p3-c3 | 13:59:20 | 0 | 0 | gpt-5.6-terra |+| …30843af8 | issues-review-p3-c1 | 13:59:21 | 0 | 0 | gpt-5.6-terra |+| …50a73a9b | issues-review-p2-c1 | 13:59:27 | 0 | 0 | gpt-5.6-terra |+| …de2b5903 | blind-spots-c3 | 14:01:28 | 0 | 0 | gpt-5.6-terra |+| …85ea81a3 | blind-spots-c2 | 14:01:29 | 0 | 0 | gpt-5.6-terra |+| …abd5ca8b | blind-spots-c1 | 14:01:32 | 0 | 0 | gpt-5.6-terra |+| …c7aca92b | blind-spots-c4 | 14:01:49 | 0 | 0 | gpt-5.6-terra |+| …ac4b02c7 | validation-c3 | 14:05:05 | 0 | 37,006 | claude-opus-4-8 |+| …219e01a4 | validation-c1 | 14:05:05 | 0 | 37,320 | claude-opus-4-8 |+| …0ef6e565 | validation-c4 | 14:05:06 | 17,141 | 19,534 | claude-opus-4-8 |+| …a159aaf0 | validation-c2 | 14:05:15 | 17,141 | 20,662 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **2/22** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 6s |+| review wave (perspectives) | 5m 06s |+| blind-spot sweep | 2m 58s |+| dedup (incl. combine/clean) | 24s |+| validation | 21m 29s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 8m 04s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | ? | 0 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | ? | 0 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | ? | 0 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | ? | 0 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | review-hog-blind-spots-general | 1 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] must_fix · bug — products/review_hog/backend/receivers.py:144-153++**Select an opted-in assignee for Stamphog**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The Stamphog resolver first selects one canonical acting reviewer, then checks only that user's toggle. This contradicts the feature contract that Stamphog should run when at least one assigned reviewer has opted in: if the task creator (or first resolved assignee) is opted out while another assigned reviewer is opted in, both the initial dispatch and webhook re-reviews are skipped.+- **Suggestion:** Resolve the assigned reviewers first, then choose an assignee with `stamphog_review_inbox_prs=True` (preserving the existing creator/ordering preference among opted-in users). Use that same resolver for the initial TaskRun dispatch as well as the webhook hook, so both paths honor the any-assignee opt-in rule.+- **Validator:** - **Checked:** The real PR diff for `products/review_hog/backend/receivers.py` (`_resolve_assigned_reviewer`, `resolve_stamphog_acting_reviewer`, and the `handle_task_run_saved` dispatch), plus the pre-existing acting-reviewer contract in `products/review_hog/backend/tests/test_inbox_trigger.py` on master, and the stamphog facade `queue_inbox_pr_review`.+- **Found:** The single-canonical-acting-reviewer gate is a deliberate, tested invariant, not an accident. Master's `test_opted_out_canonical_reviewer_blocks_the_review` asserts exactly the scenario the issue calls a bug — reviewers `["bob","alice"]`, bob (canonical) opted out, alice opted in → `mock_start.assert_not_called()` — with the comment "The canonical assignee's toggle is THE gate ... a later reviewer's opt-in must not hijack whose options the review runs with." The stamphog leg reuses this exact resolution: `resolve_stamphog_acting_reviewer`'s docstring says "Same acting-reviewer resolution as this module's own trigger," and the PR's own test comment reads "the two toggles on the one acting reviewer gate their reviews independently."+- **Found:** The gate is not separable from identity as the suggestion assumes. `queue_inbox_pr_review(..., acting_user_id=...)` runs the stamphog review under one specific user's identity/config, just like ReviewHog. The suggestion's "choose an assignee with `stamphog_review_inbox_prs=True` (preserving the creator/ordering preference among opted-in users)" is precisely the "hijack" the maintainer decision (documented, 2026-07-02/03) forbids: it would either run under a canonical user who didn't opt in, or re-pick the canonical acting reviewer based on opt-in status — breaking the tested ReviewHog selection.+- **Impact:** The finding rests on treating the PR description's loose phrase "at least one of the assigned users has stamphog_review_inbox_prs enabled" as the authoritative contract. The actual code-level contract — encoded in comments and existing tests — is the single-canonical-acting-reviewer model. The flagged behavior is intended, so this is a mistaken-premise finding (precision-over-recall: drop), not a correctness or contract break.++### [✅ VALID] should_fix · security — tools/pr-approval-agent/review_pr.py:475-477++**Suppress author familiarity for self-driving reviews**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** Setting `classification["self_driving"]` does not actually replace the human-author trust signal. `run()` still calls `_maybe_compute_familiarity()` before every LLM review, and for T1 self-driving PRs it stores the bot account's git-history familiarity in `classification["familiarity"]`. The prompt therefore renders the normal “Author familiarity” block immediately before the new provenance block, despite the latter claiming familiarity is deliberately absent. A long-lived machine account can consequently be presented as familiar with modified code and influence the review verdict.+- **Suggestion:** When `self_driving` is enabled, skip `_maybe_compute_familiarity()` (or explicitly leave `classification["familiarity"]` as `None`) so `_format_familiarity()` renders nothing. Keep provenance as the sole author-related context for this path.+- **Validator:** - **Checked:** Working tree is master (PR 75215 not checked out), so I verified against `gh pr diff 75215` combined with the unchanged `familiarity.py`/`reviewer.py` code. Traced the self-driving path through `Pipeline.run()` → `_maybe_compute_familiarity()` → `_compute_familiarity()` → `compute_familiarity()` → `Reviewer._build_review_prompt()`.+- **Found:** The PR relaxes only the bot-author refusal and draft gate. `run()` still calls `_maybe_compute_familiarity()` unconditionally before `_llm_review()` (`review_pr.py:240-242`). `_maybe_compute_familiarity()` (`review_pr.py:510-521`) is untouched by the PR and, for `tier == "T1-agent"`, writes the signal into `classification["familiarity"]` with **no `self_driving` guard**. `_compute_familiarity()` passes `author_login=pr.author` — the bot login — into `compute_familiarity()` (`review_pr.py:523-534`).+- **Found:** `compute_familiarity()` returns a populated object whenever `gh pr list --author <bot> --state merged` succeeds (`familiarity.py:88,438-520`); band is MODERATE/STRONG once the bot has merged PRs overlapping the touched paths. `_format_familiarity()` then renders the full "Author familiarity with the changed code … band STRONG; author last-touched X% of the lines …; N merged PRs in these paths" block for any non-NONE band (`reviewer.py:643-680`). The prompt appends both blocks — `{familiarity_block}{self_driving_block}` — while the new provenance block asserts "author familiarity, org membership, and merged-PR history carry no signal here" (`_format_self_driving`). The two TRUSTED blocks directly contradict, and the PR's own `__init__` comment states self_driving should make the prompt "carry the provenance instead of human-author trust signals" — intent not delivered.+- **Impact:** For the common case (a self-driving code PR classified T1-agent), a long-lived machine account that has accrued merged-PR history in the touched paths is presented to the reviewer LLM as familiar/trusted. Per `familiarity.py`'s own docstring the signal exists so "ownership norms can treat strong familiarity like owning-team membership" — i.e. it nudges toward approval, which is exactly the machine-account trust-laundering the bot-author refusal (and this carve-out's provenance framing) is meant to prevent on an auto-approval path. Reachable and realistic, not a contrived edge case.+- **Found:** The PR's tests do not catch this: `test_prompt_provenance_renders_only_for_self_driving_runs` hardcodes `familiarity: None`, and `test_self_driving_flag_reviews_the_bot_authored_draft` stubs `_llm_review` with an empty diff — so the familiarity/provenance interaction is untested and the defect ships live. The suggested fix (skip `_maybe_compute_familiarity()` or force `classification["familiarity"]=None` when `self_driving`) is correct and self-contained.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9++**Rebase this migration onto the current leaf**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The app already has `0019_reviewreport_author_login_and_more.py`, and `max_migration.txt` identifies it as the current leaf. Depending on `0018` here creates two migration leaves; subsequent `makemigrations` reports conflicting migrations and blocks normal migration development.+- **Suggestion:** Rename this migration to `0020_...`, depend on `0019_reviewreport_author_login_and_more`, and update `products/review_hog/backend/migrations/max_migration.txt` to the new migration name.+- **Validator:** - **Checked:** The PR's migration file and `max_migration.txt` patch against the current `master` state of `products/review_hog/backend/migrations/` (directory listing, `max_migration.txt`, and the dependency block of the master `0019`).+- **Found:** The conflict is real on master, not hypothetical. Master's `max_migration.txt` reads `0019_reviewreport_author_login_and_more`, and that file exists with `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]`. The PR adds `0019_reviewusersettings_stamphog_review_inbox_prs.py` (L7-9) depending on the _same_ `0018_backfill_urgency_threshold_to_consider`, and rewrites `max_migration.txt` from `0018...` to the stamphog name. Two migrations therefore branch off `0018` → two leaf nodes.+- **Impact:** Once this branch takes in master, Django's migration-graph check reports "Conflicting migrations detected; multiple leaf nodes" — `makemigrations --check` and the repo's `max_migration.txt` CI guard fail, and `migrate` refuses without a merge migration, blocking the PR and normal migration development. The PR's own `mergeable_state: "dirty"` is consistent with the `max_migration.txt` git conflict (master `...author_login` vs PR `...stamphog`). This is a concrete reliability/build-breaking defect that will occur, not speculation.+- **Priority:** `must_fix` is correct — the suggested fix (renumber to `0020_...`, depend on `0019_reviewreport_author_login_and_more`, point `max_migration.txt` at the new name) is the standard resolution and is required for the branch to merge.++### [❌ dismissed] must_fix · security — products/review_hog/backend/receivers.py:124-138++**Validate the initial inbox PR before granting the carve-out**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This dispatch passes only a PR URL and IDs to Stamphog. The queued initial-review path fetches that URL and stamps it as `inbox_review`, but does not receive or verify the task repository, head repository, or expected bot author. That provenance enables the engine's self-driving carve-out, which bypasses its normal bot/draft/author-trust gates. A self-driving task output that points at another open PR in a configured repository can therefore cause Stamphog to review and potentially approve a PR that was not created by that Inbox task.+- **Suggestion:** Pass the task repository (and preferably the run identity for a server-side lookup) into the queue task, then verify the fetched PR is repo-native, belongs to that exact repository, and is authored by the expected App bot before setting `inbox_review` or starting a review. Treat any mismatch as a no-op.+- **Validator:** - **Checked:** `process_inbox_pr_review` (the initial leg) in `products/stamphog/backend/tasks/tasks.py`, the webhook re-review leg `_inbox_rereview_carve_out` in the same file, `find_signal_implementation_run` in `products/tasks/backend/facade/api.py`, and both writers of `TaskRun.output['pr_url']` (`products/tasks/backend/webhooks.py` `find_task_run` / `_record_run_pr_url`, and the agent-server path described in `receivers.py`'s module docstring).+- **Found:** The premise is factually right that the initial leg does no bot-author/fork/task-linkage recheck — it derives the repo from the URL via `_parse_pr_url`, resolves a synced+enabled config, fetches the PR, and stamps `inbox_review`. But the two legs have different trust anchors, and the checks are only load-bearing for the webhook leg. `_inbox_rereview_carve_out` verifies `_is_bot_authored`, fork-safety (`head_repo == repo`), and `find_signal_implementation_run` precisely because it is the entry point for _arbitrary_ incoming PR webhook events. The initial leg is not: `handle_task_run_saved` fires only for a non-internal task with a `signal_report_id` (receivers.py L82-89), and the `pr_url` it forwards is that already-identified self-driving run's own recorded `output.pr_url`.+- **Found:** The trigger the issue needs — `output.pr_url` pointing at a PR _not_ created by the task (a human/fork PR the carve-out could then approve) — is ruled out by both writers. The webhook backstop records `output.pr_url` only when `head_repo_full_name == repository_full_name` (fork-safe) and the run matched within `task.repository` (webhooks.py:179-186), and the agent-server path records the PR the App bot actually opened for the task (repo-native, bot-authored). So the stored field the initial leg trusts already carries the bot-authored + repo-native + task-linked invariants the issue asks to re-verify.+- **Impact:** For the described escalation to occur, a _trusted_ producer (agent server / webhook backstop) would have to write a foreign PR URL onto the run — a what-if against an upstream-guaranteed invariant, not a reachable path via any shown call site. This is the same trust in `output.pr_url` the pre-existing ReviewHog inbox leg already relies on, so no new reachable attack surface is introduced. Tenant isolation is independently enforced (`for_team` scoping + `find_signal_implementation_run`'s `team_id` recheck), bounding any blast radius to within-tenant even if the invariant were violated. Under precision-over-recall this is defensive/speculative hardening rather than a demonstrable auth-bypass, so it does not meet the keep bar.++### [❌ dismissed] must_fix · documentation — products/stamphog/README.md:14++**Do not document the inbox StampHog integration before it exists**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** This says the inbox receiver calls a `queue_inbox_pr_review` StampHog facade and that later webhook deliveries use an inbox carve-out, but neither that facade nor `facade/inbox_hooks.py` exists in this checkout. The actual StampHog webhook path still unconditionally rejects draft and bot-authored PRs in `_review_skip_reason`, and the existing inbox receiver starts a ReviewHog workflow instead. Users following this documentation will enable a toggle and expect reviews that can never run.+- **Suggestion:** Land the documented facade, provenance flag, resolver, and webhook/engine exceptions in the same change, or remove this carve-out documentation until those paths are implemented. Keep the setting name and entry point aligned with the implemented API.+- **Validator:** - **Checked:** The PR diff for all files the finding names — `products/stamphog/backend/facade/api.py`, `facade/inbox_hooks.py`, `backend/tasks/tasks.py` (`_review_skip_reason`), and `products/review_hog/backend/receivers.py` — plus the migration/model/engine/test files, via `gh pr diff 75215`.+- **Found:** The facade IS added — `+def queue_inbox_pr_review(` in `facade/api.py` (diff ~L687), and `facade/inbox_hooks.py` is a brand-new file (`new file mode 100644 ... products/stamphog/backend/facade/inbox_hooks.py`, diff L720-725) exporting `register_inbox_acting_reviewer_resolver`/`get_inbox_acting_reviewer_resolver`. The reviewer's core premise ('neither that facade nor `facade/inbox_hooks.py` exists in this checkout') is factually wrong against the PR.+- **Found:** `_review_skip_reason` no longer 'unconditionally rejects' bots — the PR DELETES the `user.get("type") == "Bot"` lines from it (diff L943-944) and the handler overrides the skip: `carve_out = _inbox_rereview_carve_out(...)` then `if skip_reason is not None and inbox_review is None:` (diff L956-967). Draft/bot carve-out is implemented via `_InboxCarveOut`/`_inbox_rereview_carve_out`.+- **Found:** The receiver does not run ReviewHog 'instead' — `receivers.py` gates the ReviewHog leg on `settings.review_inbox_prs` AND adds `_start_stamphog_review(...)` → `queue_inbox_pr_review` gated on `settings.stamphog_review_inbox_prs`, and registers `resolve_stamphog_acting_reviewer` via `register_inbox_acting_reviewer_resolver` at `connect()`.+- **Found:** The provenance flag, migration, and tests all land in the same PR: `stamphog_review_inbox_prs` BooleanField (models.py), migration `0019_reviewusersettings_stamphog_review_inbox_prs`, and coverage in `test_inbox_trigger.py`/`test_tasks.py`/`test_integration.py`. Doc names/entry points match the implemented API (`queue_inbox_pr_review`, `stamphog_review_inbox_prs`, `facade/inbox_hooks.py`).+- **Impact:** The finding is a false positive: the documented facade, resolver, provenance flag, webhook carve-out, and engine/skip exceptions are all implemented within this same PR, so users following the docs will not 'enable a toggle and expect reviews that can never run.' The reviewer's premise reproduces only against an incomplete tree — my own checkout resolved the PR head sha `1341596e` as a 'bad object' (stuck at master `d24a844e`), which is the likely source of the stale-checkout error. Does not meet the bar (Wrong / unreproducible).++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1125-1245++**Verify inbox provenance before bypassing normal PR trust gates**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial-review worker treats all of its arguments as trusted. It resolves only a team-owned repo config and fetches the referenced PR; it never verifies that `task_run_id` and `signal_report_id` identify a non-internal signals implementation run for this team, that the run produced this exact PR, or that the PR is bot-authored with a repo-native head. Consequently, any caller that can cause a TaskRun output/receiver invocation with a GitHub URL can mint an `inbox_review` run for an arbitrary PR in a configured repository. That provenance enables the engine's bot/draft carve-out and bypasses the normal author-association, review-mode, and write-permission protections, potentially allowing an approval on an untrusted fork or unrelated PR.+- **Suggestion:** Before creating or restarting a run, fetch and validate the supplied run through `find_signal_implementation_run` (and require its run ID and signal report ID to equal the task arguments), then require the fetched PR to be bot-authored and `pr.head.repo.full_name` to equal the configured repository. Return without creating a run when any check fails. This should mirror the positive-identification checks already used by `_inbox_rereview_carve_out`.+- **Validator:** - **Checked:** Compared `process_inbox_pr_review` (PR tasks.py:1109-1245) against the webhook carve-out `_inbox_rereview_carve_out` (tasks.py:144-215); traced the engine gate in temporal/activities.py; traced the caller `handle_task_run_saved`/`_start_stamphog_review` (review_hog receivers.py:70-140, 205-230); traced both writers of `output.pr_url` (agent output API `set_task_run_output` in tasks/facade/api.py:2203 and the webhook backstop in tasks/webhooks.py:130-198); read `find_signal_implementation_run` (tasks/facade/api.py:484-516).+- **Found:** The receiver leg stamps `inbox_review` provenance from the caller args + fetched PR with none of the positive-identification the webhook leg performs — no `_is_bot_authored`, no `head.repo.full_name == repo` fork check, no `find_signal_implementation_run` run→PR linkage. `self_driving_review=bool(output.get("inbox_review"))` (activities.py:451) is the _sole_ gate unlocking the engine's bot/draft carve-out, and its own comment (activities.py:448-450) asserts "both trigger paths stamp only after positively linking the PR to a signals implementation run" — false for this leg.+- **Found:** `output.pr_url` is explicitly caller-controlled (api.py:5768) and `set_task_run_output` (api.py:2203-2226) persists it with no repo-native/fork/authorship validation. The backstop's fork check (webhooks.py:180-186) guards only the _backstop_ write, not the agent output-API write — so my earlier hypothesis that fork URLs can't reach `output.pr_url` does not hold for the agent path.+- **Found (reviewer overstatement, non-fatal):** The caller binds `task_run_id`/`signal_report_id` to the run's own real values and already enforces `not task.internal` + signal-report + assigned-reviewer (receivers.py:95-140), so those IDs aren't attacker-supplied. But the _PR→run linkage_ and bot/fork gates remain absent, which is the real defect.+- **Impact:** An actor controlling `output.pr_url` on a qualifying run (a non-internal signal-report run with an opted-in assigned reviewer — reachable via the agent output API over untrusted signal content, the codebase's modeled prompt-injection surface) can aim a gate-bypassing, approval-capable `self_driving` review at an arbitrary or fork PR in any team-configured Stamphog repo. An APPROVE posts a real GitHub approval that can satisfy required reviews with zero humans — exactly the harm the fork/author-association gates and the webhook leg's positive-identification exist to prevent, and a break of the product's documented central approval invariant. Suggested fix (mirror the webhook leg: `find_signal_implementation_run` with matching run/report IDs + bot-author + repo-native head) is on point.++### [❌ dismissed] should_fix — products/stamphog/backend/tasks/tasks.py:1107-1110++**Re-check the opt-in when the asynchronous task executes**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The opt-in is checked before Celery dispatch, but the task can execute or retry after that reviewer has disabled the toggle. `process_inbox_pr_review` receives `acting_user_id` but never consults the registered resolver or otherwise confirms that the user is still authorized. A queued initial review can therefore run after the user has revoked the preference that is intended to gate these reviews.+- **Suggestion:** At the start of the task, resolve the current acting reviewer using the inbox hook and the supplied team/report/run context. Abort unless it still resolves to the expected acting user (or otherwise explicitly represents a currently opted-in authorized reviewer).+- **Validator:** - **Checked:** `process_inbox_pr_review` (tasks.py:1109-1245) for any execution-time toggle re-check; the receiver's dispatch-time gate (review_hog receivers.py:126 `settings.stamphog_review_inbox_prs`); the webhook re-review re-check (tasks.py:201-207); the carve-out docstring's stance on preference vs safety (tasks.py:147-166); and what happens to an approval posted after opt-out (tasks.py:894-908 opt-out skip retraction; the ready_for_review note in the carve-out docstring).+- **Found:** The observation is factually correct — the task consumes `acting_user_id` only to stamp provenance (tasks.py:1180) and never re-resolves the toggle; retries (`max_retries=3`, rate-limit `countdown=max(retry_after,60)`) can widen the dispatch→execute window to ~a minute.+- **Found (defeating):** The toggle is a _preference_, not a safety gate — tasks.py:165 states "safety is never preference-gated." The review only ever runs on the team's own positively-identified self-driving bot draft, and any approval is head-pinned to the exact reviewed head, so it never stands over unreviewed code (the product's central invariant holds regardless of the toggle). A later push after opt-out dismisses the approval through the webhook skip path's `opted_out` branch (`_retract_stale_approvals_on_skip`, tasks.py:894-908).+- **Impact:** The only durable residual case (opt-out landing inside the seconds-to-~minute race AND the draft flipping ready with no intervening push) produces a _valid_ approval over code that was actually reviewed at that head — a momentary preference violation on the team's own PR, with no safety, correctness, or data consequence. That is a narrow, low-impact timing edge case, and the reviewer's authorization/security framing misreads the toggle's role; under precision-over-recall this does not meet the bar.++### [❌ dismissed] should_fix — products/stamphog/backend/tasks/tasks.py:1196-1217++**Serialize head-key deduplication with a PullRequest lock or uniqueness constraint**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The comment says the `select_for_update()` query serializes racing receiver fires, but it locks only matching `ReviewRun` rows. When two tasks process the first review for a head concurrently, there is no existing row to lock, and `ReviewRun` has no uniqueness constraint on `(pull_request, head_sha)`. Both transactions can therefore observe `existing is None`, create separate queued runs, and start duplicate reviews for the same commit.+- **Suggestion:** Lock the `PullRequest` row before querying/creating runs (for example, re-fetch it with `select_for_update()` inside the transaction), or add and handle a database uniqueness constraint for the PR/head identity. Keep the existing-run recovery behavior after acquiring that serialization point.+- **Validator:** - **Checked:** `ReviewRun` model constraints (models.py:140-170), `PullRequest` constraints (models.py:120), `_upsert_pull_request` (tasks.py:319-363), the transaction ordering in `process_inbox_pr_review` (tasks.py:1185-1234), and the webhook path's documented serialization (tasks.py:894-898).+- **Found:** The reviewer is right on the narrow facts — `select_for_update().filter(pull_request=…, head_sha=…)` locks zero rows for the first review of a head, and there is no `(pull_request, head_sha)` uniqueness (models.py:143-170; the only unique field is `delivery_id`, and inbox runs set `delivery_id=None`, tasks.py:1227).+- **Found (decisive):** Serialization is not supposed to come from that query — it comes from `_upsert_pull_request`, which runs first inside the same `transaction.atomic(using=run_write_db)` block (tasks.py:1185-1186). For an existing PR row its clock-gated UPDATE (tasks.py:349-354) takes the `PullRequest` row lock, held to commit; for a new PR row, `get_or_create`'s INSERT blocks on `unique_stamphog_pull_request` (`team_id, repo_config, pr_number`, models.py:120). A second concurrent task blocks there until the first commits, then its existing-run query (tasks.py:1202-1210, READ COMMITTED) sees the winner's committed run and returns. This is the identical mechanism the webhook leg documents and depends on (tasks.py:894-898).+- **Impact:** No duplicate runs for realistic inputs, so the reliability defect the finding describes does not occur. The only unserialized path is `incoming_updated_at is None` (tasks.py:346-348 early-returns before the UPDATE lock) together with a pre-existing PR row — reachable only if the GitHub-fetched PR has no parseable `updated_at`, which never happens for a real PR. The suggested PullRequest lock duplicates protection already in place. Premise mistaken (and the residual is a never-gonna-happen edge) → does not meet the bar.++### [❌ dismissed] should_fix — products/stamphog/backend/tasks/tasks.py:1107-1108++**Retain initial reviews across longer GitHub or Temporal outages**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** This receiver-leg task has no webhook redelivery or other durable recovery path, but it stops retrying after three retries. A GitHub rate-limit window, temporary API outage, or Temporal outage that lasts beyond those attempts permanently loses the initial inbox review; subsequent TaskRun saves are not guaranteed. This is particularly likely for rate limits because the task explicitly waits for GitHub's retry delay before consuming another limited retry.+- **Suggestion:** Use a retry policy appropriate for a durable asynchronous handoff (for example, bounded exponential backoff over a substantially longer window), or persist a recoverable pending-review record that a periodic job can resume. Keep the existing head-keyed dedupe so recovery does not create duplicate reviews.+- **Validator:** - **Checked:** The retry decorator and every retry site in `process_inbox_pr_review` (tasks.py:1109, 1150, 1162, 1165, 1237); the same policy on the sibling webhook tasks (tasks.py:721, 809, 974); the documented recovery model (tasks.py:1124-1128, 1155-1157); the head-keyed re-fire/QUEUED-restart path (tasks.py:1211-1214); and whether any periodic resweep exists (schedules.py wires only the daily digest crontab).+- **Found:** `max_retries=3, default_retry_delay=5` is confirmed — but it is byte-for-byte the retry policy the already-shipped webhook leg `process_pull_request_event` uses (tasks.py:809), so the inbox leg mirrors an accepted pattern, not a new defect. The rate-limit path adapts its countdown to GitHub's `retry_after` (`max(e.retry_after or 0, 60)`, tasks.py:1162), so a single retry that sleeps the window succeeds next attempt — the finding's 'particularly likely for rate limits' is largely defused.+- **Found:** Recovery paths exist beyond the 3 retries: the receiver re-fires on every later `output`-touching TaskRun save carrying the PR URL (including the run-completion save) and the head-keyed dedupe restarts a still-QUEUED run (tasks.py:1211-1214); later pushes re-review through the webhook carve-out. So 'permanently loses' overstates the outcome.+- **Impact:** Worst case is a missed draft-time stamphog pre-review on an experimental, per-user opt-in feature during a sustained (> retry-window) GitHub/Temporal outage — degraded experience only. A review that never runs posts nothing, so there is no stale-approval/safety exposure and no data or correctness impact, and the feature degrades gracefully (next output save or push re-triggers; ReviewHog/human review still apply). Combined with the deliberate, documented retry-don't-drop tradeoff (tasks.py:1155-1157), the suggestion is a robustness enhancement to a system-wide pattern rather than a fix for a user-affecting defect — below the bar under precision-over-recall.++### [❌ dismissed] should_fix — products/stamphog/backend/tasks/tasks.py:1140-1152++**Coalesce repeated receiver dispatches before fetching GitHub**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The TaskRun receiver intentionally re-fires whenever output carrying the PR URL is saved, and every resulting Celery task performs a GitHub GET before it can discover the existing head-keyed run. There is no queue-side debounce or cache, so routine follow-up/output saves can create an unbounded stream of duplicate jobs and GitHub requests for an unchanged PR. At scale this wastes workers and egress budget and can itself trigger the rate-limit failure path.+- **Suggestion:** Add a short-lived per-team/run/PR coalescing key around enqueueing or the initial GitHub fetch, releasing it on failure. The window should only collapse bursty duplicate saves; webhook deliveries should remain the primary path for prompt head-change re-reviews, while a later receiver save can still recover a missed webhook.+- **Validator:** - **Checked:** The receiver's dispatch guards (`handle_task_run_saved` in review_hog/receivers.py — the `"output" not in update_fields` filter, non-internal, signal-report, assigned-reviewer, and `stamphog_review_inbox_prs` gates); the fetch-before-dedupe rationale (tasks.py:1155-1157); the head-keyed dedupe/early-return (tasks.py:1202-1221); and whether any pre-fetch cache already exists.+- **Found:** Dispatches are bounded by output-carrying saves on a non-internal signal-report run with an opted-in reviewer — a handful per run, not the 'unbounded stream' claimed. Saves that don't touch `output` (status flips, log appends via `append_task_run_log`) are filtered out before dispatch. Each redundant dispatch is one read-only `get_pr` GET (tasks.py:1159) plus a dedupe that returns early once a live/delivered run exists.+- **Found:** The fetch necessarily precedes the dedupe because the dedupe key is the PR's current head, which only GitHub knows (tasks.py:1157) — so dedupe-without-fetch requires exactly the cache the finding proposes; the reviewer is right that no such cache exists today.+- **Impact:** A few redundant read-only GitHub reads per PR on an experimental, per-user opt-in feature — negligible against the GitHub App rate budget and dwarfed by the review's own API traffic (files/reviews/checks/clone/post). Not N+1, quadratic, or unbounded on realistic inputs; the rate-limit-trigger claim is speculative and, if ever reached, is absorbed by the existing adaptive retry (tasks.py:1160-1162). This is a future-scaling micro-optimization rather than a defect that bites at real scale — below the bar under precision-over-recall.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-1.mdnew file mode 100644index 000000000000..1152150f5aca--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-1.md@@ -0,0 +1,270 @@+# Reviewer-quality run — `I-gpt56sol-xhigh-1`++- **Dumped:** 2026-07-31T00:25:21+00:00+- **Report id:** `019fb571-da39-79e9-bc84-87ae19e76b87` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 1935s (32.2 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-sol` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 14 | 11 | 2 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ----------- | ---------- | --------- | ---------- |+| claude-opus-4-8 | validation | 67 | 71,576 | 444,673 | 5,943,244 | 126,672 | 1 | $9.28 | $9.28 |+| gpt-5.6-sol | review | 80 | 4,069,684 | 0 | 0 | 19,916 | 0 | — | $5.96 |+| gpt-5.6-sol | blind-spot | 24 | 1,186,032 | 0 | 0 | 7,463 | 0 | — | $1.94 |+| claude-sonnet-5 | dedup | 1 | 8,055 | 0 | 0 | 7,811 | 0 | $0.09 | $0.09 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 2,218 | 0 | $0.03 | $0.03 |+| **total** | | **173** | **5,341,328** | **444,673** | **5,943,244** | **164,080** | **1** | **$9.40** | **$17.31** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = +0.0%.+- `true $` total excludes unpriced model `gpt-5.6-sol` (104 gen(s), gw $7.91).+- naive method (all prompt tokens at input price): $35.59 — 3.8× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $13.2225 over 173 gen(s) (true $6.1368, Δ +115.5%)+ - · of which cache read: $5.1042 over 153 gen(s) (true $2.9716, Δ +71.8%)+ - · of which cache write: $2.7792 over 67 gen(s) (true $2.7792, Δ +0.0%)+ - · of which fresh (derived): $5.3391 over 173 gen(s) (true $0.3860, Δ +1283.4%)+ - output: $4.0885 over 173 gen(s) (true $3.2671, Δ +25.1%)+- 1 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …08681cdd | issues-review-p2-c3 | 23:54:02 | 0 | 0 | gpt-5.6-sol |+| …f605b158 | issues-review-p3-c2 | 23:54:02 | 0 | 0 | gpt-5.6-sol |+| …6f511d2f | issues-review-p2-c2 | 23:54:03 | 0 | 0 | gpt-5.6-sol |+| …04bb9960 | issues-review-p3-c1 | 23:54:03 | 0 | 0 | gpt-5.6-sol |+| …2c659630 | issues-review-p2-c1 | 23:54:04 | 0 | 0 | gpt-5.6-sol |+| …f1a1450d | issues-review-p1-c3 | 23:54:04 | 0 | 0 | gpt-5.6-sol |+| …04b028b4 | issues-review-p1-c1 | 23:54:06 | 0 | 0 | gpt-5.6-sol |+| …edbd202e | issues-review-p1-c2 | 23:54:06 | 0 | 0 | gpt-5.6-sol |+| …8e6bf4ae | issues-review-p1-c3 | 23:57:03 | 0 | 0 | gpt-5.6-sol |+| …e3f9223e | issues-review-p2-c1 | 23:57:15 | 0 | 0 | gpt-5.6-sol |+| …72b5b84d | issues-review-p3-c1 | 23:57:16 | 0 | 0 | gpt-5.6-sol |+| …50538900 | blind-spots-c3 | 23:58:59 | 0 | 0 | gpt-5.6-sol |+| …e78da583 | blind-spots-c2 | 23:59:02 | 0 | 0 | gpt-5.6-sol |+| …3bee49fa | blind-spots-c1 | 23:59:03 | 0 | 0 | gpt-5.6-sol |+| …d41f741d | blind-spots-c4 | 23:59:17 | 0 | 0 | gpt-5.6-sol |+| …2512c7a9 | validation-c2 | 00:02:22 | 0 | 38,051 | claude-opus-4-8 |+| …bfe5600c | validation-c1 | 00:02:25 | 0 | 37,405 | claude-opus-4-8 |+| …0a641d2a | validation-c3 | 00:02:26 | 17,141 | 19,905 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **1/18** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 24s |+| review wave (perspectives) | 5m 00s |+| blind-spot sweep | 2m 02s |+| dedup (incl. combine/clean) | 1m 16s |+| validation | 23m 28s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 7m 02s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | ? | 0 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 3 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 2 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:321-321++**Security-sensitive flag accepts arbitrary truthy values**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `bool(context.get("self_driving_review"))` enables the bot-author and draft gate bypass for any truthy JSON value, including strings such as `"false"` or objects. This weakens the contract at the boundary controlling an approval-related security exception and can incorrectly label the provenance as verified.+- **Suggestion:** Require the exact JSON boolean value, for example `self_driving=context.get("self_driving_review") is True`, or validate the complete hosted context schema and fail closed when this field is not a boolean.+- **Validator:** - **Checked:** `review_local.py` module docstring and `_build_pr_data`/`run` to trace where `self_driving_review` and other boolean flags enter, and how the `context` dict is produced.+- **Found:** The docstring (`tools/pr-approval-agent/review_local.py:16-20`) states the `context` JSON is assembled by the server that holds the token — it is trusted, server-produced input, not attacker-controlled PR content. The PR author cannot set arbitrary top-level context keys like `self_driving_review`.+- **Found:** `bool(...)` coercion is the consistent house convention for every boolean read from this same context: `draft=bool(pr.get("draft"))` (line 195), `is_outdated=bool(thread.get("is_outdated"))`, `bool(comment.get("author_is_bot"))`. `draft` is itself one of the two security gates this feature relaxes and is read with the identical pattern — so the flagged line matches, not weakens, the established boundary convention.+- **Found:** Default-closed behavior is already correct: absent key → `None` → `bool(None) == False`; a proper JSON `false` → `bool(False) == False`. Divergence from `is True` requires the trusted server to serialize a non-boolean truthy value (e.g. string `"false"`), which a boolean flag serializer does not emit.+- **Impact:** The described bypass requires a producer-side malformation from trusted server code that cannot occur with normal JSON boolean serialization, and the input is not reachable by the PR author. This is speculative what-if / defensive-boundary paranoia rather than a reachable security or correctness defect, so it does not meet the bar to surface.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9++**Migration introduces a conflicting 0019 leaf**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The app already contains `0019_reviewreport_author_login_and_more.py` and later migrations. Adding another migration numbered 0019 that also depends on 0018 creates two leaf nodes and causes Django's conflicting-migrations check to fail.+- **Suggestion:** Rebase this migration onto the current leaf, using the next available migration number and dependency, then update `products/review_hog/backend/migrations/max_migration.txt`. Run `python manage.py rebase_migration review_hog` or regenerate the migration and verify `makemigrations --check` reports no conflict.+- **Validator:** - **Checked:** the actual PR diff (`gh pr diff 75215`) for the migration and `max_migration.txt`, plus master's migration graph and every migration whose dependency is `0018_backfill_urgency_threshold_to_consider`.+- **Found:** the PR's `0019_reviewusersettings_stamphog_review_inbox_prs.py` declares `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]`, but master already has `0019_reviewreport_author_login_and_more.py` depending on the same `0018` parent, continuing through `0024_reviewreport_published_head_shas` (`products/review_hog/backend/migrations/0019_reviewreport_author_login_and_more.py:8`). On merge the graph has two siblings off `0018` and two leaf nodes (`0019_...stamphog` and `0024_...head_shas`).+- **Found:** the PR rewrites `max_migration.txt` from `0018...` to `0019_reviewusersettings_stamphog_review_inbox_prs`, colliding with master's `0024_reviewreport_published_head_shas` — the django-linear-migrations single-leaf gate this repo enforces.+- **Impact:** concrete blocker — `makemigrations --check` fails with "multiple leaf nodes", `max_migration.txt` conflicts, and CI's migration-conflict gate blocks the merge until the migration is renumbered onto the current `0024` leaf (`rebase_migration review_hog`). Meets the keep bar (contract/build break, directly introduced by the change) with a named trigger and consequence; `must_fix` is the right severity.++### [❌ dismissed] should_fix · bug — tools/pr-approval-agent/reviewer.py:568-568++**Self-driving reviews can still include bot familiarity signals**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The prompt concatenates both `familiarity_block` and `self_driving_block`. Hosted reviews call `_attach_familiarity` before the LLM review, so a T1 bot PR with any `author_pr_numbers` can receive a familiarity band and merged-history evidence. This contradicts the new provenance block's statement that machine-author familiarity and merged-PR history carry no signal, and may cause the reviewer to trust bot-wide history when judging an individual generated change.+- **Suggestion:** Suppress familiarity for self-driving runs before composing the prompt. For example, render `familiarity_block = ""` when `cl.get("self_driving")` is true, and also skip `_attach_familiarity` for these runs so telemetry and prompt state cannot imply author familiarity.+- **Validator:** - **Checked:** How `_attach_familiarity` gates the familiarity signal and how the server assembles `author_pr_numbers` vs `self_driving_review`, using the actual PR diff (`products/stamphog/backend/temporal/activities.py`, `tools/pr-approval-agent/review_local.py`, new integration test).+- **Found:** In `fetch_review_context` the PR adds `is_inbox_review = bool((run.output or {}).get("inbox_review"))` and sets `author_pr_numbers = client.get_author_merged_pr_numbers(repo, author) if author and not is_inbox_review else []` — for inbox/self-driving runs `author_pr_numbers` is hard-coded to `[]`, with a comment that the machine user's merged-PR familiarity is deliberately left absent so it isn't read as human trust context.+- **Found:** `self_driving_review=bool(output.get("inbox_review"))` keys off the same `run.output["inbox_review"]` provenance as `is_inbox_review`, so `self_driving` True ⇒ `author_pr_numbers == []` always; the two cannot diverge.+- **Found:** `_attach_familiarity` returns early on `raw_prs = context.get("author_pr_numbers"); if not raw_prs: return` (`review_local.py:301-303`), so empty `author_pr_numbers` leaves `familiarity` None, `_format_familiarity` returns `""`, and no familiarity block is concatenated — the contradiction the finding describes never renders.+- **Found:** The new `test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end` asserts both `context["self_driving_review"] is True` and `context["author_pr_numbers"] == []`, commenting "the machine user's merged-PR history must not feed familiarity" — the invariant is pinned.+- **Impact:** The finding's trigger ("a T1 bot PR with any `author_pr_numbers`") is unreachable; the PR already suppresses `author_pr_numbers` for self-driving runs at the server layer, with a test. Already-handled / wrong-premise, so it does not meet the bar.++### [❌ dismissed] must_fix · security — products/stamphog/backend/tasks/tasks.py:1110-1155,1209-1232++**Initial inbox path can mark an unrelated PR as self-driving**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This task trusts the caller-provided PR URL and provenance, then fetches any open PR in a configured repository and stamps `inbox_review`. It does not verify that `task_run_id` identifies a team-scoped signals implementation run, that its stored PR URL matches this PR, or that the fetched PR is bot-authored and repo-native. Because TaskRun output is produced by an agent, a forged or mistaken URL can make an unrelated human or fork PR enter the privileged self-driving engine path, bypassing the normal bot/draft safeguards and potentially receiving an automated approval.+- **Suggestion:** Before creating the run, resolve `task_run_id` through a team-scoped tasks facade and verify its signal report, repository, and recorded PR URL against the supplied provenance. Also require the fetched PR to satisfy the same bot-author and repo-native-head checks used by `_inbox_rereview_carve_out`. Derive `signal_report_id` and other provenance from the verified run rather than trusting Celery arguments; otherwise return without stamping `inbox_review`.+- **Validator:** - **Checked:** The caller of `process_inbox_pr_review` — `handle_task_run_saved` in `products/review_hog/backend/receivers.py:72-139` — plus how `output.pr_url` is written (`products/tasks/backend/webhooks.py:179-231`), the `find_task_run` matcher (`webhooks.py:30-79`), the webhook carve-out `_inbox_rereview_carve_out`, and the team-scoping inside the new task.++- **Found:** The initial-path trigger is a trusted internal `post_save` on a real team-scoped `TaskRun`, not an untrusted external event. The receiver already establishes the self-driving shape before dispatch: `task.signal_report_id is not None` (`receivers.py:98`), `not task.internal` (`:104`), and it passes the run's _own_ identifiers — `task_run_id=str(instance.id)` (`:137`), `signal_report_id=str(task.signal_report_id)` (`:136`), `pr_url=output.get("pr_url")` (`:93`). `_inbox_rereview_carve_out` does rigorous positive-ID because _its_ trigger is an arbitrary GitHub webhook (attacker can push any fork/human PR); that threat model does not transfer to the receiver leg.++- **Found:** In `process_inbox_pr_review`, `task_run_id`/`signal_report_id`/`acting_user_id` are only stamped as opaque provenance into `output={"inbox_review": {...}}` — they drive no cross-tenant fetch. Tenant isolation is enforced independently via `StamphogRepoConfig.objects.for_team(team_id)` (enabled + connected) and `ReviewRun.objects.for_team(team_id)`, so a wrong provenance id can only mislabel attribution, not cross a boundary.++- **Found:** `output.pr_url` is not free-form LLM output. It is set by the agent server observing the bot open its own PR (bot-authored, repo-native by construction) or by the fork-safe backstop `_record_run_pr_url`, which records only when `is_internal_branch` (`webhooks.py:179-186`) — the same fork guard the carve-out mirrors. The 'forged/fork PR URL enters the self-driving path' premise is thus not reachable; the target is constrained to the run's own repo-native bot PR inside the team's own connected+enabled repo.++- **Impact:** The requested re-verifications (re-resolve via `find_signal_implementation_run`, re-verify `pr_url` match, re-check bot-author/repo-native on the fetched PR) are belt-and-braces re-checks of invariants the trusted caller and the fork-safe `output.pr_url` write paths already establish — the 'already handled / defensive-coding paranoia' drop categories. 'Verify stored PR URL matches this PR' is also circular: the passed `pr_url` _is_ the stored `output.pr_url`. No concrete reachable trigger→consequence survives, so it does not meet the keep bar.++### [❌ dismissed] should_fix · security — products/tasks/backend/facade/api.py:484-506++**Team scoping is applied only after a cross-tenant TaskRun query**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `find_signal_implementation_run` calls the unscoped `find_task_run` first and only checks `run.team_id` after an object has been selected. Besides crossing the tenant boundary unnecessarily, a matching run from another team can win the underlying `.first()` lookup and hide a valid run in the requested team. The facade therefore does not enforce team scoping at the query boundary as its contract claims.+- **Suggestion:** Add `team_id` as an explicit argument to `find_task_run` or implement the lookup here with `TaskRun.objects.filter(team_id=team_id, ...)`, applying the tenant predicate to every PR URL and branch lookup before ordering or selecting a row.+- **Validator:** - **Checked:** The full body of `find_signal_implementation_run` (from the PR diff), the `find_task_run` it delegates to (`products/tasks/backend/webhooks.py:30-79`), the sole caller `_inbox_rereview_carve_out`, and the function's own docstring/contract.++- **Found (no tenant leak):** After `run = find_task_run(...)` the code does `if run is None or run.team_id != team_id: return None`, and the `SignalImplementationRunDTO` is only constructed on the surviving same-team run. A cross-team match is discarded before any field is read — nothing from another tenant's run reaches the caller. The security/IDOR framing does not hold: the boundary IS enforced, just as a post-filter rather than a query predicate.++- **Found (docstring accurate):** The contract states 'a run belonging to any other team returns None … no caller can accidentally bind a PR to another tenant's run' — exactly the observed behavior. The reviewer's stronger paraphrase ('enforce team scoping at the query boundary') is not what the docstring claims.++- **Found (primary leg not shadowable):** `find_task_run`'s pr_url leg filters `output__pr_url=pr_url` AND `task__repository__iexact=repository` (`webhooks.py:42-44`), and the caller always supplies `pr_url=pr.get('html_url')` (always present on a `pull_request` webhook). A PR URL globally identifies one PR, recorded in `output.pr_url` only by the single team's run that produced it, so two teams cannot both match the same `output__pr_url` — the pr_url leg cannot be shadowed by another tenant. The branch leg (`filter(branch=..., task__repository__iexact=...)`), the only place a cross-team branch collision could win `.first()`, is reached solely when the pr_url leg finds nothing, and only if two teams share the same repo and a colliding head branch.++- **Impact:** The claimed 'hide a valid same-team run → None' requires that contrived multi-tenant shared-repo colliding-branch fallback case, and even then it is fail-safe: the carve-out returns None, the caller falls to the normal skip path which retracts any stale approval — a missed re-review, never a wrong or cross-tenant approval. Narrow, low-impact, with the security premise already closed by the existing post-filter — the defensive-paranoia / never-gonna-happen-edge drop categories. On the fence → drop.++### [❌ dismissed] must_fix · bug — products/review_hog/backend/receivers.py:111-125,144-154++**Only one assignee's opt-in is considered**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The stated gate is that Stamphog runs when at least one assigned reviewer opts in, but `_resolve_assigned_reviewer` selects one canonical acting reviewer before the toggle is checked. If the task creator or first resolved reviewer is opted out while another assignee is opted in, both the initial dispatch and later webhook re-reviews are skipped incorrectly.+- **Suggestion:** Resolve all assigned organization members, then select an opted-in reviewer deterministically for the Stamphog path, preferring the assigned task creator when opted in and otherwise the first opted-in assignee. Use the same selection logic in `resolve_stamphog_acting_reviewer` so initial and webhook behavior remain consistent. Keep ReviewHog's existing single-reviewer selection semantics separate.+- **Validator:** - **Checked:** `_resolve_assigned_reviewer` selection logic and both toggle-gate call sites in `receivers.py`, the pre-existing `_resolve_acting_reviewer` it replaces (via the PR diff), the function docstring, and the webhook resolver `resolve_stamphog_acting_reviewer`.+- **Found:** the single-acting-reviewer model is not new — the old `_resolve_acting_reviewer` already gated `review_inbox_prs` on the one `acting.id` (diff line 135, removed), and the new code keeps that exact behavior, adding `stamphog_review_inbox_prs` as a parallel check on the same reviewer (`settings = ReviewUserSettings.load(...); if settings.review_inbox_prs ... if ... settings.stamphog_review_inbox_prs`, diff lines 62–74). `resolve_stamphog_acting_reviewer` reuses `_resolve_assigned_reviewer` identically (diff lines 102–107).+- **Found:** the docstring documents the single canonical reviewer as a deliberate choice — `acting = created_by when among resolved, else resolved[0]` — citing "maintainer decisions, 2026-07-02/03," and ties it to using that reviewer's ReviewHog options (perspectives / blind-spots / validator / urgency threshold) to drive the review; the PR's test comment reinforces it: "the two toggles on the one acting reviewer gate their reviews independently."+- **Impact (why it doesn't meet the bar):** the claimed bug rests on the PR description's simplified wording ("at least one of the assigned users"), which contradicts the actual, documented, intentional design that the sibling `review_inbox_prs` toggle has always followed. There is no regression and no divergence from established behavior. The reviewer's fix (scan all assignees for the toggle while keeping single-reviewer option semantics) is a design change that would split the two toggles' semantics and add complexity — overengineering, not a correctness fix. Premise is mistaken, so drop (precision over recall).++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:114-138++**A ReviewHog callback failure can prevent the independent Stamphog dispatch**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The ReviewHog callback is registered before the Stamphog callback, and both use Django's default `robust=False`. If `_start_review` raises before its internal `try` block, such as while importing its deferred Temporal modules, Django stops executing later commit callbacks. The Stamphog review is then never queued, despite its toggle being independent, and the exception can surface after the database transaction has committed.+- **Suggestion:** Register these fire-and-forget callbacks with `transaction.on_commit(..., robust=True)` and move each deferred import inside its protected `try` block. This keeps either integration's import or dispatch failure from blocking the other callback or escaping into the request/save path.+- **Validator:** - **Checked:** the two `transaction.on_commit` registrations (diff lines 64–74), the full body of `_start_review` (receivers.py:164-200) and `_start_stamphog_review` (diff lines 140-164) to locate what can raise outside their `try` blocks, and Django's `robust=False` on_commit semantics.+- **Found:** in `_start_review`, only the deferred imports at receivers.py:181-182 sit outside the `try`; the `target_kwargs` build and the `start_review_pr_workflow` call are inside `try/except Exception` (lines 188-200), which logs and swallows. `_start_stamphog_review` mirrors this (deferred import outside, `queue_inbox_pr_review` call inside `try`). So the realistic failure — Temporal/broker unavailable — is already caught in both and never propagates to halt the sibling callback.+- **Found:** the reviewer's Django claim is accurate (a raising `robust=False` hook stops later hooks), but the only trigger is the deferred import of `products.review_hog.backend.temporal.client`/`.types` actually raising. Those modules are imported on the first inbox review and cached in `sys.modules` thereafter, so the import is a no-op lookup; a real ImportError is a systemic deploy misconfiguration that breaks every ReviewHog inbox review anyway, not a transient per-save condition.+- **Impact (why it doesn't meet the bar):** the scenario where the ReviewHog callback's exception skips the stamphog dispatch requires a practically-unreachable import failure — the realistic runtime failure (workflow start error) is already handled inside the `try`. The 'exception surfaces post-commit' aspect is pre-existing to `_start_review` and gated on the same unreachable trigger. This is a never-gonna-happen edge / defensive-robustness nicety, not a failure mode that will occur; precision over recall → drop.++### [❌ dismissed] must_fix · bug — products/stamphog/backend/tasks/tasks.py:1200-1228++**Head-keyed deduplication does not serialize concurrent task deliveries**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** `select_for_update()` only locks an existing `ReviewRun`. When two receiver-triggered tasks process the same PR head concurrently and no run exists yet, both queries return `None`, both create a row, and both start separate Temporal workflows. `ReviewRun` has no uniqueness constraint on `(pull_request, head_sha)`, so duplicate reviews and conflicting GitHub output remain possible despite the stated deduplication guarantee.+- **Suggestion:** Enforce deduplication at the database boundary. Add an appropriate unique constraint or idempotency key for inbox runs and create with conflict handling, or lock the parent `PullRequest` row before checking for an existing run so concurrent executions serialize. Handle the resulting `IntegrityError` by loading and resuming the winning run.+- **Validator:** - **Checked:** The full `process_inbox_pr_review` atomic block (PR diff), `_upsert_pull_request` (`products/stamphog/backend/tasks/tasks.py:204-248`), the model constraints on `PullRequest` and `ReviewRun` (`products/stamphog/backend/models.py:78-173`), and the webhook path's documented serialization comment (`tasks.py:894-898`).++- **Found (premises right, conclusion wrong):** `ReviewRun` indeed has no `(pull_request, head_sha)` unique constraint (`models.py:140-173`; `delivery_id` is unique-but-nullable and inbox runs pass `delivery_id=None`), and `select_for_update()` over an absent row locks nothing. But the predicted double-create cannot occur, because both concurrent fires must first execute `pr_obj = _upsert_pull_request(repo_config, pr)` — the first statement in the same `transaction.atomic(using=run_write_db)` block, on the same PR — before reaching the `ReviewRun` check.++- **Found (serialization point):** `_upsert_pull_request` calls `PullRequest.objects.for_team(team_id).get_or_create(repo_config=..., pr_number=...)` against unique constraint `unique_stamphog_pull_request` on `(team_id, repo_config, pr_number)` (`models.py:120-121`). No PR row yet: the loser's duplicate INSERT blocks until the winner commits, then catches IntegrityError and re-fetches. PR row exists: the conditional refresh `.update(...)` (`tasks.py:234-239`) takes the PR row lock held to commit — the exact mechanism the webhook path documents at `tasks.py:894-898`. Either way the two fires serialize on the PullRequest row.++- **Found (loser sees winner's run):** After the winner commits its `ReviewRun`, the loser unblocks and under READ COMMITTED its `select_for_update().filter(pull_request=pr_obj, head_sha=head_sha)` sees the committed run and returns via `existing is not None` — no second create, no second workflow. Both fires carry the same `head_sha` (same fetched PR), so the filter matches.++- **Impact:** The stated failure (two rows, two workflows, conflicting GitHub output) is unreachable; dedup holds via PR-row serialization. The only unserialized crack — existing PR row AND `incoming_updated_at is None` skipping the UPDATE lock (`tasks.py:231-233`) — cannot happen here because the PR is fetched fresh from GitHub, whose payloads always carry a parseable `updated_at`. Does not meet the bar.++### [❌ dismissed] should_fix · performance — products/tasks/backend/facade/api.py:505-508++**Unmatched bot PRs can trigger an unindexed TaskRun branch scan**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The new webhook carve-out calls `find_task_run` for bot-authored PRs. If its indexed `output.pr_url` lookup misses, that helper falls back to filtering `TaskRun.branch` plus the related task repository and ordering by creation time. `TaskRun.branch` has no supporting index, so unrelated bot PR deliveries can cause an increasingly expensive scan of the TaskRun table on every synchronize or reopen event.+- **Suggestion:** Avoid the branch fallback when the authoritative PR URL was supplied, or add a query/index strategy that supports the fallback, such as an index beginning with `branch` and covering the ordering while retaining the repository join filter. Validate the chosen query with `EXPLAIN` against the expected table size.+- **Validator:** - **Checked:** `find_task_run`'s branch fallback (`products/tasks/backend/webhooks.py:62-79`), the `TaskRun`/`Task` index definitions (`products/tasks/backend/models.py:1537`, `1600-1630`; `183-185`, `266-272`), how the carve-out reaches it via `find_signal_implementation_run`, and the pre-existing caller `handle_pull_request_event` (`webhooks.py:130-217`).++- **Found (premise technically correct):** `TaskRun.branch` (`models.py:1537`) has no index and is absent from `Meta.indexes` (`1603-1630`); `Task.repository` (`183-185`) is unindexed too, and `__iexact` would defeat a btree anyway. The branch leg `filter(branch=..., task__repository__iexact=..., state__wizard_head_branch__isnull=True).first()` (default `-created_at` ordering) is scan-prone, and `find_signal_implementation_run` does fall into it when the indexed `output.pr_url` lookup misses.++- **Found (self-driving target never hits the scan):** The `output.pr_url` leg is index-backed (`task_run_output_pr_url_idx`, `models.py:1609-1613`) and runs first. A real self-driving PR records `output.pr_url` when opened, so on every later synchronize the pr_url leg matches and short-circuits; the branch leg is reached only for bot PRs whose URL matches no run (dependabot/renovate etc.), which never match the branch leg either — wasted work, but only for non-target PRs.++- **Found (pre-existing, production-exercised query):** The identical branch leg is already invoked by the tasks webhook `handle_pull_request_event` → `find_task_run` (`webhooks.py:160`) on every `opened`/`closed` PR across all tasks-app repos as the `_record_run_pr_url` backstop when the agent-side detector hasn't recorded the URL yet. Its index profile is a long-standing accepted cost, not introduced by this PR; the carve-out adds a bounded subset (bot-authored + repo-native + stamphog-enabled + pr_url-miss).++- **Impact:** Runs async inside the `process_pull_request_event` Celery task, not on the webhook request path. Stamphog is gated behind a per-user toggle plus an enabled repo config (experimental), so current invocation volume is tiny and 'increasingly expensive scan at real scale' is speculative about future broad rollout of a query that already runs at comparable/higher volume elsewhere without being a known issue. Real but bounded, pre-existing, and only for non-target PRs — below the 'bites at real scale / new problem' bar. On the fence → drop.++### [✅ VALID] must_fix (validator→consider) · security — products/tasks/backend/facade/api.py:500-508++**Branch fallback can authorize a different PR**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** When the exact PR URL does not match, find_task_run falls back to repository and branch. That fallback can return an old or otherwise unrelated run, including one whose output already names a different PR. The webhook carve-out then treats the current bot-authored PR as self-driving and permits an automated approval. Reusing a branch or opening a second PR from it is enough to trigger the incorrect binding.+- **Suggestion:** For this authorization-sensitive facade, accept a branch match only when the selected run has no recorded pr_url, and reject it when output.pr_url differs from the supplied URL. Perform the team-scoped lookup directly and prefer active runs deterministically.+- **Validator:** - **Checked:** The non-wizard branch leg of `find_task_run` (`products/tasks/backend/webhooks.py:65-79`) vs the adjacent wizard leg (`:82-97`), how `find_signal_implementation_run` forwards both `pr_url` and `head_branch` to it, and the carve-out gates in `_inbox_rereview_carve_out` that guard what reaches this facade.++- **Found (gap is real):** The non-wizard branch leg `filter(branch=branch, task__repository__iexact=repository, state__wizard_head_branch__isnull=True).first()` (`webhooks.py:69-77`) applies no `output.pr_url` consistency check and no terminal-status exclusion, returning the newest branch-matching run (default `-created_at`) regardless of which PR its `output.pr_url` names. The sibling wizard leg DOES `.exclude(status__in=_TERMINAL_RUN_STATUSES)` precisely 'so a reopened branch can't fire events on a dead run' (`:82-84`) — the authors saw this hazard but the non-wizard leg lacks the guard. `find_signal_implementation_run` adds no pr_url-match check, so a branch-matched run whose recorded PR differs from the incoming one still yields a DTO and the carve-out authorizes the incoming PR as self-driving.++- **Found (reachability narrow, blast radius bounded):** The branch leg is only reached when the indexed `output.pr_url` leg misses; for a genuine self-driving PR the URL is recorded once opened, so normal-flow synchronizes match on pr_url and never reach it. Mis-binding needs an abnormal state — a second PR sharing a prior signals run's head branch (branch reuse after close, or a second base) — and the common re-run case binds to the newest branch-B run (often correct). The incoming PR is also provably bot-authored (`_is_bot_authored`) and repo-native (`head_repo == repo` fork check), in an enabled/synced/connected stamphog repo, with an opted-in SR reviewer required — so the mis-bound PR is always a bot, repo-native PR in the team's own opted-in repo, not an arbitrary human/fork PR.++- **Impact:** In that edge state a bot PR could get a self-driving review and automated approval attributed to an unrelated signal report's reviewers, bypassing the bot/draft gate — a genuine authorization-consistency gap in a facade whose documented job is to 'positively identify' the run, with a cheap fix (reject a branch match when the run's `output.pr_url` is set and differs). But abnormal-state reachability, newest-run-wins ordering fixing the common case, and the bounded bot/repo-native/own-repo blast radius put it well below `must_fix`.++- **Priority:** Lowered to `consider` — real and worth recording, but edge-case reachable with bounded blast radius, not urgent.++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1107-1115,1182-1187++**Queued initial reviews ignore later opt-out**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The initial Celery task trusts the acting_user_id resolved before dispatch and never rechecks the reviewer assignment or stamphog toggle. If the task waits in the queue, retries after a transient failure, or the reviewer disables the feature before execution, it still stamps inbox provenance and runs the review contrary to the current preference. The webhook re-review path performs this freshness check, but the initial path does not.+- **Suggestion:** Before creating the ReviewRun, resolve the acting reviewer again from the team-scoped signal/task provenance and return without reviewing when nobody currently qualifies. Keep the queued acting_user_id only as advisory attribution, or replace it with the freshly resolved ID.+- **Validator:** - **Checked:** The `process_inbox_pr_review` body (PR diff) for any reviewer/toggle re-resolution, how `acting_user_id` is used inside it, the dispatch site in `receivers.py` (`_start_stamphog_review` via `transaction.on_commit`), and how the design characterizes the toggle vs safety (`_inbox_rereview_carve_out` docstring).++- **Found (gap real but input fresh by construction):** `process_inbox_pr_review` re-checks nothing about opt-in — its only gate is `repo_config...enabled=True`, and `acting_user_id` flows straight into the `inbox_review` provenance dict with no gating role. But the task is dispatched via `transaction.on_commit(lambda: _start_stamphog_review(...))` (`receivers.py:131-139`) immediately after the receiver read `settings.stamphog_review_inbox_prs` (`:126`), so the trusted value was verified microseconds earlier; the race window is seconds (default retry delay 5s), not the open-ended gap the webhook path faces. The webhook path re-resolves through the resolver precisely because its trigger (an arbitrary later push, possibly days on) is temporally decoupled from any prior check — the asymmetry is justified, not an oversight.++- **Found (toggle is preference, not safety; harm self-corrects):** The design explicitly states 'safety is never preference-gated' (`_inbox_rereview_carve_out` docstring) — approval retraction is independent of the toggle. A stale toggle read causes at most one initial review of the team's own bot, repo-native, draft PR in an enabled repo. If the reviewer had truly opted out, the next head-changing event routes through the webhook carve-out's `opted_out=True` path and dismisses any standing approval via `_INBOX_OPT_OUT_DISMISS_MESSAGE`. And if multiple reviewers are opted in, one toggling off wouldn't change the resolved outcome.++- **Impact:** The failure needs a reviewer to flip the toggle off in the exact seconds-window between the agent autonomously opening the PR and the queued task running — an uncorrelated narrow race — and yields only a single preference-stale review whose approval self-corrects on the next push. Defensive re-checking of a value already fresh at dispatch, guarding a preference the design deliberately decouples from safety — below the keep bar (defensive-paranoia / never-gonna-happen edge). On the fence → drop.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-2.mdnew file mode 100644index 000000000000..b88a110e8787--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/I-gpt56sol-xhigh-2.md@@ -0,0 +1,271 @@+# Reviewer-quality run — `I-gpt56sol-xhigh-2`++- **Dumped:** 2026-07-31T00:58:59+00:00+- **Report id:** `019fb590-9def-713e-aa38-4ec12d787067` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 1937s (32.3 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-sol` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 13 | 14 | 13 | 4 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | -------------- | ----------- | ---------- | ---------- | ---------- |+| claude-opus-4-8 | validation | 107 | 67,303 | 506,841 | 11,475,708 | 144,002 | 8 | $12.84 | $12.84 |+| gpt-5.6-sol | review | 66 | 3,210,045 | 0 | 0 | 18,506 | 0 | — | $4.93 |+| gpt-5.6-sol | blind-spot | 22 | 1,041,118 | 0 | 0 | 5,719 | 0 | — | $1.87 |+| claude-sonnet-5 | dedup | 1 | 7,624 | 0 | 0 | 3,110 | 0 | $0.05 | $0.05 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 460 | 0 | $0.02 | $0.02 |+| **total** | | **197** | **4,332,071** | **506,841** | **11,475,708** | **171,797** | **8** | **$12.91** | **$19.71** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.6-sol` (88 gen(s), gw $6.80).+- naive method (all prompt tokens at input price): $63.91 — 5.0× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $15.3451 over 197 gen(s) (true $9.2693, Δ +65.5%)+ - · of which cache read: $7.4245 over 178 gen(s) (true $5.7379, Δ +29.4%)+ - · of which cache write: $3.1678 over 107 gen(s) (true $3.1678, Δ +0.0%)+ - · of which fresh (derived): $4.7528 over 197 gen(s) (true $0.3637, Δ +1206.7%)+ - output: $4.3625 over 197 gen(s) (true $3.6357, Δ +20.0%)+- 8 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …3d3cd137 | issues-review-p2-c3 | 00:27:20 | 0 | 0 | gpt-5.6-sol |+| …e4c46a57 | issues-review-p3-c2 | 00:27:20 | 0 | 0 | gpt-5.6-sol |+| …ede8c6f2 | issues-review-p3-c3 | 00:27:21 | 0 | 0 | gpt-5.6-sol |+| …0ac846a5 | issues-review-p1-c1 | 00:27:22 | 0 | 0 | gpt-5.6-sol |+| …4edd1967 | issues-review-p1-c3 | 00:27:22 | 0 | 0 | gpt-5.6-sol |+| …9c3edeed | issues-review-p2-c1 | 00:27:23 | 0 | 0 | gpt-5.6-sol |+| …2d2a8264 | issues-review-p2-c2 | 00:27:23 | 0 | 0 | gpt-5.6-sol |+| …f7294063 | issues-review-p1-c2 | 00:27:25 | 0 | 0 | gpt-5.6-sol |+| …92ec51a0 | issues-review-p3-c1 | 00:27:26 | 0 | 0 | gpt-5.6-sol |+| …daf638d0 | issues-review-p2-c2 | 00:30:35 | 0 | 0 | gpt-5.6-sol |+| …f6426874 | blind-spots-c1 | 00:32:16 | 0 | 0 | gpt-5.6-sol |+| …d2b91524 | blind-spots-c2 | 00:32:16 | 0 | 0 | gpt-5.6-sol |+| …dc1c7d5d | blind-spots-c3 | 00:32:18 | 0 | 0 | gpt-5.6-sol |+| …0ea358e1 | blind-spots-c4 | 00:34:12 | 0 | 0 | gpt-5.6-sol |+| …4c0f1a02 | validation-c3 | 00:37:24 | 0 | 37,043 | claude-opus-4-8 |+| …ec2c31c0 | validation-c2 | 00:37:25 | 0 | 37,524 | claude-opus-4-8 |+| …125d04dc | validation-c1 | 00:37:26 | 17,141 | 20,251 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **1/17** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 6s |+| review wave (perspectives) | 4m 55s |+| blind-spot sweep | 4m 02s |+| dedup (incl. combine/clean) | 34s |+| validation | 22m 35s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 8m 58s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 2 |+| 3 | 3 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 1 | review-hog-blind-spots-general | 1 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | review-hog-blind-spots-general | 1 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · best_practice — products/stamphog/backend/facade/api.py:146-153++**Fire-and-forget facade performs a synchronous, failure-propagating broker call**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Despite being described as fire-and-forget, `.delay()` synchronously contacts the Celery broker. Broker latency blocks the TaskRun save path, and a broker outage raises into the receiver and can fail the originating save. Dispatch can also occur before an enclosing database transaction commits, allowing the worker to race or outlive a rollback.+- **Suggestion:** Schedule dispatch with `transaction.on_commit()` and put the broker call behind explicit best-effort error handling and logging if review enqueue failure must not break TaskRun persistence. If delivery must be guaranteed, use the repository's durable outbox pattern instead of swallowing the broker error.+- **Validator:** - **Checked:** The sole production caller of `queue_inbox_pr_review` (`_start_stamphog_review` in products/review_hog/backend/receivers.py) and the receiver `handle_task_run_saved` that invokes it; grepped the diff for every reference to confirm no other call path exists.+- **Found:** Dispatch is scheduled **only** via `transaction.on_commit(lambda: _start_stamphog_review(...))` (receivers.py, diff L203-211) — the exact fix the finding recommends. on_commit callbacks fire after a successful commit and are discarded on rollback, so the worker cannot race or outlive a rollback, nor run before the commit.+- **Found:** `_start_stamphog_review` already wraps the facade call in `try/except Exception` with `logger.exception(...)` (diff L278-288), and the enclosing `handle_task_run_saved` is itself in a try/except (diff L213-214). A broker outage therefore cannot raise into the receiver or fail the originating save — refuting the finding's central risk claim.+- **Found:** A dedicated test, `test_stamphog_queue_failure_never_raises_into_the_save_path` (diff L377-388), locks this contract in; the pattern matches CLAUDE.md's endorsed `transaction.on_commit()` Celery-dispatch guidance.+- **Impact:** Both suggested remediations (`transaction.on_commit()` + best-effort error handling/logging) are already implemented, and the failure scenarios (broken save, pre-commit dispatch, rollback race) are unreachable. The only literally-true sub-claim — that `.delay()` does a synchronous broker publish on the post-commit thread — is the standard, intentional design (heavy GitHub/DB work is offloded into the Celery task precisely to keep the save path light) and is not a defect. Drops under 'already handled' and 'wrong/unreproducible'.++### [❌ dismissed] should_fix · performance — tools/pr-approval-agent/review_local.py:324-324++**Self-driving reviews still perform expensive author-familiarity analysis**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Allowing bot-authored self-driving PRs past this gate sends T1 reviews through `_attach_familiarity`, which can run git history analysis across up to 30 files. This work is wasted for machine authors and may add substantial latency; the new prompt also states that author familiarity carries no signal, yet any computed familiarity is still rendered alongside that statement.+- **Suggestion:** Skip `_attach_familiarity` when `pipeline.self_driving` is true, and keep `classification["familiarity"]` unset for this path. Consider also avoiding the upstream merged-PR lookup for self-driving runs.+- **Validator:** - **Checked:** `_attach_familiarity` in `review_local.py`, its call site in `run()`, and where `context["author_pr_numbers"]` originates in the server (`activities.py fetch_review_context`).+- **Found:** `_attach_familiarity` (`review_local.py:301-303`) does `raw_prs = context.get("author_pr_numbers")` then `if not raw_prs: return` — it short-circuits before `_ensure_diff_path()`/`_familiarity_offline` (the git-blame-over-files work), so an empty list means zero git analysis.+- **Found:** The server sets `author_pr_numbers = []` for self-driving runs: `activities.py` computes `is_inbox_review = bool((run.output or {}).get("inbox_review"))` and `author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []`. The very same `inbox_review` provenance drives `self_driving_review=bool(output.get("inbox_review"))`, so `self_driving=True` ⇒ `author_pr_numbers=[]` by construction. The integration test asserts `context["author_pr_numbers"] == []` for the self-driving path.+- **Found:** With familiarity never computed, `classification["familiarity"]` stays `None`, and `reviewer.py:643-645` `_format_familiarity` returns `""` — the no-signal provenance block is not accompanied by any rendered familiarity.+- **Impact:** The premise is mistaken ("Wrong / unreproducible"): the expensive merged-PR lookup is already skipped upstream (exactly the reviewer's own "consider also" suggestion) and `_attach_familiarity` is a guaranteed no-op for self-driving runs, so there is no wasted git analysis, no added latency, and no conflicting familiarity text. Nothing to fix.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:225-234++**Transient broker failures permanently drop the initial Stamphog review**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The on-commit callback ultimately publishes the Stamphog job, but `_start_stamphog_review` catches every publishing failure and only logs it. Once the transaction commits, nothing retries this handoff, so a temporary broker outage or timeout silently leaves an opted-in Inbox PR unreviewed. This is especially risky because later webhook handling depends on the initial review having recorded the PR as Inbox-originated.+- **Suggestion:** Make the handoff durable or retryable. Prefer recording an idempotent dispatch/outbox row in the transaction and having a retrying worker publish it. At minimum, configure bounded Celery publish retries and propagate failure to a retry-capable caller instead of swallowing it. Keep `task_run_id` as the idempotency key so retries cannot create duplicate reviews.+- **Validator:** - **Checked:** The full PR-head `receivers.py` (`_start_stamphog_review`, lines 210-234; the `transaction.on_commit` dispatch, 126-139) and the stamphog side it hands off to — `queue_inbox_pr_review` / `process_inbox_pr_review` and the webhook carve-out `_inbox_rereview_carve_out` in `products/stamphog/backend/tasks/tasks.py`.+- **Found:** The finding's escalating premise ("later webhook handling depends on the initial review having recorded the PR as Inbox-originated") is false. `_inbox_rereview_carve_out` re-identifies the PR as self-driving from scratch on every head-changing delivery: it calls `find_signal_implementation_run(team_id, repository, pr_url, head_branch)` against the **tasks** facade and re-checks the toggle via the registered resolver (`resolver(repo_config.team_id, run.signal_report_id, run.task_created_by_id)`). It reads nothing the initial `process_inbox_pr_review` leg persisted — provenance is re-derived from the tasks TaskRun, not from any stored Stamphog run.+- **Found:** So a dropped initial publish is self-healing, not "permanent": the next push (`synchronize`/`reopen`) re-triggers the independent webhook path, and repeat `output`-touching TaskRun saves re-fire the receiver (docstring lines 76-79). The initial Celery task is also durable once published — it has internal `.retry(...)` on config-resolution/fetch/rate-limit failures (tasks.py ~1382-1398). The only unguarded step is the `.delay()` broker publish itself.+- **Impact:** The residual failure is narrow and low-impact: a transient broker blip at the exact on-commit moment AND no subsequent push to that PR AND no further output save — a skipped initial review on one draft PR, recoverable on the next commit, not data loss or a security hole. The swallow-and-log is a deliberate, documented invariant ("the broker being down must never surface into the saver") on a hot `TaskRun` save path where raising would break tasks' own save. The proposed transactional-outbox + retrying-worker is heavyweight for that residual, on an experiment-gated per-user feature. With the finding's central "permanent drop" / webhook-dependency claims mistaken, this lands on the drop side (precision over recall).++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9++**Migration creates a conflicting leaf in the review_hog graph**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** This migration depends directly on 0018, but the app already has a different 0019 migration followed by migrations through 0024. Adding this file creates two leaf branches, preventing Django from determining a single migration path and causing migration-conflict checks or deployment to fail.+- **Suggestion:** Rebase the migration onto the current leaf, rename it to the next available number (for example 0025), update its dependency to 0024_reviewreport_published_head_shas, and update max_migration.txt accordingly. Run the migration conflict check and sqlmigrate afterward.+- **Validator:** - **Checked:** Fetched the PR head tree (SHA 1341596e) migration files and `max_migration.txt`, and compared against master's `products/review_hog/backend/migrations/` graph.+- **Found:** PR adds `0019_reviewusersettings_stamphog_review_inbox_prs.py` with `dependencies = [("review_hog", "0018_backfill_urgency_threshold_to_consider")]` and sets `max_migration.txt` to that name. Master already contains `0019_reviewreport_author_login_and_more.py` — which also depends on `0018` (line 8) — continuing through `0024_reviewreport_published_head_shas`, with `max_migration.txt` = `0024_reviewreport_published_head_shas`. The PR's migrations tree only spans 0018 → new 0019, i.e. it was branched before the 0019–0024 chain landed.+- **Found:** On merge into master, two migrations both depend on `0018`, producing two leaf nodes (`0024_...` and `0019_...stamphog`). `gh pr view` reports `mergeStateStatus: DIRTY`, confirming the `max_migration.txt` collision at the git level too.+- **Impact:** Django `makemigrations --check` reports "multiple leaf nodes in the migration graph" and PostHog's django-linear-migrations `max_migration.txt` CI check fails; the schema change cannot deploy until the file is renumbered onto the current leaf (0025, depending on 0024) and `max_migration.txt` updated. This is the exact contract/deployment break the finding names, and the fix in the suggestion is correct. must_fix is the right severity.++### [❌ dismissed] should_fix · security — tools/pr-approval-agent/review_local.py:316-321++**Fail closed when parsing the privileged review flag**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `bool(context.get("self_driving_review"))` treats every non-empty value as enabled, including strings such as `"false"` or `"0"`. This flag bypasses both the bot-author and draft safety gates, so accepting malformed truthy values weakens an authorization boundary.+- **Suggestion:** Require the JSON value to be the literal boolean `true`, for example `self_driving=context.get("self_driving_review") is True`, or validate the complete hosted context against a typed schema and reject invalid flag types.+- **Validator:** - **Checked:** The flagged expression `bool(context.get("self_driving_review"))` in `review_local.py`'s `run()`, and traced where `context` and this key originate.+- **Found:** `review_local.py:391` loads the context via `json.loads(Path(args.context).read_text())` — a JSON file the server writes. The writer (`products/stamphog/backend/logic/reviewer.py` `build_reviewer_invocation`, param typed `self_driving_review: bool = False`) stores `"self_driving_review": self_driving_review`, and its caller in `activities.py` passes `bool(output.get("inbox_review"))` — a genuine Python bool. The integration test asserts `context["self_driving_review"] is True`, and `_selfdriving_context` either sets the key to bool `True` or omits it.+- **Found:** A JSON boolean deserializes to Python `True`/`False`; the key is absent for every Action-shaped context. So the value reaching `bool(...)` is only ever `True`, `False`, or `None` — never a string. `bool(True)=True`, `bool(False)=False`, `bool(None)=False` all behave correctly and already fail closed for false/missing.+- **Impact:** The "malformed truthy string" premise (`"false"`, `"0"`) cannot occur given the double `bool()` wrapping and JSON round-trip, so `is True` would change the outcome for no value that can actually reach this line. The only way to inject a string would be to already control the sandbox context file — at which point an attacker writes literal `true` and the fail-closed check stops nothing. This is defensive paranoia against an input the upstream types and call sites rule out, and the suggested "typed schema" validation is overengineering — both drop per the criteria.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1142-1191++**Initial inbox review does not verify the PR belongs to the task**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The worker trusts the queued `pr_url`, extracts any configured repository from it, fetches that PR, and stamps it as an inbox review without validating the supplied task/signal IDs, the PR's head repository, or bot authorship. Because `self_driving_review` bypasses the normal bot, draft, review-mode, and author-permission gates, a forged or poisoned task output could cause an unrelated human or fork PR in any configured team repository to receive a privileged Stamphog review and potentially an approval.+- **Suggestion:** Before creating the run, resolve `task_run_id` through the team-scoped tasks facade and require it to match `signal_report_id`, the configured repository, and the fetched PR URL or head branch. Also require the fetched PR's head repository to equal the base repository and verify the expected self-driving bot author. Fail closed unless every check succeeds; ideally expose one facade method that performs this complete team-scoped linkage validation.+- **Validator:** - **Checked:** `process_inbox_pr_review` (tasks.py diff L1061-1176) against its sibling `_inbox_rereview_carve_out` (diff L862-933); the engine's `self_driving` gate relaxations (`review_pr.py` diff L1977, L1999); and the write path for `output.pr_url`.+- **Found (real asymmetry):** the initial leg gates only on repo-config + PR `state==open` + `head_sha`; it never checks head repository (fork), never checks bot authorship, and never calls `find_signal_implementation_run`. The webhook leg deliberately does all three, including an explicit `head_repo == repo` fork check whose comment says a branch match could otherwise bind an unrelated fork PR (diff L891-896).+- **Found (gate bypass reaches an approval):** `self_driving` relaxes the bot-author and draft gates in the engine, and the engine has no fork/author-association gate of its own (those live only in the webhook Celery pre-filter the initial leg skips). The end-to-end test `test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end` (diff L1259-1297) confirms this leg posts a real GitHub APPROVE.+- **Found (poisoning is reachable, not hypothetical):** `output.pr_url` is settable via authenticated, team-scoped endpoints `set_output` / `partial_update` on `TaskRunViewSet` (scope `task:write`); `validate_set_output` only enforces `task.json_schema` (absent on signal-implementation tasks) and `set_task_run_output` stores any `pr_url` unrestricted. The webhook backstop's fork-safety (`products/tasks/backend/webhooks.py:181-186`) does not apply on this API path, so a `task:write` holder can point a non-internal signal-report run's `pr_url` at any open PR (including a fork/untrusted PR) in a Stamphog-connected repo.+- **Impact:** with an opted-in resolved reviewer, a poisoned `output.pr_url` routes an arbitrary human/fork PR through the self-driving carve-out, bypassing the fork/bot/draft/review-mode/write-permission guards Stamphog enforces everywhere else and potentially landing a real bot approval that satisfies required reviews — a trust-boundary bypass in an approval-granting path the product's own invariants require to be fail-closed. Meets the security 'keep' bar with a concrete trigger and consequence.+- **Note on remediation:** linkage-by-`pr_url` alone is insufficient (the attacker controls the field the lookup keys on), but the finding also calls for verifying the fetched PR's head repo == base and the expected bot author — those are the effective, low-cost checks the sibling leg already performs, so the fix direction is sound and not overengineering.++### [❌ dismissed] must_fix · bug — products/review_hog/backend/receivers.py:122-124,151-155++**Stamphog opt-in checks only one assignee instead of any assigned user**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The PR promises a Stamphog review when at least one assigned reviewer opts in, but `_resolve_assigned_reviewer` selects the task creator or first resolved reviewer before the Stamphog setting is checked. If that user is opted out while another assignee is opted in, both the initial review and webhook re-review are skipped. This makes assignment order determine whether the feature runs.+- **Suggestion:** Resolve Stamphog eligibility across all assigned reviewers. Preserve creator precedence when that creator is opted in; otherwise select the first resolved assignee with `stamphog_review_inbox_prs` enabled. Use that same resolver for both the initial dispatch and webhook re-check, while retaining the existing single-reviewer behavior for ReviewHog.+- **Validator:** - **Checked:** The PR-head `receivers.py` gating (`_resolve_assigned_reviewer` 159-207; both toggles checked on the one resolved reviewer at 114-139; `resolve_stamphog_acting_reviewer` 144-156) and the PR's own tests in `products/review_hog/backend/tests/test_inbox_trigger.py`.+- **Found:** The single-acting-reviewer gate is the deliberate, documented design, not an accident. `_resolve_assigned_reviewer`'s docstring (lines 160-173) states the acting reviewer is creator-when-assigned else first-resolved, and "their `review_inbox_prs` / `stamphog_review_inbox_prs` toggles gate the respective reviews," citing "maintainer decisions, 2026-07-02/03." The module docstring (17-23) frames the stamphog toggle as "a second, independent toggle" carried by "the same resolved acting reviewer."+- **Found:** Tests explicitly lock in the exact behavior the finding calls a bug. `test_opted_out_canonical_reviewer_blocks_the_review` asserts that when the canonical reviewer (bob) is opted out but a later assignee (alice) opts in, **no review runs** — comment: "a later reviewer's opt-in must not hijack whose options the review runs with." `test_non_assigned_requester_follows_the_canonical_reviewer` codifies the same rule. `test_the_two_toggles_gate_their_reviews_independently` verifies both toggles resolve off "the one acting reviewer."+- **Impact:** The finding's suggested fix ("select the first resolved assignee with `stamphog_review_inbox_prs` enabled") would directly reverse this tested maintainer decision and split Stamphog's eligibility model away from ReviewHog's (which shares `_resolve_assigned_reviewer`), making the two toggles resolve differently. The reviewer's observation rests on the PR description's loose prose ("any assigned user"); the actual, intended, test-covered behavior gates on the single canonical acting reviewer. Premise-is-intended-design → drop (precision over recall). Any real gap here is at most PR-description wording, not a code defect ReviewHog should surface.++### [✅ VALID] should_fix (validator→consider) · bug — products/tasks/backend/facade/api.py:503-505++**Team scoping is applied after an unscoped, nondeterministic task-run lookup**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** `find_task_run` searches TaskRun rows across all teams and returns the first matching URL or repository/branch row; only afterward does this facade reject a result from another team. If multiple teams have runs referring to the same repository and PR URL or branch, the unscoped lookup can select the other team's row and return `None` even though the requested team has a valid matching run. Branch lookup also has no ordering, making the outcome unstable.+- **Suggestion:** Perform the `team_id` restriction inside the TaskRun query. For example, extend `find_task_run` with an optional team scope and apply `filter(team_id=team_id)` before ordering and `.first()`, or implement the lookup directly in this facade with the same matching precedence and deterministic ordering.+- **Validator:** - **Checked:** `find_task_run` (products/tasks/backend/webhooks.py:28-84) and how `find_signal_implementation_run` (facade/api.py diff L1714-1716) consumes it, plus the caller `_inbox_rereview_carve_out` (tasks.py diff L909-918) and its skip path.+- **Found (mechanism is real):** `find_task_run` scopes by `repository` (iexact) but not by team; the pr_url leg orders by `terminal_rank, -created_at`, and both branch legs call `.first()` with no `order_by` — so branch matching is nondeterministic, and the team check happens only afterward as `run.team_id != team_id → None`. A cross-team row that sorts first therefore yields a false negative for a team that does have a matching run.+- **Found (security property intact):** the post-filter fails closed — it never returns another team's run, so this is a completeness/determinism defect, not an IDOR/tenant-isolation leak.+- **Found (trigger is rare):** a collision needs the same repository connected to two teams. The pr_url leg is practically unreachable for this — a PR URL is globally unique and lands in exactly one run's `output.pr_url` (agent server records its own run; the webhook backstop records a single matched run), so two teams sharing the same `output.pr_url` essentially cannot occur. The branch leg is the only real vector and is only reached when the pr_url leg misses; the sole caller passes `pr_url=pr.html_url` on head-changing deliveries for an already-open PR, so the URL is normally already recorded and the pr_url leg wins.+- **Impact:** worst case is a missed self-driving re-review under a rare cross-team same-repo collision, and it fails safe — `_inbox_rereview_carve_out` returns empty and the skip path still dismisses any standing approval (diff L967-985), so no stale approval survives and nothing unsafe is posted.+- **Priority:** real and cheaply fixable (scope `team_id` inside the query, add deterministic ordering to the branch legs), but the fail-safe outcome gated on a near-unreachable cross-team collision on a globally-unique key doesn't rise to should_fix — recording as `consider`.++### [❌ dismissed] should_fix · bug — tools/pr-approval-agent/reviewer.py:568-568++**Self-driving reviews still include bot-author familiarity signals**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The prompt appends both `familiarity_block` and `self_driving_block`. Hosted runs still call `_attach_familiarity`, so a bot with merged PR history can receive a non-empty familiarity block immediately before text stating that author familiarity and merged-PR history carry no signal. This contradicts the intended replacement behavior and can influence the reviewer using evidence the new provenance block explicitly declares irrelevant.+- **Suggestion:** Suppress familiarity for self-driving runs. For example, skip `_attach_familiarity` when `pipeline.self_driving` is true, or make `_build_review_prompt` render `familiarity_block = ""` whenever `cl.get("self_driving")` is true. Add coverage using a self-driving classification with non-empty familiarity to verify only the provenance block appears.+- **Validator:** - **Checked:** The prompt assembly `{constraint}{familiarity_block}{self_driving_block}` (reviewer.py:568), `_format_familiarity` (reviewer.py:635-645), `_attach_familiarity` (review_local.py:299-303), and the server coupling in `activities.py` that determines whether familiarity can ever be non-empty for a self-driving run.+- **Found:** `run_review_in_sandbox` reads both signals from the SAME `run.output` object: `author_pr_numbers = output.get("author_pr_numbers", [])` (activities.py:396) and `self_driving_review=bool(output.get("inbox_review"))` (PR diff line 1227). `fetch_review_context` sets `author_pr_numbers = ... if author and not is_inbox_review else []` where `is_inbox_review = bool((run.output or {}).get("inbox_review"))` (PR diff lines 1215-1216). So `self_driving=True` ⟺ `inbox_review` truthy ⟹ `author_pr_numbers=[]`, always, within one run.+- **Found:** With `author_pr_numbers=[]`, `_attach_familiarity` returns at `if not raw_prs: return` (review_local.py:302-303) before computing anything, leaving `classification["familiarity"]=None`, and `_format_familiarity` returns `""` for `None` (reviewer.py:643-645). The end-to-end self-driving test asserts `context["author_pr_numbers"] == []`.+- **Impact:** The stated contradiction — a non-empty familiarity block sitting next to the "familiarity carries no signal" provenance text — cannot occur for hosted self-driving runs; `familiarity_block` is always `""` there, so appending both blocks is harmless. The premise ("a bot with merged PR history can receive a non-empty familiarity block") is unreproducible given the server coupling. Adding a redundant `familiarity_block=""` guard keyed on `self_driving` is defensive future-proofing against a state the code already rules out — drop per the criteria.++### [❌ dismissed] should_fix · performance — products/tasks/backend/facade/api.py:505-505++**Replica lag can permanently suppress inbox re-reviews**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The new re-review gate calls `find_task_run` through the default read router. This lookup runs after writes to the task/run and determines whether a webhook is recognized as self-driving. If a replica has not received those writes yet, it returns `None`; the webhook path then treats the PR as ordinary, marks the delivery processed, and never retries the lookup. A transient replica delay therefore becomes a permanently missed review.+- **Suggestion:** Pin this gating lookup to the writer, for example by adding a database alias parameter to `find_task_run` and using `TaskRun.objects.using(router.db_for_write(TaskRun))` for each query in this facade path. This matches the writer-pinned reads already used before Stamphog run creation.+- **Validator:** - **Checked:** DB routing for `TaskRun` (`products/db_routing.yaml`, `posthog/product_db_router.py`, `posthog/dbrouter.py`), the sole caller `_inbox_rereview_carve_out`, `find_task_run`'s match legs (`webhooks.py:28-84`), and the skip path's approval handling.+- **Found (premise not in place):** `tasks` is not routed to a product DB — `products/db_routing.yaml` lists only `stamphog`/`visual_review`/`warehouse_sources_queue`. `TaskRun` reads go through `ReplicaRouter.db_for_read`, which returns `"default"` (primary) for any model not in the `READ_REPLICA_OPT_IN` env list (`posthog/dbrouter.py:22-31`). The stamphog writer-pin invariant the finding cites applies because stamphog's product DB always reads a replica; that does not transfer to a main-DB model.+- **Found (convention):** `find_task_run` is the same function the primary webhook path (`handle_pull_request_event`) already uses for run recognition, and it is not writer-pinned — evidence the product does not treat `TaskRun` reads as replica-lagged.+- **Found (mechanism defeated):** `find_signal_implementation_run` passes both `pr_url` and `head_branch`; the branch leg matches `TaskRun.branch`, set at run creation. A lagged `output.pr_url` write therefore cannot yield `None`. Only a fully-unreplicated run row (created within the ~<100ms lag) could, which cannot coincide with a `synchronize`/`reopen`/base-retarget delivery on an already-open PR — the only deliveries the carve-out handles (`opened` is excluded).+- **Impact:** the described replica-read is not established for this main-DB model, the trigger is practically unreachable, and even a hypothetical miss fails safe (stale approval dismissed on the skip path, diff L967-985) and self-heals on the next push — so it is neither permanent nor unsafe. Speculative + unreachable + fail-safe ⇒ below the keep bar.++### [✅ VALID] must_fix · bug — products/review_hog/backend/receivers.py:111-138++**Inbox implementation runs are rejected before either review is queued**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The new ReviewHog and Stamphog dispatch logic is unreachable for the self-driving Inbox flow. `products/signals/backend/auto_start.py` creates implementation tasks with `internal=True`, while this receiver returns earlier when `task.internal` is true. Consequently, saving the PR URL for the intended Inbox task queues neither review, regardless of either toggle.+- **Suggestion:** Replace the blanket `task.internal` rejection with a positive check that identifies the report's implementation task, such as the recorded implementation task/run association or the task's signal-report origin and implementation stage. Continue excluding research, repository-selection, and custom-agent plumbing tasks.+- **Validator:** - **Checked:** How the self-driving implementation task is created (`products/signals/backend/auto_start.py`), whether `internal` flows through unchanged (`products/tasks/backend/facade/api.py`, `products/tasks/backend/models.py`), every creator of a signals implementation task, and the receiver gate at PR-head `receivers.py:104`.+- **Found:** `auto_start.py:310-327` creates the PR-opening implementation task — `title="Implementation: …"`, `ai_stage="implementation"`, `interaction_origin="signal_report"` (comment: "Makes the agent auto-push and open a draft PR") — with an explicit `internal=True` (comment: "Internal so the run stays out of the default task list"). The flag passes through unchanged: `create_and_run_task(internal=…)` → `Task.create_and_run(internal=…)` → the `Task.internal` column (facade `api.py:888`, model `models.py`). A grep for `ai_stage="implementation"` + `interaction_origin="signal_report"` shows `auto_start.py` is the _only_ producer of this task; the other pipeline tasks are also internal (`repo_selection/agent.py:468` `internal=True`). No production code ever sets a signal-report task's `internal=False` — only `seed_inbox_data.py:279` and the test helper (`_task(internal=False)`).+- **Found:** The receiver's guard `if task.internal: return` (PR-head `receivers.py:104`) sits before both the ReviewHog (`review_inbox_prs`) and Stamphog (`stamphog_review_inbox_prs`) dispatches, and its justifying comment — "the auto-start implementation task is the only non-internal signal-report task" — is directly contradicted by `auto_start.py:327`.+- **Impact:** For the self-driving flow the PR targets (Case 1: bot opens a draft PR, its run saves `output.pr_url`), `instance.task.internal` is `True`, so the receiver early-returns and queues **neither** review regardless of either toggle. This is the feature's primary path, not an edge case — a genuine correctness/reachability bug. The suggested fix is grounded: `auto_start.py:337` already writes a `SignalReportTask` implementation-run association (`record_implementation_task`) that could serve as the positive identifier instead of the `internal` heuristic. The gate predates this PR, but the new Stamphog dispatch inherits the same unreachability, so must_fix stands.++### [❌ dismissed] must_fix · bug — products/stamphog/backend/tasks/tasks.py:1182-1192++**Queued initial reviews ignore toggle changes before execution**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The asynchronous task trusts the opt-in resolved before dispatch and stamps the supplied acting_user_id without checking the current setting. If the task is delayed or retried after that reviewer disables inbox reviews, it can still start a review and potentially approve the PR, unlike the webhook path which deliberately re-resolves the toggle for every delivery.+- **Suggestion:** Before creating or resuming an inbox ReviewRun, call the registered acting-reviewer resolver with team_id, signal_report_id, and the task creator identity obtained from a verified task run. Stop without reviewing when it returns None, and use the newly resolved user ID in the provenance rather than the queued value.+- **Validator:** - **Checked:** the initial leg `process_inbox_pr_review` (tasks.py diff L1061-1176) against the webhook carve-out's per-delivery toggle re-resolution; the receiver's dispatch-time check (`receivers.py` diff L186-211); the task's retry config (diff L1091-1096); and the role of the toggle vs. the stale-approval safety net.+- **Found (window is tiny and the check just happened):** the receiver evaluates `settings.stamphog_review_inbox_prs` and only then schedules the Celery dispatch on commit, so the initial review runs seconds later (retries add ~5s, or ≥60s on rate-limit, max 3). The reviewer would have to disable the toggle inside that narrow window, having affirmatively enabled it at the moment their self-driving PR opened.+- **Found (asymmetry is by design, not oversight):** the webhook path re-resolves because it handles deliveries across the PR's entire lifetime (Case 3 — the toggle can flip days later); the initial leg is a one-shot at open time where the toggle was just checked. The author explicitly split these (carve-out docstring: 'the initial review is the receiver leg's job') and handles toggle-off-mid-PR through dismissal on the next head-changing delivery, stating 'safety is never preference-gated' (diff L878-883).+- **Found (core invariant intact):** an initial approval is pinned to the head it actually reviewed, so it never violates the 'no approval over unreviewed commits' invariant; and if the reviewer has since opted out, the next push's skip-path retraction dismisses it. The stamped `acting_user_id` is provenance/attribution only — it grants no privilege.+- **Impact:** the sole gap is honoring a user _preference_ changed within a seconds-to-few-minutes race, where the approval already reflects a genuine review and is dismissed on the next push. That is a speculative, low-impact defensive check on a preference — not a correctness/security defect real inputs will meaningfully hit. The must_fix 'potentially approve' framing overstates it; falls below the keep bar.++### [❌ dismissed] should_fix · best_practice — tools/pr-approval-agent/reviewer.py:568-568++**Self-driving prompt still includes human-author ownership signals**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The prompt still renders the ownership block before the self-driving provenance block. For bot authors, `_summarize_ownership` will commonly set `author_on_owning_team` to false, producing `Author is NOT on the owning team`, immediately before the new block says org membership carries no signal. This contradictory trusted context can make the reviewer treat machine authorship as a reason to escalate or refuse, despite the carve-out intending to judge the diff independently.+- **Suggestion:** Keep path ownership and suggested owners, but suppress the author-team-membership note when `self_driving` is true, for example by passing that flag into `_format_ownership` and omitting only the `author_on_owning_team` branch.+- **Validator:** - **Checked:** `_format_ownership` (reviewer.py:683-700), `_summarize_ownership` (review_pr.py:602-635), the `author_on_owning_team` computation, and the provenance text in `_format_self_driving` (PR diff).+- **Found:** The finding's factual premise holds: for a bot author on team-owned paths, `check_team_membership` matches no team, so `_summarize_ownership` sets `author_on_owning_team=False` (review_pr.py:634) and appends "author <bot> is not on any owning team" (line 629), and `_format_ownership` emits "NOTE: Author is NOT on the owning team" (reviewer.py:696-697). Ownership is not gated on `self_driving`, so this text does render before the provenance block.+- **Found (mitigation):** The provenance block explicitly names and neutralizes this very signal — "The author is a machine user, so author familiarity, org membership, and merged-PR history carry no signal here — judge the diff strictly on its own merits" — and is rendered immediately after the ownership block. The prompt already instructs the model to disregard membership; this is deliberate design, not an oversight (familiarity was suppressed by data, membership is neutralized by directive).+- **Impact:** The only residual risk is the LLM weighting "not on owning team" as an escalation reason despite an explicit adjacent instruction to ignore org membership — a speculative instruction-following failure with no deterministic wrong-output, on an unmeasured prompt-quality axis. The path-ownership content is legitimately retained; suppressing just the membership note is prompt-tuning taste. Per the criteria (speculative what-if, already-handled by the provenance directive, precision-over-recall on the fence), this does not meet the bar.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-1.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-1.mdnew file mode 100644index 000000000000..d05ca150b481--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-1.md@@ -0,0 +1,234 @@+# Reviewer-quality run — `J-gpt56sol-seq-1`++- **Dumped:** 2026-07-31T08:30:39+00:00+- **Report id:** `019fb731-4834-71f4-8863-7010a1f5831d` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `1341596e721880256a1afb79bbc881364d00e302` · **run_count:** 1 · **status:** idle+- **Wall-clock:** 1727s (28.8 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-sol` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 12 | 11 | 10 | 3 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ----------- | ---------- | --------- | ---------- |+| claude-opus-4-8 | validation | 74 | 68,272 | 400,852 | 7,541,147 | 115,925 | 2 | $9.52 | $9.52 |+| gpt-5.6-sol | review | 74 | 3,779,588 | 0 | 0 | 20,577 | 0 | — | $5.46 |+| gpt-5.6-sol | blind-spot | 27 | 1,260,214 | 0 | 0 | 5,857 | 0 | — | $1.86 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 1,354 | 0 | $0.03 | $0.03 |+| claude-sonnet-5 | dedup | 1 | 5,689 | 0 | 0 | 399 | 0 | $0.02 | $0.02 |+| **total** | | **177** | **5,119,744** | **400,852** | **7,541,147** | **144,112** | **2** | **$9.56** | **$16.87** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.6-sol` (101 gen(s), gw $7.32).+- naive method (all prompt tokens at input price): $42.99 — 4.5× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $13.1657 over 177 gen(s) (true $6.6406, Δ +98.3%)+ - · of which cache read: $5.8455 over 159 gen(s) (true $3.7706, Δ +55.0%)+ - · of which cache write: $2.5053 over 74 gen(s) (true $2.5053, Δ -0.0%)+ - · of which fresh (derived): $4.8149 over 177 gen(s) (true $0.3647, Δ +1220.2%)+ - output: $3.7087 over 177 gen(s) (true $2.9157, Δ +27.2%)+- 2 gen(s) ran with >200K-token prompts; the gateway map prices these models flat, so no long-context premium is included in either column.++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …fb6d2f83 | issues-review-p3-c1 | 08:02:41 | 0 | 0 | gpt-5.6-sol |+| …1acb40b2 | issues-review-p3-c2 | 08:02:41 | 0 | 0 | gpt-5.6-sol |+| …0c1ae487 | issues-review-p2-c2 | 08:02:41 | 0 | 0 | gpt-5.6-sol |+| …6c9f0016 | issues-review-p1-c2 | 08:02:43 | 0 | 0 | gpt-5.6-sol |+| …b153fc1a | issues-review-p1-c3 | 08:02:43 | 0 | 0 | gpt-5.6-sol |+| …09226501 | issues-review-p2-c1 | 08:02:43 | 0 | 0 | gpt-5.6-sol |+| …036de04d | issues-review-p2-c3 | 08:02:43 | 0 | 0 | gpt-5.6-sol |+| …62801e4a | issues-review-p1-c1 | 08:02:46 | 0 | 0 | gpt-5.6-sol |+| …7e37c220 | issues-review-p2-c2 | 08:05:37 | 0 | 0 | gpt-5.6-sol |+| …53a07e65 | issues-review-p1-c1 | 08:05:37 | 0 | 0 | gpt-5.6-sol |+| …63abd79e | blind-spots-c1 | 08:07:41 | 0 | 0 | gpt-5.6-sol |+| …742dda3c | blind-spots-c2 | 08:07:41 | 0 | 0 | gpt-5.6-sol |+| …42a618eb | blind-spots-c4 | 08:07:42 | 0 | 0 | gpt-5.6-sol |+| …61e1b455 | blind-spots-c3 | 08:07:44 | 0 | 0 | gpt-5.6-sol |+| …bd2c5c1a | validation-c2 | 08:09:31 | 0 | 37,944 | claude-opus-4-8 |+| …bb00da88 | validation-c3 | 08:09:32 | 17,141 | 19,982 | claude-opus-4-8 |+| …247b0b12 | validation-c1 | 08:09:36 | 17,141 | 20,570 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **2/17** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 0s |+| chunking | 0s |+| perspective selection | 16s |+| review wave (perspectives) | 5m 04s |+| blind-spot sweep | 1m 55s |+| dedup (incl. combine/clean) | 5s |+| validation | 21m 22s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 6m 59s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | ? | 0 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 1 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:113-120++**PR URL parsing accepts embedded GitHub-looking substrings from arbitrary hosts**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE.search()` is not anchored to an HTTPS GitHub URL or hostname boundary. Values such as `https://attacker.example/github.com/org/repo/pull/123` are accepted and converted into a request for the real `org/repo#123`. Since this value feeds the privileged inbox-review path, malformed or attacker-influenced task output can select a different review target than the URL represents.+- **Suggestion:** Parse the URL with `urllib.parse.urlparse`, require `scheme == "https"` and `hostname == "github.com"` (or an explicitly supported allowlist), and validate the path as exactly `/<owner>/<repo>/pull/<positive integer>` with no credentials, unexpected port, or extra target-changing components.+- **Validator:** - **Checked:** Traced `_parse_pr_url` (PR-head `products/stamphog/backend/tasks/tasks.py:116`) and its sole non-test caller `process_inbox_pr_review` (`tasks.py:1110`); traced `pr_url` back through `queue_inbox_pr_review` (`facade/api.py:128`) to review_hog's `handle_task_run_saved`/`_start_stamphog_review` (`receivers.py`), where it is `TaskRun.output["pr_url"]`; checked every downstream use of the parsed `(owner/repo, number)`.+- **Found:** The parsed tuple only resolves a `team_id`-scoped `StamphogRepoConfig` filtered `enabled=True`, non-blank `installation_id`, `connected_by_user_id` set, `repository__iexact=<owner/repo>` (`tasks.py:1139-1148`); the subsequent GitHub fetch uses `repo_config.repository` and `repo_config.installation_id` from the DB (`tasks.py:1160`). The URL's scheme/host/port are never used for any request — so a spoofed `attacker.example/github.com/...` host yields the exact same extracted target as a clean URL and changes nothing downstream.+- **Found:** The suggested fix does not close the stated "select a different review target" threat. Redirection is achievable by an actor controlling `pr_url` with a perfectly anchored `https://github.com/<target>/pull/N`; requiring `hostname == "github.com"` only rejects a malformed substring form no real attacker needs. The actual missing control on the receiver leg is positive run-linkage identification — which the webhook carve-out already performs via `find_signal_implementation_run` (`products/tasks/backend/facade/api.py:484`) — not URL host anchoring.+- **Impact:** For all legitimate inputs the leftmost-match regex extracts correctly, so there is no correctness bug; the target is bounded to the team's own enabled+synced Stamphog repos; and the proposed anchoring provides no security benefit against the described redirection. This is minor input-hardening/consistency polish (matching `_is_github_pull_request_url_for_repository`), not a reachable security defect — below the keep bar (speculative/wrong-premise).++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:316-324++**Fail closed when parsing the gate-bypass flag**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `bool(context.get("self_driving_review"))` enables the self-driving carve-out for any truthy JSON value, including strings such as `"false"`, numbers, or objects. This flag bypasses the bot-author refusal and draft prerequisite and injects trusted provenance into the reviewer prompt, so malformed context can unintentionally authorize a review under relaxed gates.+- **Suggestion:** Require the exact JSON boolean `true`, for example `self_driving = context.get("self_driving_review") is True`, and reject or default closed for every other type. Consider also asserting that the resulting PR is bot-authored before retaining the flag, so the trusted machine-author claim and draft bypass cannot diverge from `PRData`.+- **Validator:** - **Checked:** The full producer→consumer chain for `self_driving_review`: `build_reviewer_invocation` (reviewer.py `+787`) which writes the context dict, its sole hosted caller `run_review_in_sandbox` (tasks.py `+1227`), the JSON round-trip into the sandbox, and both engine entrypoints (`review_local.py` `run()` and the Action's `review_pr.py`).+- **Found:** The flag is set exclusively via `self_driving_review=bool(output.get("inbox_review"))` (tasks.py `+1227`) — already a genuine Python `bool` — and `build_reviewer_invocation` places that bool into the context dict (`+787`), which is JSON-serialized to the sandbox context file. The end-to-end test confirms the on-disk value is a real JSON boolean: `assert context["self_driving_review"] is True` (test_integration `+1287`). The Action path never sets the key, so `context.get(...)` is `None`. Thus `context.get("self_driving_review")` is only ever `True`, `False`, or absent — and `bool(True) is True → True`, `bool(False) → False`, `bool(None) → False`, identical to the suggested `is True`.+- **Impact:** The premise — a truthy string/number/object slipping through — cannot be reached: the upstream `bool(...)` invariant guarantees a genuine boolean, and the context is a trusted server artifact rather than attacker-writable JSON. This is defensive hardening against an input the call-site invariant already rules out. It also yields no security benefit under the only model where parsing would matter (an attacker who can overwrite the context file would just write `true`), so the change is behaviorally a no-op for every reachable input. Falls under speculative 'what if' / defensive-coding paranoia in the drop criteria.++### [✅ VALID] must_fix (validator→should_fix) · bug — products/review_hog/backend/receivers.py:111-135,144-160++**Stamphog gate checks only one assignee instead of any opted-in assignee**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** Both the initial trigger and webhook resolver select one canonical acting reviewer, then inspect only that user's `stamphog_review_inbox_prs` setting. If that reviewer is opted out while another assigned reviewer is opted in, no Stamphog review runs. This contradicts the stated requirement that a review run when at least one assigned user has enabled the toggle, and turning off one user's toggle can incorrectly stop later re-reviews despite another assignee remaining opted in.+- **Suggestion:** Resolve the complete ordered set of assigned organization users for the Stamphog path, select an opted-in user with `next((user for user in resolved if ReviewUserSettings.load(team_id, user.id).stamphog_review_inbox_prs), None)`, and return that user's ID. Preserve the existing single acting-reviewer selection separately for ReviewHog, whose configuration is intentionally tied to the task creator or primary assignee. Use the same any-opted-in resolver for both initial dispatch and webhook rechecks.+- **Validator:** - **Checked:** the full receivers.py PR diff — `_resolve_assigned_reviewer`, the initial trigger in `handle_task_run_saved`, the webhook re-check `resolve_stamphog_acting_reviewer`, and the `inbox_hooks` registry that stamphog's webhook task calls through.+- **Found:** `_resolve_assigned_reviewer` collapses to ONE acting reviewer — `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` (receivers.py ~L204) — and both legs gate on only that user: the trigger does `if pr_url is not None and settings.stamphog_review_inbox_prs:` where `settings = ReviewUserSettings.load(team_id, acting_user_id)`, and `resolve_stamphog_acting_reviewer` re-derives the same single acting id then checks only its toggle. No path iterates the resolved set for any opted-in user.+- **Found:** for a fully auto-started self-driving PR, `created_by` is the GitHub-integration bot (per the module docstring) and is not in the resolved set, so the acting reviewer is `resolved[0]` — the first suggested reviewer by artefact order. If `resolved[0]` is opted out of stamphog while a later assignee is opted in, no stamphog review is queued; and on a later push, if `resolved[0]` toggles off, `resolve_stamphog_acting_reviewer` returns None and re-reviews stop even though another assignee remains opted in.+- **Found:** the PR body states the gate three times as any-opted-in — "any assigned reviewer opted in" (Case 1), "at least one of the assigned users has `stamphog_review_inbox_prs` enabled", "nobody is opted in, so no review runs" (Case 3). The implementation checks exactly one, so it diverges from the feature's own stated central behavior. Architecturally this fits: ReviewHog needs the single-acting collapse to pick ONE user's perspectives/urgency config to drive the review, but stamphog's toggle is a binary gate with no per-user options, so reusing the single-acting resolver for it silently ignores other assignees' opt-in.+- **Impact:** realistic multi-reviewer reports (differing per-user opt-in, default-off) hit this; stamphog reviews are skipped for cases the stated design says should run, and one user toggling off can halt re-reviews despite another remaining opted in. Concrete trigger + concrete consequence, directly in the code this PR adds.+- **Priority:** lowering must_fix → should_fix. The failure mode is fail-safe (a skipped review, never a wrong GitHub approval), the feature is explicitly experimental (draft PR, `experiment-frozen` branch), and the code docstring deliberately describes single-acting-reviewer gating both toggles — so there is a defensible intentional-design reading. The divergence from the stated any-opted-in requirement is real and worth resolving, but not the severity of a data-loss/security/wrong-approval defect.++### [❌ dismissed] should_fix · bug — products/tasks/backend/facade/api.py:506-512++**Team and self-driving filters are applied after selecting an arbitrary run**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** find_task_run searches globally and selects one matching run before this facade checks team_id, signal_report_id, and task.internal. Multiple runs can legitimately share a PR URL or repository/branch, including resumed runs, another team's run, or an unrelated/internal task. If find_task_run selects one of those, this function returns None even when a qualifying self-driving run exists, causing valid inbox re-reviews to be skipped. The branch lookup also uses an unordered first(), making the result unstable when several runs match.+- **Suggestion:** Move team_id and the self-driving task predicates into the queryset used to select the run, and retain the existing active/newest ordering for PR URL matches. Prefer extending find_task_run with explicit filters or implementing a facade-specific scoped query so selection occurs only among eligible candidates.+- **Validator:** - **Checked:** Read `find_task_run` (`products/tasks/backend/webhooks.py:29-98`), `find_signal_implementation_run` (`products/tasks/backend/facade/api.py:484-517`), the carve-out call site (`products/stamphog/backend/tasks/tasks.py:191`), and the run-provenance invariants in `products/review_hog/backend/receivers.py`.+- **Found (internal-task masking ruled out):** Internal plumbing tasks cannot mask a qualifying run — `receivers.py` documents that report-research / repo-selection / custom-agent tasks are `internal=True` and _push nothing_, so they never populate `output.pr_url` or a PR head branch and therefore never match `output__pr_url=pr_url` or `branch=head_branch`. The `task.internal` post-filter has no colliding candidate to lose to.+- **Found (cross-team masking not reachable):** The `pr_url` leg keys on `output__pr_url=pr_url` (`webhooks.py:41`). A specific GitHub PR is opened by exactly one run lineage, so its URL is unique; two teams sharing repo `org/repo` open _different_ PR numbers → different URLs → no shared `output__pr_url`. Even if `find_task_run` returned a foreign-team run, the team post-filter (`api.py:505`) fails **closed** (returns None), and the carve-out re-checks it (`tasks.py:199`), so there is no tenant leak — at most a missed round.+- **Found (resumes handled):** The documented multi-run-per-URL case (terminal original + live resume, `webhooks.py:37-39`) is same-team/same-signal-lineage, so both candidates pass the post-filters, and the ordering `terminal_rank, -created_at` already picks the live one.+- **Found (branch-leg `first()`):** The unordered `.first()` (`webhooks.py:69`) is pre-existing webhook-backstop behavior, not introduced by this PR; the carve-out always passes `pr.html_url` and self-driving runs record their pr_url, so the ordered pr_url leg resolves them and the branch leg is not the resolving path here.+- **Impact:** No realistic input produces the claimed "qualifying self-driving run masked by a non-qualifying one" skip. Worst residual is a rare missed re-review that a subsequent delivery re-triggers, and the caller's head-changing retraction still dismisses stale approvals — the stale-approval safety invariant is not preference- or timing-gated. Speculative collision scenario, below the correctness bar.++### [❌ dismissed] should_fix · bug — tools/pr-approval-agent/reviewer.py:568-568++**Self-driving reviews still include bot-author familiarity**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The prompt concatenates both `familiarity_block` and `self_driving_block`. Hosted execution still calls `_attach_familiarity`, and the server fetches merged PR numbers for the bot author, so a bot with prior merged PRs can receive a positive human-author familiarity signal. This contradicts the new provenance block and can incorrectly influence the verdict.+- **Suggestion:** Skip familiarity computation for self-driving runs and defensively omit `familiarity_block` when `cl["self_driving"]` is true.+- **Validator:** - **Checked:** The full familiarity data path for a self-driving run: the server-side context builder (`fetch_review_context` in tasks.py `+1210-1216`), the engine's `_attach_familiarity` (review_local.py, unchanged `if not raw_prs: return` at lines 301-303), and `_format_familiarity` (reviewer.py:643-645), plus whether `author_pr_numbers` and `self_driving_review` can diverge.+- **Found:** The issue's core premise — 'the server fetches merged PR numbers for the bot author' — is false. The companion change in this same PR does the opposite: `is_inbox_review = bool((run.output or {}).get("inbox_review"))` and `author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []` (tasks.py `+1215-1216`). For inbox/self-driving runs the fetch is skipped and `author_pr_numbers` is `[]` — the end-to-end test even asserts `context["author_pr_numbers"] == []` (test_integration `+1289`).+- **Found:** With empty `author_pr_numbers`, `_attach_familiarity` hits `raw_prs = context.get("author_pr_numbers")` → `if not raw_prs: return` (review_local.py:301-303), so `cl["familiarity"]` is never populated. `_format_familiarity` then returns `""` because `fam is None` (reviewer.py:643-645). So `familiarity_block` is empty precisely when `self_driving_block` renders.+- **Found:** The two flags cannot diverge — both derive from the same `run.output["inbox_review"]` provenance (`self_driving_review=bool(output.get("inbox_review"))` at tasks.py `+1227`; `author_pr_numbers` gate at `+1215`), stamped once at trigger time before either activity reads it.+- **Impact:** The described failure (a bot receiving a positive human-author familiarity signal alongside the provenance block) is unreachable: whenever `cl["self_driving"]` is true, familiarity is already absent by construction. The suggested guard would be dead code. Falls under 'wrong / unreproducible' and 'already handled elsewhere' in the drop criteria.++### [✅ VALID] should_fix (validator→consider) · code_quality — tools/pr-approval-agent/reviewer.py:697-699++**Provenance prompt falsely states every self-driving PR is a draft**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self-driving flag identifies task provenance, not current draft state, but the trusted prompt always says the PR is a draft and that draft state should be ignored. A later push can trigger another review after the PR becomes ready, making this trusted statement factually wrong.+- **Suggestion:** Pass `pr.draft` into the formatter and include the draft-specific guidance only when it is true, or phrase it conditionally without asserting the current state.+- **Validator:** - **Checked:** `_format_self_driving` (reviewer.py `+697-699`), and every path that sets the `inbox_review`/`self_driving` provenance that gates the block: the webhook re-review carve-out `_inbox_rereview_carve_out` and skip flow in tasks.py (`+862-933`, `+956-966`), and the receiver leg `process_inbox_pr_review` (`+1097-1160`). I looked specifically for a `pr.draft` guard on these paths.+- **Found:** The block hardcodes 'It is a draft on purpose ... draft state is not a caution signal for this PR' with no conditioning on actual draft state (reviewer.py `+697-699`). Neither provenance-setting path requires the PR to still be a draft: `_inbox_rereview_carve_out` gates only on head-changing action, bot authorship, repo-native head, config, task linkage, and opt-in — no draft check (`+885-933`); the receiver leg gates on `state == "open"` only, explicitly not draft (`+1097-1100`). `_review_skip_reason` returns `bot_author` for a non-draft bot PR (`+940-947`), so a self-driving PR that flipped to ready and then receives a `synchronize` still enters the carve-out and renders the block. This is a plausible workflow (a triaged draft marked ready, then a follow-up push), not a contrived one.+- **Impact:** The trusted context fed to the review LLM can state a false premise about the PR's lifecycle. Confirmed reachable, so not wrong/unreproducible — a genuine accuracy defect worth a cheap conditional fix.+- **Priority:** Lowering should_fix → consider. The reviewer's stated harm ('can incorrectly influence the verdict') is weaker than claimed: the block's only actionable instruction ('draft state is not a caution signal') is inert when there is no draft, and the sibling sentence 'judge the diff strictly on its own merits' counteracts any leniency the false 'draft on purpose' framing might induce. Reachable only in an edge case with no concrete wrong-verdict mechanism — real but minor.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:222-234++**Persist or retry failed Stamphog dispatches**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The post-commit callback catches every exception from `queue_inbox_pr_review` and only logs it. Because the TaskRun transaction has already committed and no durable retry marker is recorded, an exhausted broker publish failure permanently drops the initial Stamphog review unless an unrelated later save happens to retrigger the receiver.+- **Suggestion:** Dispatch through a durable outbox/retry mechanism, or persist pending dispatch state keyed by the task run and have a retrying worker enqueue it. Keep the save path isolated, but ensure a transient broker outage cannot silently lose the review.+- **Validator:** - **Checked:** `_start_stamphog_review` in the PR diff, the pre-existing `_start_review` (ReviewHog) leg it mirrors, the module-level docstring on re-trigger semantics (receivers.py L59-63), and the `queue_inbox_pr_review` facade behavior.+- **Found:** the catch is `except Exception: logger.exception("review_hog_stamphog_inbox_review_queue_failed")` — the failure is logged at exception level, not hidden. Both the docstring ("the broker being down must never surface into the saver") and the identical, already-accepted pattern on the ReviewHog `_start_review` leg show this swallow-and-log is a deliberate, documented convention for this file, which runs inside the tasks save path and must never raise into it. This is not a new defect introduced by the change.+- **Found:** the dispatch is a Celery broker publish (`queue_inbox_pr_review` "queues a Celery task, so the only work on this save path is the broker publish"); the only loss scenario is a rare transient broker outage at the exact on-commit moment. Recovery paths already exist: receivers.py L61-63 states repeat TaskRun saves with an unchanged target deliberately re-fire the receiver (re-dispatching the stamphog leg while the toggle is on), and PR Case 2 re-reviews via stamphog's webhook path on the next push — the finding itself concedes a later save retriggers it.+- **Impact:** the suggested remedy (a durable outbox / persisted pending-dispatch state + a retrying worker) is a substantial reliability subsystem for a best-effort, fail-safe (no wrong approval — only a possibly-delayed review), explicitly experimental feature that already has natural re-trigger paths. That is the 'add an abstraction / future-proof for a case not in scope' shape the criteria drops as overengineering, and it would apply equally to the long-standing ReviewHog leg it mirrors. It does not clear the bar of a reliability defect that will realistically bite.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1158-1183++**Inbox provenance is granted without verifying the PR belongs to the task run**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial-review task accepts `pr_url`, `acting_user_id`, `signal_report_id`, and `task_run_id` from its caller, but after fetching the PR it only checks that the PR is open and has a head SHA. It never verifies that `task_run_id` belongs to `team_id`, carries `signal_report_id`, targets this repository and head branch, or that the PR is repo-native and bot-authored. Nevertheless, it stamps `inbox_review`, which later enables the privileged engine path that bypasses bot, draft, review-mode, and author-permission gates. Because task output containing the PR URL can originate from an agent run, a mistaken or manipulated URL could cause an unrelated PR in any configured repository for the team to receive this privileged review and potentially an approval.+- **Suggestion:** Before creating the run, load the supplied task run through a team-scoped facade and require its task to be the expected non-internal signal implementation with the supplied signal report. Compare the fetched PR's repository and head branch against that run, require `head.repo.full_name` to equal the base repository, and verify the expected GitHub App bot identity. Derive the provenance fields from the verified DTO rather than trusting the Celery arguments. Apply the same verified binding to webhook re-reviews instead of treating a task's stored `pr_url` alone as proof of origin.+- **Validator:** - **Checked:** Traced the receiver leg `process_inbox_pr_review` (tasks.py:1130-1183) vs. the webhook carve-out `_inbox_rereview_carve_out` (tasks.py:144-215); the provenance→engine flow (`activities.py:451` sets `self_driving_review` from `output['inbox_review']`); and the engine gates (`tools/pr-approval-agent/review_pr.py:225,590`, `gates.py`).+- **Found (real asymmetry):** The carve-out gates provenance on `_is_bot_authored(pr)` AND repo-native `head_repo == repo` (fork-safety) AND a `find_signal_implementation_run` facade match. The receiver leg stamps the _same_ `inbox_review` provenance after checking only `state == 'open'` and a non-empty `head_sha` — no bot-author, no repo-native/fork, no run re-binding.+- **Found (no compensating gate downstream):** The engine has no fork or author-association gate; `self_driving=True` relaxes exactly the bot-author refusal and the draft prerequisite (`review_pr.py:225,590`). Fork/association filtering lives only in the webhook pre-filter and the carve-out. So the receiver leg is the only route to the engine's self-driving mode with fork-safety enforced nowhere — bypassing the control the code declares must never be bypassed (`tasks.py:73-75`: an auto-approval can satisfy required reviews with zero humans).+- **Found (fix is effective, unlike the URL-anchoring sibling):** `output.pr_url` is agent-reported via the task-run output API (`set_task_run_output`), not derived from a verified bot PR-creation response. Requiring the fetched PR to be bot-authored + repo-native would refuse a redirect to a human/fork attacker PR — closing the hole that URL validation alone cannot.+- **Impact:** A signal run that reports (via prompt-injected/mistaken agent output) a `pr_url` pointing at a fork or human-authored PR in one of the team's enabled Stamphog repos gets that PR privileged-reviewed and potentially approved, with no fork/bot/association gate anywhere — an errant GitHub approval that can satisfy required reviews. Reachable, though bounded to the team's own enabled repos and gated on the acting reviewer's toggle.+- **Priority:** Keeping must_fix. Note two overstatements in the suggestion that do NOT lower the core severity: re-verifying that `task_run_id` belongs to `team_id`/carries `signal_report_id` is largely redundant (the in-process review_hog caller already establishes these from the real TaskRun and Celery args aren't externally injectable), and the claim that webhook re-reviews 'treat stored pr_url alone as proof' is inaccurate (the carve-out already does bot+fork+facade-match). The genuinely missing controls are the bot-author and repo-native checks on the receiver leg's fetched PR.++### [❌ dismissed] should_fix · bug — products/stamphog/backend/tasks/tasks.py:1185-1201++**Receiver refires can create duplicate review workflows**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The deduplication uses `select_for_update()` only on matching `ReviewRun` rows. When no run exists for the current head, there is nothing to lock, so concurrent receiver tasks can both observe `existing is None`, create separate runs, and start duplicate Temporal/LLM reviews. This is especially plausible because every matching TaskRun output save refires this task.+- **Suggestion:** Serialize the check-and-create operation by locking the parent `PullRequest` row before querying `ReviewRun`, for example by reloading `pr_obj` through `select_for_update()` inside the transaction. Then perform the existing-head lookup, supersession, and creation while holding that lock. Alternatively, add a database-backed idempotency constraint specifically for inbox runs.+- **Validator:** - **Checked:** The receiver-leg transaction body in `process_inbox_pr_review` (tasks.py:1160-1220), `_upsert_pull_request` (tasks.py:319-363), `_start_review_workflow` (tasks.py:366-382), `_supersede_prior_runs` (tasks.py:415-430), the `PullRequest`/`ReviewRun` constraints (models.py:118-145,207-), and the webhook path's documented locking.+- **Found (the missed lock):** The dedup is not the `select_for_update()` alone. `_upsert_pull_request` runs first in the same `transaction.atomic`; its conditional `UPDATE ... WHERE payload_updated_at <= incoming` matches for same-head concurrent refires (identical GitHub snapshot) and takes the PR row's write lock held to commit, serializing the two transactions. On a first-ever review the `get_or_create` INSERT contends on `UniqueConstraint(team_id, repo_config, pr_number)` (models.py:120) instead. Either way T2 blocks until T1 commits, then its `existing` select sees T1's committed QUEUED run and no-ops.+- **Found (loser paths covered):** A transaction that does NOT get the lock only reaches that state via a stale/older snapshot (UPDATE matches 0 rows), and the stale-snapshot recheck (`pr_obj.payload_updated_at > incoming` → return) drops it before the create. This mirrors the webhook path's own comment: `_upsert_pull_request`'s conditional UPDATE takes the PR row lock, held to commit, serializing deliveries.+- **Found (only-gap unreachable):** The single unserialized branch is `incoming_updated_at is None` (early return before the conditional UPDATE, and the stale recheck is guarded on `incoming is not None`). GitHub PR payloads always include `updated_at`, so `get_pr` never yields None here.+- **Impact:** No duplicate Temporal/LLM reviews occur under realistic concurrency — the premise overlooks the PR-row / unique-index serialization that precedes the `existing` check, so it does not meet the bar (already handled). The suggested `(pull_request, head_sha)` uniqueness would additionally break legitimate same-head re-reviews (a base retarget creates a new run without moving the head).++### [❌ dismissed] must_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1185-1190++**Queued initial reviews ignore a later toggle opt-out**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The Celery task trusts the toggle decision made before it was queued and stamps `inbox_review` without resolving the acting reviewer again. If the reviewer disables inbox reviews while this task is delayed or retrying, the task can still launch a privileged review and post an approval after opt-out. The webhook re-review path already rechecks this preference, so the initial path has inconsistent toggle semantics.+- **Suggestion:** Before creating or resuming the run, resolve the current acting reviewer through `get_inbox_acting_reviewer_resolver()` using the verified signal/task provenance. Return without starting a workflow when nobody is currently opted in, and use the freshly resolved user ID in the stamped provenance.+- **Validator:** - **Checked:** The initial-leg dispatch chain (`review_hog/receivers.py` `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review.delay`), the Celery task config and body (`process_inbox_pr_review`, tasks.py:1108-1245), the webhook leg's re-check (`_inbox_rereview_carve_out` → `get_inbox_acting_reviewer_resolver`, tasks.py:201-207), and the opt-out skip handling in `process_pull_request_event` (tasks.py:880-909).+- **Found (observation is accurate but window is tiny):** The dispatcher checks `settings.stamphog_review_inbox_prs` immediately before `.delay()`, and the task (`max_retries=3, default_retry_delay=5`; rate-limit retries `max(retry_after,60)`) runs within seconds-to-minutes. The initial leg indeed does not re-resolve the toggle; the flip-off must land inside that short queue/retry window to matter.+- **Found (no invariant violated):** Any verdict the initial leg posts is over code it actually reviewed on the team's OWN positively-linked self-driving draft PR — not 'an approval over unreviewed code' (the invariant the product guards). The toggle is explicitly a preference, not a safety gate: AGENTS.md states a mid-PR toggle-off 'stops new runs' but 'safety is never preference-gated.'+- **Found (safety residual already handled):** If the initial leg posts an APPROVE after opt-out, the next head-changing webhook delivery hits `carve_out.opted_out=True` and calls `_retract_stale_approvals_on_skip(..., _INBOX_OPT_OUT_DISMISS_MESSAGE)` (tasks.py:894-898), dismissing the standing approval. With no subsequent push, the approval simply stands on the user's own draft PR they requested a review of moments earlier.+- **Impact:** A rare, benign preference-timing race on the user's own linked self-driving PR, with the only safety-relevant residual retracted by the webhook skip path on any later head change — no gate bypass beyond what other findings cover, and no stated invariant broken. Severity is far below the claimed must_fix; below the keep bar (rare/low-impact + already-handled). The 'privileged review / approval after opt-out' framing overstates it by implying an arbitrary target when it is the legitimately-linked PR.diff --git a/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-2.md b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-2.mdnew file mode 100644index 000000000000..497c37ee6080--- /dev/null+++ b/products/review_hog/eval/experiments/2026-07-reviewer-model-glm52/runs/J-gpt56sol-seq-2.md@@ -0,0 +1,302 @@+# Reviewer-quality run — `J-gpt56sol-seq-2`++- **Dumped:** 2026-07-31T09:11:34+00:00+- **Report id:** `019fb731-4834-71f4-8863-7010a1f5831d` · **PR:** https://github.com/PostHog/posthog/pull/75215+- **Head:** `a7fb363bef6947e4e7fc30a0fe8a0a4cc4deaa82` · **run_count:** 2 · **status:** idle+- **Wall-clock:** 1141s (19.0 min)++## Config snapshot++- runtime / model / effort: `codex` / `gpt-5.6-sol` / `xhigh`+- single-chunk gate / chunk target / soft-max additions = 400 / 300 / 600++## Funnel & cost++| chunks | review units | raw issues | after dedup | passed validator |+| ------ | ------------ | ---------- | ----------- | ---------------- |+| 4 | 25 | 15 | 14 | 6 |++- **review units** = every (perspective|blind-spot × chunk) sandbox review that ran = the model-held-constant cost proxy.++### Cache-aware spend (local `$ai_generation`, best-effort)++| model | stage | gens | fresh in | cache write | cache read | output | >200K gens | true $ | gw $ |+| --------------- | --------------------------- | ------- | ------------- | ----------- | ------------- | ---------- | ---------- | --------- | ---------- |+| gpt-5.6-sol | review | 111 | 5,785,449 | 0 | 0 | 27,305 | 0 | — | $8.28 |+| claude-opus-4-8 | validation | 53 | 51,442 | 315,205 | 5,217,388 | 48,074 | 0 | $6.04 | $6.04 |+| gpt-5.6-sol | blind-spot | 26 | 1,350,608 | 0 | 0 | 5,591 | 0 | — | $2.02 |+| claude-sonnet-5 | dedup | 1 | 14,291 | 0 | 0 | 377 | 0 | $0.03 | $0.03 |+| claude-sonnet-5 | other:perspective_selection | 1 | 5,981 | 0 | 0 | 1,460 | 0 | $0.03 | $0.03 |+| **total** | | **192** | **7,207,771** | **315,205** | **5,217,388** | **82,807** | **0** | **$6.10** | **$16.39** |++- `true $` = list-price back-calc (fresh 1× + cache write 1.25× + cache read 0.1× + output); `gw $` = gateway `$ai_total_cost_usd` (LiteLLM). Δ (priced buckets) = -0.0%.+- `true $` total excludes unpriced model `gpt-5.6-sol` (137 gen(s), gw $10.30).+- naive method (all prompt tokens at input price): $29.18 — 4.8× the true cost; never gate on it.+- gateway per-side cross-check (gens emitting the field; LiteLLM's `input_cost` is the whole input side, cache included):+ - input side (fresh + cache write + cache read): $14.1851 over 192 gen(s) (true $4.8765, Δ +190.9%)+ - · of which cache read: $5.5389 over 169 gen(s) (true $2.6087, Δ +112.3%)+ - · of which cache write: $1.9700 over 53 gen(s) (true $1.9700, Δ +0.0%)+ - · of which fresh (derived): $6.6762 over 192 gen(s) (true $0.2978, Δ +2142.2%)+ - output: $2.2071 over 192 gen(s) (true $1.2202, Δ +80.9%)++### Turn-1 cache reads per sandbox unit (cross-sandbox sharing tripwire)++| unit | step | first gen | t1 cache read | t1 cache write | models |+| --------- | ------------------- | --------- | ------------- | -------------- | --------------- |+| …62657b93 | issues-review-p3-c2 | 08:53:36 | 0 | 0 | gpt-5.6-sol |+| …49fb5c58 | issues-review-p2-c3 | 08:53:36 | 0 | 0 | gpt-5.6-sol |+| …db5406bd | issues-review-p2-c2 | 08:53:37 | 0 | 0 | gpt-5.6-sol |+| …9fd40be8 | issues-review-p3-c3 | 08:53:37 | 0 | 0 | gpt-5.6-sol |+| …7422e084 | issues-review-p1-c3 | 08:53:37 | 0 | 0 | gpt-5.6-sol |+| …c4152fc3 | issues-review-p2-c1 | 08:53:39 | 0 | 0 | gpt-5.6-sol |+| …7b946f61 | issues-review-p3-c1 | 08:53:39 | 0 | 0 | gpt-5.6-sol |+| …65adefe6 | issues-review-p1-c1 | 08:53:40 | 0 | 0 | gpt-5.6-sol |+| …d40b5d59 | issues-review-p1-c2 | 08:53:40 | 0 | 0 | gpt-5.6-sol |+| …345b1852 | issues-review-p2-c1 | 08:56:54 | 0 | 0 | gpt-5.6-sol |+| …5555b4a4 | issues-review-p1-c1 | 08:56:55 | 0 | 0 | gpt-5.6-sol |+| …13c1f822 | issues-review-p2-c2 | 08:56:56 | 0 | 0 | gpt-5.6-sol |+| …b17c8c17 | issues-review-p3-c1 | 08:57:00 | 0 | 0 | gpt-5.6-sol |+| …453088b2 | issues-review-p1-c2 | 08:57:01 | 0 | 0 | gpt-5.6-sol |+| …6390c87f | issues-review-p3-c2 | 08:57:19 | 0 | 0 | gpt-5.6-sol |+| …00bcfb73 | blind-spots-c2 | 08:59:30 | 0 | 0 | gpt-5.6-sol |+| …866bef79 | blind-spots-c3 | 08:59:33 | 0 | 0 | gpt-5.6-sol |+| …4cfe8832 | blind-spots-c1 | 08:59:33 | 0 | 0 | gpt-5.6-sol |+| …8241b260 | blind-spots-c4 | 08:59:35 | 0 | 0 | gpt-5.6-sol |+| …6cffbabd | validation-c2 | 09:01:39 | 0 | 37,914 | claude-opus-4-8 |+| …ce94e76c | validation-c1 | 09:01:41 | 17,141 | 20,264 | claude-opus-4-8 |++- units with turn-1 cache_read > 0: **1/21** (report the distribution, not a median).++## Stage timing (wall-clock)++| stage | duration |+| --------------------------- | -------- |+| fetch + snapshot | 50m 32s |+| chunking | 0s |+| perspective selection | 19s |+| review wave (perspectives) | 6m 16s |+| blind-spot sweep | 2m 06s |+| dedup (incl. combine/clean) | — |+| validation | 62m 08s |++- **Review stage total (selection → last finder unit, wave + blind-spot):** 8m 23s — the reviewer-model speed comparison number.+- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.++## Chunking++- **chunk 1** (8 files): products/review_hog/backend/models.py, products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py, products/review_hog/backend/api/settings.py, products/review_hog/backend/receivers.py, products/review_hog/frontend/CodeReviewScene.tsx, products/review_hog/frontend/generated/api.schemas.ts, products/review_hog/frontend/generated/api.zod.ts, services/mcp/src/api/generated.ts+- **chunk 2** (8 files): products/stamphog/backend/facade/api.py, products/stamphog/backend/facade/inbox_hooks.py, products/stamphog/backend/tasks/tasks.py, products/stamphog/backend/temporal/activities.py, products/stamphog/backend/logic/reviewer.py, products/tasks/backend/facade/api.py, products/tasks/backend/facade/contracts.py, tach.toml+- **chunk 3** (4 files): tools/pr-approval-agent/review_pr.py, tools/pr-approval-agent/review_local.py, tools/pr-approval-agent/reviewer.py, tools/pr-approval-agent/version.py+- **chunk 4** (2 files): products/stamphog/AGENTS.md, products/stamphog/README.md++## Per-review-unit breakdown++| pass | chunk | perspective | raw issues |+| ---- | ----- | ---------------------------------------------- | ---------- |+| 1 | 1 | ? | 0 |+| 1 | 1 | ? | 0 |+| 1 | 2 | review-hog-perspective-contracts-security | 1 |+| 1 | 2 | review-hog-perspective-contracts-security | 2 |+| 1 | 3 | ? | 0 |+| 1 | 3 | review-hog-perspective-contracts-security | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 1 | review-hog-perspective-logic-correctness | 1 |+| 2 | 2 | ? | 0 |+| 2 | 2 | review-hog-perspective-logic-correctness | 2 |+| 2 | 3 | ? | 0 |+| 2 | 3 | review-hog-perspective-logic-correctness | 2 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 1 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 1 |+| 3 | 2 | review-hog-perspective-performance-reliability | 1 |+| 3 | 3 | ? | 0 |+| 1000 | 1 | ? | 0 |+| 1000 | 1 | ? | 0 |+| 1000 | 2 | ? | 0 |+| 1000 | 2 | review-hog-blind-spots-general | 1 |+| 1000 | 3 | ? | 0 |+| 1000 | 3 | ? | 0 |+| 1000 | 4 | ? | 0 |+| 1000 | 4 | ? | 0 |++## Findings (post-dedup) with validator verdict++### [❌ dismissed] should_fix · security — products/stamphog/backend/tasks/tasks.py:113-120++**PR URL parsing accepts embedded GitHub-looking substrings from arbitrary hosts**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `_PR_URL_RE.search()` is not anchored to an HTTPS GitHub URL or hostname boundary. Values such as `https://attacker.example/github.com/org/repo/pull/123` are accepted and converted into a request for the real `org/repo#123`. Since this value feeds the privileged inbox-review path, malformed or attacker-influenced task output can select a different review target than the URL represents.+- **Suggestion:** Parse the URL with `urllib.parse.urlparse`, require `scheme == "https"` and `hostname == "github.com"` (or an explicitly supported allowlist), and validate the path as exactly `/<owner>/<repo>/pull/<positive integer>` with no credentials, unexpected port, or extra target-changing components.+- **Validator:** - **Checked:** Traced `_parse_pr_url` (PR-head `products/stamphog/backend/tasks/tasks.py:116`) and its sole non-test caller `process_inbox_pr_review` (`tasks.py:1110`); traced `pr_url` back through `queue_inbox_pr_review` (`facade/api.py:128`) to review_hog's `handle_task_run_saved`/`_start_stamphog_review` (`receivers.py`), where it is `TaskRun.output["pr_url"]`; checked every downstream use of the parsed `(owner/repo, number)`.+- **Found:** The parsed tuple only resolves a `team_id`-scoped `StamphogRepoConfig` filtered `enabled=True`, non-blank `installation_id`, `connected_by_user_id` set, `repository__iexact=<owner/repo>` (`tasks.py:1139-1148`); the subsequent GitHub fetch uses `repo_config.repository` and `repo_config.installation_id` from the DB (`tasks.py:1160`). The URL's scheme/host/port are never used for any request — so a spoofed `attacker.example/github.com/...` host yields the exact same extracted target as a clean URL and changes nothing downstream.+- **Found:** The suggested fix does not close the stated "select a different review target" threat. Redirection is achievable by an actor controlling `pr_url` with a perfectly anchored `https://github.com/<target>/pull/N`; requiring `hostname == "github.com"` only rejects a malformed substring form no real attacker needs. The actual missing control on the receiver leg is positive run-linkage identification — which the webhook carve-out already performs via `find_signal_implementation_run` (`products/tasks/backend/facade/api.py:484`) — not URL host anchoring.+- **Impact:** For all legitimate inputs the leftmost-match regex extracts correctly, so there is no correctness bug; the target is bounded to the team's own enabled+synced Stamphog repos; and the proposed anchoring provides no security benefit against the described redirection. This is minor input-hardening/consistency polish (matching `_is_github_pull_request_url_for_repository`), not a reachable security defect — below the keep bar (speculative/wrong-premise).++### [❌ dismissed] must_fix · security — tools/pr-approval-agent/review_local.py:316-324++**Fail closed when parsing the gate-bypass flag**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** `bool(context.get("self_driving_review"))` enables the self-driving carve-out for any truthy JSON value, including strings such as `"false"`, numbers, or objects. This flag bypasses the bot-author refusal and draft prerequisite and injects trusted provenance into the reviewer prompt, so malformed context can unintentionally authorize a review under relaxed gates.+- **Suggestion:** Require the exact JSON boolean `true`, for example `self_driving = context.get("self_driving_review") is True`, and reject or default closed for every other type. Consider also asserting that the resulting PR is bot-authored before retaining the flag, so the trusted machine-author claim and draft bypass cannot diverge from `PRData`.+- **Validator:** - **Checked:** The full producer→consumer chain for `self_driving_review`: `build_reviewer_invocation` (reviewer.py `+787`) which writes the context dict, its sole hosted caller `run_review_in_sandbox` (tasks.py `+1227`), the JSON round-trip into the sandbox, and both engine entrypoints (`review_local.py` `run()` and the Action's `review_pr.py`).+- **Found:** The flag is set exclusively via `self_driving_review=bool(output.get("inbox_review"))` (tasks.py `+1227`) — already a genuine Python `bool` — and `build_reviewer_invocation` places that bool into the context dict (`+787`), which is JSON-serialized to the sandbox context file. The end-to-end test confirms the on-disk value is a real JSON boolean: `assert context["self_driving_review"] is True` (test_integration `+1287`). The Action path never sets the key, so `context.get(...)` is `None`. Thus `context.get("self_driving_review")` is only ever `True`, `False`, or absent — and `bool(True) is True → True`, `bool(False) → False`, `bool(None) → False`, identical to the suggested `is True`.+- **Impact:** The premise — a truthy string/number/object slipping through — cannot be reached: the upstream `bool(...)` invariant guarantees a genuine boolean, and the context is a trusted server artifact rather than attacker-writable JSON. This is defensive hardening against an input the call-site invariant already rules out. It also yields no security benefit under the only model where parsing would matter (an attacker who can overwrite the context file would just write `true`), so the change is behaviorally a no-op for every reachable input. Falls under speculative 'what if' / defensive-coding paranoia in the drop criteria.++### [✅ VALID] must_fix (validator→should_fix) · bug — products/review_hog/backend/receivers.py:111-135,144-160++**Stamphog gate checks only one assignee instead of any opted-in assignee**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** Both the initial trigger and webhook resolver select one canonical acting reviewer, then inspect only that user's `stamphog_review_inbox_prs` setting. If that reviewer is opted out while another assigned reviewer is opted in, no Stamphog review runs. This contradicts the stated requirement that a review run when at least one assigned user has enabled the toggle, and turning off one user's toggle can incorrectly stop later re-reviews despite another assignee remaining opted in.+- **Suggestion:** Resolve the complete ordered set of assigned organization users for the Stamphog path, select an opted-in user with `next((user for user in resolved if ReviewUserSettings.load(team_id, user.id).stamphog_review_inbox_prs), None)`, and return that user's ID. Preserve the existing single acting-reviewer selection separately for ReviewHog, whose configuration is intentionally tied to the task creator or primary assignee. Use the same any-opted-in resolver for both initial dispatch and webhook rechecks.+- **Validator:** - **Checked:** the full receivers.py PR diff — `_resolve_assigned_reviewer`, the initial trigger in `handle_task_run_saved`, the webhook re-check `resolve_stamphog_acting_reviewer`, and the `inbox_hooks` registry that stamphog's webhook task calls through.+- **Found:** `_resolve_assigned_reviewer` collapses to ONE acting reviewer — `acting = next((user for user in resolved if user.id == task_created_by_id), resolved[0])` (receivers.py ~L204) — and both legs gate on only that user: the trigger does `if pr_url is not None and settings.stamphog_review_inbox_prs:` where `settings = ReviewUserSettings.load(team_id, acting_user_id)`, and `resolve_stamphog_acting_reviewer` re-derives the same single acting id then checks only its toggle. No path iterates the resolved set for any opted-in user.+- **Found:** for a fully auto-started self-driving PR, `created_by` is the GitHub-integration bot (per the module docstring) and is not in the resolved set, so the acting reviewer is `resolved[0]` — the first suggested reviewer by artefact order. If `resolved[0]` is opted out of stamphog while a later assignee is opted in, no stamphog review is queued; and on a later push, if `resolved[0]` toggles off, `resolve_stamphog_acting_reviewer` returns None and re-reviews stop even though another assignee remains opted in.+- **Found:** the PR body states the gate three times as any-opted-in — "any assigned reviewer opted in" (Case 1), "at least one of the assigned users has `stamphog_review_inbox_prs` enabled", "nobody is opted in, so no review runs" (Case 3). The implementation checks exactly one, so it diverges from the feature's own stated central behavior. Architecturally this fits: ReviewHog needs the single-acting collapse to pick ONE user's perspectives/urgency config to drive the review, but stamphog's toggle is a binary gate with no per-user options, so reusing the single-acting resolver for it silently ignores other assignees' opt-in.+- **Impact:** realistic multi-reviewer reports (differing per-user opt-in, default-off) hit this; stamphog reviews are skipped for cases the stated design says should run, and one user toggling off can halt re-reviews despite another remaining opted in. Concrete trigger + concrete consequence, directly in the code this PR adds.+- **Priority:** lowering must_fix → should_fix. The failure mode is fail-safe (a skipped review, never a wrong GitHub approval), the feature is explicitly experimental (draft PR, `experiment-frozen` branch), and the code docstring deliberately describes single-acting-reviewer gating both toggles — so there is a defensible intentional-design reading. The divergence from the stated any-opted-in requirement is real and worth resolving, but not the severity of a data-loss/security/wrong-approval defect.++### [❌ dismissed] should_fix · bug — products/tasks/backend/facade/api.py:506-512++**Team and self-driving filters are applied after selecting an arbitrary run**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** find_task_run searches globally and selects one matching run before this facade checks team_id, signal_report_id, and task.internal. Multiple runs can legitimately share a PR URL or repository/branch, including resumed runs, another team's run, or an unrelated/internal task. If find_task_run selects one of those, this function returns None even when a qualifying self-driving run exists, causing valid inbox re-reviews to be skipped. The branch lookup also uses an unordered first(), making the result unstable when several runs match.+- **Suggestion:** Move team_id and the self-driving task predicates into the queryset used to select the run, and retain the existing active/newest ordering for PR URL matches. Prefer extending find_task_run with explicit filters or implementing a facade-specific scoped query so selection occurs only among eligible candidates.+- **Validator:** - **Checked:** Read `find_task_run` (`products/tasks/backend/webhooks.py:29-98`), `find_signal_implementation_run` (`products/tasks/backend/facade/api.py:484-517`), the carve-out call site (`products/stamphog/backend/tasks/tasks.py:191`), and the run-provenance invariants in `products/review_hog/backend/receivers.py`.+- **Found (internal-task masking ruled out):** Internal plumbing tasks cannot mask a qualifying run — `receivers.py` documents that report-research / repo-selection / custom-agent tasks are `internal=True` and _push nothing_, so they never populate `output.pr_url` or a PR head branch and therefore never match `output__pr_url=pr_url` or `branch=head_branch`. The `task.internal` post-filter has no colliding candidate to lose to.+- **Found (cross-team masking not reachable):** The `pr_url` leg keys on `output__pr_url=pr_url` (`webhooks.py:41`). A specific GitHub PR is opened by exactly one run lineage, so its URL is unique; two teams sharing repo `org/repo` open _different_ PR numbers → different URLs → no shared `output__pr_url`. Even if `find_task_run` returned a foreign-team run, the team post-filter (`api.py:505`) fails **closed** (returns None), and the carve-out re-checks it (`tasks.py:199`), so there is no tenant leak — at most a missed round.+- **Found (resumes handled):** The documented multi-run-per-URL case (terminal original + live resume, `webhooks.py:37-39`) is same-team/same-signal-lineage, so both candidates pass the post-filters, and the ordering `terminal_rank, -created_at` already picks the live one.+- **Found (branch-leg `first()`):** The unordered `.first()` (`webhooks.py:69`) is pre-existing webhook-backstop behavior, not introduced by this PR; the carve-out always passes `pr.html_url` and self-driving runs record their pr_url, so the ordered pr_url leg resolves them and the branch leg is not the resolving path here.+- **Impact:** No realistic input produces the claimed "qualifying self-driving run masked by a non-qualifying one" skip. Worst residual is a rare missed re-review that a subsequent delivery re-triggers, and the caller's head-changing retraction still dismisses stale approvals — the stale-approval safety invariant is not preference- or timing-gated. Speculative collision scenario, below the correctness bar.++### [❌ dismissed] should_fix · bug — tools/pr-approval-agent/reviewer.py:568-568++**Self-driving reviews still include bot-author familiarity**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The prompt concatenates both `familiarity_block` and `self_driving_block`. Hosted execution still calls `_attach_familiarity`, and the server fetches merged PR numbers for the bot author, so a bot with prior merged PRs can receive a positive human-author familiarity signal. This contradicts the new provenance block and can incorrectly influence the verdict.+- **Suggestion:** Skip familiarity computation for self-driving runs and defensively omit `familiarity_block` when `cl["self_driving"]` is true.+- **Validator:** - **Checked:** The full familiarity data path for a self-driving run: the server-side context builder (`fetch_review_context` in tasks.py `+1210-1216`), the engine's `_attach_familiarity` (review_local.py, unchanged `if not raw_prs: return` at lines 301-303), and `_format_familiarity` (reviewer.py:643-645), plus whether `author_pr_numbers` and `self_driving_review` can diverge.+- **Found:** The issue's core premise — 'the server fetches merged PR numbers for the bot author' — is false. The companion change in this same PR does the opposite: `is_inbox_review = bool((run.output or {}).get("inbox_review"))` and `author_pr_numbers = client.get_author_merged_pr_numbers(...) if author and not is_inbox_review else []` (tasks.py `+1215-1216`). For inbox/self-driving runs the fetch is skipped and `author_pr_numbers` is `[]` — the end-to-end test even asserts `context["author_pr_numbers"] == []` (test_integration `+1289`).+- **Found:** With empty `author_pr_numbers`, `_attach_familiarity` hits `raw_prs = context.get("author_pr_numbers")` → `if not raw_prs: return` (review_local.py:301-303), so `cl["familiarity"]` is never populated. `_format_familiarity` then returns `""` because `fam is None` (reviewer.py:643-645). So `familiarity_block` is empty precisely when `self_driving_block` renders.+- **Found:** The two flags cannot diverge — both derive from the same `run.output["inbox_review"]` provenance (`self_driving_review=bool(output.get("inbox_review"))` at tasks.py `+1227`; `author_pr_numbers` gate at `+1215`), stamped once at trigger time before either activity reads it.+- **Impact:** The described failure (a bot receiving a positive human-author familiarity signal alongside the provenance block) is unreachable: whenever `cl["self_driving"]` is true, familiarity is already absent by construction. The suggested guard would be dead code. Falls under 'wrong / unreproducible' and 'already handled elsewhere' in the drop criteria.++### [✅ VALID] should_fix (validator→consider) · code_quality — tools/pr-approval-agent/reviewer.py:697-699++**Provenance prompt falsely states every self-driving PR is a draft**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** The self-driving flag identifies task provenance, not current draft state, but the trusted prompt always says the PR is a draft and that draft state should be ignored. A later push can trigger another review after the PR becomes ready, making this trusted statement factually wrong.+- **Suggestion:** Pass `pr.draft` into the formatter and include the draft-specific guidance only when it is true, or phrase it conditionally without asserting the current state.+- **Validator:** - **Checked:** `_format_self_driving` (reviewer.py `+697-699`), and every path that sets the `inbox_review`/`self_driving` provenance that gates the block: the webhook re-review carve-out `_inbox_rereview_carve_out` and skip flow in tasks.py (`+862-933`, `+956-966`), and the receiver leg `process_inbox_pr_review` (`+1097-1160`). I looked specifically for a `pr.draft` guard on these paths.+- **Found:** The block hardcodes 'It is a draft on purpose ... draft state is not a caution signal for this PR' with no conditioning on actual draft state (reviewer.py `+697-699`). Neither provenance-setting path requires the PR to still be a draft: `_inbox_rereview_carve_out` gates only on head-changing action, bot authorship, repo-native head, config, task linkage, and opt-in — no draft check (`+885-933`); the receiver leg gates on `state == "open"` only, explicitly not draft (`+1097-1100`). `_review_skip_reason` returns `bot_author` for a non-draft bot PR (`+940-947`), so a self-driving PR that flipped to ready and then receives a `synchronize` still enters the carve-out and renders the block. This is a plausible workflow (a triaged draft marked ready, then a follow-up push), not a contrived one.+- **Impact:** The trusted context fed to the review LLM can state a false premise about the PR's lifecycle. Confirmed reachable, so not wrong/unreproducible — a genuine accuracy defect worth a cheap conditional fix.+- **Priority:** Lowering should_fix → consider. The reviewer's stated harm ('can incorrectly influence the verdict') is weaker than claimed: the block's only actionable instruction ('draft state is not a caution signal') is inert when there is no draft, and the sibling sentence 'judge the diff strictly on its own merits' counteracts any leniency the false 'draft on purpose' framing might induce. Reachable only in an edge case with no concrete wrong-verdict mechanism — real but minor.++### [❌ dismissed] should_fix · best_practice — products/review_hog/backend/receivers.py:222-234++**Persist or retry failed Stamphog dispatches**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The post-commit callback catches every exception from `queue_inbox_pr_review` and only logs it. Because the TaskRun transaction has already committed and no durable retry marker is recorded, an exhausted broker publish failure permanently drops the initial Stamphog review unless an unrelated later save happens to retrigger the receiver.+- **Suggestion:** Dispatch through a durable outbox/retry mechanism, or persist pending dispatch state keyed by the task run and have a retrying worker enqueue it. Keep the save path isolated, but ensure a transient broker outage cannot silently lose the review.+- **Validator:** - **Checked:** `_start_stamphog_review` in the PR diff, the pre-existing `_start_review` (ReviewHog) leg it mirrors, the module-level docstring on re-trigger semantics (receivers.py L59-63), and the `queue_inbox_pr_review` facade behavior.+- **Found:** the catch is `except Exception: logger.exception("review_hog_stamphog_inbox_review_queue_failed")` — the failure is logged at exception level, not hidden. Both the docstring ("the broker being down must never surface into the saver") and the identical, already-accepted pattern on the ReviewHog `_start_review` leg show this swallow-and-log is a deliberate, documented convention for this file, which runs inside the tasks save path and must never raise into it. This is not a new defect introduced by the change.+- **Found:** the dispatch is a Celery broker publish (`queue_inbox_pr_review` "queues a Celery task, so the only work on this save path is the broker publish"); the only loss scenario is a rare transient broker outage at the exact on-commit moment. Recovery paths already exist: receivers.py L61-63 states repeat TaskRun saves with an unchanged target deliberately re-fire the receiver (re-dispatching the stamphog leg while the toggle is on), and PR Case 2 re-reviews via stamphog's webhook path on the next push — the finding itself concedes a later save retriggers it.+- **Impact:** the suggested remedy (a durable outbox / persisted pending-dispatch state + a retrying worker) is a substantial reliability subsystem for a best-effort, fail-safe (no wrong approval — only a possibly-delayed review), explicitly experimental feature that already has natural re-trigger paths. That is the 'add an abstraction / future-proof for a case not in scope' shape the criteria drops as overengineering, and it would apply equally to the long-standing ReviewHog leg it mirrors. It does not clear the bar of a reliability defect that will realistically bite.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:1158-1183++**Inbox provenance is granted without verifying the PR belongs to the task run**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The initial-review task accepts `pr_url`, `acting_user_id`, `signal_report_id`, and `task_run_id` from its caller, but after fetching the PR it only checks that the PR is open and has a head SHA. It never verifies that `task_run_id` belongs to `team_id`, carries `signal_report_id`, targets this repository and head branch, or that the PR is repo-native and bot-authored. Nevertheless, it stamps `inbox_review`, which later enables the privileged engine path that bypasses bot, draft, review-mode, and author-permission gates. Because task output containing the PR URL can originate from an agent run, a mistaken or manipulated URL could cause an unrelated PR in any configured repository for the team to receive this privileged review and potentially an approval.+- **Suggestion:** Before creating the run, load the supplied task run through a team-scoped facade and require its task to be the expected non-internal signal implementation with the supplied signal report. Compare the fetched PR's repository and head branch against that run, require `head.repo.full_name` to equal the base repository, and verify the expected GitHub App bot identity. Derive the provenance fields from the verified DTO rather than trusting the Celery arguments. Apply the same verified binding to webhook re-reviews instead of treating a task's stored `pr_url` alone as proof of origin.+- **Validator:** - **Checked:** Traced the receiver leg `process_inbox_pr_review` (tasks.py:1130-1183) vs. the webhook carve-out `_inbox_rereview_carve_out` (tasks.py:144-215); the provenance→engine flow (`activities.py:451` sets `self_driving_review` from `output['inbox_review']`); and the engine gates (`tools/pr-approval-agent/review_pr.py:225,590`, `gates.py`).+- **Found (real asymmetry):** The carve-out gates provenance on `_is_bot_authored(pr)` AND repo-native `head_repo == repo` (fork-safety) AND a `find_signal_implementation_run` facade match. The receiver leg stamps the _same_ `inbox_review` provenance after checking only `state == 'open'` and a non-empty `head_sha` — no bot-author, no repo-native/fork, no run re-binding.+- **Found (no compensating gate downstream):** The engine has no fork or author-association gate; `self_driving=True` relaxes exactly the bot-author refusal and the draft prerequisite (`review_pr.py:225,590`). Fork/association filtering lives only in the webhook pre-filter and the carve-out. So the receiver leg is the only route to the engine's self-driving mode with fork-safety enforced nowhere — bypassing the control the code declares must never be bypassed (`tasks.py:73-75`: an auto-approval can satisfy required reviews with zero humans).+- **Found (fix is effective, unlike the URL-anchoring sibling):** `output.pr_url` is agent-reported via the task-run output API (`set_task_run_output`), not derived from a verified bot PR-creation response. Requiring the fetched PR to be bot-authored + repo-native would refuse a redirect to a human/fork attacker PR — closing the hole that URL validation alone cannot.+- **Impact:** A signal run that reports (via prompt-injected/mistaken agent output) a `pr_url` pointing at a fork or human-authored PR in one of the team's enabled Stamphog repos gets that PR privileged-reviewed and potentially approved, with no fork/bot/association gate anywhere — an errant GitHub approval that can satisfy required reviews. Reachable, though bounded to the team's own enabled repos and gated on the acting reviewer's toggle.+- **Priority:** Keeping must_fix. Note two overstatements in the suggestion that do NOT lower the core severity: re-verifying that `task_run_id` belongs to `team_id`/carries `signal_report_id` is largely redundant (the in-process review_hog caller already establishes these from the real TaskRun and Celery args aren't externally injectable), and the claim that webhook re-reviews 'treat stored pr_url alone as proof' is inaccurate (the carve-out already does bot+fork+facade-match). The genuinely missing controls are the bot-author and repo-native checks on the receiver leg's fetched PR.++### [❌ dismissed] should_fix · bug — products/stamphog/backend/tasks/tasks.py:1185-1201++**Receiver refires can create duplicate review workflows**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The deduplication uses `select_for_update()` only on matching `ReviewRun` rows. When no run exists for the current head, there is nothing to lock, so concurrent receiver tasks can both observe `existing is None`, create separate runs, and start duplicate Temporal/LLM reviews. This is especially plausible because every matching TaskRun output save refires this task.+- **Suggestion:** Serialize the check-and-create operation by locking the parent `PullRequest` row before querying `ReviewRun`, for example by reloading `pr_obj` through `select_for_update()` inside the transaction. Then perform the existing-head lookup, supersession, and creation while holding that lock. Alternatively, add a database-backed idempotency constraint specifically for inbox runs.+- **Validator:** - **Checked:** The receiver-leg transaction body in `process_inbox_pr_review` (tasks.py:1160-1220), `_upsert_pull_request` (tasks.py:319-363), `_start_review_workflow` (tasks.py:366-382), `_supersede_prior_runs` (tasks.py:415-430), the `PullRequest`/`ReviewRun` constraints (models.py:118-145,207-), and the webhook path's documented locking.+- **Found (the missed lock):** The dedup is not the `select_for_update()` alone. `_upsert_pull_request` runs first in the same `transaction.atomic`; its conditional `UPDATE ... WHERE payload_updated_at <= incoming` matches for same-head concurrent refires (identical GitHub snapshot) and takes the PR row's write lock held to commit, serializing the two transactions. On a first-ever review the `get_or_create` INSERT contends on `UniqueConstraint(team_id, repo_config, pr_number)` (models.py:120) instead. Either way T2 blocks until T1 commits, then its `existing` select sees T1's committed QUEUED run and no-ops.+- **Found (loser paths covered):** A transaction that does NOT get the lock only reaches that state via a stale/older snapshot (UPDATE matches 0 rows), and the stale-snapshot recheck (`pr_obj.payload_updated_at > incoming` → return) drops it before the create. This mirrors the webhook path's own comment: `_upsert_pull_request`'s conditional UPDATE takes the PR row lock, held to commit, serializing deliveries.+- **Found (only-gap unreachable):** The single unserialized branch is `incoming_updated_at is None` (early return before the conditional UPDATE, and the stale recheck is guarded on `incoming is not None`). GitHub PR payloads always include `updated_at`, so `get_pr` never yields None here.+- **Impact:** No duplicate Temporal/LLM reviews occur under realistic concurrency — the premise overlooks the PR-row / unique-index serialization that precedes the `existing` check, so it does not meet the bar (already handled). The suggested `(pull_request, head_sha)` uniqueness would additionally break legitimate same-head re-reviews (a base retarget creates a new run without moving the head).++### [❌ dismissed] must_fix · best_practice — products/stamphog/backend/tasks/tasks.py:1185-1190++**Queued initial reviews ignore a later toggle opt-out**+_perspective: review-hog-blind-spots-general · directly-related: True_++- **Problem:** The Celery task trusts the toggle decision made before it was queued and stamps `inbox_review` without resolving the acting reviewer again. If the reviewer disables inbox reviews while this task is delayed or retrying, the task can still launch a privileged review and post an approval after opt-out. The webhook re-review path already rechecks this preference, so the initial path has inconsistent toggle semantics.+- **Suggestion:** Before creating or resuming the run, resolve the current acting reviewer through `get_inbox_acting_reviewer_resolver()` using the verified signal/task provenance. Return without starting a workflow when nobody is currently opted in, and use the freshly resolved user ID in the stamped provenance.+- **Validator:** - **Checked:** The initial-leg dispatch chain (`review_hog/receivers.py` `handle_task_run_saved` → `_start_stamphog_review` → `queue_inbox_pr_review.delay`), the Celery task config and body (`process_inbox_pr_review`, tasks.py:1108-1245), the webhook leg's re-check (`_inbox_rereview_carve_out` → `get_inbox_acting_reviewer_resolver`, tasks.py:201-207), and the opt-out skip handling in `process_pull_request_event` (tasks.py:880-909).+- **Found (observation is accurate but window is tiny):** The dispatcher checks `settings.stamphog_review_inbox_prs` immediately before `.delay()`, and the task (`max_retries=3, default_retry_delay=5`; rate-limit retries `max(retry_after,60)`) runs within seconds-to-minutes. The initial leg indeed does not re-resolve the toggle; the flip-off must land inside that short queue/retry window to matter.+- **Found (no invariant violated):** Any verdict the initial leg posts is over code it actually reviewed on the team's OWN positively-linked self-driving draft PR — not 'an approval over unreviewed code' (the invariant the product guards). The toggle is explicitly a preference, not a safety gate: AGENTS.md states a mid-PR toggle-off 'stops new runs' but 'safety is never preference-gated.'+- **Found (safety residual already handled):** If the initial leg posts an APPROVE after opt-out, the next head-changing webhook delivery hits `carve_out.opted_out=True` and calls `_retract_stale_approvals_on_skip(..., _INBOX_OPT_OUT_DISMISS_MESSAGE)` (tasks.py:894-898), dismissing the standing approval. With no subsequent push, the approval simply stands on the user's own draft PR they requested a review of moments earlier.+- **Impact:** A rare, benign preference-timing race on the user's own linked self-driving PR, with the only safety-relevant residual retracted by the webhook skip path on any later head change — no gate bypass beyond what other findings cover, and no stated invariant broken. Severity is far below the claimed must_fix; below the keep bar (rare/low-impact + already-handled). The 'privileged review / approval after opt-out' framing overstates it by implying an arbitrary target when it is the legitimately-linked PR.++### [✅ VALID] must_fix · security — products/stamphog/backend/tasks/tasks.py:124-127,161-171++**Carve-out trusts any bot identity as the self-driving author**+_perspective: review-hog-perspective-contracts-security · directly-related: True_++- **Problem:** The privileged webhook path only verifies that the PR author is some GitHub bot. A different installed bot with repository write access can open a repo-native PR from a branch associated with a signal implementation run and inherit the bypass of draft, review-mode, and author-permission gates. The task lookup proves a related run exists, but it does not prove this bot created the PR.+- **Suggestion:** Require the expected PostHog Code GitHub App bot login and confirm the matched run used bot authorship before granting provenance. Add those identity facts to SignalImplementationRunDTO if necessary, and fail closed when the expected bot identity cannot be established.+- **Validator:** - **Checked:** `_inbox_rereview_carve_out` (products/stamphog/backend/tasks/tasks.py:144-215), its author gate `_is_bot_authored` (tasks.py:124-127), the run lookup `find_signal_implementation_run` (products/tasks/backend/facade/api.py:484-516) and its `find_task_run` matcher (products/tasks/backend/webhooks.py:30-99), plus the product's own bot-identity model in logic/github_client.py and products/stamphog/CLAUDE.md.+- **Found:** The carve-out grants a review + approval bypass on an 'any Bot' floor (tasks.py:169 calls `_is_bot_authored`, which returns True for `user.type == 'Bot'` OR `'[bot]' in login`). Its own comment at tasks.py:170-171 asserts the stronger invariant it does not enforce ('authorship is forced to the team's GitHub App machine user').+- **Found:** The run match is not authorship proof. `find_task_run`'s branch leg (webhooks.py:69-77) matches on `branch == pr.head.ref` + repository and, unlike the wizard leg, does NOT exclude terminal runs — so any past or present non-wizard signal-implementation run's branch name in that repo satisfies it. Fork-safety (tasks.py:176-178) only enforces repo-native head, not author identity.+- **Found:** The same product treats 'any Bot' trust as unacceptable for approval-adjacent decisions: `_is_own_bot_actor(..., allow_any_bot=False)` requires the exact `<slug>[bot]` (github_client.py:53-69), and CLAUDE.md:32-33 states a fuzzy 'any Bot' match 'must never dismiss or adopt another bot's review.' The carve-out is precisely such an approval-adjacent decision using the forbidden fuzzy floor.+- **Impact:** An attacker-controlled bot with repository write access can open a repo-native PR whose head branch reuses a signal-run branch name, pass the 'any Bot' floor and the branch-leg run match, and inherit the draft/bot/review-mode/write-permission bypass — causing StampHog to review and potentially post a standing GitHub approval on a PR that is not genuinely a PostHog Code self-driving run. This is a real trust-boundary gap consistent with the product's documented invariant, and the requested fix (require the expected `<slug>[bot]` login, confirm bot authorship on the matched run, fail closed when identity is unestablished) matches the existing `allow_any_bot=False` pattern.++### [✅ VALID] must_fix · bug — products/review_hog/backend/migrations/0019_reviewusersettings_stamphog_review_inbox_prs.py:7-9++**Rebase this migration onto the current ReviewHog migration leaf**+_perspective: review-hog-perspective-logic-correctness · directly-related: True_++- **Problem:** This adds a second `0019` migration depending on `0018`, while the app already has an existing migration chain from `0019_reviewreport_author_login_and_more` through `0024_reviewreport_published_head_shas`. Django will detect two conflicting leaf migrations and refuse to migrate.+- **Suggestion:** Run `python manage.py rebase_migration review_hog` so this becomes the next migration after `0024_reviewreport_published_head_shas` (currently `0025`), and update `max_migration.txt` accordingly.+- **Validator:** - **Checked:** the full `products/review_hog/backend/migrations/` chain on master, the fork point's `dependencies`, `max_migration.txt`, and whether django_linear_migrations is active.+- **Found:** master already has `0019_reviewreport_author_login_and_more` → ... → `0024_reviewreport_published_head_shas`, and `0019_reviewreport_author_login_and_more.py:8` depends on `0018_backfill_urgency_threshold_to_consider`. The PR's new `0019_reviewusersettings_stamphog_review_inbox_prs` also depends on `0018`, so `0018` now has two children and the graph has two leaves (`0024` and the new `0019`). `max_migration.txt` currently pins the single leaf `0024_reviewreport_published_head_shas`.+- **Found:** `django_linear_migrations` is installed (`posthog/settings/web.py:207`), so besides Django's own "multiple leaf nodes" error on migrate/makemigrations, the linear-migrations consistency check (single leaf must match `max_migration.txt`) fails in CI.+- **Impact:** Concrete trigger — merging this branch onto current master; concrete consequence — `manage.py migrate`/`makemigrations --check` errors with conflicting leaf nodes and CI blocks, so the migration never applies. The suggested `rebase_migration review_hog` (renumber to `0025` after `0024` and update `max_migration.txt`) is the correct remedy. Matches the PR's `dirty` mergeable state.++### [❌ dismissed] must_fix · bug — products/review_hog/backend/receivers.py:114-114,151-155++**Pin toggle gates to the writer database**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** Both the initial dispatch and webhook re-review gate call `ReviewUserSettings.load()` through the default read route. A recently changed toggle can therefore be read from a lagging replica. Most critically, a webhook arriving immediately after opt-out may observe the old `true` value and launch a review that can restore an approval the user intended to disable. Stamphog's existing `enabled` gates explicitly pin reads to `router.db_for_write(...)` to avoid this failure mode.+- **Suggestion:** Load `ReviewUserSettings` from the writer for these decision gates, for example by adding a writer-pinned settings loader using `.using(router.db_for_write(ReviewUserSettings))`, and use it in both the TaskRun receiver and `resolve_stamphog_acting_reviewer`.+- **Validator:** - **Checked:** the two active DB routers (`posthog/dbrouter.py`, `posthog/product_db_router.py`), the product-DB registry `products/db_routing.yaml`, the replica opt-in setting, and `ReviewUserSettings.load()` itself.+- **Found:** `ReviewUserSettings` is in the `review_hog` app (`products/review_hog/backend/apps.py:6`), which is NOT listed in `products/db_routing.yaml` (only `stamphog`, `visual_review`, `warehouse_sources_queue` are). So `ProductDBRouter.db_for_read`/`db_for_write` return `None` for it — no reader/writer split.+- **Found:** `ReplicaRouter.db_for_read` (`posthog/dbrouter.py:22-31`) sends reads to `"replica"` only when the model name is in `READ_REPLICA_OPT_IN`, else `"default"`. `READ_REPLICA_OPT_IN` is env-driven and empty by default (`posthog/settings/data_stores.py:271-272`), and nothing opts `ReviewUserSettings` in. `load()` (`products/review_hog/backend/models.py:363-367`) issues a plain `.for_team(...).filter(...).first()` with no `.using()`, so it already reads from `default` (the writer/primary) — a strongly-consistent read.+- **Found:** Stamphog's `db_for_write` pins exist because Stamphog IS a registered product DB whose `db_for_read` returns `stamphog_db_reader`, a genuine lagging replica (`posthog/product_db_router.py:27-35`, and its own code comments warn about a "lagged reader"). That rationale is specific to product-DB models and does not transfer to a main-DB model.+- **Impact:** The finding's premise (stale read from a lagging replica → webhook restoring an approval after opt-out) cannot occur here — the read is already against the primary. The suggested `.using(router.db_for_write(ReviewUserSettings))` resolves to `"default"`, exactly the current read target, so it is a no-op that only adds misleading ceremony. Wrong/unreproducible: a sibling-product convention misapplied to a differently-routed model.++### [✅ VALID] should_fix · performance — products/stamphog/backend/tasks/tasks.py:1201-1207++**Failed reviews can be relaunched repeatedly for the same commit**+_perspective: review-hog-perspective-performance-reliability · directly-related: True_++- **Problem:** The deduplication explicitly excludes FAILED runs. Because the TaskRun receiver deliberately fires again whenever output is saved, every subsequent save can create another ReviewRun for the same unchanged head after a deterministic failure. A permanently failing repository or reviewer configuration can therefore repeatedly consume Temporal, sandbox, GitHub, and LLM capacity without any new code to review.+- **Suggestion:** Treat a FAILED run for the same head as handled, or add a bounded retry policy keyed by pull request and head SHA with an attempt limit and cooldown. Require a new head or an explicit manual retry to launch further reviews after that budget is exhausted.+- **Validator:** - **Checked:** the dedup at `process_inbox_pr_review` (products/stamphog/backend/tasks/tasks.py:1202-1210), what re-fires it (review_hog/backend/receivers.py `handle_task_run_saved` + `_start_stamphog_review` → facade `queue_inbox_pr_review`), the stamphog workflow-id/reuse policy (products/stamphog/backend/temporal/client.py:43-48), and the webhook path's create/dedup (tasks.py:1054-1073) for comparison.+- **Found:** The dedup query excludes both SUPERSEDED and FAILED (tasks.py:1207 `.exclude(status__in=(ReviewRunStatus.SUPERSEDED, ReviewRunStatus.FAILED))`), so once a review for a given `head_sha` terminates FAILED, `existing` is None and a new QUEUED ReviewRun is created; there is no attempt cap or per-(PR,head) cooldown anywhere.+- **Found:** The trigger is not head-change-gated. `handle_task_run_saved` fires on every TaskRun `output` save carrying `pr_url`, gated only by the _TaskRun's_ own status (receivers.py `if instance.status in (FAILED, CANCELLED): return`) — not the ReviewRun's. The module docstring states the implementation run deliberately stays `in_progress` and is babysat, so `output` is saved repeatedly for an unchanged PR head.+- **Found:** Nothing collapses the re-launch at the Temporal layer: the workflow id is `f"stamphog-review-{review_run_id}"` (client.py:43), keyed per ReviewRun, so each new row starts a _fresh_ full sandbox+LLM+GitHub review. This is the ReviewHog leg's deterministic-workflow-id + USE_EXISTING collapse (receivers.py docstring) that the stamphog leg lacks specifically after a FAILED run.+- **Found (asymmetry):** The webhook path (tasks.py:1054-1073) is naturally bounded — it keys on GitHub `delivery_id` idempotency, and GitHub does not redeliver an unchanged head — so it never loops on the same commit. The inbox receiver leg is uniquely exposed because its trigger repeats for an unchanged head.+- **Impact:** A deterministically failing review (e.g. a repo whose gateway-credential minting or egress config always fails, or a PR that reliably crashes the engine — realistic `mark_review_failed` causes) re-launches a full sandbox+LLM+GitHub+Temporal run on every subsequent TaskRun output save with no new code to review, and records repeated FAILED runs. Transient failures self-heal (a success re-arms the dedup), so the exposure is the deterministic-failure class — a real resource/reliability defect with a concrete, cheap fix (treat same-head FAILED as handled, or cap/cooldown by PR+head). `should_fix` is appropriate given the deterministic-failure precondition.diff --git a/products/review_hog/eval/scripts/dump_result.py b/products/review_hog/eval/scripts/dump_result.pyindex a336f647223d..040fd9162e46 100644--- a/products/review_hog/eval/scripts/dump_result.py+++ b/products/review_hog/eval/scripts/dump_result.py@@ -342,9 +342,12 @@ for a in arts:chunks = cchunk_count = len(chunks.chunks) if chunks else 0-# Perspective results → raw issue count + per-(pass,chunk) breakdown.+# Perspective results → raw issue count + per-(pass,chunk) breakdown (+ completion timestamps for+# stage timing; pass >= 1000 is the blind-spot sweep's reserved pass number).perspective_rows: list[tuple[int, int, str, int]] = [] # (pass, chunk, source_perspective, n_issues)raw_issues = 0+wave_done_ts: list[datetime] = []+blind_done_ts: list[datetime] = []for a in arts:if a.type == ReviewReportArtefact.ArtefactType.PERSPECTIVE_RESULT:c = parse_artefact_content(a.type, a.content)@@ -353,6 +356,7 @@ for a in arts:raw_issues += nsrc = next((i.source_perspective for i in c.review.issues if i.source_perspective), "?")perspective_rows.append((c.pass_number, c.chunk_id, src, n))+ (blind_done_ts if c.pass_number >= 1000 else wave_done_ts).append(a.created_at)perspective_rows.sort()review_units = len(perspective_rows)@@ -371,6 +375,41 @@ for a in arts:dedup_count = len(findings)valid_count = sum(1 for k in findings if (v := verdicts.get(k)) and v.is_valid)++# Stage timing — wall-clock derived from artefact `created_at` (each stage/unit persists on+# completion). Valid for fresh, non-resumed runs; a resumed run reuses old artefacts and skews this.+def _stage_secs(a: datetime | None, b: datetime | None) -> float | None:+ return (b - a).total_seconds() if a and b and b > a else None+++def _fmt_dur(secs: float | None) -> str:+ if secs is None:+ return "—"+ m, s = divmod(int(secs), 60)+ return f"{m}m {s:02d}s" if m else f"{s}s"+++_ts: dict[str, list[datetime]] = {}+for a in arts:+ _ts.setdefault(str(a.type), []).append(a.created_at)+_snapshot_ts = max(_ts.get("pr_snapshot", []), default=None)+_chunk_ts = max(_ts.get("chunk_set", []), default=None)+_select_ts = max(_ts.get("perspective_selection", []), default=None)+_wave_end = max(wave_done_ts, default=None)+_blind_end = max(blind_done_ts, default=None)+_finding_first = min(_ts.get("issue_finding", []), default=None) # dedup persists findings in one batch+_verdict_end = max(_ts.get("validation_verdict", []), default=None)+stage_timing_rows = [+ ("fetch + snapshot", _stage_secs(report.created_at, _snapshot_ts)),+ ("chunking", _stage_secs(_snapshot_ts, _chunk_ts)),+ ("perspective selection", _stage_secs(_chunk_ts, _select_ts)),+ ("review wave (perspectives)", _stage_secs(_select_ts, _wave_end)),+ ("blind-spot sweep", _stage_secs(_wave_end, _blind_end)),+ ("dedup (incl. combine/clean)", _stage_secs(_blind_end or _wave_end, _finding_first)),+ ("validation", _stage_secs(_finding_first, _verdict_end)),+]+review_stage_secs = _stage_secs(_select_ts, _blind_end or _wave_end)+# Spend (best-effort).start_dt = (datetime.fromtimestamp(RUN_START_EPOCH, tz=UTC) if RUN_START_EPOCH else datetime.now(UTC) - timedelta(hours=2)@@ -410,6 +449,18 @@ for line in spend_lines:w(line)w("")+w("## Stage timing (wall-clock)\n")+w("| stage | duration |")+w("| ----- | -------- |")+for stage_name, stage_secs in stage_timing_rows:+ w(f"| {stage_name} | {_fmt_dur(stage_secs)} |")+w("")+w(+ f"- **Review stage total (selection → last finder unit, wave + blind-spot):** {_fmt_dur(review_stage_secs)} — the reviewer-model speed comparison number."+)+w("- Derived from artefact `created_at` (persisted on completion); only meaningful for fresh, non-resumed runs.")+w("")+w("## Chunking\n")if chunks:for ch in chunks.chunks:@@ -449,7 +500,7 @@ with open(path, "w") as fh:fh.write("\n".join(lines) + "\n")print( # noqa: T201 — playground eval script, stdout is the intended output channel- f"DUMP_OK label={LABEL} chunks={chunk_count} units={review_units} raw={raw_issues} dedup={dedup_count} valid={valid_count} -> {path}"+ f"DUMP_OK label={LABEL} chunks={chunk_count} units={review_units} raw={raw_issues} dedup={dedup_count} valid={valid_count} review_stage={_fmt_dur(review_stage_secs)} -> {path}")if spend_headline:print(spend_headline) # noqa: T201 — playground eval script, stdout is the intended output channel