Skip to content

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

109 KB
Raw Blame

ReviewHog Architecture

Terms

PostHog Review is the product name on every outward surface: GitHub comments, MCP tools, API docs, and UI prose. Code review is the name of the in-app page and its nav entry only. ReviewHog is the internal codename. Code, logs, metric names, keys, and developer docs use it. An @posthog review comment starts a Standard review, and @posthog review --deep starts a Deep review. No label starts a review.

The UI and the text PostHog Review posts use the user-facing names. Code, API values, and stored data use the internal names.

  • Standard (internal name Flash, flash): the automatic review every push gets. A fixed set of reviewers on a lower-cost model. It never pushes to the branch.
  • Deep (internal name Full, full): the review someone asks for with the Review button, the @posthog review --deep comment, or an Inbox report. It uses the requester's perspectives, validator, and threshold.
  • Resolve: the stage after a Deep review that fixes review comments on the PR branch, only when the PR owner opted in (resolve_comments).
  • Inbox review: a Deep review of a PR the PostHog agent opened for an Inbox report. The report's assigned reviewer counts as the PR owner.
  • Perspective: one angle a Deep review reads the code from, such as logic and correctness. Each one is a review skill.
  • Threshold: the lowest finding priority a Deep review posts to GitHub (urgency_threshold). Findings below it stay in the report in PostHog.

Overview

ReviewHog (products/review_hog) is an automated GitHub PR code reviewer. It is a Django app (backend/apps.py, label review_hog, module products.review_hog.backend). A run fetches a PR from GitHub, splits it into logically reviewable chunks, picks which perspectives each chunk actually needs (perspective selection, a cheap one-shot), runs the selected perspective reviews in parallel on each chunk inside sandbox agents, then combines → scope-cleans → deduplicates → validates the findings, renders a markdown report, and posts inline review comments back to the PR. Each review perspective (Logic & Correctness, Contracts & Security, Performance & Reliability) is a DB-synced LLMA skill the sandbox agent pulls over MCP — the same canonical-skill pattern the Signals scouts use.

The repo-access LLM steps (perspective review, blind-spot check, validation) run inside sandbox agents spawned through the shared products/tasks infrastructure (Task/TaskRun → Temporal ProcessTaskWorkflow → Modal/Docker sandbox → agent-server) — ReviewHog composes a prompt, hands it to the Tasks runner, and gets back the validated model, owning no sandbox/Temporal code. The pure-text steps (chunking, perspective selection, dedup) run within size gates as one-shot direct LLM-gateway calls (reviewer/sandbox/direct_llm.py, structured outputs against the same pydantic models; chunking/dedup fall back to the sandbox above their gates, selection falls back to running everything). Run state is persisted to Postgres (ReviewReport + ReviewReportArtefact) — there is no on-disk store; the only external side effect is the GitHub review it posts.

This document is the present-tense architecture reference — what ReviewHog is today. Its companion DECISIONS.md is the full record of why it got there: the staged build history, the design decisions (with the alternatives weighed and rejected), the gotchas, the grounded implementation maps, and the roadmap — including the designed-but-unbuilt loop. Nothing is summarized away; go there to check the reasoning behind any part of this reference. Status & next below is a short summary of what's in flight, with the detail in DECISIONS.md.

Keep the docs in sync, each in its lane. This reference is the source of truth for ReviewHog's architecture — the pipeline shape, the sandbox/contract surface it binds to in products/tasks, the data models, the prompts, the artefact layout. A merge or refactor that moves or renames what ReviewHog depends on is exactly such a change: re-point the affected sections here, don't leave them stale. Land the reasoning, build history, and roadmap updates in DECISIONS.md — that's the record that grows over time, so this reference stays lean and present-tense. Don't let the build log grow back into this file.


Status & next

ReviewHog runs end-to-end: label / UI / inbox / automatic authored-PR triggers → the Temporal pipeline → published PR review. Automatic Standard reviews run on new PRs and pushes, including drafts in repositories that turn draft reviews on, unless the owner turns them off (a draft gets one review, and the next one runs when it is marked ready), but never on PRs with the skip-agent-review label, in every repository a project reviews, for the authors that the project rule, the repository exceptions, and each person's own choices select (backend/automatic_review_rules.py). The per-PR queue serializes reviews and coalesces automatic pushes into a follow-up for the latest head. The current focus is productionizing the reviewer-topology eval and tightening the finder/validator balance (validator strictness, fewer junk candidates, the coverage gap). The broader loop that reacts to comments and implements fixes is designed but not built; the pipeline below is the body of each review turn. The resolution stage — a post-review, standalone-capable stage that triages every unresolved review thread and implements the worth-and-safe ones directly on the PR branch — is built and live-qualified (e2e on its own PR #72074, 2026-07-18 — verdicts, findings, and the GO call in eval/experiments/2026-07-resolution-e2e/FINAL_REPORT.md): ResolvePRWorkflow (backend/temporal/resolution.py) drives one warm writable sandbox session per PR (one thread per turn, humans → ReviewHog → other bots), persists per-thread thread_verdict artefacts on the living report, replies/resolves server-side from verdicts (bot threads only; humans keep the final word). A reply has a fixed shape (<reply_shape> in prompts/thread_resolution/prompt.jinja): one verdict sentence, a --- divider, then at most 3 short lines (5 for an escalation), in Simplified Technical English via the writing-simplified-technical-english skill the sandbox image carries. Test and lint output never enters the reply text: the driver posts the verdict's verification under it as a collapsed "How this was verified" block (_verification_section) after the commit link, and inserts the blank line GitHub needs before a --- the model wrote directly under its verdict (_normalize_reply_divider). A reply past the shape (more than 5 support lines or 150 visible words) is folded, not cut: the verdict and the first lines stay visible and the rest lands under a collapsed "More detail" block, with a warning logged (_fold_overlong_reply). The whole posted body is scrubbed of credential shapes last (tools/redaction.py::redact_secrets: PostHog secret key prefixes, GitHub token shapes, and x-access-token clone URLs), because the sandbox holds live tokens and the agent may paste command output into verification; the review stage runs the same scrub over the review body and every inline finding comment in publish_review.py::_post_github_review. A FIXED verdict's echoed commit SHA is verified server-side before delivery (commit_on_branch); an unproven SHA posts the reply without the commit link and never auto-resolves. A real commit is then checked against the hard-floor path backstop (commit_restricted_paths): one touching .github/, CODEOWNERS, or dependency manifests delivers a human-review warning instead of the link and never auto-resolves either.

TODO (BLOCKING public release): the three remaining injection-surface hardening items from the July e2e GO conditions. Manual review is available to explicitly enabled projects. Resolution is limited to projects with the review-hog flag, for repositories their teams own. This is a limited rollout; the feature flag does not establish repository or comment trust. Operators must assess both before enabling resolution. DECISIONS.md Stage 7 records the 2026-09-30 decision to accept the existing risks for this limited manual rollout. The path backstop above is built; these are deliberately deferred (maintainer decisions 2026-08-06 and 2026-08-10, recorded in DECISIONS.md Stage 7) and MUST land before public release or resolution on untrusted PRs or repositories the team does not own:

  1. Structural comment rendering — thread comments still render as flat text in the resolution prompt, so a commenter can forge an "OWNER" header or a fake "SAFE TO FIX" verdict inside their own comment (tools/thread_resolution.py::render_thread). Fix: JSON-encode the conversation like the review stage's PR_COMMENTS (and decide whether to expose the real comment databaseId as ground truth). Prompt-content change → validate with a live e2e run.
  2. Author-permission gate — no code rule restricts whose comment may drive a write turn; the policy is the hard part (review bots and external contributors both carry author_association: NONE, so a naive filter drops exactly the bot threads the stage exists to resolve). Decide which associations may drive write turns and how trusted bots stay in scope. The same policy must cover standing-verdict overrides: today a "SAFE TO FIX" reply from any non-bot account substitutes for the worth judgment with no association gate, so the thread's own low-trust asker can wave their own ask through the worth bar (safety bar and hard floors still apply).
  3. Pre-push restricted-paths enforcement — the path backstop is detection, not prevention: GitHub's createCommitOnBranch makes commit and push one atomic act, so a fix commit touching .github/, CODEOWNERS, or dependency manifests is already on the PR branch (and CI is already running it) before commit_restricted_paths looks. The guard must move into the signed-commit tooling itself, before the mutation fires — a cross-product change (desktop agent package signed-git-tool / signed-commit.ts plus the Tasks facade threading the policy in, plus a sandbox image rebuild), which is why it is a gate rather than a fix in this repo.

Full reviews can include resolving: a published Full review chains into the stage when the PR owner opted in (resolve_comments, default off), whoever triggered the review (review_request_rules.ResolutionGate). The owner (backend/pr_owner.py) is the author when the GitHub login maps to an active member; for a self-driving PR that the PostHog GitHub App opened, it is the Inbox report's canonical reviewer; otherwise nobody, and a PR without an owner never gets writes. Flash never resolves. The chained run applies the owner's resolution criteria. Standalone entry: the run_resolution command or the UI / MCP resolve-only action, which answers 409 resolution_not_opted_in unless the owner opted in; _prepare_run checks the same gate again before any write. Before every push the stage also holds on a protected head branch (CommitHold.BRANCH_PROTECTED, read from GitHub's branch API; a failed read raises), next to the merge queue and stacked-PR holds. Design + decision record: DECISIONS.md Stage 7; vocabulary: CONTEXT.md; the live-e2e qualification plan (the resolver fixes its own PR): eval/experiments/2026-07-resolution-e2e/PLAN.md.

Fix profiles are canonical resolution-criteria skills that set how eager the fixer is. review-hog-resolution-criteria is the default. review-hog-resolution-criteria-gaps fixes reachable bugs and leaves typos, nits, wording, stale docs and style. review-hog-resolution-criteria-small fixes small, contained issues and leaves findings whose fix needs a design choice. Each profile is the default text plus a profile section, with the same safety rules, hard limits and human overrides. A profile leaves a thread as escalate with a reply that opens "Left for the author:", so the thread stays open. All three are in CANONICAL_RESOLUTION_SKILL_NAMES (reviewer/skill_loader.py), so every user sees and can select them. Only the default auto-seeds active; a profile is active only after the user selects it.

Resolution visibility & the busy-guard (grilled 2026-08-13, DECISIONS.md "Resolution-stage visibility & cycle guard"; ADR adr/0001): a run opens with a resolution_run work-list artefact (queued thread ids + counts) written by _prepare_run, and reviewer/progress.py::resolution_states derives the run's state from artefacts alone — resolving (delivered verdicts — reply_posted — counted against the queue, fresh activity), completed (a closing run note, author RESOLUTION_RUN_NOTE_AUTHOR), or died-partway (no note, stale). The PR-comment counters likewise count only threads whose GitHub writes landed (delivered_outcomes); judged-but-undelivered threads join the closing tally's "couldn't handle" count instead. The reviews API exposes it as the row's resolution field ("Resolving comments · 6/10" / "Resolution didn't finish · stopped at 6/10" in the scene), the PR status comment carries a "Resolve comments" row in its step table (update_resolution_status_comment — spliced into the review's comment, created on demand for standalone runs, failure-edited on the final attempt), with a patched workflow-level backstop (fail_resolution_activity, fired from ResolvePRWorkflow's except) covering the deaths the activity handler can't see — prepare failures, timeouts, cancellation, worker death — by idling the report and writing the failed section from the persisted work-list, and each queued thread's opening comment gets a best-effort 👀 reaction (queue marker; never removed). The API's busy-guard (temporal/client.py::workflow_running, fail-open describe on the deterministic IDs) refuses a review request while the PR's resolve-pr runs and a standalone resolution while its review queue runs. Automatic requests remain in the review queue until resolution finishes; the chained post-publish resolution starts within the active review turn.

TODO (SOON) — react to thread replies: answer and act when a human responds to an escalated (or any settled) thread. The per-thread mechanics already exist and are e2e-proven: a new human comment beats the verdict watermark and re-opens triage for exactly that thread, standing verdicts ("SAFE TO FIX" / "E2E REQUIRED") steer the re-judged outcome, and everything else skips at zero cost. What's missing is the trigger: nothing starts a resolution run when the reply lands, so today the conversation only advances when someone runs run_resolution / the resolve-only action. Build the comment trigger — a pull_request_review_comment (created) event → the existing trigger API → start_resolution_workflow for that PR (debounced; skip when the commenter is ReviewHog itself) — so replying to an escalation gets an actual answer: implement on a go-ahead, decline-and-say-why on a disagreement, re-escalate with the new context otherwise. Mind the known blind spot: the work-list only fetches unresolved threads, so replies on already-resolved (FIXED) threads are invisible — the trigger should either unresolve-on-human-reply or the fetch must include threads with comments newer than their verdict watermark (see the resolution e2e's F-findings).

TODO (later thoughts, cost) — let the resolver lean on the validator's work. For ReviewHog's own threads the report already holds a researched validation_verdict per finding (argumentation, category, adjusted priority) — yet the resolution turn starts from just the thread text and re-investigates the same code cold in an opus-xhigh sandbox (~$1/turn in the e2e). No clear task yet; directions when this gets picked up: join a bot thread back to its finding + verdict and put that argumentation in the turn prompt as a head start, and see whether that shortens turns or lets bot-thread turns run a cheaper tier while human threads keep the full treatment.

TODO — check whether the reviewers sweep too wide, and how to move them closer to the validation bar. The resolution e2e's review leg found 55 raw issues, dedup kept 48, and the validator kept 12 — a 75% kill rate, with every raw must_fix downgraded on the way through. Either the finders are paying for breadth the validator just throws away (wasted sandbox spend + validation load), or wide-then-strict is the correct division of labor and the funnel is healthy. Decide with data, not taste: measure per-perspective precision (share of a perspective's finds that survive validation — the e2e run splits 12 survivors as security 4 / logic 3 / blind-spot 3 / performance 2), then try pulling the validation-criteria bar into the perspective skills themselves (the reviewer reads the same skill the validator applies, so it self-filters before emitting) and compare survivor count, coverage, and cost against the wide baseline. Ties into the topology-experiment conclusion that skill content + validator strictness — not topology — is the binding constraint.

The full roadmap — every open thread with its reasoning, the loop design, the grounded implementation maps, and the experiment backlog — is in DECISIONS.md (start at its "🎯 NEXT" section) and eval/ (RUN_LOG.md, POTENTIAL_EXPERIMENTS.md, experiments/).

Before public release: land the three BLOCKING resolution-stage hardening TODOs above (structural comment rendering + author-permission gate + pre-push restricted-paths enforcement). Enabling another project for manual review does not clear these requirements for public or untrusted use.


Preflight — is everything ready for a local review?

Check these four things before a local run_review; don't re-derive them from code each time.

  1. Temporal worker up — the dev-stack (phrocs) process temporal-worker must be running (phrocs MCP get_process_status, or the hogli TUI). It hot-reloads via nodemon on any products/**/*.py edit — never start a second worker (it dies on port 8001 already-in-use). The backend process must be running too.

  2. ngrok tunnels up (only the user can start ngrok): curl -s http://localhost:4040/api/tunnels must list all three — django → :8010, gateway → :3308 (LLM gateway), mcp → :8787. Without them the Modal sandboxes can't reach the local backend / gateway / MCP. A tunnel can be up while its local service is down: the llm-gateway process can crash at stack boot (exit 127), which shows as HTTP 502 on the gateway tunnel while django/mcp answer 200. Probe all three from Modal's network, and on a 502 check the process in phrocs and restart it — the tunnel itself is fine.

  3. Target PR is reviewable — non-fork (fork PRs are rejected at fetch) and open. Drafts ARE reviewed and published (there is no draft gate) — warn the user before publishing on someone's draft. Private repos outside PostHog work: fetch, clone, and publish all resolve the team's GitHub App installation token per repo server-side, so any repo the integration's installation can access is reviewable. The PR's reviewable additions count picks the chunking path: ≤400 single chunk (no chunking LLM), ≤5000 one-shot LLM chunking, above that sandbox chunking (slowest).

  4. Prior state — check for an existing report so you know whether this is a fresh r1 or a re-review (same-SHA re-runs no-op at publish via the marker + published_head_sha):

    PGPASSWORD=posthog psql -h localhost -p 5432 -d posthog -U posthog -c \
      "SELECT pr_number, status, run_count, head_sha, published_head_sha \
       FROM review_hog_reviewreport WHERE repository='PostHog/posthog' AND pr_number=<N> AND team_id=1;"
    

Run it (no GITHUB_TOKEN env — fetch and publish resolve the team's GitHub App installation token server-side; publishing is opt-in per run via --publish):

flox activate -- bash -c "DJANGO_SETTINGS_MODULE=posthog.settings python manage.py \
  run_review --pr-url https://github.com/PostHog/posthog/pull/<N> --team-id 1 --user-id 1 [--publish]"

Verify a run: review_hog_reviewreport.run_count bumps once per finalized turn (status returns to idle), or inspect activity-level progress in Temporal:

docker exec posthog-temporal-1 tctl --address temporal:7233 --ns default workflow show \
  --workflow_id "review-pr:<team>:<owner>/<repo>:<pr>"

Stall check — confirm the sandboxes are alive after the fan-out. Within ~15–20 minutes of the perspective wave starting, the ngrok request log (curl -s "http://localhost:4040/api/requests/http?limit=5", or the ngrok terminal dashboard) must show task fetches from the sandboxes. Open issues-review process-task workflows with zero tunnel traffic means the sandboxes never started — the worker can wedge before sandbox provisioning while its heartbeat signals keep flowing, so Temporal looks alive and artefact-count polling can't tell "slow agents" from "nothing running" (perspective units normally finish in ~8–15 min). A run in that state does not recover on its own: restart the temporal worker (via phrocs). The fresh worker retries the stuck activities, and the head_sha-scoped DB resume makes the redo cheap.


Pipeline

ReviewPRQueueWorkflow (backend/temporal/scheduling.py) serializes requests for a PR and starts each turn as a child workflow. ReviewPRWorkflow (backend/temporal/workflow.py) drives the setup activities → two fan-out child workflows (perspective review / validate) → finishing activities, each stage an activity in backend/temporal/activities.py. Only small values cross boundaries (report_id + head_sha + unit keys / JSON issue slices); every activity reloads its inputs from the per-turn pr_snapshot artefact, so no big payload hits Temporal's ~2 MiB cap. State persists to Postgres (ReviewReport + ReviewReportArtefact); there is no on-disk store. Each fan-out child bounds its per-unit sandbox activities with a fresh asyncio.Semaphore(MAX_CONCURRENT_SANDBOXES) (constants.py) + gather(return_exceptions=True) — there is no module-level semaphore. The expensive, turn-stable sandbox stages (chunk / perspective review) are idempotent via a head_sha-scoped DB resume — a re-run reuses their rows instead of re-calling the sandbox; dedup recomputes, while validation resumes per issue off its persisted verdicts (load_run_validations). The validator runs one warm multi-turn session per chunk (one verdict per turn); there is no separate analyze stage (the reviewer self-investigates from the diff + the PR intent).

Visual flow (this compact diagram is the only one — a full-detail ARCHITECTURE_DIAGRAM.mmd existed and was deleted deliberately; every attempt to keep it readable and current failed, so don't recreate it):

flowchart TD
    PR["PR URL"] --> FETCH["1. Fetch PR data (GitHub API)"]
    FETCH --> SCHEMA["2. Generate JSON schemas from Pydantic models"]
    SCHEMA --> CHUNK{{"3. Chunk PR (single chunk ≤400 adds; one-shot ≤5k, else sandbox)"}}
    CHUNK --> SELECT{{"4. Select perspectives per chunk (one-shot, fail-open → dense)"}}
    SELECT --> L1{{"5a. Perspective — Logic & Correctness"}}
    SELECT --> L2{{"5b. Perspective — Contracts & Security"}}
    SELECT --> L3{{"5c. Perspective — Performance & Reliability"}}
    L1 --> BLIND{{"6. Blind-spot sweep (1/chunk, told which lenses succeeded)"}}
    L2 --> BLIND
    L3 --> BLIND
    BLIND --> DEDUP{{"7. Dedup (combine + scope-clean local; pre-filter + one-shot ≤50 candidates, else sandbox; drops prior comments' and prior turns' re-finds)"}}
    DEDUP --> VALIDATE{{"8. Per-chunk validation (warm session, parallel)"}}
    VALIDATE --> MD["9. Build review body + finalize (DB)"]
    MD --> PUBLISH["10. Publish PR review (GitHub API, DB-driven)"]

Single-agent Flash (the Flash default)

A Flash turn runs one of two designs, picked by the fetch activity (select_review_design, reviewer/constants.py). The single-agent design (reviewhog-flash-2-3) replaces steps 4, 5, and 8 below with parallel Codex sandbox sessions, all on the PR's arm set (below) and all returning SingleAgentReview:

  • The main session (single_agent_review_activity) reviews the whole PR. Its system prompt is core.md (the DevEx-owned rubric, adapted from OpenAI's Codex review rubric). A failed main session fails the turn.
  • Two lens sessions (lens_review_activity, FLASH_LENSES): performance and reliability, and contracts and security. Their system prompts (lens_performance_reliability.md, lens_contracts_security.md) are DevEx-owned copies of the two pipeline perspective skills, and lens_priority.md follows their finding format. A PR with at most FLASH_LENS_CHUNK_MAX_LINES (600) reviewable changed lines is one lens part with every file. A larger PR splits into parts over its reviewable files (plan_lens_chunks, tools/split_pr_into_chunks.py: no LLM call, directories kept together, files never split), at most FLASH_LENS_MAX_CHUNKS (4); above that the parts grow to about equal size. Reviewable lines leave out only files nobody authors by hand: lockfiles, snapshots, generated code, binary and image assets, and max_migration.txt. One session runs per lens and part, so a turn opens at most 9 sessions, under one MAX_CONCURRENT_SANDBOXES semaphore. A lens session gets FLASH_LENS_SESSION_TIMEOUT (10 minutes, retry included) instead of the sandbox timeout. A failed or timed-out lens session costs only its own findings.

Arm sets. SINGLE_AGENT_ARM_SETS (reviewer/constants.py) names each set of arms the sessions can run on: one arm for the main session, one for every lens session. The control set runs every session on SINGLE_AGENT_FLASH_ARM (gpt-6.1-sol @ medium). The multivariate reviewhog-single-agent-arms flag, keyed by the PR like the splits in the push gate, picks a set by its variant; no variant, an unknown variant, an evaluation failure, or a coordinated PR gives control, so turning the flag off is the kill switch. The fetch activity records the name on ReviewMeta.arm_set, and every session of the turn reads it from SandboxStageInput.arm_set. A set's name keeps its meaning: another model or effort gets a new name. A session on another arm than the control arm whose agent fails runs once more on the control arm, so an outage of that model never costs the review. Each result is stamped with the arm that ran it, and dedup reads each session's result under its own arm, else the control arm. The started, completed, and failed events carry single_agent_arm_set; the completed event also counts flash_arm_fallbacks. Session cost is on $ai_generation by $ai_model and ai_stage.

The fetch activity records the number of lens parts on ReviewMeta.lens_chunk_count; each lens activity rebuilds its part from the PR snapshot. The task prompt (prompt.jinja) carries the title, description, numbered diff, earlier turns' findings, and the finding format, plus a scope section for a lens part. A diff over FLASH_PROMPT_DIFF_MAX_CHARS (about 200K tokens) shrinks to the reviewable files, and then to the file list alone; the file list marks every file whose diff is left out, and the prompt says how to read it with git: fetch the PR's merge base by its commit id, then diff it against the head. The fetch activity reads the merge base from GitHub's compare API for a single-agent turn (PRFetcher.fetch_merge_base_sha) and keeps it on the pr_snapshot. The prompt puts it into the command only when it is a full commit id, so no text from the repository, such as a branch name, reaches the session's shell. Without one, the prompt tells the session to read those files at the head. There is no team slot: every team runs the same DevEx-owned prompts.

Each session persists as one perspective_result under a reserved pass (SINGLE_AGENT_PASS_NUMBER 2000, lenses 2001 and 2002) and its part. On a follow-up turn, a finding more than FLASH_FOLLOW_UP_CHANGE_MARGIN_LINES (3) lines from any code that changed since completed_head_sha drops as old_code first (ChangedSinceReview). An automatic turn after run FLASH_WHOLE_PR_TURNS (1) drops every P2 and P3 finding there, so a fix only draws findings about the fix: the first run reviews the whole pull request with the larger first-review cap, and every later automatic run reviews the push. Requested turns (@posthog review, the label, the UI) drop only P3 findings there. The two heads' PR snapshots are compared by line content per file, so lines a base merge only moved stay old. Must-fix findings, files whose patch GitHub left out, a first review, and a re-run at the reviewed head skip the check. Step 7 then runs as two dedup calls in parallel (dedupe_flash_findings, tools/single_agent_review.py), both one-shot OpenAI calls on FLASH_DEDUP_MODEL (gpt-6-luna @ medium, run_oneshot_openai_review): the main findings against earlier turns, and the lens findings against the same plus the main findings as anchors, so a lens finding can lose to a main finding but never the reverse. Flash never reads PR comments, so it posts what it finds whatever people or other bots already said. Both calls send every finding to the LLM; the pipeline's positional pre-filter does not apply to Flash. The dedup output (IssueDeduplication, shared with the pipeline) names what each duplicate repeats (duplicate_of: the finding kept in its place, an earlier turn's finding by its issue key, or a PR comment id). A finding that survives takes the priority of the most severe duplicate removed in its favor, so a lens P1 that repeats a main P3 posts as must-fix. A removal holds only when what it names survives (_resolve_duplicates): a finding that names itself or an id its call was not shown stays, findings that name each other in a loop keep the first one in the compose order (priority, P level, main before lens, session order), and a removal whose target also drops records the survivor at the end of the chain. A Flash dedup call that fails non-retryably (the gateway rejects the model), or fails on the activity's last attempt, falls back to the positional pre-filter alone: a finding on the lines of an earlier turn's finding drops as its repeat, and findings of this turn never drop each other. The turn logs it, marks those drops dedup_fallback, and reports flash_dedup_fallback, so a dedup failure never fails a turn whose sessions succeeded. compose_flash_findings then ranks the findings highest priority first, a reported P0 before a P1 of the same stored priority, and the main session first on ties, before anything persists. Every must-fix (P0/P1) finding is kept outside the cap, up to FLASH_MUST_FIX_CAP_MULTIPLIER (2) times the cap, and P2 and then P3 findings fill the slots left under the cap, flash_max_findings(parts) (4 plus 2 per lens part past the first, up to 10). The first review (run 1) gets FLASH_FIRST_REVIEW_CAP_MULTIPLIER (2) times that cap: a cut finding is recorded only as a dropped_finding, not as a finding later turns dedup against, so a later turn would find it again and post it on its own. No validator runs, so dedup writes an accept-as-found verdict per survivor. P0/P1 store as must_fix, P2 as should_fix, P3 as consider, and the finding's reported_priority keeps the reviewer's P0-P3, so P0 and P1 stay apart for analysis. One exception: a dedup survivor takes a more severe duplicate's level when both fold into the same stored priority (a P0 merged into a P1); the dropped_finding record keeps the duplicate's own level. Findings publish inline. An optional suggestion_code is stored on the finding but never posted. A PR past the lens part cap gets one sentence that says the review ran in larger parts (ReviewMeta.lens_chunks_capped, large_pr_note). A Standard review adds it to its summary line, and a clean Standard turn posts a short review with it next to the 👍. That review has its own hidden reviewhog:large-pr-note marker, so a pull request gets it once and re-reviews do not repeat it. It does not set the published watermark, so a later turn on the head still publishes its findings.

The finding budget (reviewer/finding_budget.py) caps what automatic Standard reviews post on one pull request in total. It counts every valid finding that published turns let through their urgency threshold, from every mode and trigger. Once the pull request has FINDING_BUDGET (20) posted findings, compose_flash_findings keeps only the must-fix findings of an automatic turn: they count toward the budget but always post. Automatic reviews run on every pull request as a safeguard, so past the budget they only raise what must be fixed. A review someone asks for (a comment, the label, the UI) is not limited, and SandboxStageInput.trigger_source tells the dedup stage which kind ran. A finding that fits under the turn's cap but not under the budget drops as budget. A review that still posts ends with one line that says how many it left out and, where comment commands run, offers @posthog review --deep: the head already has its Standard review, so only a Deep review runs on it again. A turn that keeps nothing stays silent. Fixing or resolving a finding gives no budget back, because a coding agent that fixes and resolves everything would otherwise refill it. Pull requests split into two arms by a hash of the repository and number (budget_arm). Only the budget arm applies the budget, and finding_budget_arm on reviewhog_review_completed and reviewhog_finding_outcome splits the measurement.

The same module counts review rounds (ReviewRound): the turns that published on the pull request before this one, by any mode and trigger, plus one. From round ROUND_CAP (3) on, a review that posts findings ends with a line that names the round and asks the author to reconsider the approach, because an author and a reviewer that fix one finding at a time loop, and most of what a late round flags was already there in the first. A clean turn carries no note. Every reviewhog_review_completed event carries review_round, so convergence (how many rounds a pull request takes before a clean turn) reads from the events.

The first review that posts findings on a pull request ends with one more note (first_review_note in backend/review_notes.py). It links the report in the PostHog Review UI (report_deep_link). On a Standard review, where comment commands run, it also offers @posthog review --deep. Later reviews do not repeat the note: the published watermark is set after the first post.

Every finding the turn drops after scope cleaning persists as a dropped_finding artefact (DroppedFindingArtefact, written by replace_dropped_findings beside replace_deduplicated_findings in the dedup activity): the full finding with its reported_priority, the session's pass and part, the disposition (old_code, dedup_prior, dedup_comment, dedup_anchor, dedup_sibling, cap, or budget), duplicate_of (an issue key, or comment:<id>), the rank in the composed order for a cut finding, the cap, and the lens part count. A retried turn replaces its rows by run_index. Only analysis reads them, and publishing counts the budget drops for its note: the status comment, outcome classification, load_prior_findings, and the reviews API read issue_finding rows, so a dropped finding can neither post nor suppress a later finding.

A Flash turn of any size runs the single-agent design. The pipeline design (reviewhog-flash-1-1), the steps below, runs a Flash turn only when the reviewhog-flash-pipeline-kill-switch feature flag is on (organization-keyed, read in the fetch activity by reviewer/feature_flags.py). The flag moves Flash turns back to the pipeline without a deploy; a flag evaluation error reads as off. FLASH_DESIGN_DEFAULT is the code default. Full turns always run the pipeline. reviewhog_review_started reports the choice as review_design and its cause as review_design_reason (full_mode, default, kill_switch).

Step-by-step (as orchestrated by ReviewPRWorkflow)

  1. Parse PR URL — PRParser.parse_github_pr_url regex-extracts owner/repo/pr_number; raises on a malformed URL.

  2. Fetch PR data — PRFetcher(owner, repo, pr_number, token, installation_id).fetch_pr_data() (tools/github_meta.py, GitHub REST via the gated egress transport — see tools/github_client.py; token is the team's GitHub App installation token, resolved server-side in the activity — no env GITHUB_TOKEN) returns (pr_metadata, pr_comments, pr_files, diff) in-process — no files. The fetch activity rejects fork PRs (PRMetadata.is_fork) non-retryably before opening the report. The diff is the reviewed files' raw unified patch (the point-in-time snapshot). Lockfiles, minified assets, snapshots, *.schema.py, *.txt, build dirs, and test files are filtered out, with their comments (PRFilter). A single-agent Flash turn keeps test and *.txt files (review_tests_and_text), so the fetch activity picks the design before it fetches. branch = pr_metadata.head_branch is threaded (as explicit kwargs, alongside team_id / user_id) into every sandbox activity — there is no ContextVar identity. The team's GitHub integration is validated up front by validate_github_integration_activity; upsert_review_report opens the living ReviewReport, and persist_commit_snapshot(…, diff=…) records this turn's snapshot (gated on the head_sha watermark).

  3. Generate schemas — generate_all_schemas() materializes Model.model_json_schema() for the five LLM-facing models into prompts/<stage>/schema.json (static package assets, not per-run state); the prompt templates embed these. Must run before any prompt rendering.

  4. Chunk the PR — split_pr_into_chunks (1 LLM call, validates ChunksList) groups changed files into logically reviewable chunks ordered by review priority. Within CHUNKING_ONESHOT_MAX_ADDITIONS (5000 reviewable added lines) the call is a one-shot gateway call (run_oneshot_review, Sonnet 5 @ xhigh, structured outputs — the prompt embeds metadata + comments + patches inline, so no repo access is needed); above the gate it stays a sandbox call, pinned to the same Sonnet 5 @ xhigh via the CHUNKING_* constants (identical prompt — the sandbox only adds repo access the agent may not use). Returns the ChunksList; persists a chunk_set row (and resumes from it on a re-run of the same head).

  5. Parallel perspective review — review_chunks runs three independent specialist perspectives concurrently per chunk (one sandbox activity per (perspective × chunk), bounded by the child workflow's asyncio.Semaphore), each with no cross-perspective context — overlap is left to dedup (7). The prompt quotes only the PR author's own inline comments (intent and replies), never other reviewers', so the review judges the code before dedup matches its findings against what others already raised. The chunking prompt gets the same author-only comments, because its chunk summaries reach every review prompt:

    • Logic & Correctness (PerspectiveType.LOGIC_CORRECTNESS)
    • Contracts & Security (PerspectiveType.CONTRACTS_SECURITY)
    • Performance & Reliability (PerspectiveType.PERFORMANCE_RELIABILITY)

    The three perspectives come from the ordered PERSPECTIVES registry (reviewer/skill_loader.py); load_perspectives_for_run(team_id) pins each one's current LLMSkill version for the run. Delivery is pull — the prompt instructs the sandbox agent to skill-get(review-hog-perspective-…, version=N) over MCP and apply that perspective's focus, rather than splicing the focus text into the prompt. Each perspective×chunk is one sandbox call validating IssuesReview (step name issues-review-p{pass}-c{chunk}); the reviewer self-investigates the chunk from the diff + <pr_intent> (no separate analysis pass is fed in). Returns dict[(pass, chunk), IssuesReview]; persists/resumes per-pair perspective_result rows. (The pass ordinal = the perspective's 1-based position in PERSPECTIVES.) A blind-spot sweep then runs once per chunk under a reserved pass number, told which lenses already ran, to catch what none of them surfaced.

  6. Combine + scope-clean — combine_issues(perspective_results) flattens every perspective×chunk Issue (stamping source_perspective from the ordinal), then clean_issues(issues, pr_files) drops issues whose file/lines don't overlap the PR diff. Both pure, in-process.

  7. Deduplicate — deduplicate_issues(issues, pr_metadata, pr_comments, …) first runs a deterministic positional pre-filter (_select_dedup_candidates): only issues sharing a file + overlapping lines with another issue or an earlier turn's finding, or sitting in a file any PR comment is on, can be duplicates (the review does not see other reviewers' comments, so it often raises their problem on other lines), so isolated issues survive without an LLM call (and a zero-candidate run skips the LLM entirely). Colliding candidates go to the single LLM dedupe call (IssueDeduplication) — a one-shot gateway call within DEDUP_ONESHOT_MAX_FINDINGS (50 issues entering dedup; the prompt is pure text), the sandbox path above it pinned to the same Sonnet 5 @ xhigh via the DEDUP_* constants — which also drops findings any prior inline comment already raised — every reviewer (bot or human, ReviewHog's own included) treated uniformly, the author handle passed through for context. Only a Full turn reads PR comments here, and it reads them again at dedup time (_current_pr_comments), because other review bots often post while it runs; comments GitHub no longer places on a line (outdated) do not count. Each duplicate names what it repeats, and the final status comment lists the findings another reviewer's comment already raises (already_raised, ReviewHog's own comments excluded) with a link to that comment, so the agreement shows instead of disappearing. A pipeline Flash turn reads no comments. Returns the canonical post-dedup list[Issue]; persist_findings mirrors them to issue_finding rows.

  8. Validate — the ValidateIssuesWorkflow child groups the survivors by chunk and fans out one warm multi-turn session per chunk (concurrent across chunks, bounded by its asyncio.Semaphore): validate_chunk_activity opens one sandbox, validates the chunk's issues as sequential turns (one verdict per turn), and persists each validation_verdict row via persist_verdict (paired to findings by issue_key). Resume-aware: load_run_validations splits the chunk's issues into already-judged / pending, so a retry re-researches only the pending ones. The keep/drop criteria are pulled, not baked: the prompt instructs the agent to skill-get the team's review-hog-validation-criteria skill (version pinned by load_validation_skill_for_run), so the bar for "this issue matters" is team-owned, like the perspectives.

  9. Build report + finalize — build_review_body(issues, validations, pr_files) renders the public body in-process (verdicts sourced from the DB via load_run_validations, the same rows publish reads). The body is one line: how many findings this turn publishes, by severity ("Found 2 must fix, 1 consider.") — no chunk walk, no file inventory, no summary of the diff, because nobody reads one. Valid MUST_FIX/SHOULD_FIX findings whose line isn't on the diff are still appended as an "Other findings (outside the changed lines)" section so they aren't silently dropped at publish. finalize_review_report stores it as ReviewReport.report_markdown and bumps the run watermark. On publishing runs it defers the idle write to the publish stage — the report stays active through stage 10, publish_persisted_review returns it to idle on every outcome, and the failure activity restores rest on a dead run — so the reviews API never reports a completed-but-unpublished turn as at rest (the UI's poll would stop on that snapshot and freeze a wrong "Not published"). Non-publishing runs go idle at finalize; progress_payload labels the deferred window "finalizing".

  10. Publish — publish_review (GitHub REST via the gated egress transport, DB-driven) reads the body from ReviewReport.report_markdown and the inline comments from the valid finding/verdict rows (load_valid_findings), posts a PR review (event="COMMENT", pinned to the reviewed head_sha via commit_id) with inline comments for is_valid MUST_FIX/SHOULD_FIX findings that land on a line present in the current diff (CONSIDER dropped). It posts whenever there's ≥1 valid publishable finding — if all are off-diff (no inline comments resolve) the body still posts, carrying them in the Other-findings section, so a review is never dropped wholesale. Falls back to a body-only review when posting with inline comments fails. Authenticates with the team's installation token. Gated per run by inputs.publish (the workflow only dispatches this stage when publishing is on); the eval CLI defaults it off, the Stamphog handoff sets it on. Both publish-idempotency marker scans (_review_already_posted here, _find_marker_comment on the status comment) trust the marker only in app-bot comments/reviews — on a public repo anyone can paste it, and a spoofed match would suppress the publish or clobber a stranger's comment. Reactions: once a publishing turn passes every gate, the workflow puts a 👀 on the PR (add_review_reaction_activity) and removes it by the returned reaction id when the turn ends, on success, failure, or cancellation (the finally around the review stages). Both calls are fail-open and gated by the reviewhog-pr-reactions-2026-10 patch. The 👀 is a cue for people only. The per-head review state is review_hog's public read API, facade/review_status.py::review_status_for_head (contract HeadReviewStatus in facade/contracts.py, implemented by head_review_status.py). Stamphog cannot import it (ReviewHog depends on stamphog, never the reverse), so receivers.connect() registers review_evidence_for_stamphog, a thin adapter onto stamphog's facade/review_evidence.py registry, with the reviewer named "PostHog Review". It answers per head: pending while a request for the head waits in the queue (the queue workflow's requested_heads query) or a turn on the head runs, through its publish; completed with the kind, the valid findings count, the published flag, the merge base the diff was taken against and the skipped files (filtered files, files GitHub sent without a patch, and the files of every pipeline chunk that no review unit finished, because a turn completes when only some of its units fail); failed when the turn for the head failed; None for any other head or a repository no project owns. When a publishing turn ends, after publish or after the failure is recorded, nudge_stamphog_activity calls stamphog's request_rereview_after_external_review (behind the reviewhog-nudge-stamphog-2026-10 patch, fail-open). Stamphog decides whether a WAIT at that head runs again. After the completed or failed analytics event, the same activity calls every callback in facade/finished_review_hooks.py with the turn's outcome, the valid findings count and the review's deep link. The commands product registers one to post the result in the Slack thread that asked for the review. A product that depends on review_hog registers there instead of being imported, and a callback that raises is logged and never fails the turn. Standard turns post no status comment (the same patch): the 👀 shows the turn runs, and the outcome is the review, a 👍 on the PR when nothing is publishable, or one failure comment per head (post_failure_comment, hidden reviewhog:failed marker) posted by fail_status_comment_activity. A later publish with findings, in either mode, first removes the app's own 👍 (remove_own_pr_reactions, matched with is_app_bot_author). The 👍 does not come back: a clean turn adds it only while no turn of the PR published findings (published_head_sha unset). A clean Standard turn that a person asked for (REQUESTED_TRIGGERS: the label, a comment, the UI, or the CLI) also posts a one-line review that says it found nothing, because the 👍 is easy to miss next to other bots' reactions. It has a hidden reviewhog:clean-reply:<report>:<head> marker, so each head gets one reply, also when a workflow retry starts a new turn. A second request on the same head reuses the findings stored for that head (load_perspective_results), runs no sandbox and posts nothing new, because the first reply already answers it. Automatic and inbox turns keep only the 👍. Status comments that earlier turns left on the PR stay as they are, and a Standard turn never refreshes them. On the publish path of a Deep turn a live status comment (reviewer/status_comment.py) is posted at kickoff as one table with a row per step of the turn's review design, edited as the steps fill in, and rewritten with the outcome: the full found counts, what was published, and — when the urgency threshold held findings back — whose threshold it was (the author's / the requester's / the default, from resolved_from) plus a "View them in PostHog" deep link to the exact report (/project/<team>/code-review?review=<report id>, a permanent public contract — the frontend URL sync and report_deep_link must keep agreeing on it). The status comment header of a flash turn, in each of its states, names PostHog Review (flash) instead of PostHog Review. A single-agent turn shows its own three steps (preparing, reviewing, finalizing) on the status comment and the in-app row, not the pipeline's six: the fetch records the design on the turn's pr_snapshot, and progress_payload reads it from there. A clean flash turn shows the plain line "Nothing worth raising." and never the clean-review media; a full turn follows the celebrate_clean_reviews setting. Flash comments posted before reviewhog-flash-1-1 open with a banner line (LEGACY_FLASH_MODE_MESSAGE_PREFIX); the publish-idempotency scan and the outcome comment matcher still recognize it. The promo, the review body, and the inline comments carry no flash label, so one review shows the label once. An inline comment is one plain-text line, **P{n} · {title}**, then one paragraph with the issue and its fix (a pipeline finding's suggestion joins the body with one space), then the hidden REVIEW_HOG_FINDING_MARKER. No GitHub suggestion block is posted. A single-agent finding shows its reported_priority while that level still folds into the effective priority; otherwise must_fix shows P1, should_fix P2, and consider P3 (display_level). The body's Other-findings section uses the same heading, then the file and lines, then the same paragraph. The outcome sweep (find_finding_comment) matches a finding to its comment by the whole first line, for any P level and for the older ### {title} heading. A reply or reaction counts as engagement unless ReviewHog's own app left it (engagement_method), so the resolution stage's 👀 queue marker never marks a finding reacted. The validator's argumentation stays out of GitHub; the reviews API returns it as validator_note. When every publishable finding posts inline, a Deep review body is only the hidden publish marker, because the tally repeats the comments. A Standard review body then carries one summary line instead (render_review_summary, "PostHog Review · Standard · reviewed abc1234: 1 Must fix."), because Standard has no status comment. The body-only fallback always posts the full body. The workflow captures one reviewhog_review_started product-analytics event per turn that passed every gate (track_review_started_activity) and, after the publish stage, one reviewhog_review_completed per finalized turn (published or stored), carrying repository / PR / trigger / finding-count / PR-size properties (track_review_completed_activity). Both carry pr_draft from the turn's PR snapshot, null when the snapshot is unavailable; a dead turn gets reviewhog_review_failed instead. All three, and the per-finding reviewhog_finding_outcome, carry routing properties from reviewer/telemetry.py: the tier, reviewer configuration, validator and resolver pins, and review mode when known. Flash turn events name the Flash arm in both seats. A single-agent turn's completed event also carries its finding funnel and session health: flash_cap, flash_lens_parts, flash_reviewable_lines, per session (main or a lens name) flash_candidates, flash_must_fix (P0/P1 as the session reported them) and flash_must_fix_share, then flash_after_dedup, flash_dropped per disposition, flash_kept, flash_budget_left (null outside the finding budget), flash_lens_failures, flash_lens_timeouts, and flash_slowest_session_seconds. The dedup activity returns the counts on DedupResult.flash_stats, and the workflow measures the sessions in workflow time. Cost stays on $ai_generation, per ai_stage. Flash finding outcomes use the mode and model configurations saved in the finding's validation_context, so later changes to the Flash defaults do not relabel an earlier finding. Full finding outcomes retain the report's arm at classification time; tier and resolver labels remain report-level and module-level values. Findings with no readable context retain the legacy report-level labels and review_mode: null. Started carries the arm as the turn began; completed the arm at the end, which differs when a person's trigger lifted the tier mid-turn or, rarely, when the registry dropped the arm's model mid-turn (review_arm_fallback). Best-effort: telemetry can never fail a review. Turn event IDs distinguish Full and Flash, and the single-agent design from the pipeline, while preserving the legacy Full and pipeline Flash IDs across deployments. Completion-rate calculations match failures and completions by report, turn, and mode; an absent mode means Full for legacy events. After the skill sync, record_turn_marker_activity records the turn's version marker: a version id per review mode and design (reviewhog-flash-2-3, built by reviewhog_version_for_mode from the manual (major, minor) bumps in REVIEWHOG_VERSIONS, reviewer/constants.py) plus a 7-character fingerprint (reviewer/fingerprint.py). Full, Flash pipeline, and Flash single agent evolve separately, so each bumps its own version. The fingerprint hashes the review mode, the review and validator arms, the chunking / dedup / one-shot pins, the review-turn prompts and schemas, and the content of the skills the acting user runs, team edits included. A single-agent turn hashes its own prompt files (main and lens), the dedup prompt, its arm, the Flash dedup pins, and the Flash limits (finding cap, posted priorities, lens part size and count, prompt diff budget) instead. A change to any hashed input (a prompt, a skill, a model pin, or a Flash limit) changes it without a version bump. The marker persists as a turn_marker artefact (with the hashed inputs, for comparing two fingerprints), and records the turn's design. The review list, the review drawer, and the status comment read a turn's design from its marker, because a later turn on the same head writes a newer snapshot with its own design. goes on reviewhog_review_completed as reviewhog_version / reviewhog_fingerprint, and ends the final status comment as a hidden <!-- reviewhog-version: <version id> <fingerprint> --> line (no visible text). Best-effort like the events. A turn without a marker (started before the patch, or the marker failed) sends both properties as null.


Sandbox execution layer

Most LLM work funnels through one helper, run_sandbox_review(...), in backend/reviewer/sandbox/executor.py. The single-turn steps (issues review, plus chunking/deduplication above their one-shot gates) call it with a prompt, the Pydantic model to validate against, and a step_name. Validation instead drives a warm multi-turn session per chunk via the sibling helpers start_sandbox_session / continue_sandbox_session / end_sandbox_session (one verdict per turn). The sandbox-free counterpart for the gated chunking/dedup calls is run_oneshot_review(...) in backend/reviewer/sandbox/direct_llm.py (same call shape minus repository/branch; one gateway Messages call, structured outputs, no sandbox).

Every sandbox opened here lands in the posthog-sandbox-self-driving Modal app rather than the default one, because its tasks carry origin_product=REVIEW_HOG (see SELF_DRIVING_ORIGIN_PRODUCTS in products/tasks/backend/logic/services/sandbox.py). ReviewHog owns no sandbox code, so this needs nothing here: the app is resolved inside the Tasks provisioning activity. Same image and resources as any other run — the split only separates the fleet's Modal cost from user-driven runs.

ReviewHog owns each session's lifecycle. Tasks with origin_product=review_hog do not expose the agent's finish tool, because it marks the TaskRun terminal and tears down the sandbox before the caller can validate the final JSON or send another validation turn. The agent returns JSON at the end of each turn; the caller validates it and ends the session when its work is complete.

run_sandbox_review(team_id, user_id, repository, branch, prompt, system_prompt, model_to_validate, step_name) -> Model | None:

  1. Does not own concurrency — the caller bounds it: each fan-out child workflow wraps its per-unit sandbox activities in a fresh asyncio.Semaphore(MAX_CONCURRENT_SANDBOXES) (constants.py). The old module-level _sandbox_semaphore was removed in the Temporal migration.
  2. Concatenates full_prompt = f"{system_prompt}\n\n{prompt}" — there is no separate system role; the agent receives one combined prompt.
  3. Builds a CustomPromptSandboxContext inline from the explicit team_id / user_id / repository it receives — there is no ContextVar identity (the migration deleted bind_sandbox_identity / _sandbox_context_for). team_id / user_id are threaded as explicit activity inputs from the entry point — the run_review --team-id / --user-id CLI args, or the production trigger (the PR's author + their team). The team's kind="github" Integration is validated up front by a separate validate_github_integration_activity, not here.
  4. Spawns the agent via _run_prompt(...) → MultiTurnSession.start(prompt, context, model=…, branch, step_name) (imported from the Tasks facade products.tasks.backend.facade.agents; impl at products.tasks.backend.logic.services.custom_prompt_multi_turn_runner). start runs the agent and validates its end-of-turn JSON against model_to_validate internally, returning (session, model). On success the caller session.end()s (the runner keeps the workflow/sandbox alive between turns, so a single-turn caller must end it) and returns the validated model; on a sandbox error or a parse/validation failure start ends its own session and raises, so the helper logs and returns None. There is no output_path / _error.txt and no manual JSON extraction — persistence is the caller's job. The runner persists the full agent log at task_run.log_url (S3 / Tasks UI), so the executor never copies it locally. Each task also gets an origin_key of {random}:{workflow_id_prefix} (the prefix holds owner/repo:pr_number), which lands on $ai_generation as task_origin_key so review cost can be summed per PR. The key caps at 128 characters: only the step text is cut, and an owner/repo too long to fit becomes a stable digest, so the PR number always survives.

The perspective review (the blind-spot sweep rides the same activity) runs on a different model family than the rest — OpenAI Codex gpt-6.1-sol, with initial_permission_mode="full-access", at an effort set by the report's review tier. The pins are per report, not per process: each ReviewReport persists a review arm (adapter / model / effort / permission mode) plus the tier it was chosen from (review_tier, and for agent PRs the Signals priority that placed it there, review_signal_priority), decided once at report creation and kept for the report's life, so a report never mixes arms across turns. The tier table (REVIEW_ARMS_BY_TIER, constants.py): a person's PR → human (xhigh); an agent PR — a report created with a Signals link, which only the inbox trigger passes — routes by the report's priority as it stood when the implementation task was created (the inbox receiver reads the latest priority_judgment with a created_at < task.created_at cut-off via persisted_report_priority and passes it into the workflow inputs; the implementation agent can append judgments through the artefact API, so a later one must not pick its own review's effort): P0/P1 → xhigh, P2 → medium, P3/P4 → low, no readable judgment → agent_unprioritized at xhigh with a warning. One exception to stickiness: a person's trigger (label / UI / CLI) that starts a review of a report in a cheaper tier lifts it to human for that and every later turn, never the reverse; a resolve-only run upserts the same row but does not lift (lift_tier_on_human_trigger). A person's Full trigger that lands while the report's review is still running signals the existing queue and preserves a pending Full request. The trigger endpoints write the lift themselves (lift_review_tier_for_joined_trigger) and answer joined_running_review; remaining Full units and later Full turns use the human tier, while an active Flash turn keeps its Flash arm. Every project runs the arm of its tier. load_review_arm → resolve_review_arm honors a persisted arm only while it stays a registry-supported combo — anything else falls back to the default (full-strength) pins and stamps review_arm_fallback on the run's analytics events. Chunking, dedup, and the validator stay on Claude at fixed pins; the resolution stage runs the validator's model at lower effort (claude-opus-5-5 @ high). One per-turn override sits on top of all of this: Flash mode (review_mode on the workflow input, REVIEW_MODE_FLASH; the UI trigger's run_mode=flash) runs both sandbox seats — the perspective wave with its blind-spot sweep, and the validator — on one arm, FLASH_ARM (gpt-6-luna, Codex with full-access), for that turn only. flash_arm_for_effort selects the acting user's saved medium (default) or xhigh effort, snapshotted when the turn starts. The preference applies to automatic, UI, and CLI Flash requests that run on the pipeline design. The single-agent design ignores it, so the settings page has no control for it: the saved value only matters when the kill switch sends Flash back to the pipeline. The report's tier and arm are untouched, so the PR's next normal trigger reviews normally; review_arm_for_mode / validation_arm_for_mode are the two helpers the activities and the analytics events both read, so a flash turn's events name the flash arm in both seats. A flash turn never chains the resolution stage. Both modes instruct the agent to fetch pinned review and validation skills over MCP (see Prompts). See DECISIONS.md for the Sonnet-vs-Sol production A/B that picked Sol (and the full-access permission-mode gotcha headless Codex needs) and for the tier decision, and Selecting the sandbox model & reasoning effort below for the path that applies these knobs.

backend/reviewer/sandbox/code_context.py is pure-local: prepare_code_context(chunk_filenames, pr_files) emits Claude-Code-style @path#Lstart-end references for the changed line ranges of each file (merging adjacent ranges), so the agent reads exactly the changed lines. These are embedded into the prompts.

Downstream chain (owned by products/tasks, current master)

run_sandbox_review (executor.py)
  → imports MultiTurnSession / CustomPromptSandboxContext
      from products.tasks.backend.facade.agents   (facade re-export; impl under logic/services/)
  → MultiTurnSession.start(model=…)       (logic/services/custom_prompt_multi_turn_runner.py)
    → create_task_and_trigger             (logic/services/custom_prompt_internals.py)
      → Task.create_and_run(..., create_pr=False, mode="background", branch=…)
        → Temporal ProcessTaskWorkflow
          → get_sandbox_for_repository activity
            → Sandbox.create() (Modal default; Docker when SANDBOX_PROVIDER=docker)
            → clone_repository(...)  +  git fetch --depth 1 origin <branch> && git checkout -B <branch> FETCH_HEAD
          → agent-server runs the prompt, streams JSONL (ACP session/update) to S3 (TaskRun.log_url)
  → start() polls S3 for the end-of-turn message, parses + validates against the model internally
  → returns (session, model); caller ends the session and returns the model (None on failure)

The PR-branch checkout that ReviewHog depends on is performed by master's get_sandbox_for_repository.py block (driven by ctx.branch, which originates from TaskRun.branch), not by ReviewHog. The contract surface ReviewHog binds to — imported only through the Tasks facade products.tasks.backend.facade.agents (Tasks is an isolated product; tach enforces the boundary) and that any future merge must preserve: MultiTurnSession.start(prompt, context, model, *, branch, step_name) -> (session, model), CustomPromptSandboxContext(team_id, user_id, repository), and session.end().

Selecting the sandbox model & reasoning effort

Read this before testing another model (Sonnet, a new Codex model, a different effort). It is a two-package path: the Django side sets the knobs and the @posthog/agent package applies them. A pinned run is three values — runtime_adapter + model + reasoning_effort; provider is derived from the adapter (claude → anthropic, codex → openai), never set by hand.

The Django side — where the knobs are set + validated.

  • Pick the values (ReviewHog): reviewer/constants.py REVIEW_{RUNTIME_ADAPTER,MODEL,REASONING_EFFORT,INITIAL_PERMISSION_MODE} feed DEFAULT_REVIEW_ARM (the human tier's arm), and REVIEW_ARMS_BY_TIER derives the cheaper tiers from it; review_chunk_activity loads the report's persisted arm (load_review_arm → resolve_review_arm) and passes it as kwargs to run_sandbox_review (reviewer/sandbox/executor.py), which threads them onto the CustomPromptSandboxContext. To change the reviewer fleet-wide, change the pins; to change one tier, change its entry in REVIEW_ARMS_BY_TIER (the executor kwargs exist for every single-turn stage).
  • The registry (source of truth for what's allowed) — products/tasks/backend/temporal/process_task/utils.py, re-exported framework-free from the facade products/tasks/backend/facade/run_config.py (import from the facade): RuntimeAdapter (claude|codex), LLMProvider, ReasoningEffort, RUNTIME_PROVIDER_BY_ADAPTER, and the pure checks get_provider_for_runtime_adapter / get_supported_reasoning_efforts / get_reasoning_effort_error. Which models exist and what efforts each takes comes from products/tasks/backend/model_catalog.py, the one definition both the backend and the generated TypeScript projections read. A new model/effort must be added there or the combo is rejected. test_constants.py locks the ReviewHog combo to this registry at unit time.
  • Transport into the sandbox: Task._build_task writes extra_state[{runtime_adapter, provider, model, reasoning_effort}] → get_task_processing_context reads it back → start_agent_server → build_agent_runtime_env_prefix (logic/services/sandbox.py) emits POSTHOG_CODE_{RUNTIME_ADAPTER,PROVIDER,MODEL,REASONING_EFFORT} env prefixed onto the agent launch command.

@posthog/agent — where they are consumed + applied (packages/agent/packages/agent in this repo). The sandbox image (products/tasks/backend/sandbox/images/Dockerfile.sandbox-base) installs the published package by default, so an agent-side fix reaches reviews only once it is published and the image rebuilt; set LOCAL_POSTHOG_CODE_MONOREPO_ROOT to build the local package into the image instead.

  • Entry src/server/bin.ts reads + zod-validates POSTHOG_CODE_{RUNTIME_ADAPTER,MODEL,REASONING_EFFORT}, guards with isSupportedReasoningEffort (src/adapters/reasoning-effort.ts — the agent-side mirror of the Python registry; hard-errors server startup on an unsupported combo), then constructs the AgentServer.
  • Adapter split: Codex → src/adapters/codex-app-server/session-config.ts::collaborationModeForTurn sends { mode, settings: { model, reasoning_effort } } as the per-turn collaborationMode (codex applies a provided collaboration mode as is and ignores the turn's effort param when one is sent, so the pinned effort has to ride along here or every turn runs at the model's default effort — this is the line that applies a tier's effort to gpt-6.1-sol); Claude → the claude adapter's session config sets the model and effort (effort only for the claude adapter). Startup validation (bin.ts + isSupportedReasoningEffort) checks the model/effort combo against the registry, but not that the gateway actually serves the model. The sandbox reviewer path has no allow-list fallback: _doInitializeSession → createAcpConnection passes the pinned model straight to codex (no gatewayModels, so SessionConfigState.allowedModelIds stays unset), so a pin to an unserved model fails review turns instead of falling back to a default. The sanitizedModel / allowedModelIds downgrade lives only in agent.ts::Agent.run (the local desktop path); the claude adapter's resolveInitialModelId fallback covers Claude but not the codex reviewer arm — verify $ai_model and $ai_effort on the review generations whenever a pin changes.

Recipe — testing e.g. Sonnet. Set runtime_adapter = "claude", model to a catalog id, and an effort that model supports; provider auto-derives to anthropic. The same applies to a Codex model with runtime_adapter = "codex". Every id and its efforts live in model_catalog.py; run hogli build:projections after editing it, which updates the TypeScript projections the desktop app and the web composer read.


Data models

All Pydantic. models/__init__.py is the authoritative registry that generates the five LLM-facing schema.json files from Model.model_json_schema() — schema.json files are generated artifacts; edit the model and regenerate, never hand-edit.

Model File Schema-backed? Role
ChunksList / Chunk / FileInfo models/split_pr_into_chunks.py ✅ chunking PR → reviewable chunks (chunk_type, key_changes)
Issue / IssuesReview / LineRange / IssuePriority / PerspectiveType models/issues_review.py ✅ issues_review (IssuesReview) Issue is the shared currency of the dedup → validate → publish stages; Issue.source_perspective records which perspective found it
IssueDeduplication / DuplicateIssue models/issue_deduplicator.py ✅ issue_deduplicator ids of issues to drop
IssueValidation models/issue_validation.py ✅ issue_validation is_valid + category (+ optional adjusted_priority) per issue
PRMetadata / PRComment / PRFile / PRFileUpdate models/github_meta.py — internal raw GitHub ingestion

Issue.id encodes provenance as "{pass_number}-{chunk_id}-{issue_number}" and is parsed back throughout the pipeline to route validations. IssuePriority is MUST_FIX / SHOULD_FIX / CONSIDER. The validator may override a finding's priority via adjusted_priority (validator-wins, resolved at read time by effective_priority); see DECISIONS.md.


Prompts

Under backend/reviewer/prompts/, one directory per LLM stage, each with prompt.jinja + (generated) schema.json. All prompts embed their schema via {{ ... | safe }} and demand "Return ONLY the JSON content". Most begin with {{ CLAUDE_CODE_CONTEXT | safe }} (the @path#L… references).

  • chunking/prompt.jinja — group changed files into logical, independently reviewable chunks by cohesion / imports / layer boundaries; order by review priority. → ChunksList.
  • issues_review/prompt.jinja — the core review prompt, run once per perspective per chunk; 10-step process with mandatory codebase investigation. In both full and Flash mode, the <your_review_perspective> block instructs the agent to skill-get(PERSPECTIVE_SKILL_NAME, version=N) over MCP and apply that perspective's focus. Validation uses the same delivery path for its pinned criteria. → IssuesReview. The perspective focuses themselves live as DB-synced LLMA skills at products/review_hog/skills/review-hog-perspective-{logic-correctness,contracts-security,performance-reliability}/SKILL.md.
  • issue_deduplicator/prompt.jinja — mark duplicates (same file + overlapping lines + similar root cause) and issues matching prior review comments; keep the single most comprehensive representative. → IssueDeduplication.
  • issue_validation/prompt.jinja — validate one issue against the live codebase; "DO NOT implement fixes, ONLY assess." Criteria-agnostic: a <your_validation_criteria> block tells the agent to skill-get(review-hog-validation-criteria, version=N) over MCP and apply that team-owned bar for the keep/drop (is_valid) decision — default bar: keep real user-affecting correctness / security / data-loss / contract / performance issues; drop overengineering, speculation, defensive paranoia, never-gonna-happen edges, and style. The criteria live as a DB-synced LLMA skill at products/review_hog/skills/review-hog-validation-criteria/SKILL.md. → IssueValidation.

A separate blind-spots skill (skills/review-hog-blind-spots-general/SKILL.md) drives the per-chunk sweep; it is pull-delivered the same way. The perspective / validation / blind-spot skills are all team-owned and customizable — see DECISIONS.md (the customizable-perspectives / per-user-enablement sections). The invariant that keeps this safe: the output schema is fixed (code), only the skill body (logic) is editable, so editing a skill can never change the output format the downstream pipeline depends on. Customs arrive two ways from the Code review scene: "Create your own" (an authoring agent task guided by the review-hog-authoring skill) and "Use an existing skill" — an adopted skill, a verbatim copy of any team skill duplicated under the kind's prefix and activated in one flow (copy-not-reference; see adr/0002).


Persistence (Postgres — no on-disk store)

There is no reviews/<pr>/ tree. A run's state is in-process within the workflow and mirrored to Postgres on ReviewReport / ReviewReportArtefact. Per-run state by kind:

  • Fetch outputs (pr_metadata, pr_comments, pr_files) — in-process return values, never persisted (re-fetchable from GitHub). The reviewed unified diff rides back as a string and becomes the per-turn commit artefact (the durable point-in-time snapshot).
  • Working state (the resume substrate, head_sha-scoped): chunk_set, perspective_result, and the pr_snapshot artefacts. A perspective_result is stamped with the reviewer model and reasoning effort that wrote it and is only reused by a turn running that configuration: a Flash turn and a Full turn can share a commit, and a Full turn must never resume Luna's results in place of running Sol (rows without the required stamps are never reused). A Full turn can run on the single-agent arm, so each design also reads only its own passes (is_single_agent_pass: the reserved passes from SINGLE_AGENT_PASS_NUMBER up belong to the single-agent sessions). A pr_snapshot carries the design it was fetched for, and the review and dedup stages read only their own design's snapshot, because the single-agent fetch keeps test and text files that the pipeline fetch drops. The raw/cleaned/combined issue sets are in-process values down the combine→clean→dedup chain.
  • Outputs: issue_finding + validation_verdict artefacts (the canonical findings/verdicts) and ReviewReport.report_markdown (the rendered review body) + the head_sha / last_seen_comment_id watermark. A single-agent turn also writes one dropped_finding artefact per finding that dedup or the cap dropped (analysis only, see Single-agent Flash).
  • Prompts / agent logs: rendered in-process and sent to the sandbox; the full prompt + conversation is in the S3 agent log at task_run.log_url (the executor never copies it locally). Generated prompts/<stage>/schema.json are static package assets in the source tree, not per-run state.

Data model (products/review_hog/backend/models.py). Both models are fail-closed team-scoped (CLAUDE.md IDOR rule) via class X(UUIDModel, TeamScopedRootMixin):

  • ReviewReport — the living per-PR document, unique on (team, repository, pr_number) (the idempotency key, so re-runs append turns rather than create a new report; branch-only targets key on (team, repository, head_branch) WHERE pr_number IS NULL). Carries status (active/idle/closed), run_count, last_run_at, the head_sha + last_seen_comment_id watermark, published_head_sha, the rendered report_markdown, acting_user, author_login (the PR author's GitHub login, refreshed from the fetched metadata every turn — powers the "For you" scope's authored-PRs match), run_urgency_threshold (the gate the last completed turn's body/publish ran under, stamped at finalize alongside run_count — what the drawer buckets findings by; null for pre-column turns), the persisted review arm (review_runtime_adapter / review_model / review_reasoning_effort / review_initial_permission_mode) with the tier it came from (review_tier, review_signal_priority — decided once at creation, lifted only by a person's trigger; see Sandbox execution layer), and the signal_report_id / trigger_source provenance.
  • ReviewReportArtefact — the append-only work log mirroring SignalReportArtefact, with a funnel that derives type from the content-model class and maps ArtefactAttribution → created_by_id / task_id. ArtefactType: issue_finding, dropped_finding, validation_verdict, task_run, commit, code_reference, note, plus the working-state types chunk_set, perspective_result, perspective_selection, pr_snapshot.

Content schemas (reviewer/artefact_content.py, pydantic): ReviewIssueFinding and ValidationVerdict are ReviewHog-owned; Commit / CodeReference / TaskRunArtefact / NoteArtefact are reused from the Signals leaf. See DECISIONS.md for the "reuse the leaf, own the model" boundary and why a PR review is not a SignalReport.


Entry point, commands & configuration

  • Run a review: python manage.py run_review --pr-url <github_pr_url> --team-id <id> --user-id <id> (backend/management/commands/run_review.py, blocking execute_review_pr_workflow, default no-publish, with an optional --publish). All three args are required. Add --review-mode flash for Luna review and validation at the acting user's saved effort (medium by default, or xhigh), or use the default --review-mode full. The startup banner shows the selected review mode and whether publishing was requested.
    • Default local-testing PR: an origin-branch PR — its head branch must live on PostHog/posthog, because the sandbox clones the base repo and checks out the head branch by name (get_sandbox_for_repository, owned by products/tasks), so a fork PR fails at the checkout step. Until the sandbox learns to fetch refs/pull/N/head, test against origin-branch PRs.
  • Publish a computed review without recomputing: python manage.py publish_review --pr-url <url> --team-id <id>. This publishes the latest completed turn at the head that turn reviewed (completed_head_sha, falling back to head_sha for pre-column rows), so a later failed turn's commit cannot be published instead (DB-driven; no Temporal, no sandbox). The command infers Full or Flash from the completed turn's findings, defaulting to Full for legacy unstamped runs. An explicit --review-mode must match the stored mode.
  • Reset local state: DEBUG=1 python manage.py reset_review_hog [--dry-run] [--yes] wipes all ReviewHog rows across every team (DEBUG-only; GitHub comments untouched).
  • Lint: ruff check products/review_hog/ --fix && ruff format products/review_hog/
  • Tests: the product's backend:test script covers both backend/tests and backend/reviewer/tests (sandbox calls mocked, fixtures under reviewer/tests/fixtures/; persistence/model tests hit the test DB). Verify against that script, not a hand-picked path — backend/reviewer/tests/ is easy to forget.

Configuration read at runtime:

  • Project access uses the existing boolean review-hog feature flag for the Code review menu, scene, and all project ReviewHog APIs. Staff also need the flag; normal membership and scope checks still apply. Set every release condition to the project group, match its id property against the allowed project IDs, and use 100% rollout. Replace broader conditions and include existing projects before deployment. This property identifies the active environment in both the browser and API. Include each environment that should have access; enabling a parent does not enable its child environments. ReviewHog shares its data under the parent project, but access remains independently flag-gated in each environment. Use the id property rather than the group key: the browser and MCP use the project's UUID as the group key, while the backend permission passes its numeric ID. Newly enabled projects get manual review and resolution. Each project needs a GitHub App integration covering the repository. Canonical skills seed on first configuration reads and each review run.
  • GitHub auth — the team's GitHub App installation token, resolved server-side per activity via GitHubIntegration.first_for_team_repository(team_id, repo) (_installation_auth returns (get_access_token(), github_installation_id), auto-refreshing); resolution-thread deliveries re-resolve it per thread, since a warm session can outlive the ~1h token TTL. No GITHUB_TOKEN env var; the worker no longer needs one. All calls route through posthog.egress.github.transport.github_request (via reviewer/tools/github_client.py), metered against the installation's shared egress budget.
  • --team-id / --user-id (CLI, required) — the team the review runs and persists under, and the user the sandbox tasks run as. They are threaded as explicit activity inputs (no ContextVar identity); the team's kind="github" Integration is validated up front by validate_github_integration_activity. The sandbox repository is the PR's own owner/repo, derived from the PR URL.
  • Settings storage — personal preferences live in ReviewUserSettings.preferences, a sparse JSON dict typed by backend/preferences.py: an absent key inherits, unknown keys and invalid values are ignored on read, and a write equal to the inherited value removes the key. urgency_threshold and celebrate_clean_reviews inherit from the project defaults in ReviewProjectSettings.preferences, then from the code defaults; the other keys (default_review_mode follow/flash/off, review_drafts default on, resolve_comments default off, the two Inbox opt-ins) inherit from code only. Read them with ReviewUserSettings.load_preferences[_many]. The older boolean and choice columns on ReviewUserSettings are unused. A GET creates no row; the first PATCH does.
  • Repository ownership (backend/ownership.py) — a repository belongs to at most one project, like GitHub's install picker. A ReviewInstallationClaim per (project, installation) is all (every repository no other project selected, at most one project per installation) or selected. A ReviewRepository row is either selected into its project or a repository exception (flash_for); a repository has one row across all projects. Ownership: a selected row (or a row in the project that claims all) → that project; else the all claim → that project; else nobody, so no automatic review and the Stamphog handoff starts nothing. The webhook prefilter (OwnedRepositoryPrefilter) caches a per-installation summary and fails open. Repository lookups match GitHub's repository id first and then the name, and backfill both. The installation id is not part of a repository's identity (a reinstall gets a new one), so rows and personal choices are unique by name and id. The repository list in the settings comes from the core GitHub integration's cached repository list (repository_overview), which the core installation_repositories webhook keeps fresh. A repository write must match a name and id in that list, so a project cannot reserve a repository id the installation does not report.
  • Stamphog handoff — Stamphog calls the finished-review callback receivers.py registers in its facade/finished_review_hooks.py, and the run carries request_external_review (backend/stamphog_handoff.py). The handoff finds the owning project by repository name and reviews the head Stamphog judged, unless that head already has a pending or completed review. No label, GitHub Action, shared secret, or environment variable is involved. See the triggers paragraph below.
  • Automatic authored-PR trigger runs in the owning project and requires that project's GitHub integration for the delivery's installation. The rules in backend/automatic_review_rules.py decide, highest first: the author's choice for the repository (ReviewUserRepositoryChoice, flash/off, stored only when it differs from the inherited result), the author's default_review_mode unless follow, the repository exception, then the project rule (ReviewProjectSettings.flash_for: everyone except the excepted people, the listed people, or opt-in only, the default). Bot authors and authors who map to no active member get automatic Flash only when the project sets bot_prs=run; the review then runs as the user who connected the installation, with default settings and no resolution. No per-deploy team id picks the project for any trigger.
  • One feature flag. review-hog is the only ReviewHog flag. Automatic Flash reviews, the Stamphog handoff, resolution, manual Flash, Inbox reviews, the Stamphog Inbox switch, and the tiered review arms are available wherever it is on. DECISIONS.md records why the separate review-hog-internal gate went away.
  • GITHUB_APP_SLUG (instance setting) names the app, and posthog_app_login() in products/review_hog/backend/app_identity.py derives its <slug>[bot] login. is_app_bot_author trusts only that login; unset, it trusts no author in production (local development and tests fall back to any Bot-typed author).

Customer setup path. Nothing in ReviewHog's behavior depends on a per-deploy team id, so any project can enable it:

  1. Turn on the review-hog flag for the project.
  2. Connect GitHub through the core GitHub integration (the PostHog GitHub App installation).
  3. In the Code review settings, claim the installation: all repositories (at most one project per installation) or only selected repositories.
  4. Set the project rule (automatic Flash for everyone, for listed people, or opt-in only) and the bot rule.

Triggers. Six entry points feed the same per-PR ReviewPRQueueWorkflow: the run_review CLI (manual / eval), the Stamphog handoff of a refused or escalated self-driving PR in a repository that a project reviews, a UI "Review this PR" field in the Code review scene (any installation-accessible PR; its split button's run_mode also carries the review-without-resolving, resolve-only, and Flash variants; Flash pins resolution off), an inbox trigger (a TaskRun receiver auto-reviews self-driving Signals implementations once their PR exists — a pushed branch without a PR is not reviewed, and the PR must sit in the task's own repository because output.pr_url is written by whoever controls the run, the sandbox agent included), MCP tools (review-hog-reviews-{trigger,list,get}, defined in products/review_hog/mcp/tools.yaml and gated on the review-hog feature flag) that drive the same reviews viewset with a personal API key or OAuth token, and automatic authored-PR Flash reviews. The automatic trigger consumes signed GitHub pull_request deliveries through review_hog_authored_prs and queues a Celery task for the ownership, identity, and rule checks. It accepts opened, synchronize, and ready_for_review for open PRs whose head and base belong to the delivery's repository, including drafts. A draft is skipped (draft_skipped) unless its repository turned draft reviews on (ReviewRepository.review_drafts, default off) and the PR owner kept review_drafts on. A bot or an unmapped author follows the repository alone. The workflow checks both again when a queued run starts, and before it skips a draft it reads the draft state from GitHub again, because the queue drops a ready_for_review request for a head the run already holds. A failed read keeps the skip. A skipped draft's first automatic review then comes from ready_for_review, and automatic_reviewed_head_sha keeps a head that was already reviewed as a draft from a second review. A draft that is reviewed gets its first automatic review only: the push gate's draft rule skips the later pushes, and ready_for_review reviews everything since the last reviewed head, also when the author marks it ready without a push. A PR with the skip-agent-review label gets no automatic review (label_skipped). The task checks the payload labels, and the turn checks the labels its fetch reads from GitHub again, because gh pr create --label adds labels after the opened delivery. The turn ends before the status comment, so a skip leaves nothing on the PR. Removing the label does not start a review; comment @posthog review for one. The @posthog review comment, the UI button, and the Stamphog handoff ignore both the switch and the skip label. The webhook handler reads only the cached ownership summary, so the task checks ownership again. Enabling the setting performs no backfill; existing PRs become eligible on their next push. The turn rechecks ownership and the rules before starting. Flash publishes every kept finding (it records consider as the turn's threshold) and never starts resolution. No Flash after Full: once a PR has a published Full review, automatic dispatch skips it (full_review_published), the turn's recheck refuses it, and a manual Flash request answers 409 flash_after_full. The same review_hog_authored_prs consumer (the name is the dedup key, so it stays) routes through facade/github.py::accept_pull_request_event (backend/pull_request_events.py), and a labeled delivery starts nothing. The Stamphog handoff queues process_stamphog_handoff, which finds the project that owns the repository (it can differ from the Stamphog project). The review runs as the PR owner, else as the user who connected the installation (Integration.created_by) with default settings and no resolution; a running resolution drops the handoff. Counters: posthog_review_hog_authored_pr_review_total and posthog_review_hog_stamphog_handoff_total, keyed by outcome. facade/github.py::owning_team_id(installation_id, repository) answers the same ownership question for other products, for example a PR comment command dispatcher. The UI and MCP paths are one surface: the viewset carries the grantable review_hog scope (review_hog:read for list / retrieve / perspective_stats, review_hog:write for trigger). Both require the review-hog feature flag, and the trigger action checks the URL, GitHub App access, fork status, and open state regardless of caller. The trigger action and the @posthog review comment (facade/reviews.py) both call requested_reviews.request_pr_review(), which applies the owner rule for resolution and the no-Flash-after-Full refusal. Settings: an automatic review follows the owner's rules (Flash reads no personal settings), the UI / MCP Review button and the comment follow the person who asks, the label follows the owner, and an Inbox review follows the report's reviewer. See DECISIONS.md for each trigger's auth / scope / identity rules.

The review-pr-queue workflow keeps the existing per-PR workflow ID and records requests through signals. It has at most one pending request each for Full, manual Flash, and automatic Flash, taking explicit requests before automatic ones. It waits for an active resolution stage and runs each review in a review-pr child workflow with the existing retry and comment behavior. An explicit Full request remains pending during an active Flash turn and runs if that head still needs a Full review. Automatic pushes coalesce to the latest head; a rule change that stops the author's automatic review prevents pending automatic reviews from starting without canceling a running turn. automatic_reviewed_head_sha advances only after publication succeeds or finds nothing to publish, so a failed publication can retry and an empty review does not repeat. An automatic follow-up turn (one with an automatic_reviewed_head_sha) first runs the push gate (reviewer/push_gate.py) on the PR's own commits since that head. Its rules, in order: no_new_commits (the PR gained no commit and its full diff is unchanged; a force-push that drops commits runs the review), reviewhog_commits_only (the ReviewHog app authored every new commit, such as resolution fixes; this includes the PostHog app's commits on self-driving PRs, which share the app identity), merge_only (the PR's full diff against its base is unchanged, as after a base merge or a rebase), draft (the PR is a draft and no earlier rule skips the push), late_follow_up (the push would start review number LATE_FOLLOW_UP_RUN_INDEX or a later one), small_pr (the PR has fewer than SMALL_PR_REVIEWABLE_LINES_BELOW reviewable lines, the size the lens parts use), quiet_small_push (the last review kept no finding and the push changes at most QUIET_PUSH_MAX_OWN_CODE_LINES own code lines; skipped pushes add up until one crosses the limit), and throttled (the PR spent its review budget). The draft rule reads the draft state from the turn's own PR snapshot: every turn fetches the PR before the gate and the snapshot load is latest-wins, so a PR marked ready at an unchanged head reads as ready. A draft skip reads the PR from GitHub again after the gate's other reads: a PR marked ready while the turn runs sends a ready request that the queue drops, because it asks for the head the running turn gates. If the PR is ready by then, the gate uses the decision of the rules before draft. A failed read reviews the push. Only a PR marked ready between that read and the end of the turn keeps its changes unreviewed until the next trigger. A draft decision keeps the own_code_lines of the rules that ran before it. The throttled rule keeps a token bucket per PR in Redis (PUSH_BUDGET): it holds two reviews and gets one back every 30 minutes. Only a push that every earlier rule lets through takes a token, so a draft push or a merge from the base costs nothing. A push that finds the bucket empty waits for the next trigger like any other skip. A Redis failure reviews the push. A head pays once: a turn that runs again at the same head, as an activity retry or a retried review-pr child, does not take a second token. A retry after a denial asks the bucket again, so it cannot get past the budget. The first review and human triggers never reach the gate, so they neither take nor need a token. Two per-PR splits run on top of these rules. Their flags are keyed like the coordinator flag, and a flag that is off puts every PR in the control arm. reviewhog-zero-change-skip adds the zero_change rule after quiet_small_push: the gate compares the stored single-agent PR snapshots of the last automatically reviewed head and this head (ChangedSinceReview), and a PR whose reviewed files did not change skips in the treatment arm. merge_only already skips a push whose whole PR diff is unchanged (a base merge, a rebase, an amend), so this rule catches pushes that change only files the review leaves out, such as generated files and snapshots. The snapshots leave lockfiles out too, so a PR with a lockfile at either head never matches, and neither does a PR with a file whose patch GitHub left out (PRChange.comparable). The control arm reviews the push and records the match, so it is the audit. A missing snapshot never matches. A skipped push does not move the baseline, so the next comparison covers it. reviewhog-delta-band lets a turn that passes every rule review only what changed: from run DELTA_BAND_FIRST_RUN_INDEX (3) on, with changed reviewable lines at most DELTA_BAND_MAX_CHANGE_SHARE (3%) of the PR's reviewable lines, no dependency file changed, and a comparison the snapshots show in full: no lockfile in the PR, no file without a patch, and no file that left the PR (plan_delta_review). The first follow-up always reviews the whole PR. A delta turn passes the baseline head to its sessions (SandboxStageInput.delta_since_head_sha), runs one session per lens, and each prompt shows only the changed files with the diff blocks around the changed lines (delta_files), plus the earlier findings, the full repository at the head, and the git command for the whole diff since the baseline, which also shows code the PR no longer changes. A gate failure, or a baseline snapshot that is gone when the prompt is built, gives the whole-PR prompt, also in each lens session. The gate event carries pr_changed_lines, both arms, coordinator, delta_eligible and delta_review; every completed event carries zero_change_skip_arm, delta_band_arm and delta_review, so each split compares by arm over PR lifecycles. A coordinated PR always records the control arm of the delta split, so a delta comparison leaves out gate events with coordinator set. Each rule has a SKIP_* switch, and every rule skips. The three value rules never take over a gate failure, and they do not run on a retry of a turn that already finalized its head. A push that no rule matches reviews with the reason no_rule_matched. A skipped turn posts no status comment and leaves automatic_reviewed_head_sha in place, so the next push is judged against the last reviewed head. Any gate failure reviews the push. Each decision emits reviewhog_push_gate_decided with skipped, would_skip, the reason, own_code_lines, the lines the new own commits change in code files (empty when GitHub could not list every file of a commit), pr_draft, the draft state the gate used (null when the snapshot is unavailable), and reviewable_lines and previous_findings, the inputs of the value rules (null when the gate could not read them); the event key includes the draft state and the reason, so a draft or throttle skip and a later review at the same head stay two events, so skip rules that weigh push size can be calibrated offline. The first automatic review and every comment, UI, inbox, Stamphog, and manual trigger never reach the gate. An automatic review of a draft that posts findings ends with a note: it is the only automatic review while the PR is a draft, @posthog review (or the Code review page when github-commands is off) reviews new changes sooner, and marking the PR ready reviews them otherwise. Comment, UI, and Stamphog reviews leave the note out, because they also run for authors without automatic reviews. Reviews start only from a trigger (a push, a comment, the UI, the inbox, a Stamphog handoff, or a manual run) and run right away. ReviewHog never schedules a review for later, for example on a timer after a skipped push: nobody waits for a review that arrives at an unknown time, and a late review can land while the PR sits in a merge queue or under a stack. A change that the gate skips gets reviewed at the next trigger, or not at all.

Review surfaces (Code review scene). The reviews API's scope=mine ("For you") matches reports where the viewer is the acting user OR the PR's author — author_login compared case-insensitively against the viewer's linked GitHub login (User.get_github_login(), the reverse of the author→user mapping the reviewer runs under; no linked login → acting-user match only). scope=everyone is the whole project; retrieve is project-wide so any listed review opens. A specific report is linkable at /code-review?review=<report id> (mirrored to/from the drawer by reviewHogSettingsLogic's URL sync; the status comment's held-back link targets it, so the param is a permanent contract). The drawer buckets a review's findings into published vs below-threshold by the detail's stored run_urgency_threshold — the viewer's current setting is only the fallback for pre-column rows — and its first tab reads "Published" only when the review actually posted (published_head_sha set), "Kept" otherwise. The scene keeps itself current by polling the reviews list — every 10s while a run is in progress or freshly triggered, every 30s otherwise, paused on hidden tabs with an immediate refresh on tab return — and a poll response that shows a run finishing also refreshes the perspective stats and an open drawer's detail (reviewHogSettingsLogic).

An active review stays visible while its report or working artefacts have activity within IN_PROGRESS_STALE_AFTER (30 minutes). Long-running chunking, selection, review, deduplication, and validation activities also refresh ReviewReport.updated_at every minute, so an agent can keep working without producing an artefact during that window. Each refresh is scoped to the team, report, active status, and reviewed commit. These refreshes stop when the activity exits, and stale reviews still expire after the same quiet window. Temporal heartbeats continue independently of the database refresh. The list selects running candidates by their latest report update, so newer stale runs cannot push a live run off the page.


Known issues & tech debt

  • ✅ RESOLVED — transient sandbox timeout silently drops a review. Superseded by the Temporal migration and later hardening: every review unit is an activity with RetryPolicy(maximum_attempts=2), failed units are counted and logged per stage (never silent), and a fan-out stage losing more than FAN_OUT_FAILURE_FLOOR = 0.70 of its units fails the run loudly (_enforce_failure_floor, temporal/workflow.py). Validation turn failures additionally retry with skip-resume.
  • TODO — perspective fan-out back-loads the last perspective. ReviewPerspectivesWorkflow.run builds the wave gather in perspective order (units = [(p, c) for p in ordered for c in inputs.chunk_ids], temporal/workflow.py); with a FIFO semaphore the last perspective queues at the back, so the Performance reviews tend to finish last. It is genuinely parallel, but not balanced per-chunk. Fix: interleave the task list by chunk (P1c1, P2c1, P3c1, P1c2, …) so a chunk's perspectives co-schedule. (Raising MAX_CONCURRENT_SANDBOXES partly mitigates by leaving fewer tasks queued.)
  • Per-stage failure policy (deliberate). Chunking, selection, and dedup run under _ONESHOT_RETRY (5 spaced, escalating attempts — provider-overload spells last minutes, so back-to-back retries all land inside the same spell); chunking and dedup fail the run once retries exhaust (single-unit stages, nothing to degrade to), while selection fails open to the dense product. The perspective wave and blind-spot sweep are best-effort under the 70% failure floor; validation retries per chunk, and only the final attempt degrades to skipping the failing issue. Every best-effort stage is floor-bounded and logs its losses.
  • Resume identity residual — working-state cache is roster-blind. The per-head perspective_result / perspective_selection rows resume on positional (pass_number, chunk_id) keys, so if a different acting user (different enabled-perspective roster) resumes a turn that persisted working state without stamping published_head_sha (a zero-findings or crashed turn), slots can silently mis-map. Identical rosters are always safe. Fix belongs with cross-turn finding identity: key results by skill_name(+version) instead of slot, and drop persisted selection/results whose recorded roster differs from the run's.
  • TODO — the drawer's "Published" flag trusts the report-lifetime watermark, not the shown turn. The reviews API computes published as published_head_sha IS NOT NULL, while the drawer shows the latest completed turn's findings. A report that published once and later finalizes a turn that never posts (store-only re-run, or publish_review failing past retries) shows that turn's findings under "Published" with no not-published banner. Fix: retrieve already loads the completed head — expose per-turn truth (published_head_sha == completed_head_sha) on the detail payload and gate the drawer's published flag on it.
  • TODO — no resolution-stage progress label. A resolution run holds the report active at a published head, where progress_payload falls through to a review-stage label ("deduplicating"; the pre-publish window reads "finalizing"). A dedicated resolving stage needs the serializer enum, the frontend stage labels, and regenerated types — deliberately left out of the staleness fix.
  • Accepted gap — a stopped standalone resolution on a never-reviewed PR never shows in the scene list. Such a report has no last_run_at (only review turns stamp it), and the list admits it only while its activity is fresh — mutually exclusive with the stale-based "stopped" state, so the row drops out exactly when it would say "didn't finish" (the detail endpoint excludes it too). Accepted because the PR status comment now carries the failure notice reliably (the workflow-level fail_resolution_activity backstop) and the flow is rare (/resolve / inbox handoffs on PRs ReviewHog never reviewed). Fixing it means a new list slice for reports with a recent resolution_run plus an aging-out bound for stopped rows.
  • Accepted gap — a resolution turn longer than the 30-minute staleness window shows a false "didn't finish". Resolution writes once per settled thread, so a single long turn (worst: the first, which carries sandbox boot
    • clone) can outlast IN_PROGRESS_STALE_AFTER with the run healthy — the row reads "stopped" while a retrigger correctly 409s. Accepted: typical turns run a few minutes, the label self-corrects on the next verdict, and the busy-guard still prevents double runs. If turns ever grow, add a periodic DB liveness beat inside resolve_threads_activity (Temporal's Heartbeater pings Temporal only, never the DB the UI reads).
  • TODO (BLOCKING public release): resolution-stage injection hardening. Structural (JSON) comment rendering in the resolution prompt, the author-permission gate, and pre-push restricted-paths enforcement in the signed-commit tooling are NOT built; only the prompt floors + the post-push delivery backstop stand between a hostile PR comment and a write turn. The backstop cannot retract a push: the commit is on the branch, and CI has seen it, before the check runs. Explicitly enabled projects can use manual resolution for repositories their teams own. Public release and resolution on untrusted PRs or unowned repositories remain blocked until all three protections land. See the BLOCKING TODO in Status & next and DECISIONS.md Stage 7.