:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(stamphog): give hosted reviews their missing signals and retention (#85564)
Julian Bez58e057baa5ae
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex f2563bba3d14..202118c94215 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -42,6 +42,25 @@ head-changing event must retract standing approvals itself:legit approval. UNLIKE the fail-closed startup sweep, the terminal sweep is fail-open: a GitHub errormust not block the terminal save (the integrity gap on error is the pre-existing exposure, no worse).+The one deliberate exception is **approval retention**.+A head-changing delivery whose push left the PR's own diff byte-identical skips both the retraction and the review (`_standing_approval_retention` in the Celery task, deciding through [`logic/approval_retention.py`](backend/logic/approval_retention.py)).+It is content-based rather than commit-based: the PR's own unified diff at the approved head against the same at the current head.+So a merge of the base branch that touches none of the PR's files retains, and a merge that resolves a conflict inside one of them re-reviews.+Comparing the diff text rather than per-file blob shas is deliberate, because the text carries file modes and renames, and a blob sha covers contents only.+The one thing the text does not carry is binary content, which git renders as `Binary files ... differ` over an abbreviated blob id, so a diff mentioning one is refused rather than compared.++There is deliberately no "this file is harmless" rule, and adding one back needs a very good argument.+Successive review passes found every candidate wrong in this repository: lockfiles select the dependency code that gets installed, tests run in CI with CI's credentials, a file under a `generated/` directory can be hand-edited and still compiles into a service, `docs/onboarding` is aliased into the production frontend, MDX compiles to JavaScript, snapshot files are JavaScript modules the test runner executes, and even plain Markdown ships, because `services/mcp` imports `.md` templates and product `tools.yaml` files compile `.md` prompts into shipped tool definitions.++Both sides are read with `compare_diff`, from the base and head shas the run and the payload already fixed.+That is load-bearing rather than incidental: `get_pr_files` answers for whichever head is live when the request runs, so a contributor could push the approved content, let the comparison run, and push the unreviewed head back.+Retention must never consult that endpoint.++Everything ambiguous falls through to the normal path, which dismisses first: no standing approval, an approval already at this head, a run with no recorded base sha, an empty diff on either side, a diff describing a binary change, or any GitHub error, a diff too large for GitHub to render included.+Retention also re-checks GitHub that the stored approval is still active, because a maintainer dismissing it by hand updates nothing in the product DB, and skipping the review over a dismissed approval would leave the PR with neither.+A retained head is recorded on the approving run (`retained_head_shas`), because `_record_merged_pull_request` matches an approving run on `head_sha` alone and would otherwise treat every retained merge as unapproved and drop it from the digest for good.+Self-driving inbox runs are excluded so the carve-out's head pinning stays untouched.+## Supersession and terminal statesA newer relevant delivery supersedes older non-terminal runs. Rules that keep this sound:@@ -168,6 +187,18 @@ bot-reviewer WAIT behavior (`TRUSTED_REACTOR_BOTS` mirrored in `temporal/constanownership summaries (individual owners count, not just teams). When you change one runtime,check the other; divergence here has produced real approve-when-should-wait findings.+Inputs the Action fetches over the network reach the sandbox through the context JSON instead, and+dropping one is a silent behavior change rather than a missing section. `author_team_slugs` feeds+`author_on_owning_team`, which the reviewer prompt reads with a default of `True`, so an unset key+tells the reviewer that every author owns the code they touched. `pr_provenance` needs no token and+is computed in the sandbox from the checkout.++One divergence is deliberate. A pending `Migration risk` check returns WAIT here rather than+falling through to a refusal, because a hosted refusal costs a ReviewHog handoff and a trigger-label+strip over what is a race with CI. It also can't reuse `Pipeline._only_pending_migration_check`: that+method disqualifies on any failing gate other than the deny-list, and a migrations deny always drags+the tier gate to T2-never with it, so it answers False for every PR it exists to catch.+## Temporal specifics- Registering a new activity requires adding it to `temporal/registry.py` — thediff --git a/products/stamphog/backend/logic/approval_retention.py b/products/stamphog/backend/logic/approval_retention.pynew file mode 100644index 000000000000..5eb9e9a5f953--- /dev/null+++ b/products/stamphog/backend/logic/approval_retention.py@@ -0,0 +1,61 @@+"""Decide whether a push leaves a standing stamphog approval in place.++GitHub never dismisses an approval automatically. The review workflow therefore retracts+stamphog's approval before every re-review. That is correct for a push that changes code. It is+wrong for the push that dominates a long-lived PR: a merge of the base branch. Such a merge does not+change the PR's own diff, but it still costs the PR its merge readiness. It also forces a full+sandboxed review to derive the same verdict again.++Retention answers one question, and it never judges whether a given file matters. The question is+whether the PR's own diff is byte-identical to the diff that was approved.++Three properties of that comparison are necessary for safety. A review finding caused each one:++- Both sides come from `compare_diff` on two commit shas. `get_pr_files` answers for the head that+ is live when the request runs, and a contributor can move that head.+- The comparison uses diff text, not per-file blob shas. The text carries file modes and renames. A+ blob sha covers contents only, and GitHub's file payload carries no mode.+- The comparison refuses anything that it cannot see. See the guards in `approved_diff_unchanged`.++Do not add an allowlist of harmless files. One existed, and every entry in it was executable+somewhere in this repository. Plain Markdown is executable too, because it ships through+`services/mcp` templates and product `tools.yaml` prompts.+"""++from __future__ import annotations++import re++# Heads that a run's approval covers in addition to the head it was posted at. The merge handler+# matches an approving run on head_sha alone, so without this record a retained PR merges as+# unapproved.+RETAINED_HEADS_KEY = "retained_head_shas"++# Bounds the list on a PR that takes many base-branch merges. Only the recent heads can still be+# the merged head, so the oldest entries are safe to drop.+MAX_RETAINED_HEADS = 50++# The only reason an approval survives a push. The webhook skip log records this value.+UNCHANGED_DIFF = "unchanged_diff"+++# git renders a binary change as this line over an abbreviated blob id, and never as content. Two+# different binaries whose ids share that prefix produce the same line. An attacker can pad one+# binary until its id collides, so a diff that carries this line cannot show whether the content+# changed.+_BINARY_MARKER_RE = re.compile(r"^Binary files\b.*differ$", re.MULTILINE)+++def approved_diff_unchanged(approved_diff: str, current_diff: str) -> bool:+ """Whether the PR's own diff is byte-identical to the one that was approved.++ Returns False for everything ambiguous. An empty diff on either side counts as ambiguous rather+ than as "nothing changed". A PR with no changes at all is degenerate, and two blanks compare+ equal, so such a comparison would retain an approval on no evidence. A diff that describes a+ binary change is refused for a sharper reason, see _BINARY_MARKER_RE.+ """+ if not approved_diff.strip() or not current_diff.strip():+ return False+ if _BINARY_MARKER_RE.search(approved_diff) or _BINARY_MARKER_RE.search(current_diff):+ return False+ return approved_diff == current_diffdiff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.pyindex 24acee8f3569..498856c8e614 100644--- a/products/stamphog/backend/logic/github_client.py+++ b/products/stamphog/backend/logic/github_client.py@@ -85,6 +85,13 @@ def _is_own_sticky_comment(comment: dict, expected_login: str | None) -> bool:_MAX_PAGES = 20_PER_PAGE = 100+# Ceiling on a single compare diff. The value sits well above any diff that stamphog could have+# approved, because stamphog's size gate refuses much smaller diffs. It also sits well below the+# cost of an unbounded read: GitHub answers 200 for a diff of any size, and a range that spans+# thousands of files returns hundreds of megabytes.+MAX_COMPARE_DIFF_BYTES = 5 * 1024 * 1024++# Trim each inline review-thread comment body to bound the payload that rides in run.output. The# reviewer only needs the gist of a maintainer's "do not merge", not a novel._REVIEW_THREAD_BODY_MAX = 4000@@ -414,6 +421,7 @@ class StamphogGitHubClient:json_body: dict[str, Any] | None = None,headers: dict[str, str] | None = None,timeout: int = 15,+ stream: bool = False,) -> requests.Response:"""Installation-authenticated request through the gated egress transport.@@ -438,11 +446,15 @@ class StamphogGitHubClient:params=params,json=json_body,timeout=timeout,+ stream=stream,)# Only trusted installation-token responses feed the limiter's per-installation tier tracking.remember_observed_core_limit(self.installation_id, response)if response.status_code == 401 and attempt == 0:logger.info("stamphog github: 401, refreshing installation token", installation_id=self.installation_id)+ # A streamed body holds its connection until a caller reads it or closes it. This+ # path abandons the response, so it must close the response itself.+ response.close()continueraise_if_github_rate_limited(response)return response@@ -616,6 +628,51 @@ class StamphogGitHubClient:breakreturn files+ def compare_diff(self, repo: str, base_sha: str, head_sha: str) -> str:+ """The unified diff between two commits, as text.++ Both ends are commit shas rather than refs, so the result is a property of two immutable+ objects. ``get_pr_files`` differs: it answers for the head that is live when the request+ runs, so a caller cannot bind its answer to a particular commit.++ The path uses three-dot semantics, so GitHub diffs from the merge base of the two commits. A+ caller that passes a PR's base sha and its head sha therefore gets the PR's own changes, and+ not the commits that the base branch gained since. The text carries everything that git+ records about the change, which includes file modes and renames. A per-file blob sha carries+ none of that. GitHub answers 4xx when a diff is too large to render, and this method raises+ on that status rather than returning a shorter diff.+ """+ path = f"/repos/{repo}/compare/{base_sha}...{head_sha}"+ response = self._request(+ "GET",+ path,+ endpoint="/repos/{owner}/{repo}/compare/{basehead}",+ headers={"Accept": "application/vnd.github.diff"},+ stream=True,+ )+ if response.status_code != 200:+ raise StamphogGitHubError(+ f"Failed to diff {base_sha}...{head_sha} in {repo}: {response.text[:300]}",+ status_code=response.status_code,+ )+ # Read with a ceiling rather than into memory. GitHub answers 200 for a diff of any size,+ # and a range that spans thousands of files returns hundreds of megabytes. A caller cannot+ # cancel that transfer after it starts. A diff over the ceiling raises, and every caller+ # treats an error as "cannot answer".+ chunks: list[bytes] = []+ read = 0+ try:+ for chunk in response.iter_content(chunk_size=64 * 1024):+ read += len(chunk)+ if read > MAX_COMPARE_DIFF_BYTES:+ raise StamphogGitHubError(+ f"Diff {base_sha}...{head_sha} in {repo} exceeds {MAX_COMPARE_DIFF_BYTES} bytes"+ )+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks).decode("utf-8", errors="replace")+def get_pr_reviews(self, repo: str, number: int) -> list[dict]:"""Fetch the PR's top-level reviews, paginating through GitHub's list endpoint.diff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.pyindex 3a39b1594e1b..a0d3f27742af 100644--- a/products/stamphog/backend/logic/reviewer.py+++ b/products/stamphog/backend/logic/reviewer.py@@ -104,6 +104,7 @@ def build_reviewer_invocation(check_runs: list[dict],pr_reactions: list[dict],author_pr_numbers: list[int],+ author_team_slugs: list[str],base_sha: str,head_sha: str,repo: str,@@ -121,6 +122,9 @@ def build_reviewer_invocation(``author_pr_numbers`` are the author's merged-PR numbers the server fetched(the engine needs them for the git-blame familiarity signal, which itotherwise gets from a `gh` call it can't make in the sandbox).+ ``author_team_slugs`` are every GitHub team the author belongs to, which the+ engine intersects with the teams owning the changed paths to tell the reviewer+ whether the author owns the code (another `gh` call the sandbox can't make).``self_driving_review`` lets the engine review a bot-authored draft, the one exceptionto its bot-author refusal. It defaults closed here and in the engine, the Action runtimenever sets it, and only a run stamped with inbox provenance turns it on.@@ -137,6 +141,7 @@ def build_reviewer_invocation("check_runs": check_runs,"pr_reactions": pr_reactions,"author_pr_numbers": list(author_pr_numbers),+ "author_team_slugs": list(author_team_slugs),"self_driving_review": self_driving_review,}command = ["uv", "run", f"{engine_dir}/review_local.py", "--context", context_path]diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex 98847a03a183..c8123d7395d7 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -24,6 +24,12 @@ from posthog.models.instance_setting import get_instance_settingfrom products.stamphog.backend.facade.enums import TERMINAL_STATUSES, ReviewMode, ReviewRunStatus, ReviewVerdictfrom products.stamphog.backend.facade.inbox_hooks import get_inbox_acting_reviewer_resolver+from products.stamphog.backend.logic.approval_retention import (+ MAX_RETAINED_HEADS,+ RETAINED_HEADS_KEY,+ UNCHANGED_DIFF,+ approved_diff_unchanged,+)from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_headfrom products.stamphog.backend.logic.audiences import ResolvedAudience, resolve_audiencesfrom products.stamphog.backend.logic.github_client import StamphogGitHubClient@@ -516,6 +522,93 @@ def _retract_approvals_on_base_retarget(repo_config: StamphogRepoConfig, pr: dic)+def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str, Any]) -> bool:+ """Whether a standing approval survives this push, rather than being dismissed and re-reviewed.++ Compares the PR's own diff at the head that the approval was posted for against its diff at the+ head that this delivery carries. ``compare_diff`` reads both sides from commit shas that the+ payload and the run already fixed, so a contributor cannot point either side at content that the+ PR is not on.++ Returns False for everything ambiguous: no PR row, no standing approval, an approval already at+ this head, a run with no recorded base sha, an empty diff on either side, or any GitHub error. A+ diff too large for GitHub to render is one such error. A same-head re-review is allowed to void+ the approval on purpose.+ """+ team_id = repo_config.team_id+ pr_number = pr.get("number")+ head_sha = (pr.get("head") or {}).get("sha") or ""+ base_sha = (pr.get("base") or {}).get("sha") or ""+ if pr_number is None or not head_sha or not base_sha:+ return False++ # Writer pin for the same reason that _retract_stale_approvals_on_skip uses one. This read+ # decides whether an approval stands, and a lagged reader that misses the approving run falls+ # through to a dismissal that the approval did not need.+ pull_request = (+ PullRequest.objects.for_team(team_id)+ .using(router.db_for_write(PullRequest))+ .filter(repo_config=repo_config, pr_number=pr_number)+ .first()+ )+ if pull_request is None:+ return False++ standing = (+ ReviewRun.objects.for_team(team_id)+ .using(router.db_for_write(ReviewRun))+ .filter(+ pull_request=pull_request,+ posted_review_id__isnull=False,+ approval_dismissed_at__isnull=True,+ )+ .exclude(head_sha=head_sha)+ .order_by("-created_at")+ .first()+ )+ if standing is None or standing.posted_review_id is None or not standing.head_sha:+ return False++ approved_pr = (standing.output or {}).get("pr")+ approved_base = (approved_pr or {}).get("base") if isinstance(approved_pr, dict) else None+ approved_base_sha = (approved_base or {}).get("sha") if isinstance(approved_base, dict) else ""+ if not approved_base_sha:+ return False++ client = StamphogGitHubClient(repo_config.installation_id)+ # posted_review_id records that stamphog approved, and not that the approval still stands. A+ # maintainer who dismisses it by hand on GitHub updates nothing here. Retention over a dismissed+ # approval would skip the replacement review and leave the PR with no approval at all. An+ # unreadable or unconfigured identity yields an empty list, which falls through to the review.+ active_ids = {review.get("id") for review in client.list_own_active_approvals(repo_config.repository, pr_number)}+ if standing.posted_review_id not in active_ids:+ return False++ approved_diff = client.compare_diff(repo_config.repository, approved_base_sha, standing.head_sha)+ current_diff = client.compare_diff(repo_config.repository, base_sha, head_sha)+ if not approved_diff_unchanged(approved_diff, current_diff):+ return False+ _record_retained_head(standing, head_sha)+ return True+++def _record_retained_head(run: ReviewRun, head_sha: str) -> None:+ """Note that this run's approval also covers ``head_sha``.++ ``_record_merged_pull_request`` matches an approving run on ``head_sha`` alone. Without this+ record a retained PR merges as unapproved, and it drops out of the daily digest permanently,+ because ``merged_at`` makes the redelivery a no-op. The reviewed head stays on ``head_sha``+ itself, which the dismissal sweep and ``post_verdict``'s guards read.+ """+ stored = (run.output or {}).get(RETAINED_HEADS_KEY) or []+ retained = [sha for sha in stored if isinstance(sha, str)]+ if head_sha in retained:+ return+ retained.append(head_sha)+ run.output = {**(run.output or {}), RETAINED_HEADS_KEY: retained[-MAX_RETAINED_HEADS:]}+ run.save(update_fields=["output", "updated_at"])++def _retract_stale_approvals_on_skip(repo_config: StamphogRepoConfig, pr: dict[str, Any], message: str) -> None:"""Retract a standing stamphog approval when a head-changing event is skipped before the workflow.@@ -645,6 +738,23 @@ def _record_merged_pull_request(payload: dict[str, Any], delivery_id: str) -> No.order_by("-created_at").first())+ if approving_run is None and pr_head_sha:+ # A retained approval covers a head that it was never posted at (see+ # _record_retained_head). The diff at that head is byte-identical to the approved diff, so+ # the merge is stamphog-approved.+ approving_run = (+ ReviewRun.objects.for_team(team_id)+ .using(router.db_for_write(ReviewRun))+ .filter(+ pull_request=pr_obj,+ verdict=ReviewVerdict.APPROVED,+ approval_dismissed_at__isnull=True,+ **{f"output__{RETAINED_HEADS_KEY}__contains": [pr_head_sha]},+ )+ .order_by("-created_at")+ .first()+ )+approved = approving_run is not Noneif repo_config.digest_enabled and approving_run is not None:# The approving run reviewed exactly the head that merged, so its summary describes what@@ -1058,6 +1168,30 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Non_mark_pr_event_processed(delivery_id)return+ # A push that leaves the approved diff untouched needs no fresh verdict. A dismissal would drop+ # the PR out of merge readiness while a full sandboxed review derives the same answer again.+ # This check sits after every trust gate above, so the code retains an approval only on a push+ # that this same path would have reviewed. Self-driving inbox runs are excluded, which keeps+ # their head-pinning carve-out untouched.+ if action in _HEAD_CHANGING_ACTIONS and inbox_review is None:+ try:+ retained = _standing_approval_retention(repo_config, pr)+ except Exception:+ # This is an optimization, so it must never cost a review. An unreachable GitHub or an+ # unexpected payload falls through to the full path, and never retries or retains.+ logger.warning("stamphog_pr_event_retention_check_failed", delivery_id=delivery_id, exc_info=True)+ retained = False+ if retained:+ logger.info(+ "stamphog_pr_event_approval_retained",+ repo=repo,+ pr_number=pr_number,+ reason=UNCHANGED_DIFF,+ )+ if delivery_id:+ _mark_pr_event_processed(delivery_id)+ return+team_id = repo_config.team_id# Recovery fast path: a run for this delivery already exists (a redelivery/Celery retry thatdiff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.pyindex 080644f3d707..3fcfdc2b4a63 100644--- a/products/stamphog/backend/temporal/activities.py+++ b/products/stamphog/backend/temporal/activities.py@@ -236,6 +236,13 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:# familiarity section from the reviewer prompt; the review itself proceeds normally.is_inbox_review = bool((run.output or {}).get("inbox_review"))author_pr_numbers = client.get_author_merged_pr_numbers(repo, author) if author and not is_inbox_review else []+ # The engine cannot resolve which of the owning teams the author belongs to. The sandbox holds+ # no token, and the engine learns the owning teams only after it reads the checkout's ownership+ # sources. One bulk lookup here gives the engine every team that the author belongs to, and the+ # engine intersects that list with the teams that own the changed paths. Inbox reviews skip this+ # lookup for the same reason that they skip author_pr_numbers: the author is the App machine+ # user, so its team membership says nothing about who wrote the diff.+ author_team_slugs = client.get_user_team_slugs(repo.split("/")[0], author) if author and not is_inbox_review else []policy_files: dict[str, str] = {}for path in (*STAMPHOG_POLICY_PATHS, *STAMPHOG_OPTIONAL_POLICY_PATHS):@@ -254,6 +261,7 @@ def fetch_review_context(input: StamphogReviewInput) -> dict:"pr_reactions": client.get_pr_reactions(repo, pull_request.pr_number),"policy_files": policy_files,"author_pr_numbers": author_pr_numbers,+ "author_team_slugs": author_team_slugs,}run.save(update_fields=["output", "updated_at"])@@ -400,6 +408,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:pr_reactions = output.get("pr_reactions", [])policy_files = output.get("policy_files", {})author_pr_numbers = output.get("author_pr_numbers", [])+ author_team_slugs = output.get("author_team_slugs", [])# The trusted source for each policy file is the repo's default branch layered over the# server-shipped defaults (see _effective_policy_files): policy.yml is a section overlay, the@@ -440,6 +449,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:check_runs=check_runs,pr_reactions=pr_reactions,author_pr_numbers=author_pr_numbers,+ author_team_slugs=author_team_slugs,base_sha=base_sha,head_sha=run.head_sha,repo=repo,diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.pyindex c15824ebf79d..97fb655eaf0d 100644--- a/products/stamphog/backend/tests/test_logic.py+++ b/products/stamphog/backend/tests/test_logic.py@@ -2,7 +2,7 @@ import jsonfrom collections.abc import Callableimport pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, override_settings@@ -10,10 +10,16 @@ import jwtfrom parameterized import parameterizedfrom products.stamphog.backend.facade.enums import AudienceReason+from products.stamphog.backend.logic.approval_retention import approved_diff_unchangedfrom products.stamphog.backend.logic.audiences import resolve_audiencesfrom products.stamphog.backend.logic.digest import DigestPRSummary, DigestSummaryfrom products.stamphog.backend.logic.digest_config import RepoDigestConfig, load_repo_digest_config-from products.stamphog.backend.logic.github_client import StamphogGitHubClient, StamphogGitHubError, _build_app_jwt+from products.stamphog.backend.logic.github_client import (+ MAX_COMPARE_DIFF_BYTES,+ StamphogGitHubClient,+ StamphogGitHubError,+ _build_app_jwt,+)from products.stamphog.backend.logic.reviewer import build_reviewer_invocation, parse_reviewer_outputfrom products.stamphog.backend.logic.slack_digest import _build_blocks, _build_fallback_textfrom products.stamphog.backend.models import StamphogRepoConfig@@ -114,6 +120,7 @@ class BuildReviewerInvocationTests(SimpleTestCase):check_runs=[],pr_reactions=[],author_pr_numbers=[],+ author_team_slugs=[],base_sha="base",head_sha="head",repo="owner/repo",@@ -513,3 +520,76 @@ class OwnedFileCountTests(SimpleTestCase):owned = next(a for a in resolve_audiences(repo_config, {}, gate_result) if a.key == "team-replay")assert len(owned.owned_files) == 10assert owned.owned_file_count == 200+++_DIFF = """diff --git a/posthog/api/thing.py b/posthog/api/thing.py+index aaa..bbb 100644+--- a/posthog/api/thing.py++++ b/posthog/api/thing.py+@@ -1,2 +1,3 @@+ keep++added+"""++_DIFF_MODE_FLIPPED = _DIFF.replace("index aaa..bbb 100644", "old mode 100644\nnew mode 100755\nindex aaa..bbb 100755")+++class CompareDiffSizeTests(SimpleTestCase):+ @staticmethod+ def _streamed(body: bytes) -> MagicMock:+ response = MagicMock(status_code=200)+ response.iter_content.return_value = iter([body[i : i + 1024] for i in range(0, len(body), 1024)])+ return response++ def test_diff_under_the_ceiling_is_returned(self) -> None:+ response = self._streamed(b"diff --git a/x b/x\n")++ with patch.object(StamphogGitHubClient, "_request", return_value=response):+ assert StamphogGitHubClient("42").compare_diff("o/r", "base", "head") == "diff --git a/x b/x\n"++ def test_oversized_diff_raises_instead_of_buffering(self) -> None:+ # GitHub answers 200 for a diff of any size, and a range that spans thousands of files+ # returns hundreds of megabytes. This ceiling refuses the cost of reading that into a+ # worker.+ response = self._streamed(b"x" * (MAX_COMPARE_DIFF_BYTES + 4096))++ with patch.object(StamphogGitHubClient, "_request", return_value=response):+ with pytest.raises(StamphogGitHubError):+ StamphogGitHubClient("42").compare_diff("o/r", "base", "head")+++class ApprovalRetentionTests(SimpleTestCase):+ def test_unchanged_diff_retains_across_a_base_merge(self) -> None:+ # A merge of the base branch into a PR is the most common push on a long-lived PR. It does+ # not change the PR's own diff, so there is nothing new to review, and a dismissal would+ # drop the PR out of merge readiness for no reason.+ assert approved_diff_unchanged(_DIFF, _DIFF) is True++ def test_content_change_dismisses(self) -> None:+ assert approved_diff_unchanged(_DIFF, _DIFF.replace("+added", "+something else")) is False++ def test_mode_flip_dismisses(self) -> None:+ # A blob sha covers a file's contents and not its tree mode, so a per-file sha comparison+ # missed an executable-bit flip on a file that the PR already edits. The unified diff+ # carries the mode, and the comparison therefore uses the diff text.+ assert approved_diff_unchanged(_DIFF, _DIFF_MODE_FLIPPED) is False++ def test_binary_change_fails_closed(self) -> None:+ # git renders a binary change over an abbreviated blob id and never as content, so two+ # different binaries whose ids share that prefix produce the same line. An attacker can pad+ # one binary until its id collides, so a diff that carries this line cannot show whether the+ # content changed.+ binary = (+ "diff --git a/thing.wasm b/thing.wasm\n"+ "index aaa1234..bbb5678 100644\n"+ "Binary files a/thing.wasm and b/thing.wasm differ\n"+ )++ assert approved_diff_unchanged(binary, binary) is False+ assert approved_diff_unchanged(_DIFF + binary, _DIFF + binary) is False++ @parameterized.expand([("both_empty", "", ""), ("approved_empty", "", _DIFF), ("current_empty", _DIFF, "")])+ def test_empty_diff_fails_closed(self, _name: str, approved: str, current: str) -> None:+ # Two blanks compare equal. Retention on that evidence would treat an unreadable answer as+ # "nothing changed".+ assert approved_diff_unchanged(approved, current) is Falsediff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex c4021dcfcadd..94bb3b52d020 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -12,8 +12,9 @@ from posthog.models import Project, Teamfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.scoping import team_scope-from products.stamphog.backend.facade.enums import ReviewMode, ReviewRunStatus-from products.stamphog.backend.models import PullRequest, ReviewRun, StamphogRepoConfig+from products.stamphog.backend.facade.enums import AudienceReason, ReviewMode, ReviewRunStatus, ReviewVerdict+from products.stamphog.backend.logic.audiences import ResolvedAudience+from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfigfrom products.stamphog.backend.tasks.tasks import (_INBOX_OPT_OUT_DISMISS_MESSAGE,_parse_pr_url,@@ -56,6 +57,7 @@ def _pr_payload(repo: str = REPO,pr_number: int = 42,head_sha: str = "sha-1",+ base_sha: str = "base-1",head_branch: str = "feature-branch",head_repo: str | None = None,author_login: str = "member-dev",@@ -71,6 +73,7 @@ def _pr_payload(head["repo"] = {"full_name": head_repo}pr: dict[str, Any] = {"number": pr_number,+ "base": {"sha": base_sha},"html_url": f"https://github.com/{repo}/pull/{pr_number}","head": head,"user": {"login": author_login, "type": user_type},@@ -92,7 +95,14 @@ def _pr_payload(def _run_task(- payload: dict[str, Any], delivery_id: str, team_id: int, author_permission: str = "write", app_slug: str = APP_SLUG+ payload: dict[str, Any],+ delivery_id: str,+ team_id: int,+ author_permission: str = "write",+ app_slug: str = APP_SLUG,+ pr_files: list[dict[str, Any]] | None = None,+ active_approval_ids: list[int] | None = None,+ compare_diffs: list[str] | None = None,):# transaction.on_commit never fires on its own outside a real commit, so run it# inline; execute_stamphog_review_workflow is a Temporal network call and gets mocked, as is@@ -106,7 +116,22 @@ def _run_task(patch("products.stamphog.backend.tasks.tasks.StamphogGitHubClient") as mock_client,):mock_client.return_value.get_collaborator_permission.return_value = author_permission+ mock_client.return_value.get_pr_files.return_value = pr_files or []+ # Retention reads both sides of its comparison with compare_diff, and it reads the approved+ # head first.+ if compare_diffs is None:+ mock_client.return_value.compare_diff.return_value = ""+ else:+ mock_client.return_value.compare_diff.side_effect = list(compare_diffs)+ # Retention trusts only an approval that GitHub still reports as active. Default to the id+ # that the retention tests post, so the check passes unless a test empties it on purpose.+ mock_client.return_value.list_own_active_approvals.return_value = [+ {"id": review_id} for review_id in (active_approval_ids if active_approval_ids is not None else [9])+ ]process_pull_request_event(payload, delivery_id)+ # This context patches the GitHub client, so a test that asserts on a GitHub call must use the+ # mock that this context created, and must not patch the same target again from outside.+ mock_execute.github = mock_client.return_valuereturn mock_execute@@ -1238,3 +1263,169 @@ def test_inbox_receiver_leg_refuses_non_self_driving_prs(team, repo_config, pr_kwith team_scope(team.id):assert ReviewRun.objects.count() == 0mock_execute.assert_not_called()+++_APPROVED = """diff --git a/posthog/api/thing.py b/posthog/api/thing.py+index aaa..bbb 100644+--- a/posthog/api/thing.py++++ b/posthog/api/thing.py+@@ -1,2 +1,3 @@+ keep++added+"""+++def _approved_run(team_id: int) -> None:+ with team_scope(team_id):+ ReviewRun.objects.filter(pull_request__pr_number=42).update(+ verdict=ReviewVerdict.APPROVED,+ posted_review_id=9,+ output={"pr": {"base": {"sha": "base-1"}}},+ )++[email protected]_db(databases=PRODUCT_DATABASES)+ "same_diff,expect_retained",+ [(True, True), (False, False)],+ ids=["identical_diff_retains", "changed_diff_dismisses"],+)+def test_push_retains_the_approval_only_when_the_diff_is_identical(team, repo_config, same_diff, expect_retained):+ # A merge of the base branch does not change any blob in the PR's own diff, so there is nothing+ # new to review, and a dismissal would drop the PR out of merge readiness. A blob that did move+ # is content that the approval no longer covers, and that case keeps the stale-approval+ # invariant intact.+ #+ # Each case uses its own delivery id, because _mark_pr_event_processed writes to the+ # process-wide cache. A shared id would let the first case remove the second case's deliveries+ # as duplicates.+ current_diff = _APPROVED if same_diff else _APPROVED.replace("+added", "+something else")+ _run_task(_pr_payload(), f"delivery-retention-approved-{same_diff}", team.id)+ _approved_run(team.id)++ with patch("products.stamphog.backend.tasks.tasks.dismiss_stale_approvals_for_head", return_value=1) as dismiss:+ mock_execute = _run_task(+ _pr_payload(action="synchronize", head_sha="sha-2"),+ f"delivery-retention-push-{same_diff}",+ team.id,+ compare_diffs=[_APPROVED, current_diff],+ )++ with team_scope(team.id):+ run_count = ReviewRun.objects.count()+ if expect_retained:+ dismiss.assert_not_called()+ mock_execute.assert_not_called()+ assert run_count == 1+ else:+ mock_execute.assert_called_once()+ assert run_count == 2++[email protected]_db(databases=PRODUCT_DATABASES)+def test_retention_reads_both_sides_from_pinned_commits(team, repo_config):+ # get_pr_files answers for the head that is live when the request runs. A contributor could push+ # the approved content, wait for the comparison, and then push the unreviewed head again. Two+ # immutable commits leave no such window. Retention must therefore never call the PR-files+ # endpoint, and must pin each side to the base and the head that it decides about.+ _run_task(_pr_payload(), "delivery-pinned-approved", team.id)+ _approved_run(team.id)++ mock_execute = _run_task(+ _pr_payload(action="synchronize", head_sha="sha-2", base_sha="base-2"),+ "delivery-pinned-push",+ team.id,+ compare_diffs=[_APPROVED, _APPROVED],+ )++ client = mock_execute.github+ client.get_pr_files.assert_not_called()+ assert [call.args[1:] for call in client.compare_diff.call_args_list] == [+ ("base-1", "sha-1"),+ ("base-2", "sha-2"),+ ]++[email protected]_db(databases=PRODUCT_DATABASES)+def test_manually_dismissed_approval_is_not_retained(team, repo_config):+ # A maintainer who dismisses stamphog's review on GitHub updates nothing in the product DB, so+ # the stored review id still looks like a standing approval. Retention over it would skip the+ # replacement review and leave the PR with no approval at all.+ _run_task(_pr_payload(), "delivery-dismissed-approved", team.id)+ _approved_run(team.id)++ mock_execute = _run_task(+ _pr_payload(action="synchronize", head_sha="sha-2"),+ "delivery-dismissed-push",+ team.id,+ compare_diffs=[_APPROVED, _APPROVED],+ active_approval_ids=[],+ )++ mock_execute.assert_called_once()+ with team_scope(team.id):+ assert ReviewRun.objects.count() == 2++[email protected]_db(databases=PRODUCT_DATABASES)+def test_retained_approval_still_counts_as_approved_at_merge(team, repo_config):+ # The merge handler matches an approving run on head_sha alone. A retained approval was posted+ # at an earlier head, so without the retained-head record the merge reads as unapproved, and the+ # PR drops out of the daily digest permanently, because merged_at makes the redelivery a+ # no-op.+ with team_scope(team.id):+ repo_config.digest_enabled = True+ repo_config.save()+ _run_task(_pr_payload(), "delivery-retain-merge-approved", team.id)+ _approved_run(team.id)++ _run_task(+ _pr_payload(action="synchronize", head_sha="sha-2"),+ "delivery-retain-merge-push",+ team.id,+ compare_diffs=[_APPROVED, _APPROVED],+ )+ with team_scope(team.id):+ run = ReviewRun.objects.get(pull_request__pr_number=42)+ assert run.output["retained_head_shas"] == ["sha-2"]++ payload = _pr_payload(action="closed", head_sha="sha-2")+ payload["pull_request"]["merged"] = True+ payload["pull_request"]["merged_at"] = "2026-08-19T00:00:00Z"+ # Audience resolution calls GitHub for team membership. Stub it, so that the assertion covers+ # only whether the merge counted as approved, which is the one thing that the retained head+ # decides.+ audience = ResolvedAudience(key="team:devex", reason=AudienceReason.AUTHORED)+ with patch("products.stamphog.backend.tasks.tasks.resolve_audiences", return_value=[audience]) as resolve:+ _run_task(payload, "delivery-retain-merge-closed", team.id)++ resolve.assert_called_once()+ with team_scope(team.id):+ merged = PullRequest.objects.get(repo_config=repo_config, pr_number=42)+ assert merged.merged_at is not None+ assert list(PullRequestAudience.objects.filter(pull_request=merged).values_list("audience_key", flat=True)) == [+ "team:devex"+ ]++[email protected]_db(databases=PRODUCT_DATABASES)+ "output",+ [{}, {"pr": None}, {"pr": {"base": None}}, {"pr": {"base": {}}}],+ ids=["no_pr", "null_pr", "null_base", "empty_base"],+)+def test_retention_needs_a_usable_approved_base_sha(team, repo_config, output):+ # Without the base, the code cannot pin the approved side. A malformed payload must therefore+ # read as "cannot answer", and must not raise into the caller's catch-all.+ _run_task(_pr_payload(), f"delivery-base-{list(output)}-{output}", team.id)+ with team_scope(team.id):+ ReviewRun.objects.filter(pull_request__pr_number=42).update(posted_review_id=9, output=output)++ mock_execute = _run_task(+ _pr_payload(action="synchronize", head_sha="sha-2"),+ f"delivery-base-push-{list(output)}-{output}",+ team.id,+ compare_diffs=[_APPROVED, _APPROVED],+ )++ mock_execute.assert_called_once()diff --git a/tools/pr-approval-agent/review_local.py b/tools/pr-approval-agent/review_local.pyindex 74a21c6909ff..3f02b6ccc313 100644--- a/tools/pr-approval-agent/review_local.py+++ b/tools/pr-approval-agent/review_local.py@@ -54,7 +54,7 @@ from familiarity import (_read_diff,_select_considered_files,)-from gates import POLICY+from gates import POLICY, assign_tierfrom github import (TRUSTED_REACTOR_BOTS,PRData,@@ -64,7 +64,9 @@ from github import (_prompt_worthy_author,_reaction_emoji,is_bot_author,+ pr_provenance,)+from migration_risk import migration_check_pendingfrom policy import FamiliarityPolicyfrom review_pr import REPO_ROOT, GateResult, Pipeline, flush_analyticsfrom version import STAMPHOG_VERSION@@ -218,23 +220,54 @@ def _build_pr_data(context: dict) -> PRData:)-def _ownership_summary(ownership: dict) -> str:- """Mirror _summarize_ownership's emptiness rule: individual owners count as ownership context- even with zero teams, or the prompt would claim "no owned paths" while hiding the handles the- reviewer should route escalations to."""- owners = [*ownership.get("teams", []), *ownership.get("individuals", [])]- if owners:- return f"touches {', '.join(owners)}"- return "no owned paths touched"+def _apply_ownership_summary(pipeline: Pipeline, author_team_slugs: set[str]) -> None:+ """Mirror Pipeline._summarize_ownership with team membership injected instead of fetched.+ The Action resolves membership with one `gh` call per owning team. The sandbox holds no token,+ so the server supplies every team that the author belongs to, and this function does the+ intersection.-def _run_gates_offline(pipeline: Pipeline) -> None:- """Run the four deterministic gate checks — the same ones _run_gates runs.+ `author_on_owning_team` matters beyond the summary text. The reviewer prompt reads that key with+ a default of True, so an unset key tells the reviewer that the author owns the code, whoever+ opened the PR. An unresolvable lookup arrives as an empty set and yields "not on any owning+ team". The Action fails in the same direction, and that direction is the safe one for a bot that+ approves.+ """+ cl = pipeline.classification+ ownership = cl.get("ownership", {})+ individuals = ownership.get("individuals", [])+ teams = ownership.get("teams", [])+ if ownership.get("team_count", 0) == 0 and not individuals:+ cl["ownership_summary"] = "no owned paths touched"+ return- Mirrors Pipeline._run_gates minus its `_summarize_ownership` call, which- shells out to `gh` for author-team membership. Membership is advisory- reviewer context (never a gate), so it is simply omitted here; the ownership- teams themselves are still resolved locally from the checkout.+ author = pipeline.pr.author+ author_teams = [team for team in teams if team.split("/")[-1] in author_team_slugs]++ parts = []+ if teams:+ parts.append(f"touches {', '.join(teams)}")+ if individuals:+ # Individuals never enter the membership check. The author either is one of them or is+ # not.+ suffix = f" (author {author} is one of them)" if f"@{author}" in individuals else ""+ parts.append(f"individually owned by {', '.join(individuals)}{suffix}")+ if author_teams:+ parts.append(f"author {author} is on {', '.join(author_teams)}")+ elif teams:+ parts.append(f"author {author} is not on any owning team")+ if ownership.get("cross_team"):+ parts.append("cross-team change")++ cl["ownership_summary"] = "; ".join(parts)+ cl["author_on_owning_team"] = bool(author_teams)+++def _run_gates_offline(pipeline: Pipeline, author_team_slugs: set[str]) -> None:+ """Run the four deterministic gate checks, the same ones that _run_gates runs.++ Mirrors Pipeline._run_gates, and replaces _summarize_ownership's `gh` membership lookup with the+ server-injected team set (see _apply_ownership_summary)."""gates = [("prerequisites", pipeline._check_prerequisites),@@ -246,7 +279,7 @@ def _run_gates_offline(pipeline: Pipeline) -> None:passed, message = check()pipeline.gate_results.append(GateResult(name, passed, message))- pipeline.classification["ownership_summary"] = _ownership_summary(pipeline.classification.get("ownership", {}))+ _apply_ownership_summary(pipeline, author_team_slugs)def _familiarity_offline(@@ -318,6 +351,39 @@ def _attach_familiarity(pipeline: Pipeline, context: dict) -> None:print(f"warning: familiarity computation failed ({exc}); continuing without the signal")+def _blocked_only_by_pending_migration_check(pipeline: Pipeline) -> bool:+ """True when only the unfinished migration analyzer keeps this PR from a review.++ `Pipeline._only_pending_migration_check` cannot answer this. It disqualifies the PR on any+ failing gate other than the deny-list, and a migrations deny always pulls the tier gate down to+ T2-never as well. That method therefore returns False for every migration PR that it exists to+ catch.++ This function derives the tier again with the migrations deny removed, rather than special-casing+ the gate. A PR that is T2 for another reason (breadth, size, a second deny) therefore stays+ refused, and does not wait for a check that cannot change the outcome.+ """+ pr = pipeline.pr+ cl = pipeline.classification+ if cl.get("deny_categories") != ["migrations"]:+ return False+ if not migration_check_pending(pr.check_runs, pr.file_paths):+ return False+ if any(not gate.passed and gate.gate not in ("deny-list", "tier") for gate in pipeline.gate_results):+ return False+ tier_without_migrations = assign_tier(+ deny_categories=[],+ allow_listed_only=bool(cl.get("allow_listed_only")),+ is_test_only=bool(cl.get("is_test_only")),+ has_new_files=pr.has_new_files,+ lines_total=pr.lines_total,+ files_changed=len(pr.files),+ breadth=cl.get("breadth", ""),+ commit_type=cl.get("commit_type"),+ )+ return tier_without_migrations != "T2-never"++def run(context: dict) -> dict:"""Run the full offline review and return the to_dict() contract."""# The hosted server sets self_driving_review only for PRs it verified came from a self-driving@@ -328,6 +394,11 @@ def run(context: dict) -> dict:0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")), head_checkout=True)pipeline.pr = _build_pr_data(context)+ # Reads commit trailers with `git log base..head` against the checkout, so it needs no token+ # and runs here exactly as it runs in the Action. Without this call, the agent-authorship+ # evidence and the stamphog_review_completed provenance properties are null for every hosted+ # review.+ pipeline.provenance = pr_provenance(pipeline.pr.base_sha, pipeline.pr.head_sha, REPO_ROOT)if pipeline.pr.author_is_bot and not pipeline.self_driving:pipeline._refuse_bot_author()@@ -335,9 +406,30 @@ def run(context: dict) -> dict:try:pipeline._classify()- _run_gates_offline(pipeline)+ _run_gates_offline(pipeline, {str(slug) for slug in context.get("author_team_slugs") or []})gate_verdict = pipeline._gate_verdict()+ # A `Migration risk` check that has not reported yet is a race with CI, and not a judgment+ # on the PR. The deny-list matched only because the engine cannot yet tell a safe migration+ # from a risky one. The verdict is WAIT rather than REFUSE because the hosted runtime routes+ # every refusal to a ReviewHog handoff and strips the trigger label. A refusal would+ # therefore escalate a transient check to a second review agent, and force the author to+ # re-request the review that it displaced.+ if _blocked_only_by_pending_migration_check(pipeline):+ pipeline.final_verdict = "WAIT"+ pipeline.reviewer_output = {+ "verdict": "WAIT",+ "reasoning": (+ "The `Migration risk` check has not finished for this commit, so stamphog cannot "+ "tell a safe migration from a risky one yet. The review runs again on the next "+ "push, or you can re-request it once the check reports."+ ),+ "risk": "unknown",+ "issues": [],+ }+ pipeline._capture_review_completed(gate_verdict, "PENDING-MIGRATION-CHECK")+ return pipeline.to_dict()+# Mirror the Action's in-flight reviewer-bot handling, minus the wait: there is no token in# the sandbox to poll with, and the SERVER already waited out the race (workflow bot-wait# loop) and refreshed this snapshot before provisioning. Bots still showing fresh 👀 herediff --git a/tools/pr-approval-agent/test_review_local.py b/tools/pr-approval-agent/test_review_local.pyindex ae68d335d587..ce7af8a90d54 100644--- a/tools/pr-approval-agent/test_review_local.py+++ b/tools/pr-approval-agent/test_review_local.py@@ -14,6 +14,7 @@ sys.modules.setdefault("claude_agent_sdk.types", MagicMock())import review_pr # noqa: E402import review_local # noqa: E402+from github import CommitProvenance # noqa: E402from review_pr import Pipeline # noqa: E402@@ -64,15 +65,121 @@ def test_commented_reviews_are_dropped_offline(monkeypatch) -> None:assert assurance["head_approvals"] == ["dave"]-def test_ownership_summary_preserves_individual_owners() -> None:- # Individuals-only ownership (team_count == 0) used to collapse to "no owned paths touched",- # hiding the owner handles from the reviewer prompt — the LLM would approve instead of routing- # to the named owner. Mirrors _summarize_ownership's emptiness rule.- assert review_local._ownership_summary({"teams": [], "individuals": ["@a-handle"]}) == "touches @a-handle"- assert review_local._ownership_summary({"teams": ["org/devex"], "individuals": ["@a-handle"]}) == (- "touches org/devex, @a-handle"+def _ownership_pipeline(ownership: dict, author: str = "alice") -> Pipeline:+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pipeline.pr = MagicMock(author=author)+ pipeline.classification = {"ownership": ownership}+ return pipeline+++ "ownership,author_team_slugs,expected_summary,expected_on_team",+ [+ # Individuals-only ownership (team_count == 0) must not collapse to "no owned paths+ # touched". That summary would hide the owner handles that the reviewer needs for+ # escalations.+ ({"team_count": 0, "teams": [], "individuals": ["@a-handle"]}, set(), "individually owned by @a-handle", False),+ (+ {"team_count": 0, "teams": [], "individuals": ["@alice"]},+ set(),+ "individually owned by @alice (author alice is one of them)",+ False,+ ),+ ({"team_count": 0, "teams": [], "individuals": []}, set(), "no owned paths touched", None),+ (+ {"team_count": 1, "teams": ["org/devex"], "individuals": []},+ set(),+ "touches org/devex; author alice is not on any owning team",+ False,+ ),+ (+ {"team_count": 1, "teams": ["org/devex"], "individuals": []},+ {"devex"},+ "touches org/devex; author alice is on org/devex",+ True,+ ),+ (+ {"team_count": 2, "teams": ["org/a", "org/b"], "individuals": [], "cross_team": True},+ {"a"},+ "touches org/a, org/b; author alice is on org/a; cross-team change",+ True,+ ),+ ],+)+def test_ownership_summary_reflects_author_team_membership(+ ownership: dict, author_team_slugs: set, expected_summary: str, expected_on_team: bool | None+) -> None:+ # author_on_owning_team drives the reviewer prompt's "NOTE: Author is NOT on the owning team",+ # which reads the key with a default of True. An unset key tells the reviewer that every author+ # owns the code that they touched, and the note then never appears on a hosted review.+ pipeline = _ownership_pipeline(ownership)++ review_local._apply_ownership_summary(pipeline, author_team_slugs)++ assert pipeline.classification["ownership_summary"] == expected_summary+ assert pipeline.classification.get("author_on_owning_team") is expected_on_team+++def _run_context(files: list[dict], check_runs: list[dict] | None = None) -> dict:+ return {+ "repo": "PostHog/posthog",+ "head_sha": "h" * 40,+ "base_sha": "b" * 40,+ "pr": {+ "number": 1,+ "title": "feat(x): add a column",+ "state": "OPEN",+ "mergeable_state": "clean",+ "user": {"login": "alice", "type": "User"},+ },+ "files": files,+ "check_runs": check_runs or [],+ }+++def _api_file(filename: str, status: str = "added") -> dict:+ return {"filename": filename, "additions": 10, "deletions": 0, "status": status, "patch": "@@"}+++def test_pending_migration_check_waits_instead_of_refusing(monkeypatch) -> None:+ # A migration PR whose "Migration risk" check has not reported yet matches the deny-list only+ # because the engine cannot tell a safe migration from a risky one. A REFUSED verdict would+ # start the hosted runtime's refusal path, which is a ReviewHog handoff and a trigger-label+ # strip, for a race with CI. WAIT keeps the label and runs the review again on the next push.+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])+ monkeypatch.setattr(review_local, "pr_provenance", lambda *a, **k: None)+ context = _run_context([_api_file("posthog/migrations/0999_add_col.py")])++ result = review_local.run(context)++ assert result["final_verdict"] == "WAIT"+ assert "Migration risk" in result["reviewer"]["reasoning"]+++def test_offline_run_carries_commit_provenance(monkeypatch) -> None:+ # pr_provenance reads commit trailers from the checkout and needs no token, so the sandbox can+ # compute it. Without this call, provenance is null on every hosted review, which drops+ # agent-authorship from the evidence bundle and from the stamphog_review_completed+ # properties.+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])+ monkeypatch.setattr(+ review_local,+ "pr_provenance",+ lambda *a, **k: CommitProvenance(+ commit_count=3, agent_commit_count=2, generated_by=("claude",), task_ids=("t-1",)+ ),)- assert review_local._ownership_summary({"teams": [], "individuals": []}) == "no owned paths touched"+ context = _run_context([_api_file("posthog/migrations/0999_add_col.py")])++ result = review_local.run(context)++ assert result["provenance"] == {+ "agent_authored": True,+ "commit_count": 3,+ "agent_commit_count": 2,+ "generated_by": ["claude"],+ "task_ids": ["t-1"],+ }def _thread_context(review_threads: list[dict]) -> dict: