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.

perf(stamphog): cut sandbox and pre-check latency, time every step (#106516)

Julian Bezf54c2ae12406
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 91f84243cd03..2cea41138851 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -251,9 +251,10 @@ Without those keys (a manual `review_pr.py` run) the engine reads git history in
The engine's git has no credential, so every object it reads must arrive in `_clone_pr` or `_prefetch_review_blobs`: an on-demand promisor fetch is anonymous and a private repository refuses it.
Test clone changes with `GIT_NO_LAZY_FETCH=1`, because a public repository hides that failure.
-The server's pre-check (`refuse_on_pre_gates`, `backend/logic/engine_pregate.py`) runs `review_local.py --pregate` in a child process on the worker, in a temporary tree with the run's effective trusted policy.
+The server's pre-check (`refuse_on_pre_gates`, `backend/logic/engine_pregate.py`) runs `review_local.py --pregate` in a child process on the worker, in a temporary tree with the run's effective trusted policy and the PR head's `AGENT_APPROVALS.md` files.
It never imports the engine: the engine's bare module names and its import-time policy load would bind to the worker's own checkout.
-Its fast refusal may only cover what the sandbox review would also refuse, because nothing re-reviews it.
+Its fast verdict (a gate refusal, or the pending-migration WAIT) may only be one the sandbox review would also reach, because nothing re-reviews it.
+Every input the sandbox reads from its checkout must reach the tree too, or finality must not depend on it: the folder files decide the size gate, and the manifest scripts scan still needs git, so a dependency manifest keeps the pending-migration case undecided.
`pregate()` decides that finality in the engine, and the server adds the file-list guards in `pregate_skip_reason` (head moved, list truncated, renames).
Anything in doubt, and any error, falls through to the full review.
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index 9ff45e709dfc..a5639ecf954e 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -132,13 +132,17 @@ Why the digest works this way: [`docs/digest.md`](docs/digest.md).
Hosted flow: webhook → Celery (`backend/tasks/tasks.py`) → Temporal (`backend/temporal/workflow.py`) → sandboxed engine → verdict posted back (`post_verdict`).
The workflow dismisses stale approvals first, waits out other in-flight reviewer bots, then reviews.
Before the wait, the worker runs the engine's gates alone on the fetched context (`review_local.py --pregate`).
+The server also reads every `AGENT_APPROVALS.md` that governs a changed file at the PR head, so the pre-check budgets the size gate like the sandbox does.
When a gate refusal is certain to hold in the full review, stamphog posts it right away with a short LLM note on what the author can do, and skips the wait and the sandbox.
-Anything less certain, such as a size gate that a folder `AGENT_APPROVALS.md` could lift or a migration whose `Migration risk` check has not reported, gets the full review.
+A migration whose `Migration risk` check has not reported gets the same WAIT the full review would give, without the sandbox.
+Anything less certain, such as a PR with renamed files, a dependency manifest next to a pending migration, or folder files that could not be read, gets the full review.
A dismissed approval is also hidden on the PR timeline as outdated, so superseded reviews do not pile up. Hiding is best-effort and never blocks the dismissal.
Reviews run in an isolated Modal sandbox with per-run minted credentials.
The sandbox fetches the PR head and its merge base at depth 1, checks out the head, and runs `review_local.py` against a pre-fetched context, with no GitHub token inside the sandbox.
+Every posted verdict emits a `stamphog_review_timings` event with one `stamphog_timing_<step>_ms` property per step: each context read, the bot wait, the pre-check or sandbox steps, the engine's own phases (uv launch, gates, familiarity, LLM, flush), and the verdict post.
+
**Stacked PRs.** A stacked PR targets its parent's branch and depends on parent code that has not merged yet.
The sandbox checkout is already the PR head, so the reviewer's Read, Grep and Glob see the post-stack tree and parent symbols resolve.
The server reads the merge base from GitHub's compare API, and the sandbox fetches that commit next to the head, so the diff stays scoped to the PR's own changes.
diff --git a/products/stamphog/backend/logic/engine_pregate.py b/products/stamphog/backend/logic/engine_pregate.py
index c5c8111d714b..3d464728ba1a 100644
--- a/products/stamphog/backend/logic/engine_pregate.py
+++ b/products/stamphog/backend/logic/engine_pregate.py
@@ -13,6 +13,11 @@ process, inside a temporary tree laid out like the sandbox checkout: the run's t
under ``.stamphog/``, the engine under ``tools/pr-approval-agent``, the owners resolver beside it.
The child gets a clean environment with no ``PYTHONPATH``, so the engine resolves its bare imports
from its own directory and never from the worker's modules.
+
+The sandbox checkout also carries the PR head's AGENT_APPROVALS.md files, which can raise or lower a
+folder's size ceiling. The server reads every one that governs a changed file from GitHub at the
+reviewed head and writes it into the same tree, so the pre-check budgets the size gate like the
+sandbox does.
"""
from __future__ import annotations
@@ -20,12 +25,21 @@ from __future__ import annotations
import os
import sys
import json
+import time
import tempfile
import subprocess
from collections.abc import Mapping
-from pathlib import Path
+from pathlib import Path, PurePosixPath
+
+import structlog
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
+from posthog.ownership.github_files import GitHubFilesFetcher
+
+from products.stamphog.backend.logic.github_client import StamphogGitHubClient
+
+logger = structlog.get_logger(__name__)
# This file is products/stamphog/backend/logic/engine_pregate.py. The engine is a data directory of
# the product. owners_yaml is a distribution the production venv installs, so it lives under the repo
@@ -38,6 +52,14 @@ OWNERS_PACKAGE_DIR = Path(__file__).resolve().parents[4] / "packages" / "owners-
_ENGINE_SUBDIR = Path("tools") / "pr-approval-agent"
_OWNERS_SUBDIR = Path("tools") / "owners" / "owners_yaml"
+# Mirrors _FOLDER_POLICY_FILENAME in the engine's policy.py, which the backend cannot import.
+FOLDER_POLICY_FILENAME = "AGENT_APPROVALS.md"
+_FOLDER_POLICY_BUDGET_SECONDS = 10
+# Well past the ancestor directories of any real PR, and small enough to stay one or two probes.
+_MAX_FOLDER_POLICY_CANDIDATES = 300
+# The files ride in run.output. A real folder file is a few hundred bytes of frontmatter and prose.
+_MAX_FOLDER_POLICY_BYTES = 256 * 1024
+
# A gate-only run imports the engine and evaluates a few regexes. A run that takes longer than this
# is broken, and the caller then falls through to the sandbox review.
PREGATE_TIMEOUT_SECONDS = 30
@@ -49,14 +71,16 @@ class EnginePregateError(RuntimeError):
@frozen
class PregateOutcome:
- # True only when the full sandbox review would also end REFUSED.
- final_deny: bool
+ # True only when the full sandbox review would end with the same verdict as ``result``.
+ final: bool
# True when an LLM summary would improve the refusal text. The bot-author refusal has its own.
needs_summary: bool
# The engine's reviewer model, so the summary call uses the model the gateway token allows.
summary_model: str
# The engine's to_dict() contract, the same shape the sandbox review prints. None when not final.
result: dict | None
+ # Why a non-final outcome needs the sandbox, for telemetry. Empty when final.
+ not_final_reason: str = ""
def pregate_skip_reason(pr: Mapping[str, object], files: list[dict], head_sha: str) -> str | None:
@@ -78,6 +102,70 @@ def pregate_skip_reason(pr: Mapping[str, object], files: list[dict], head_sha: s
return None
+def folder_policy_candidates(files: list[dict]) -> list[str] | None:
+ """Every AGENT_APPROVALS.md path that could govern a changed file: one per ancestor directory.
+
+ The engine walks the same chain from each changed file's directory up to the repo root. The PR
+ controls the paths, so past _MAX_FOLDER_POLICY_CANDIDATES the answer is None rather than a
+ truncated list, which the pre-check must never treat as complete.
+ """
+ directories: set[PurePosixPath] = set()
+ for entry in files:
+ directories.update(PurePosixPath(entry.get("filename") or "").parents)
+ if len(directories) > _MAX_FOLDER_POLICY_CANDIDATES:
+ return None
+ return sorted((directory / FOLDER_POLICY_FILENAME).as_posix() for directory in directories)
+
+
+def fetch_folder_policy_files(
+ client: StamphogGitHubClient, repo: str, head_sha: str, files: list[dict]
+) -> dict[str, str] | None:
+ """The PR head's AGENT_APPROVALS.md files that govern ``files``, or None when they are unknown.
+
+ None keeps the pre-check on its conservative size rule, so a failure here only makes a fast path
+ less likely. Never raises.
+
+ One batched probe finds which candidates exist. GraphQL shows a symlink as a plain blob of its
+ target path, so each file that exists is then read from the contents API, which resolves a link
+ to an in-repo file the way the sandbox checkout does. Any other kind of entry means unknown.
+ """
+ candidates = folder_policy_candidates(files)
+ if candidates is None:
+ logger.info("stamphog_folder_policy_candidates_capped", repo=repo)
+ return None
+ deadline = time.monotonic() + _FOLDER_POLICY_BUDGET_SECONDS
+ try:
+ fetcher = GitHubFilesFetcher.from_token(
+ client.installation_token(),
+ installation_id=client.installation_id,
+ refresh=client.refresh_installation_token,
+ priority=Priority.NORMAL,
+ )
+ exists = fetcher.files_exist(repo, head_sha, candidates, deadline)
+ found: dict[str, str] = {}
+ for path in sorted(path for path, present in exists.items() if present):
+ remaining = int(deadline - time.monotonic())
+ if remaining <= 0:
+ logger.info("stamphog_folder_policy_budget_exhausted", repo=repo)
+ return None
+ entry = client.get_file_at_ref(repo, path, head_sha, timeout=remaining)
+ # The probe just saw this path, so a miss here is a disagreement, not an absence.
+ if entry is None:
+ logger.info("stamphog_folder_policy_vanished", repo=repo)
+ return None
+ if entry.kind != "file":
+ logger.info("stamphog_folder_policy_not_a_file", repo=repo, kind=entry.kind)
+ return None
+ found[path] = entry.text
+ if sum(len(text) for text in found.values()) > _MAX_FOLDER_POLICY_BYTES:
+ logger.info("stamphog_folder_policy_bytes_capped", repo=repo)
+ return None
+ return found
+ except Exception:
+ logger.warning("stamphog_folder_policy_fetch_failed", repo=repo, exc_info=True)
+ return None
+
+
def engine_source_files() -> dict[str, str]:
"""The engine's Python modules by file name, without its tests."""
if not ENGINE_DIR.is_dir():
@@ -132,10 +220,11 @@ def _parse_outcome(stdout: str) -> PregateOutcome:
raise EnginePregateError("the engine pre-check result is not an object")
result = parsed.get("result")
return PregateOutcome(
- final_deny=parsed.get("final_deny") is True and isinstance(result, dict),
+ final=parsed.get("final") is True and isinstance(result, dict),
needs_summary=parsed.get("needs_summary") is True,
summary_model=str(parsed.get("summary_model") or ""),
result=result if isinstance(result, dict) else None,
+ not_final_reason=str(parsed.get("not_final_reason") or ""),
)
@@ -145,7 +234,7 @@ def run_engine_pregate(
"""Run ``review_local.py --pregate`` on ``context`` under ``policy_files`` and parse its answer.
``policy_files`` maps repo-relative paths to the effective trusted policy, the same set the
- sandbox injects. ``environment`` is added to the child's otherwise empty environment: pass the
+ sandbox injects, plus any folder files from ``fetch_folder_policy_files``. ``environment`` is added to the child's otherwise empty environment: pass the
analytics keys only on the run whose result is posted, so the engine emits its
``stamphog_review_completed`` event once.
"""
diff --git a/products/stamphog/backend/logic/familiarity_facts.py b/products/stamphog/backend/logic/familiarity_facts.py
index aeb5a541ffa1..058162ec1d02 100644
--- a/products/stamphog/backend/logic/familiarity_facts.py
+++ b/products/stamphog/backend/logic/familiarity_facts.py
@@ -18,6 +18,7 @@ import time
from bisect import bisect_left
from concurrent.futures import Future, ThreadPoolExecutor, wait
from datetime import UTC, datetime, timedelta
+from enum import StrEnum
from pathlib import PurePosixPath
from typing import Any
@@ -66,8 +67,9 @@ _BLAME_TIMEOUT_SECONDS = 6
_HISTORY_TIMEOUT_SECONDS = 10
_MAX_PARALLEL_REQUESTS = 8
# History aliases per request. GitHub resolves the aliases of one request one after another, so a
-# large batch runs into the same ten-second abort as a large blame.
-_HISTORY_PATHS_PER_REQUEST = 10
+# large batch runs into the same ten-second abort as a large blame. One failed request drops every
+# fact, so small requests that run in parallel are cheaper than large ones that time out.
+_HISTORY_PATHS_PER_REQUEST = 4
# A directory's history counts prior PRs, and the engine's MODERATE band needs only a few, so the
# newest 100 commits per directory are enough. A file's history only answers "did the author touch it".
_DIRECTORY_HISTORY_COMMITS = 100
@@ -170,6 +172,19 @@ def _ranges_touching(blame_ranges: list[dict], lines: list[int]) -> list[dict]:
return touching
+class FamiliarityStatus(StrEnum):
+ """Why the familiarity facts look the way they do, for telemetry."""
+
+ OK = "ok"
+ PARTIAL_BLAME = "partial_blame"
+ NOT_WANTED = "not_wanted"
+ NO_MERGE_BASE = "no_merge_base"
+ HISTORY_TIMED_OUT = "history_timed_out"
+ HISTORY_FAILED = "history_failed"
+ RATE_LIMITED = "rate_limited"
+ ERROR = "error"
+
+
@frozen
class ReviewHistory:
"""What the server learned about the PR's history before the review.
@@ -180,6 +195,7 @@ class ReviewHistory:
merge_base_sha: str | None
familiarity_facts: dict | None
+ status: FamiliarityStatus
class FamiliarityFactsCollector:
@@ -205,7 +221,7 @@ class FamiliarityFactsCollector:
timeout=_HISTORY_TIMEOUT_SECONDS,
)
- def collect(self, considered: list[dict], deadline: float) -> dict | None:
+ def collect(self, considered: list[dict], deadline: float) -> tuple[dict | None, FamiliarityStatus]:
"""The familiarity facts for the considered files, or None on any failure but a per-file blame one.
A file whose blame fails, or does not finish inside the budget, is left out, and the engine
@@ -245,9 +261,12 @@ class FamiliarityFactsCollector:
executor.shutdown(wait=False, cancel_futures=True)
if any(future in pending for future in history_futures):
logger.warning("stamphog_familiarity_facts_timed_out", repo=self.repo)
- return None
+ return None, FamiliarityStatus.HISTORY_TIMED_OUT
finished_blame = {path: future for path, future in blame_futures.items() if future not in pending}
- return self._assemble(blame_targets, finished_blame, history_futures, directories)
+ facts, status = self._assemble(blame_targets, finished_blame, history_futures, directories)
+ if status == FamiliarityStatus.OK and len(finished_blame) < len(blame_futures):
+ status = FamiliarityStatus.PARTIAL_BLAME
+ return facts, status
def _assemble(
self,
@@ -255,8 +274,9 @@ class FamiliarityFactsCollector:
blame_futures: dict[str, Future[list[dict]]],
history_futures: list[Future[dict[str, list[dict]]]],
directories: list[str],
- ) -> dict | None:
+ ) -> tuple[dict | None, FamiliarityStatus]:
commits: dict[str, dict] = {}
+ status = FamiliarityStatus.OK
def remember(node: dict) -> str | None:
fact = _commit_fact(node)
@@ -265,14 +285,19 @@ class FamiliarityFactsCollector:
commits[fact[0]] = fact[1]
return fact[0]
+ futures: list[Future[Any]] = [*blame_futures.values(), *history_futures]
+ if any(
+ isinstance(future.exception(), GitHubRateLimitError | GitHubEgressBudgetExhausted) for future in futures
+ ):
+ logger.warning("stamphog_familiarity_facts_rate_limited", repo=self.repo)
+ return None, FamiliarityStatus.RATE_LIMITED
+
blame: dict[str, list[dict]] = {}
for path, future in blame_futures.items():
error = future.exception()
- if isinstance(error, GitHubRateLimitError | GitHubEgressBudgetExhausted):
- logger.warning("stamphog_familiarity_facts_rate_limited", repo=self.repo)
- return None
if error is not None:
logger.info("stamphog_familiarity_blame_failed", repo=self.repo, error=type(error).__name__)
+ status = FamiliarityStatus.PARTIAL_BLAME
continue
blame[path] = [
{"start": touching["start"], "end": touching["end"], "oid": oid}
@@ -287,19 +312,20 @@ class FamiliarityFactsCollector:
error = history_future.exception()
if error is not None:
logger.warning("stamphog_familiarity_history_failed", repo=self.repo, error=type(error).__name__)
- return None
+ return None, FamiliarityStatus.HISTORY_FAILED
for path, nodes in history_future.result().items():
oids = [oid for node in nodes if (oid := remember(node)) is not None]
# A root-level file is both a directory pathspec and a file path, so it can land in both.
if path in wanted_directories:
path_history.update(oids)
file_history.setdefault(path, []).extend(oids)
- return {
+ facts = {
"commits": commits,
"blame": blame,
"path_history": sorted(path_history),
"file_history": file_history,
}
+ return facts, status
def fetch_review_history(
@@ -316,12 +342,14 @@ def fetch_review_history(
merge_base_sha = None
author_node_id = (pr.get("user") or {}).get("node_id")
- if not include_familiarity or merge_base_sha is None or not author_node_id:
- return ReviewHistory(merge_base_sha=merge_base_sha, familiarity_facts=None)
+ if not include_familiarity or not author_node_id:
+ return ReviewHistory(merge_base_sha=merge_base_sha, familiarity_facts=None, status=FamiliarityStatus.NOT_WANTED)
+ if merge_base_sha is None:
+ return ReviewHistory(merge_base_sha=None, familiarity_facts=None, status=FamiliarityStatus.NO_MERGE_BASE)
try:
collector = FamiliarityFactsCollector(client, repo, merge_base_sha, str(author_node_id))
- facts = collector.collect(select_considered_files(files), deadline)
+ facts, status = collector.collect(select_considered_files(files), deadline)
except Exception:
logger.warning("stamphog_familiarity_facts_failed", repo=repo, exc_info=True)
- facts = None
- return ReviewHistory(merge_base_sha=merge_base_sha, familiarity_facts=facts)
+ facts, status = None, FamiliarityStatus.ERROR
+ return ReviewHistory(merge_base_sha=merge_base_sha, familiarity_facts=facts, status=status)
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index eb105102c77d..670820c0569c 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -23,6 +23,7 @@ import jwt
import requests
import structlog
+from posthog.dataclasses import frozen
from posthog.egress.github.limiter import remember_observed_core_limit
from posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limited
from posthog.egress.limiter.policies import Priority
@@ -369,6 +370,17 @@ def list_user_accessible_repositories(installation_id: str, user_access_token: s
return sorted(set(full_names))
+@frozen
+class RepoPathEntry:
+ """One path at a ref, as the contents API reports it."""
+
+ # The contents API's own type ("file", "symlink", "dir", "submodule"), or "unreadable" for a
+ # file the API returned without its content.
+ kind: str
+ # The file's text. Empty for anything but a file.
+ text: str
+
+
class StamphogGitHubClient:
"""Installation-scoped GitHub client for one Stamphog App installation.
@@ -1165,6 +1177,41 @@ class StamphogGitHubClient:
break
return sorted(set(full_names))
+ def get_file_at_ref(self, repo: str, path: str, ref: str, *, timeout: int = 15) -> RepoPathEntry | None:
+ """``path`` at ``ref`` from the contents API, or ``None`` if it doesn't exist.
+
+ The kind is ``file`` for a regular file, and also for a symlink whose target is a regular file
+ in the repository, in which case the text is the target's, the same text a checkout that
+ follows the link reads. Any other kind comes back with empty text.
+ """
+ # The path comes from the PR, so `?` or `#` in it must not end the URL path.
+ response = self._request(
+ "GET",
+ f"/repos/{repo}/contents/{quote(path, safe='/')}",
+ endpoint="/repos/{owner}/{repo}/contents/{path}",
+ params={"ref": ref},
+ timeout=timeout,
+ )
+ if response.status_code == 404:
+ return None
+ if response.status_code != 200:
+ raise StamphogGitHubError(
+ f"Failed to fetch {repo}:{path}@{ref}: {response.text[:200]}", status_code=response.status_code
+ )
+ data = self._json(response, f"/repos/{repo}/contents/{path}")
+ if not isinstance(data, dict):
+ return RepoPathEntry(kind="dir", text="")
+ kind = str(data.get("type") or "unknown")
+ if kind != "file":
+ return RepoPathEntry(kind=kind, text="")
+ # A file over the API's inline limit comes back with encoding "none" and no content.
+ if data.get("encoding") != "base64" or not isinstance(data.get("content"), str):
+ return RepoPathEntry(kind="unreadable", text="")
+ try:
+ return RepoPathEntry(kind=kind, text=base64.b64decode(data["content"]).decode("utf-8"))
+ except (binascii.Error, UnicodeDecodeError) as exc:
+ raise StamphogGitHubError(f"Failed to decode base64 contents for {repo}:{path}") from exc
+
def get_default_branch_file(self, repo: str, path: str) -> str | None:
"""Fetch a file's text from the repo's DEFAULT branch, or ``None`` if it doesn't exist.
diff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.py
index df4849515b8f..d911a43c49b3 100644
--- a/products/stamphog/backend/logic/reviewer.py
+++ b/products/stamphog/backend/logic/reviewer.py
@@ -254,6 +254,14 @@ def _parse_legacy(obj: dict) -> ReviewerVerdict:
return ReviewerVerdict(verdict=verdict, reasoning=reasoning, showstoppers=showstoppers)
+def parse_engine_timings(raw: str) -> dict[str, int]:
+ """The engine's own phase timings from its result line, or {} when it printed none."""
+ timings = (_find_result_object(raw) or {}).get("timings_ms")
+ if not isinstance(timings, dict):
+ return {}
+ return {str(name): value for name, value in timings.items() if isinstance(value, int)}
+
+
def _find_result_object(raw: str) -> dict | None:
for line in reversed((raw or "").splitlines()):
line = line.strip()
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index 77e3ee52b8f3..5b5c829422c7 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -16,20 +16,25 @@ single verdict JSON.
from __future__ import annotations
+import io
import os
+import re
import json
import time
import shlex
import base64
import random
+import tarfile
import threading
-from collections.abc import Iterator, Sequence
-from concurrent.futures import ThreadPoolExecutor
+import contextvars
+from collections.abc import Callable, Iterator, Sequence
+from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
-from pathlib import Path
+from pathlib import Path, PurePosixPath
+from typing import Any
from urllib.parse import urlparse
from django.conf import settings
@@ -45,7 +50,7 @@ from temporalio import activity
from posthog.dataclasses import frozen
from posthog.llm.gateway_client import AIGatewayConfig, resolve_ai_gateway_config
from posthog.models import User
-from posthog.ph_client import ph_scoped_capture
+from posthog.ph_client import ph_background_capture, ph_scoped_capture
from posthog.temporal.common.utils import asyncify
from products.stamphog.backend.facade.enums import (
@@ -61,6 +66,7 @@ from products.stamphog.backend.logic.engine_pregate import (
ENGINE_DIR,
PregateOutcome,
engine_source_files,
+ fetch_folder_policy_files,
owners_package_files,
pregate_skip_reason,
run_engine_pregate,
@@ -73,12 +79,14 @@ from products.stamphog.backend.logic.reviewer import (
ReviewerInvocation,
ReviewerVerdict,
build_reviewer_invocation,
+ parse_engine_timings,
parse_reviewer_output,
)
from products.stamphog.backend.logic.scrubbing import neutralize_active_markdown, scrub_credentials
from products.stamphog.backend.models import PullRequest, PullRequestAudience, ReviewRun, StamphogRepoConfig
from products.stamphog.backend.temporal.constants import (
CLONE_STEP_TIMEOUT_SECONDS,
+ NETWORK_RESTRICTED_AGENT_ENV,
PREFETCH_DIFF_BLOBS_TIMEOUT_SECONDS,
REVIEWER_TIMEOUT_SECONDS,
RUN_REVIEW_TIMEOUT,
@@ -92,6 +100,7 @@ from products.stamphog.backend.temporal.constants import (
STAMPHOG_SANDBOX_CONTEXT_PATH,
STAMPHOG_SANDBOX_ENGINE_DIR,
STAMPHOG_SANDBOX_OWNERS_DIR,
+ STAMPHOG_SANDBOX_PAYLOAD_PATH,
STAMPHOG_SANDBOX_REPO_DIR,
STAMPHOG_TRUSTED_REACTOR_BOTS,
SandboxPhaseError,
@@ -103,6 +112,14 @@ from products.tasks.backend.facade.sandbox import (
get_sandbox_class_for_backend,
)
+_ENGINE_RELATIVE_DIR = PurePosixPath(STAMPHOG_SANDBOX_ENGINE_DIR).relative_to(STAMPHOG_SANDBOX_REPO_DIR).as_posix()
+_OWNERS_RELATIVE_DIR = PurePosixPath(STAMPHOG_SANDBOX_OWNERS_DIR).relative_to(STAMPHOG_SANDBOX_REPO_DIR).as_posix()
+_OWNERS_PACKAGE_RELATIVE_DIR = f"{_OWNERS_RELATIVE_DIR}/owners_yaml"
+_CONTEXT_RELATIVE_PATH = PurePosixPath(STAMPHOG_SANDBOX_CONTEXT_PATH).relative_to(STAMPHOG_SANDBOX_REPO_DIR).as_posix()
+
+# The context reads are a dozen GitHub round trips plus the familiarity reads, which run their own pool.
+_CONTEXT_FETCH_WORKERS = 8
+
# Server-shipped default policy files, the base layer every repo's config sits on. Named by the
# basename of each STAMPHOG_POLICY_PATHS entry (policy.yml / review-guidance.md): a repo with no
# config reviews under these as-is, a repo's policy.yml overlays its sections onto the default's
@@ -336,6 +353,10 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
token every frontend snippet ships — so its blast radius is event spam, not data access; it's still
added to llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
hosted runtime/team/run context onto those events.
+
+ NETWORK_RESTRICTED_AGENT_ENV stops the Claude Code CLI under the Agent SDK from calling its own
+ telemetry, error-reporting and update hosts. The egress allowlist blocks them, and a blocked call
+ waits for its timeout before the CLI exits.
"""
gateway = resolve_ai_gateway_config()
if gateway is None:
@@ -352,6 +373,7 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
"STAMPHOG_REPO_DIR": STAMPHOG_SANDBOX_REPO_DIR,
"AI_GATEWAY_URL": gateway.url,
"AI_GATEWAY_API_KEY": token,
+ **NETWORK_RESTRICTED_AGENT_ENV,
}
return {**env, **_engine_analytics_environment(_hosted_analytics_properties(run))}, gateway
@@ -398,84 +420,147 @@ def _pr_commit_messages(client: StamphogGitHubClient, repo: str, pr_number: int,
return None
+class _StepTimer:
+ """Wall-clock milliseconds per named step, for the run output and the worker log."""
+
+ def __init__(self) -> None:
+ self.timings_ms: dict[str, int] = {}
+
+ @contextmanager
+ def step(self, name: str) -> Iterator[None]:
+ # Recorded on failure too, so the log line shows how long the failing step ran.
+ started = time.monotonic()
+ try:
+ yield
+ finally:
+ self.timings_ms[name] = int((time.monotonic() - started) * 1000)
+
+
@activity.defn
@asyncify
def fetch_review_context(input: StamphogReviewInput) -> dict:
- """Load the PR, its changed files, the author's merged PRs, and default-branch policy."""
+ """Load the PR, its changed files, the author's merged PRs, and default-branch policy.
+
+ The reads are independent GitHub round trips, so they run concurrently. Only the reads that need
+ the PR's author or its file list wait for those two.
+ """
run = _load_run(input)
pull_request = run.pull_request
repo_config = pull_request.repo_config
repo = repo_config.repository
+ number = pull_request.pr_number
client = StamphogGitHubClient(repo_config.installation_id)
- pr = client.get_pr(repo, pull_request.pr_number)
- files = client.get_pr_files(repo, pull_request.pr_number)
# Self-driving runs skip the author's history: the author is the App machine user, so
# familiarity from its merged PRs would read to the engine as human trust. Without facts the
# engine only omits the familiarity section from the reviewer prompt; the review proceeds normally.
is_inbox_review = bool((run.output or {}).get("inbox_review"))
- # The familiarity facts cost a few GraphQL round trips and depend only on the PR and its files,
- # so they are read in a background thread while the fetches below run. fetch_review_history
- # bounds its own time and never raises.
- history_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="stamphog-review-history")
- history_future = history_executor.submit(
- fetch_review_history, client, repo, pr, files, include_familiarity=not is_inbox_review
- )
- history_executor.shutdown(wait=False)
- # Reviews feed the engine's prerequisite gate — an active CHANGES_REQUESTED must block auto-approval.
- reviews = client.get_pr_reviews(repo, pull_request.pr_number)
- # Top-level discussion comments are blocker context (a maintainer's "please hold").
- discussion = client.get_pr_discussion(repo, pull_request.pr_number)
- # Inline review threads (GraphQL-only) carry a maintainer's unresolved "do not merge" that the
- # top-level discussion misses; fails closed on truncation/errors, same as get_pr_discussion.
- review_threads = client.get_pr_review_threads(repo, pull_request.pr_number)
- # Head-commit check runs let the engine's migration gate see a passing "Migration risk" check.
- check_runs = client.get_check_runs(repo, run.head_sha)
- commit_messages = _pr_commit_messages(client, repo, pull_request.pr_number, run.head_sha)
-
- author = (pr.get("user") or {}).get("login") or pull_request.author_login
- # Skipped for self-driving runs, like the familiarity facts above.
- 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):
- content = client.get_default_branch_file(repo, path)
- if content is not None:
- policy_files[path] = content
-
- history: ReviewHistory = history_future.result()
+ timer = _StepTimer()
+ started = time.monotonic()
+ # Mint the installation token once up front. On a cold cache every pool thread would mint its own.
+ client.installation_token()
+ executor = ThreadPoolExecutor(max_workers=_CONTEXT_FETCH_WORKERS, thread_name_prefix="stamphog-context")
+ try:
- run.output = {
- **(run.output or {}),
- "pr": pr,
- "files": files,
- "reviews": reviews,
- "discussion": discussion,
- "review_threads": review_threads,
- "check_runs": check_runs,
- "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,
- # Always set, null included: its presence tells the engine the server owns familiarity,
- # so a null means "absent" rather than "compute it from git".
- "familiarity_facts": history.familiarity_facts,
- "merge_base_sha": history.merge_base_sha,
- # Always set, null included, for the same reason: the sandbox checkout holds no history,
- # so the engine must not fall back to `git log` for the provenance trailers.
- "commit_messages": commit_messages,
- }
+ def submit(name: str, fetch: Callable[..., Any], *args: Any, **kwargs: Any) -> Future[Any]:
+ def timed_fetch() -> Any:
+ with timer.step(name):
+ return fetch(*args, **kwargs)
+
+ # A pool thread does not inherit Temporal's activity context, and activity.logger raises
+ # without it. Each read gets its own copy, because one context cannot run in two threads.
+ return executor.submit(contextvars.copy_context().run, timed_fetch)
+
+ pr_future = submit("pr", client.get_pr, repo, number)
+ files_future = submit("files", client.get_pr_files, repo, number)
+ # Reviews feed the engine's prerequisite gate — an active CHANGES_REQUESTED must block auto-approval.
+ reviews_future = submit("reviews", client.get_pr_reviews, repo, number)
+ # Top-level discussion comments are blocker context (a maintainer's "please hold").
+ discussion_future = submit("discussion", client.get_pr_discussion, repo, number)
+ # Inline review threads (GraphQL-only) carry a maintainer's unresolved "do not merge" that the
+ # top-level discussion misses; fails closed on truncation/errors, same as get_pr_discussion.
+ review_threads_future = submit("review_threads", client.get_pr_review_threads, repo, number)
+ # Head-commit check runs let the engine's migration gate see a passing "Migration risk" check.
+ check_runs_future = submit("check_runs", client.get_check_runs, repo, run.head_sha)
+ commit_messages_future = submit("commit_messages", _pr_commit_messages, client, repo, number, run.head_sha)
+ reactions_future = submit("pr_reactions", client.get_pr_reactions, repo, number)
+ policy_futures = {
+ path: submit(f"policy:{path}", client.get_default_branch_file, repo, path)
+ for path in (*STAMPHOG_POLICY_PATHS, *STAMPHOG_OPTIONAL_POLICY_PATHS)
+ }
+
+ pr = pr_future.result()
+ files = files_future.result()
+ author = (pr.get("user") or {}).get("login") or pull_request.author_login
+ # The familiarity facts depend only on the PR and its files. fetch_review_history bounds its
+ # own time and never raises.
+ history_future = submit(
+ "history", fetch_review_history, client, repo, pr, files, include_familiarity=not is_inbox_review
+ )
+ folder_policy_future = submit(
+ "folder_policy_files", fetch_folder_policy_files, client, repo, run.head_sha, files
+ )
+ # Skipped for self-driving runs, like the familiarity facts above.
+ author_pr_numbers_future = (
+ submit("author_pr_numbers", client.get_author_merged_pr_numbers, repo, author)
+ if author and not is_inbox_review
+ else None
+ )
+ # 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_future = (
+ submit("author_team_slugs", client.get_user_team_slugs, repo.split("/")[0], author)
+ if author and not is_inbox_review
+ else None
+ )
+
+ policy_files: dict[str, str] = {}
+ for path, future in policy_futures.items():
+ content = future.result()
+ if content is not None:
+ policy_files[path] = content
+ history: ReviewHistory = history_future.result()
+
+ run.output = {
+ **(run.output or {}),
+ "pr": pr,
+ "files": files,
+ "reviews": reviews_future.result(),
+ "discussion": discussion_future.result(),
+ "review_threads": review_threads_future.result(),
+ "check_runs": check_runs_future.result(),
+ "pr_reactions": reactions_future.result(),
+ "policy_files": policy_files,
+ "author_pr_numbers": author_pr_numbers_future.result() if author_pr_numbers_future else [],
+ "author_team_slugs": author_team_slugs_future.result() if author_team_slugs_future else [],
+ # Always set, null included: its presence tells the engine the server owns familiarity,
+ # so a null means "absent" rather than "compute it from git".
+ "familiarity_facts": history.familiarity_facts,
+ "familiarity_status": history.status,
+ "merge_base_sha": history.merge_base_sha,
+ # Always set, null included, for the same reason: the sandbox checkout holds no history,
+ # so the engine must not fall back to `git log` for the provenance trailers.
+ "commit_messages": commit_messages_future.result(),
+ # Read at the PR head, unlike policy_files: the sandbox checkout is the head, and the pre-check
+ # must budget the size gate as the sandbox does. None means unknown.
+ "folder_policy_files": folder_policy_future.result(),
+ "context_timings_ms": {**timer.timings_ms, "total": int((time.monotonic() - started) * 1000)},
+ }
+ finally:
+ # A failed read raises out of its result() above and fails the activity, which retries. The
+ # other reads are abandoned rather than awaited.
+ executor.shutdown(wait=False, cancel_futures=True)
run.save(update_fields=["output", "updated_at"])
- activity.logger.info(f"Fetched review context for run {run.id} (pr #{pull_request.pr_number}, {len(files)} files)")
- return {"pr_number": pull_request.pr_number, "file_count": len(files), "head_sha": run.head_sha}
+ activity.logger.info(
+ f"Fetched review context for run {run.id} (pr #{number}, {len(files)} files); "
+ f"timings: {run.output['context_timings_ms']}"
+ )
+ return {"pr_number": number, "file_count": len(files), "head_sha": run.head_sha}
@activity.defn
@@ -563,13 +648,23 @@ def list_in_flight_reviewer_bots(input: StamphogReviewInput) -> dict:
run = _load_run(input)
if run.status == ReviewRunStatus.SUPERSEDED:
return {"in_flight": []}
+ started_at = timezone.now()
repo_config = run.pull_request.repo_config
client = StamphogGitHubClient(repo_config.installation_id)
reactions = client.get_pr_reactions(repo_config.repository, run.pull_request.pr_number)
- run.output = {**(run.output or {}), "pr_reactions": reactions}
+ now = timezone.now()
+ # From the first poll's start to this poll's end. The workflow stops polling after the poll that
+ # finds no bot in flight, so the last write is the whole wait.
+ bot_wait = (run.output or {}).get("bot_wait") or {"started_at": started_at.isoformat(), "polls": 0}
+ first_started_at = parse_datetime(str(bot_wait.get("started_at") or "")) or started_at
+ bot_wait = {
+ "started_at": first_started_at.isoformat(),
+ "polls": int(bot_wait.get("polls") or 0) + 1,
+ "ms": int((now - first_started_at).total_seconds() * 1000),
+ }
+ run.output = {**(run.output or {}), "pr_reactions": reactions, "bot_wait": bot_wait}
run.save(update_fields=["output", "updated_at"])
- now = timezone.now()
# Exclude stamphog's own bot login: STAMPHOG_TRUSTED_REACTOR_BOTS is a hardcoded set of OTHER
# reviewer bots' logins, so this app's own 👀 (posted by signal_review_started) can't collide
# with it today — but that set is just literal strings, not a same-app check, so a future
@@ -626,22 +721,6 @@ def _step_timeout(deadline: float, ceiling_seconds: int) -> int:
return min(ceiling_seconds, remaining)
-class _StepTimer:
- """Wall-clock milliseconds per sandbox step, for the run output and the worker log."""
-
- def __init__(self) -> None:
- self.timings_ms: dict[str, int] = {}
-
- @contextmanager
- def step(self, name: str) -> Iterator[None]:
- # Recorded on failure too, so the log line shows how long the failing step ran.
- started = time.monotonic()
- try:
- yield
- finally:
- self.timings_ms[name] = int((time.monotonic() - started) * 1000)
-
-
def _destroy_sandbox_in_background(sandbox: SandboxBase, run_id: str) -> None:
"""Tear the sandbox down on a daemon thread, so the verdict does not wait for it.
@@ -722,21 +801,32 @@ def _fast_refusal_summary(run: ReviewRun, outcome: PregateOutcome) -> str | None
_release_reviewer_token(gateway, token)
+def _save_pregate_outcome(run: ReviewRun, pregate_outcome: str) -> None:
+ run.output = {**(run.output or {}), "pregate_outcome": pregate_outcome}
+ run.save(update_fields=["output", "updated_at"])
+
+
def _refuse_on_pre_gates(run: ReviewRun) -> dict:
output = run.output or {}
skip_reason = pregate_skip_reason(output.get("pr") or {}, output.get("files") or [], run.head_sha)
if skip_reason is not None:
activity.logger.info(f"Run {run.id}: pre-gates skipped ({skip_reason})")
+ _save_pregate_outcome(run, f"skipped:{skip_reason}")
return {"refused": False, "skipped": skip_reason}
context = json.loads(_review_invocation(run, output.get("merge_base_sha")).context_json)
# The same trusted set the sandbox injects, so both runs judge the PR under the same policy.
policy_files = _effective_policy_files(run.pull_request.repo_config.repository, output.get("policy_files", {}))
+ folder_policy_files = output.get("folder_policy_files")
+ if isinstance(folder_policy_files, dict):
+ policy_files = {**policy_files, **folder_policy_files}
+ context["folder_policies_known"] = True
timer = _StepTimer()
# No analytics env on this first run: it only decides, and the posted run below emits the event.
with timer.step("pregate"):
outcome = run_engine_pregate(context, policy_files, environment={})
- if not outcome.final_deny:
+ if not outcome.final:
+ _save_pregate_outcome(run, f"not_final:{outcome.not_final_reason or 'unknown'}")
return {"refused": False}
summary = None
@@ -752,7 +842,7 @@ def _refuse_on_pre_gates(run: ReviewRun) -> dict:
}
with timer.step("render"):
final = run_engine_pregate(context, policy_files, environment=_engine_analytics_environment(properties))
- if not final.final_deny or final.result is None:
+ if not final.final or final.result is None:
raise RuntimeError("the engine pre-check changed its answer between two runs on the same context")
# The same last-line JSON contract the sandbox prints, so post_verdict parses it unchanged. The
@@ -763,22 +853,25 @@ def _refuse_on_pre_gates(run: ReviewRun) -> dict:
"reviewer_exit_code": 0,
"timings_ms": timer.timings_ms,
"fast_path": True,
+ "pregate_outcome": f"final:{final.result.get('final_verdict')}",
}
run.save(update_fields=["output", "updated_at"])
- activity.logger.info(f"Pre-gate refusal for run {run.id}; step timings: {timer.timings_ms}")
+ activity.logger.info(f"Pre-gate verdict for run {run.id}; step timings: {timer.timings_ms}")
return {"refused": True}
@activity.defn
@asyncify
def refuse_on_pre_gates(input: StamphogReviewInput) -> dict:
- """Refuse a PR on its deterministic gates alone, before the bot wait and the sandbox.
+ """Settle a PR on its deterministic gates alone, before the bot wait and the sandbox.
Runs the engine's gate-only pre-check on the stored context (see logic/engine_pregate.py). Only a
- deny the full review would also reach counts, and then the refusal is persisted in the sandbox's
- output shape, so post_verdict and everything after it work unchanged. Everything else, including
- any failure here, returns ``refused: False`` and the run takes the full review path, which runs
- every gate again. This step can therefore only make a refusal faster, never cause one.
+ verdict the full review would also reach counts: a gate refusal, or the WAIT for a pending
+ `Migration risk` check. It is persisted in the sandbox's output shape, so post_verdict and
+ everything after it work unchanged, and ``refused`` is True for both, because the workflow reads
+ that key to skip the sandbox. Everything else, including any failure here, returns
+ ``refused: False`` and the run takes the full review path, which runs every gate again. This step
+ can therefore only make a non-approval faster, never cause one.
"""
run = _load_run(input)
if run.status == ReviewRunStatus.SUPERSEDED:
@@ -787,6 +880,7 @@ def refuse_on_pre_gates(input: StamphogReviewInput) -> dict:
return _refuse_on_pre_gates(run)
except Exception:
activity.logger.exception(f"Run {run.id}: pre-gates failed; falling through to the full review")
+ _save_pregate_outcome(run, "error")
return {"refused": False, "skipped": "error"}
@@ -817,7 +911,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
# review-norms prose are both loaded by the engine — the latter straight into the reviewer's
# SYSTEM prompt. We must NOT fall back to the PR head's copy, or a contributor could ship
# malicious guidance ("approve my PR") in a repo whose default branch lacks the file — the
- # PR-head wipe in _inject_policy_files stays mandatory, and the fallback content is
+ # PR-head wipe in _review_payload_command stays mandatory, and the fallback content is
# server-owned, never the PR's.
policy_files = _effective_policy_files(repo, policy_files)
@@ -898,17 +992,18 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
with timer.step("prefetch"):
_prefetch_review_blobs(sandbox, merge_base_sha, token, deadline)
# The prefetch swallows its own failure, including a timeout that consumed the rest
- # of the budget. Re-check here, because the three steps below write through the
- # sandbox filesystem API and cannot take a deadline: passing one would switch them
- # to an exec-based write, which is a different mechanism, not a bounded one.
+ # of the budget. Re-check here, because the archive write below goes through the
+ # sandbox filesystem API and cannot take a deadline: passing one would switch it to
+ # an exec-based write, which is a different mechanism, not a bounded one.
_step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS)
with timer.step("ship_engine"):
- _inject_policy_files(sandbox, policy_files)
- _ship_engine(sandbox)
- _write_context(sandbox, invocation)
+ _ship_review_payload(sandbox, policy_files, invocation.context_json, deadline)
+ # GNU date prints epoch milliseconds, so the engine can report how long `uv run` took to
+ # reach its main().
command = (
- f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
+ f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && "
+ f"STAMPHOG_LAUNCHED_AT_MS=$(date +%s%3N) {_harden_reviewer_command(invocation.command)}"
)
with timer.step("reviewer"):
result = sandbox.execute(command, timeout_seconds=_step_timeout(deadline, REVIEWER_TIMEOUT_SECONDS))
@@ -926,6 +1021,7 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
"reviewer_raw": scrub_credentials(result.stdout, token, gateway_token),
"reviewer_exit_code": result.exit_code,
"timings_ms": timer.timings_ms,
+ "engine_timings_ms": parse_engine_timings(result.stdout),
}
run.save(update_fields=["output", "updated_at"])
@@ -1096,10 +1192,73 @@ def _remove_own_eyes_reaction(client: StamphogGitHubClient, run: ReviewRun) -> N
client.remove_pr_reaction(pull_request.repo_config.repository, pull_request.pr_number, reaction_id)
+def _timing_properties(prefix: str, timings_ms: object) -> dict[str, int]:
+ if not isinstance(timings_ms, dict):
+ return {}
+ return {
+ f"stamphog_timing_{prefix}{re.sub(r'[^a-z0-9]+', '_', str(name).lower()).strip('_')}_ms": value
+ for name, value in timings_ms.items()
+ if isinstance(value, int)
+ }
+
+
+def _review_timing_properties(run: ReviewRun, verdict: str, post_verdict_ms: int) -> dict[str, object]:
+ """Where a review spent its time, from the created run to the posted verdict, one property per step.
+
+ ``stamphog_timing_sandbox_exec_tail_ms`` is the reviewer step minus the engine's own run, which is
+ process exit and the provider's exec overhead.
+ """
+ output = run.output or {}
+ pull_request = run.pull_request
+ steps = output.get("timings_ms") or {}
+ engine = output.get("engine_timings_ms") or {}
+ bot_wait = output.get("bot_wait") or {}
+ properties: dict[str, object] = {
+ **_hosted_analytics_properties(run),
+ "stamphog_repo": pull_request.repo_config.repository,
+ "stamphog_pr_number": pull_request.pr_number,
+ "stamphog_final_verdict": verdict,
+ "stamphog_fast_path": bool(output.get("fast_path")),
+ "stamphog_pregate_outcome": output.get("pregate_outcome"),
+ "stamphog_familiarity_status": output.get("familiarity_status"),
+ "stamphog_bot_wait_polls": bot_wait.get("polls", 0),
+ "stamphog_timing_total_ms": int((timezone.now() - run.created_at).total_seconds() * 1000),
+ "stamphog_timing_bot_wait_ms": bot_wait.get("ms", 0),
+ "stamphog_timing_post_verdict_ms": post_verdict_ms,
+ **_timing_properties("context_", output.get("context_timings_ms")),
+ **_timing_properties("", steps),
+ **_timing_properties("engine_", engine),
+ }
+ if isinstance(steps.get("reviewer"), int) and isinstance(engine.get("total"), int):
+ properties["stamphog_timing_sandbox_exec_tail_ms"] = steps["reviewer"] - engine["total"]
+ return properties
+
+
+def _capture_review_timings(run: ReviewRun, verdict: str, post_verdict_ms: int) -> None:
+ """Emit ``stamphog_review_timings`` once per run. Best effort: the verdict is already posted and saved.
+
+ The background client, because a per-call client and its synchronous flush would block every
+ review's last activity for seconds. A retried post_verdict finds the marker and sends nothing.
+ """
+ if (run.output or {}).get("timings_captured"):
+ return
+ try:
+ ph_background_capture()(
+ distinct_id=run.pull_request.author_login or run.pull_request.repo_config.repository,
+ event="stamphog_review_timings",
+ properties=_review_timing_properties(run, verdict, post_verdict_ms),
+ )
+ run.output = {**(run.output or {}), "timings_captured": True}
+ run.save(update_fields=["output", "updated_at"])
+ except Exception:
+ activity.logger.exception(f"Failed to capture review timings for run {run.id}")
+
+
@activity.defn
@asyncify
def post_verdict(input: StamphogReviewInput) -> dict:
"""Parse the engine output and post the approval or sticky comment."""
+ post_started = time.monotonic()
run = _load_run(input)
pull_request = run.pull_request
repo_config = pull_request.repo_config
@@ -1332,6 +1491,7 @@ def post_verdict(input: StamphogReviewInput) -> dict:
# "review in flight" 👀 now, whichever verdict landed (approved, gated, refused, escalate).
_remove_own_eyes_reaction(client, run)
+ _capture_review_timings(run, str(parsed.verdict), int((time.monotonic() - post_started) * 1000))
activity.logger.info(f"Posted verdict {parsed.verdict} for run {run.id}")
return {"verdict": str(parsed.verdict)}
@@ -1649,70 +1809,72 @@ def _effective_policy_files(repo: str, policy_files: dict[str, str]) -> dict[str
return effective
-def _inject_policy_files(sandbox: SandboxBase, policy_files: dict[str, str]) -> None:
- """Overwrite the checkout's ``.stamphog/*`` policy files with the trusted versions.
-
- Written AFTER checkout, so the trusted default-branch policy and review norms win
- over whatever the (untrusted) PR head carried. The engine reads them from the tree
- at import via its repo-root walk — this is what makes the run judge the PR against
- our policy, not the PR's own.
+def _review_payload_archive(policy_files: dict[str, str], context_json: str) -> bytes:
+ """Everything the reviewer needs beside the checkout, as one gzipped tar rooted at the checkout.
- Every policy path's PR-head copy is deleted first — required AND optional: an uninjected
- optional file (a repo with no steering.md) must not leave the PR head's planted copy behind
- for the engine to load, any more than a missing policy.yml would.
+ Each ``write_file`` and ``execute`` call is one round trip to the sandbox provider, and the engine
+ alone is some twenty files. One archive and one extract command replace them.
"""
- for path in (*STAMPHOG_POLICY_PATHS, *STAMPHOG_OPTIONAL_POLICY_PATHS):
- sandbox.execute(f"rm -f {shlex.quote(f'{STAMPHOG_SANDBOX_REPO_DIR}/{path}')}", timeout_seconds=30)
- for path, content in policy_files.items():
- _write_sandbox_file(sandbox, f"{STAMPHOG_SANDBOX_REPO_DIR}/{path}", content)
-
-
-def _ship_engine(sandbox: SandboxBase) -> None:
- """Ship the Action's review engine into the sandbox checkout at its canonical path.
-
- Placing it under ``<checkout>/tools/pr-approval-agent`` means the engine's repo-root
- walk lands on the checkout, so it reads the injected trusted policy. The PR head's own
- copy (if any) is overwritten — we always run our version, not the PR's.
- """
- files = engine_source_files()
- if "review_local.py" not in files:
+ members = {
+ **policy_files,
+ **{f"{_ENGINE_RELATIVE_DIR}/{name}": content for name, content in engine_source_files().items()},
+ **{f"{_OWNERS_PACKAGE_RELATIVE_DIR}/{name}": content for name, content in owners_package_files().items()},
+ _CONTEXT_RELATIVE_PATH: context_json,
+ }
+ if f"{_ENGINE_RELATIVE_DIR}/review_local.py" not in members:
raise RuntimeError(f"engine source dir {ENGINE_DIR} is missing review_local.py")
- # Wipe the directory first: the PR head's checkout may carry attacker-controlled files beside
- # our engine (e.g. tools/pr-approval-agent/yaml.py), which Python would import ahead of uv's
- # installed dependency — arbitrary code execution with the sandbox's LLM creds. Overwriting only
- # our known modules would leave those shadow files in place, so start from an empty dir.
- engine_dir = shlex.quote(STAMPHOG_SANDBOX_ENGINE_DIR)
- sandbox.execute(f"rm -rf {engine_dir} && mkdir -p {engine_dir}", timeout_seconds=30)
- for name, content in files.items():
- sandbox.write_file(f"{STAMPHOG_SANDBOX_ENGINE_DIR}/{name}", content.encode())
- _ship_owners_package(sandbox)
-
-
-def _ship_owners_package(sandbox: SandboxBase) -> None:
- """Ship the owners-yaml resolver package the engine's ownership format imports.
-
- The default policy declares a ``hogli-resolver`` ownership source, and gates.py imports
- ``owners_yaml`` from ``tools/owners`` next to the engine dir in the sandbox. Same trust
- posture as the engine: always our copy, which overwrites whatever the PR head carried at that
- path. Repos without
- owners.yaml/product.yaml files simply resolve to "no ownership-source match".
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
+ for path, content in members.items():
+ data = content.encode()
+ info = tarfile.TarInfo(path)
+ info.size = len(data)
+ info.mode = 0o644
+ archive.addfile(info, io.BytesIO(data))
+ return buffer.getvalue()
+
+
+def _review_payload_command() -> str:
+ """Wipe the PR head's copies of everything the archive carries, then extract the archive.
+
+ Written AFTER checkout, so the trusted default-branch policy and review norms win over whatever
+ the (untrusted) PR head carried. The engine reads them from the tree at import via its repo-root
+ walk, which is what makes the run judge the PR against our policy, not the PR's own.
+
+ Every policy path's PR-head copy is deleted first, required AND optional: an uninjected optional
+ file (a repo with no steering.md) must not leave the PR head's planted copy behind for the engine
+ to load, any more than a missing policy.yml would.
+
+ The engine and owners directories are wiped whole: the PR head's checkout may carry
+ attacker-controlled files beside our engine (e.g. tools/pr-approval-agent/yaml.py), which Python
+ would import ahead of uv's installed dependency, which is arbitrary code execution with the
+ sandbox's LLM creds. Overwriting only our known modules would leave those shadow files in place.
"""
- target = f"{STAMPHOG_SANDBOX_OWNERS_DIR}/owners_yaml"
- quoted = shlex.quote(STAMPHOG_SANDBOX_OWNERS_DIR)
- sandbox.execute(f"rm -rf {quoted} && mkdir -p {shlex.quote(target)}", timeout_seconds=30)
- for name, content in owners_package_files().items():
- sandbox.write_file(f"{target}/{name}", content.encode())
-
+ repo_dir = shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)
+ policy_paths = " ".join(shlex.quote(path) for path in (*STAMPHOG_POLICY_PATHS, *STAMPHOG_OPTIONAL_POLICY_PATHS))
+ return (
+ f"cd {repo_dir} && rm -f {policy_paths} && "
+ f"rm -rf {shlex.quote(_ENGINE_RELATIVE_DIR)} {shlex.quote(_OWNERS_RELATIVE_DIR)} && "
+ f"tar -xzf {shlex.quote(STAMPHOG_SANDBOX_PAYLOAD_PATH)} --no-same-owner && "
+ f"rm -f {shlex.quote(STAMPHOG_SANDBOX_PAYLOAD_PATH)}"
+ )
-def _write_context(sandbox: SandboxBase, invocation: ReviewerInvocation) -> None:
- """Write the review context JSON the engine consumes into the checkout."""
- _write_sandbox_file(sandbox, invocation.context_path, invocation.context_json)
+def _ship_review_payload(
+ sandbox: SandboxBase, policy_files: dict[str, str], context_json: str, deadline: float
+) -> None:
+ """Place the trusted policy, the engine, the owners resolver and the review context in the checkout.
-def _write_sandbox_file(sandbox: SandboxBase, path: str, content: str) -> None:
- parent = path.rsplit("/", 1)[0] if "/" in path else "."
- sandbox.execute(f"mkdir -p {shlex.quote(parent)}", timeout_seconds=30)
- sandbox.write_file(path, content.encode())
+ The engine goes under ``<checkout>/tools/pr-approval-agent``, so its repo-root walk lands on the
+ checkout and reads the injected trusted policy. We always run our version, not the PR's.
+ """
+ sandbox.write_file(STAMPHOG_SANDBOX_PAYLOAD_PATH, _review_payload_archive(policy_files, context_json))
+ result = sandbox.execute(_review_payload_command(), timeout_seconds=_step_timeout(deadline, 60))
+ if result.exit_code != 0:
+ # The reviewer reads an untrusted PR head, so tar's stderr can name repository paths. Keep it
+ # in the worker log only.
+ activity.logger.error(f"Review payload extract failed: {result.stderr[:500]}")
+ raise RuntimeError(f"extracting the review payload failed with exit code {result.exit_code}")
def _stamp_digest_audience_if_merged(
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 284c33867463..2d5ddff91e7f 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -49,6 +49,8 @@ STAMPHOG_REVIEWHOG_LABEL = "reviewhog"
# vendor the engine with the resolver beside it and the engine resolves the two layouts by offset.
STAMPHOG_SANDBOX_OWNERS_DIR = f"{STAMPHOG_SANDBOX_REPO_DIR}/tools/owners"
STAMPHOG_SANDBOX_CONTEXT_PATH = f"{STAMPHOG_SANDBOX_REPO_DIR}/.stamphog_review_context.json"
+# Outside the checkout, so the archive never shows up in the tree the reviewer explores.
+STAMPHOG_SANDBOX_PAYLOAD_PATH = "/tmp/stamphog/review-payload.tar.gz"
# Trusted review-norms prose the engine reads as its reviewer system guidance, and
# the gate policy entrypoint. Both are fetched from the target repo's DEFAULT branch
@@ -112,3 +114,10 @@ SANDBOX_RETRY_POLICY = RetryPolicy(
initial_interval=timedelta(seconds=10),
non_retryable_error_types=["SandboxPhaseError"],
)
+
+# The Claude Code CLI's own switches for its telemetry, error reporting and auto-update traffic.
+NETWORK_RESTRICTED_AGENT_ENV = {
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
+ "DISABLE_TELEMETRY": "1",
+ "DISABLE_ERROR_REPORTING": "1",
+}
diff --git a/products/stamphog/backend/temporal/workflow.py b/products/stamphog/backend/temporal/workflow.py
index 2c8d62d908e4..36639313ccf8 100644
--- a/products/stamphog/backend/temporal/workflow.py
+++ b/products/stamphog/backend/temporal/workflow.py
@@ -84,9 +84,10 @@ class StamphogReviewWorkflow(PostHogWorkflow):
)
# A PR that fails a deterministic gate is refused whatever the reviewer says, so the
- # engine's own gates run here first on the stored context. A final deny is persisted in
- # the sandbox's output shape, and the run skips the bot wait and the sandbox. Gated for
- # replay like the eyes reaction above.
+ # engine's own gates run here first on the stored context. A final gate verdict (a deny,
+ # or the WAIT for a pending migration check) is persisted in the sandbox's output shape,
+ # and the run skips the bot wait and the sandbox. Gated for replay like the eyes reaction
+ # above.
refused_on_pre_gates = False
if workflow.patched("stamphog-pre-gates"):
try:
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index b83ab83d8b53..fb773bfd10c5 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -13,10 +13,13 @@ audience / channel-resolution / digest logic) runs as real code. The dev runner
from __future__ import annotations
+import io
import re
import hmac
import json
+import base64
import hashlib
+import tarfile
import threading
from collections.abc import Iterable
from dataclasses import dataclass
@@ -24,6 +27,8 @@ from typing import Any
from slack_sdk.errors import SlackApiError
+from products.stamphog.backend.temporal.constants import STAMPHOG_SANDBOX_PAYLOAD_PATH, STAMPHOG_SANDBOX_REPO_DIR
+
# --- Webhook payload + signing (mirrors what GitHub sends) ---
_RELEVANT_PR_FIELDS = ("number", "title", "body")
@@ -186,6 +191,8 @@ class GitHubRecorder:
# Per-repository overrides for the same paths, for cases where two connected repos must
# answer differently (one carries a root owners.yaml, another does not).
self.repo_files: dict[tuple[str, str], str] = {}
+ # (repo, path) -> link target, for a symlink the contents API reports as a symlink object.
+ self.repo_symlinks: dict[tuple[str, str], str] = {}
# Repositories with no commits at all. GitHub answers their head lookup with a null
# defaultBranchRef, which is what a freshly created connected repo looks like.
self.empty_repositories: set[str] = set()
@@ -247,7 +254,8 @@ class GitHubRecorder:
if method == "DELETE" and (m := _PR_REACTION_DELETE_RE.match(path)):
return self._remove_reaction(m.group("repo"), int(m.group("number")), int(m.group("rid")))
if method == "GET" and (m := _CONTENTS_RE.match(path)):
- return self._get_contents(m.group("repo"), m.group("path"))
+ raw = "raw" in (kwargs.get("headers") or {}).get("Accept", "")
+ return self._get_contents(m.group("repo"), m.group("path"), raw=raw)
if method == "POST" and path == "/graphql":
return self._graphql(json_body or {})
if method == "GET" and (m := _REVIEWS_RE.match(path)):
@@ -301,10 +309,16 @@ class GitHubRecorder:
numbers = self.author_merged.get((repo, author), []) if page == 1 else []
return FakeResponse(200, json_data={"items": [{"number": n} for n in numbers]})
- def _get_contents(self, repo: str, path: str) -> FakeResponse:
+ def _get_contents(self, repo: str, path: str, *, raw: bool = True) -> FakeResponse:
+ if (repo, path) in self.repo_symlinks:
+ target = self.repo_symlinks[(repo, path)]
+ return FakeResponse(200, json_data={"type": "symlink", "path": path, "target": target})
content = self.repo_files.get((repo, path), self.policy_files.get(path))
if content is None:
return FakeResponse(404, text="not found")
+ if not raw:
+ encoded = base64.b64encode(content.encode()).decode()
+ return FakeResponse(200, json_data={"type": "file", "path": path, "encoding": "base64", "content": encoded})
return FakeResponse(200, text=content, headers={"Content-Type": "text/plain; charset=utf-8"})
def _graphql(self, body: dict) -> FakeResponse:
@@ -366,6 +380,8 @@ class GitHubRecorder:
continue
path = str(expression).split(":", 1)[1]
content = self.repo_files.get((repo, path), self.policy_files.get(path))
+ if (repo, path) in self.repo_symlinks:
+ content = self.repo_symlinks[(repo, path)]
if content is None:
field[f"f{name[1:]}"] = None
else:
@@ -604,7 +620,8 @@ def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, byte
"""A sandbox class returning ``engine_output`` for the reviewer command, no-ops otherwise.
``write_sink``, when given, records every ``write_file`` as ``(path, payload)`` so a test can
- assert what was injected into the checkout (e.g. the default policy files).
+ assert what was injected into the checkout (e.g. the default policy files). The review payload
+ archive is recorded member by member, at the path it extracts to in the checkout.
"""
class _FakeSandbox:
@@ -637,7 +654,13 @@ def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, byte
return FakeExecResult(stdout=stdout, stderr="", exit_code=0)
def write_file(self, path: str, payload: bytes) -> FakeExecResult:
- if write_sink is not None:
+ if write_sink is not None and path == STAMPHOG_SANDBOX_PAYLOAD_PATH:
+ with tarfile.open(fileobj=io.BytesIO(payload), mode="r:gz") as archive:
+ for member in archive.getmembers():
+ extracted = archive.extractfile(member)
+ assert extracted is not None
+ write_sink.append((f"{STAMPHOG_SANDBOX_REPO_DIR}/{member.name}", extracted.read()))
+ elif write_sink is not None:
write_sink.append((path, payload))
return FakeExecResult(stdout="", stderr="", exit_code=0)
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index cfcb21eb960b..7ae819dd06c2 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -2,6 +2,7 @@ import os
import json
import uuid
import threading
+from contextlib import nullcontext
from pathlib import Path
import pytest
@@ -49,6 +50,7 @@ from products.stamphog.backend.temporal.activities import (
run_review_in_sandbox,
)
from products.stamphog.backend.temporal.constants import (
+ NETWORK_RESTRICTED_AGENT_ENV,
SANDBOX_RETRY_POLICY,
STAMPHOG_SANDBOX_CONTEXT_PATH,
STAMPHOG_SANDBOX_REPO_DIR,
@@ -222,7 +224,9 @@ def test_signed_webhook_drives_review_and_posts_approval(team, stamphog_chain: S
]
recorder.author_history["src"] = [commit("c-author", author)]
- status = stamphog_chain.post_webhook(_opened_event(101, author, head_sha), delivery_id=str(uuid.uuid4()))
+ capture_fn = MagicMock()
+ with patch.object(activities, "ph_background_capture", return_value=capture_fn):
+ status = stamphog_chain.post_webhook(_opened_event(101, author, head_sha), delivery_id=str(uuid.uuid4()))
assert status == 202
pr = PullRequest.objects.for_team(team.id).get(repo_config=repo_config, pr_number=101)
@@ -230,6 +234,23 @@ def test_signed_webhook_drives_review_and_posts_approval(team, stamphog_chain: S
assert run.status == ReviewRunStatus.COMPLETED
assert run.verdict == ReviewVerdict.APPROVED
+ (timings_call,) = [c for c in capture_fn.call_args_list if c.kwargs["event"] == "stamphog_review_timings"]
+ timings = timings_call.kwargs["properties"]
+ assert timings["stamphog_review_run_id"] == str(run.id)
+ assert timings["stamphog_final_verdict"] == "approved"
+ assert timings["stamphog_pregate_outcome"] == "skipped:file_list_incomplete"
+ assert timings["stamphog_familiarity_status"] == "ok"
+ assert timings["stamphog_bot_wait_polls"] == 1
+ assert {
+ "stamphog_timing_total_ms",
+ "stamphog_timing_context_total_ms",
+ "stamphog_timing_context_history_ms",
+ "stamphog_timing_clone_ms",
+ "stamphog_timing_ship_engine_ms",
+ "stamphog_timing_reviewer_ms",
+ "stamphog_timing_post_verdict_ms",
+ } <= set(timings)
+
# The sandbox gets familiarity from GitHub facts, and only the blame ranges of changed lines ride
# along. It therefore needs no history, and the prefetch walks none.
assert run.output["merge_base_sha"] == recorder.merge_base_sha
@@ -266,40 +287,94 @@ def _api_file(filename: str) -> dict:
return {"filename": filename, "status": "modified", "additions": 8, "deletions": 1, "patch": "@@ -1 +1 @@"}
+def _big_api_file(filename: str, additions: int) -> dict:
+ return {**_api_file(filename), "additions": additions, "deletions": 0}
+
+
+_LIFTING_FOLDER_FILE = "---\nstamphog:\n size_gate:\n max_lines: 1000\n---\nTall PRs are normal here.\n"
+
+
@pytest.mark.parametrize(
- "files, summary, engine_breaks, expect_fast_path, expect_in_body",
+ "files, summary, engine_breaks, folder_read_fails, expect_pregate_outcome, expect_in_body",
[
pytest.param(
- [_api_file("terraform/main.tf")], FAST_REFUSAL_SUMMARY, False, True, FAST_REFUSAL_SUMMARY, id="deny"
+ [_api_file("terraform/main.tf")],
+ FAST_REFUSAL_SUMMARY,
+ False,
+ False,
+ "final:REFUSED",
+ FAST_REFUSAL_SUMMARY,
+ id="deny",
),
pytest.param(
[_api_file("terraform/main.tf")],
None,
False,
- True,
+ False,
+ "final:REFUSED",
"deny-list: matches: infra_cicd",
id="deny-summary-failed",
),
# A broken pre-check must cost only the shortcut, never the review.
- pytest.param([_api_file("terraform/main.tf")], None, True, False, None, id="engine-breaks"),
- # No Migration risk check has reported, so the full review can end WAIT rather than REFUSED.
+ pytest.param([_api_file("terraform/main.tf")], None, True, False, "error", None, id="engine-breaks"),
+ # No Migration risk check has reported, and nothing else could change the answer in the sandbox.
+ pytest.param(
+ [_api_file("posthog/migrations/0999_add_col.py")],
+ None,
+ False,
+ False,
+ "final:WAIT",
+ "Migration risk",
+ id="pending-migration",
+ ),
+ pytest.param(
+ [_big_api_file("lib/big.py", 900)], None, False, False, "final:REFUSED", "too large", id="size-folders-read"
+ ),
+ pytest.param(
+ [_big_api_file("lib/big.py", 900)],
+ None,
+ False,
+ True,
+ "not_final:size_folder_override",
+ None,
+ id="size-folders-unknown",
+ ),
+ # sym/AGENT_APPROVALS.md is a symlink out of the repo, which the sandbox would follow, so the
+ # folder files are unknown and the size band stays with the sandbox.
+ pytest.param(
+ [_big_api_file("sym/big.py", 900)],
+ None,
+ False,
+ False,
+ "not_final:size_folder_override",
+ None,
+ id="size-with-a-symlinked-folder-file",
+ ),
+ # The PR head's src/AGENT_APPROVALS.md lifts the ceiling, so the sandbox review must decide.
pytest.param(
- [_api_file("posthog/migrations/0999_add_col.py")], None, False, False, None, id="pending-migration"
+ [_big_api_file("src/deep/big.py", 900)],
+ None,
+ False,
+ False,
+ "not_final:no_failing_gate",
+ None,
+ id="size-lifted-by-a-folder-file",
),
- pytest.param(_pr_files(), None, False, False, None, id="clean"),
+ pytest.param(_pr_files(), None, False, False, "not_final:no_failing_gate", None, id="clean"),
],
)
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
-def test_a_final_gate_deny_is_refused_without_a_sandbox(
+def test_a_final_gate_verdict_is_posted_without_a_sandbox(
team,
stamphog_chain: StamphogChain,
files: list[dict],
summary: str | None,
engine_breaks: bool,
- expect_fast_path: bool,
+ folder_read_fails: bool,
+ expect_pregate_outcome: str,
expect_in_body: str | None,
) -> None:
- # The engine's own pre-check runs in a real child process here: a deny the full review would
+ # The engine's own pre-check runs in a real child process here: a verdict the full review would
# also reach skips the bot wait and the sandbox, and anything else still gets the full review.
repo_config = _repo_config(team.id)
author, head_sha = "devex-dev", "sha-pregate"
@@ -308,16 +383,23 @@ def test_a_final_gate_deny_is_refused_without_a_sandbox(
REPO, 101, pr_object, files, commit_messages=("feat: infra\n\nGenerated-By: PostHog Code\nTask-Id: t-1",)
)
+ stamphog_chain.recorder.repo_files[(REPO, "src/AGENT_APPROVALS.md")] = _LIFTING_FOLDER_FILE
+ stamphog_chain.recorder.repo_symlinks[(REPO, "sym/AGENT_APPROVALS.md")] = "../../shared/policy.md"
+
engine_failure = EnginePregateError("the engine pre-check exited with code 1") if engine_breaks else None
with (
patch("products.stamphog.backend.temporal.activities.summarize_refusal", return_value=summary),
patch.object(activities, "run_engine_pregate", side_effect=engine_failure, wraps=activities.run_engine_pregate),
+ patch.object(activities, "fetch_folder_policy_files", return_value=None)
+ if folder_read_fails
+ else nullcontext(),
):
assert stamphog_chain.post_webhook(_opened_event(101, author, head_sha), delivery_id=str(uuid.uuid4())) == 202
pull_request = PullRequest.objects.for_team(team.id).get(repo_config=repo_config, pr_number=101)
run = ReviewRun.objects.for_team(team.id).filter(pull_request=pull_request).latest("created_at")
- if not expect_fast_path:
+ assert run.output["pregate_outcome"] == expect_pregate_outcome
+ if expect_in_body is None:
assert stamphog_chain.sandbox_class.created_configs != []
assert "fast_path" not in run.output
return
@@ -761,7 +843,9 @@ def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
"POSTHOG_API_KEY",
"POSTHOG_HOST",
"STAMPHOG_EXTRA_PROPERTIES",
+ *NETWORK_RESTRICTED_AGENT_ENV,
}
+ assert all(env[name] == "1" for name in NETWORK_RESTRICTED_AGENT_ENV)
assert not OAuthAccessToken.objects.filter(user_id=user.id).exists()
mint_call, revoke_call = mint.call_args_list
diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.py
index 9b0e3fcb130b..8937e9b87318 100644
--- a/products/stamphog/backend/tests/test_logic.py
+++ b/products/stamphog/backend/tests/test_logic.py
@@ -18,7 +18,7 @@ from products.stamphog.backend.logic.approval_retention import approved_diff_unc
from products.stamphog.backend.logic.audiences import resolve_audiences
from products.stamphog.backend.logic.digest import DigestPRSummary, DigestSummary, _build_selection_prompt
from products.stamphog.backend.logic.digest_config import RepoDigestConfig, load_repo_digest_config
-from products.stamphog.backend.logic.familiarity_facts import ReviewHistory, fetch_review_history
+from products.stamphog.backend.logic.familiarity_facts import FamiliarityStatus, ReviewHistory, fetch_review_history
from products.stamphog.backend.logic.github_client import (
MAX_COMPARE_DIFF_BYTES,
StamphogGitHubClient,
@@ -288,15 +288,24 @@ class FamiliarityFactsTests(SimpleTestCase):
@parameterized.expand(
[
- ("one_blame_fails", {"blame_error": StamphogGitHubError("502")}, True),
- ("rate_limited", {"blame_error": GitHubRateLimitError("slow down")}, False),
- ("history_fails", {"history_error": StamphogGitHubError("502")}, False),
+ ("one_blame_fails", {"blame_error": StamphogGitHubError("502")}, True, FamiliarityStatus.PARTIAL_BLAME),
+ ("rate_limited", {"blame_error": GitHubRateLimitError("slow down")}, False, FamiliarityStatus.RATE_LIMITED),
+ ("history_fails", {"history_error": StamphogGitHubError("502")}, False, FamiliarityStatus.HISTORY_FAILED),
+ (
+ "history_rate_limited",
+ {"history_error": GitHubRateLimitError("slow down")},
+ False,
+ FamiliarityStatus.RATE_LIMITED,
+ ),
]
)
- def test_failures_degrade_one_file_or_drop_all_facts(self, _name: str, errors: dict, facts_kept: bool) -> None:
+ def test_failures_degrade_one_file_or_drop_all_facts(
+ self, _name: str, errors: dict, facts_kept: bool, status: FamiliarityStatus
+ ) -> None:
history = _fetch_history(_FamiliarityClient(**errors))
assert history.merge_base_sha == "mb"
+ assert history.status == status
if facts_kept:
# The engine counts the lines of a file without blame as not owned.
assert history.familiarity_facts is not None
@@ -314,6 +323,7 @@ class FamiliarityFactsTests(SimpleTestCase):
client.release.set()
assert history.familiarity_facts is None
+ assert history.status == FamiliarityStatus.HISTORY_TIMED_OUT
def test_a_slow_blame_leaves_only_its_file_out(self) -> None:
client = _FamiliarityClient()
@@ -328,6 +338,7 @@ class FamiliarityFactsTests(SimpleTestCase):
assert facts is not None
assert facts["blame"] == {}
assert facts["path_history"] == ["c-author"]
+ assert history.status == FamiliarityStatus.PARTIAL_BLAME
class ReviewTriggerTests(SimpleTestCase):
diff --git a/products/stamphog/backend/tests/test_policy_defaults.py b/products/stamphog/backend/tests/test_policy_defaults.py
index 29779c15c433..e279eeb75ff9 100644
--- a/products/stamphog/backend/tests/test_policy_defaults.py
+++ b/products/stamphog/backend/tests/test_policy_defaults.py
@@ -21,8 +21,8 @@ from products.stamphog.backend.temporal import activities # noqa: E402
from products.stamphog.backend.temporal.activities import ( # noqa: E402
_clone_pr,
_effective_policy_files,
- _inject_policy_files,
_prefetch_review_blobs,
+ _review_payload_command,
)
from products.stamphog.backend.temporal.constants import ( # noqa: E402
STAMPHOG_POLICY_ENTRYPOINT,
@@ -109,23 +109,16 @@ def test_repo_guidance_and_steering_pass_through() -> None:
assert effective[STAMPHOG_STEERING_PATH] == "steer this way\n"
-def test_inject_policy_files_wipes_optional_paths_from_pr_head() -> None:
+def test_review_payload_command_wipes_optional_paths_from_pr_head() -> None:
# steering.md is injected only when the repo's default branch has it — so the wipe must cover it
# regardless, or a PR head could plant a steering.md the reviewer would trust as maintainer prose.
- executed: list[str] = []
-
- class _RecordingSandbox:
- def execute(self, command: str, timeout_seconds: int | None = None) -> None:
- executed.append(command)
-
- def write_file(self, path: str, payload: bytes) -> None:
- return None
-
- _inject_policy_files(_RecordingSandbox(), {}) # type: ignore[arg-type]
+ command = _review_payload_command()
- wipes = [cmd for cmd in executed if cmd.startswith("rm -f")]
- assert any(".stamphog/steering.md" in cmd for cmd in wipes)
- assert any(".stamphog/policy.yml" in cmd for cmd in wipes)
+ wipe, _, extract = command.partition("tar -xzf")
+ assert ".stamphog/steering.md" in wipe
+ assert ".stamphog/policy.yml" in wipe
+ assert "rm -rf tools/pr-approval-agent tools/owners" in wipe
+ assert extract
def test_clone_and_prefetch_carry_the_credential_on_every_github_fetch() -> None:
diff --git a/products/stamphog/packages/pr-approval-agent/review_local.py b/products/stamphog/packages/pr-approval-agent/review_local.py
index 250c3881ffb3..2d528a954a22 100644
--- a/products/stamphog/packages/pr-approval-agent/review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/review_local.py
@@ -39,14 +39,16 @@ this script runs, so a PR head cannot substitute its own gate. The reviewer key
comes from the environment (ANTHROPIC_API_KEY).
`--pregate` is the server's gate-only pre-check (see pregate()). The server runs it on the worker,
-in a temporary tree that holds only the trusted policy files and this engine, before it waits for
-other bots or makes a sandbox.
+in a temporary tree that holds the trusted policy files, this engine and, when the server could read
+them, the PR head's AGENT_APPROVALS.md files, before it waits for other bots or makes a sandbox.
"""
import os
import json
import time
import argparse
+from collections.abc import Iterator
+from contextlib import contextmanager
from pathlib import Path
from familiarity import (
@@ -62,7 +64,7 @@ from familiarity import (
_select_considered_files,
familiarity_from_facts,
)
-from gates import POLICY, assign_tier, substantive_size
+from gates import POLICY, assign_tier, dependency_manifests_without_lockfile, substantive_size
from gateway import REVIEWER_MODEL
from github import (
TRUSTED_REACTOR_BOTS,
@@ -82,6 +84,32 @@ from policy import FamiliarityPolicy
from review_pr import REPO_ROOT, GateResult, Pipeline, flush_analytics
from version import STAMPHOG_VERSION
+# The hosted server exports the sandbox's wall clock in milliseconds right before `uv run`, so the
+# engine can report how long uv and the interpreter took to reach main().
+LAUNCHED_AT_ENV = "STAMPHOG_LAUNCHED_AT_MS"
+
+_TIMINGS_MS: dict[str, int] = {}
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+@contextmanager
+def _timed_phase(name: str) -> Iterator[None]:
+ started = _now_ms()
+ try:
+ yield
+ finally:
+ _TIMINGS_MS[name] = _now_ms() - started
+
+
+def _launched_at_ms() -> int | None:
+ try:
+ return int(os.environ.get(LAUNCHED_AT_ENV, ""))
+ except ValueError:
+ return None
+
def _api_file_status(status: str) -> str:
"""Map a get_pr_files status string onto the single-letter code the engine expects.
@@ -446,15 +474,20 @@ def _blocked_only_by_pending_migration_check(pipeline: Pipeline) -> bool:
_CHECKOUT_FREE_GATES = frozenset({"prerequisites", "deny-list", "tier"})
-def _size_denial_is_final(pipeline: Pipeline) -> bool:
+def _size_denial_is_final(pipeline: Pipeline, folder_policies_known: bool) -> bool:
"""True when no folder override on the PR head can lift the size gate.
- The pre-check has no checkout, so it reads no AGENT_APPROVALS.md and budgets every file against
- the global ceilings. A folder file can raise a ceiling up to the policy's delegation contract, and
- the whole-PR roof is the most generous ceiling in play. A PR past the higher of the global ceiling
+ With ``folder_policies_known``, the server wrote every AGENT_APPROVALS.md that governs a changed
+ file at the PR head into the pre-check tree, so the size gate budgets exactly as in the sandbox.
+
+ Otherwise the pre-check reads no AGENT_APPROVALS.md and budgets every file against the global
+ ceilings. A folder file can raise a ceiling up to the policy's delegation contract, and the
+ whole-PR roof is the most generous ceiling in play. A PR past the higher of the global ceiling
and the contract ceiling therefore fails the size gate in the sandbox, whatever folder files it
carries. A PR between the two can pass there, so it is not final here.
"""
+ if folder_policies_known:
+ return True
lines, files = substantive_size(pipeline.pr.files)
line_contract = POLICY.overrides.get("size_gate.max_lines")
file_contract = POLICY.overrides.get("size_gate.max_files")
@@ -463,22 +496,58 @@ def _size_denial_is_final(pipeline: Pipeline) -> bool:
return lines > line_ceiling or files > file_ceiling
-def _denial_is_final(pipeline: Pipeline) -> bool:
+def _pending_migration_outcome_is_known(pipeline: Pipeline, folder_policies_known: bool) -> bool:
+ """True when the pre-check reaches the same pending-migration decision as the sandbox.
+
+ That decision reads the whole gate set. Only two inputs of it need a checkout: the folder size
+ grants, which ``folder_policies_known`` supplies, and the manifest scripts scan, which reads git
+ and can add a deny. A PR with a dependency manifest therefore stays undecided.
+ """
+ return folder_policies_known and not dependency_manifests_without_lockfile(pipeline.pr.file_paths)
+
+
+def _denial_is_final(pipeline: Pipeline, folder_policies_known: bool) -> bool:
"""True when the full sandbox review of this PR must also end REFUSED.
A migrations-only deny with a pending `Migration risk` check ends as WAIT in the sandbox (see
- _blocked_only_by_pending_migration_check). That outcome depends on the size gate, which the
- pre-check cannot always settle, so only a failing prerequisite, which both runs see identically,
- keeps that case final.
+ _blocked_only_by_pending_migration_check). Unless the pre-check can settle that decision, only a
+ failing prerequisite, which both runs see identically, keeps that case final.
"""
failed = {gate.gate for gate in pipeline.gate_results if not gate.passed}
if (
pipeline.classification.get("deny_categories") == ["migrations"]
and migration_check_pending(pipeline.pr.check_runs, pipeline.pr.file_paths)
and "prerequisites" not in failed
+ and not _pending_migration_outcome_is_known(pipeline, folder_policies_known)
):
return False
- return bool(failed & _CHECKOUT_FREE_GATES) or ("size" in failed and _size_denial_is_final(pipeline))
+ return bool(failed & _CHECKOUT_FREE_GATES) or (
+ "size" in failed and _size_denial_is_final(pipeline, folder_policies_known)
+ )
+
+
+def _pending_migration_wait() -> dict:
+ """The WAIT the full review returns while the `Migration risk` check has not reported."""
+ return {
+ "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": [],
+ }
+
+
+def _not_final_reason(pipeline: Pipeline) -> str:
+ """Why a pre-check that did not settle the verdict leaves it to the sandbox, for telemetry."""
+ failed = {gate.gate for gate in pipeline.gate_results if not gate.passed}
+ if not failed:
+ return "no_failing_gate"
+ if failed == {"size"}:
+ return "size_folder_override"
+ return "pending_migration_check"
def _gate_refusal_reasoning(pipeline: Pipeline) -> str:
@@ -493,13 +562,20 @@ def pregate(context: dict) -> dict:
"""Gate-only run for the hosted server, before it waits for other bots or makes a sandbox.
It drives the same Pipeline steps as run(), on the same context, with no checkout and no LLM.
- ``final_deny`` is True only when the sandbox review would also end REFUSED. The server then posts
- ``result`` as the verdict and skips the sandbox. Any other outcome falls through to the full
+ ``final`` is True only when the sandbox review would end with the same verdict as ``result``,
+ which is a gate refusal or a pending-migration WAIT. The server then posts ``result`` as the
+ verdict and skips the sandbox. Any other outcome falls through to the full
review, which runs every gate again.
+ A pending `Migration risk` check that alone blocks the review is final too, as the same WAIT the
+ sandbox would return, when the pre-check can settle it (see _pending_migration_outcome_is_known).
+
A gate refusal takes its reasoning from ``refusal_reasoning`` in the context, which the server
fills with a short LLM summary, or else from the gate messages. ``needs_summary`` tells the server
whether a summary is worth asking for: the bot-author refusal carries its own text.
+
+ ``folder_policies_known`` in the context means the server placed the PR head's AGENT_APPROVALS.md
+ files in the pre-check tree. ``not_final_reason`` names why a non-final outcome needs the sandbox.
"""
pipeline = Pipeline(
0,
@@ -514,16 +590,24 @@ def pregate(context: dict) -> dict:
# repository. Without them, provenance stays null on the fast-path event.
if "commit_messages" in context:
pipeline.provenance = _context_provenance(context, pipeline.pr)
- outcome = {"final_deny": False, "needs_summary": False, "summary_model": REVIEWER_MODEL, "result": None}
+ folder_policies_known = context.get("folder_policies_known") is True
+ outcome = {"final": False, "needs_summary": False, "summary_model": REVIEWER_MODEL, "result": None}
if pipeline.pr.author_is_bot and not pipeline.self_driving:
pipeline._refuse_bot_author()
- return {**outcome, "final_deny": True, "result": pipeline.to_dict()}
+ return {**outcome, "final": True, "result": pipeline.to_dict()}
pipeline._classify()
_run_gates_offline(pipeline, {str(slug) for slug in context.get("author_team_slugs") or []})
- if not _denial_is_final(pipeline):
- return outcome
+ if _blocked_only_by_pending_migration_check(pipeline):
+ if not _pending_migration_outcome_is_known(pipeline, folder_policies_known):
+ return {**outcome, "not_final_reason": "pending_migration_check"}
+ pipeline.final_verdict = "WAIT"
+ pipeline.reviewer_output = _pending_migration_wait()
+ pipeline._capture_review_completed(pipeline._gate_verdict(), "PENDING-MIGRATION-CHECK")
+ return {**outcome, "final": True, "result": pipeline.to_dict()}
+ if not _denial_is_final(pipeline, folder_policies_known):
+ return {**outcome, "not_final_reason": _not_final_reason(pipeline)}
pipeline.final_verdict = "REFUSED"
pipeline.reviewer_output = {
@@ -533,7 +617,7 @@ def pregate(context: dict) -> dict:
"issues": [],
}
pipeline._capture_review_completed("DENIED", "GATES-ONLY")
- return {**outcome, "final_deny": True, "needs_summary": True, "result": pipeline.to_dict()}
+ return {**outcome, "final": True, "needs_summary": True, "result": pipeline.to_dict()}
def run(context: dict) -> dict:
@@ -559,8 +643,9 @@ def run(context: dict) -> dict:
return pipeline.to_dict()
try:
- pipeline._classify()
- _run_gates_offline(pipeline, {str(slug) for slug in context.get("author_team_slugs") or []})
+ with _timed_phase("gates"):
+ pipeline._classify()
+ _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
@@ -571,16 +656,7 @@ def run(context: dict) -> dict:
# 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.reviewer_output = _pending_migration_wait()
pipeline._capture_review_completed(gate_verdict, "PENDING-MIGRATION-CHECK")
return pipeline.to_dict()
@@ -604,8 +680,10 @@ def run(context: dict) -> dict:
}
return pipeline.to_dict()
- _attach_familiarity(pipeline, context)
- pipeline._llm_review(gate_verdict)
+ with _timed_phase("familiarity"):
+ _attach_familiarity(pipeline, context)
+ with _timed_phase("llm"):
+ pipeline._llm_review(gate_verdict)
finally:
if pipeline._diff_path is not None:
pipeline._diff_path.unlink(missing_ok=True)
@@ -657,6 +735,9 @@ def main() -> None:
print(json.dumps(pregate_result), flush=True)
return
+ launched_at = _launched_at_ms()
+ if launched_at is not None:
+ _TIMINGS_MS["launch"] = _now_ms() - launched_at
try:
result = run(context)
except Exception as exc: # never let a crash become a silent non-verdict
@@ -664,7 +745,11 @@ def main() -> None:
# Flush BEFORE the final line: batched capture events are dropped at process exit otherwise,
# and any client noise the flush prints must stay above the machine-readable line.
- flush_analytics()
+ with _timed_phase("flush"):
+ flush_analytics()
+ if launched_at is not None:
+ _TIMINGS_MS["total"] = _now_ms() - launched_at
+ result["timings_ms"] = dict(_TIMINGS_MS)
# The single machine-readable line the server parses — always last on stdout.
print(json.dumps(result), flush=True)
diff --git a/products/stamphog/packages/pr-approval-agent/test_review_local.py b/products/stamphog/packages/pr-approval-agent/test_review_local.py
index cc840e32d50a..08277744f454 100644
--- a/products/stamphog/packages/pr-approval-agent/test_review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/test_review_local.py
@@ -1,6 +1,7 @@
"""Tests for the offline review entrypoint's context handling."""
import sys
+import json
from datetime import UTC, datetime
from typing import Any
@@ -568,10 +569,17 @@ def test_hosted_stacked_review_never_creates_a_worktree(monkeypatch) -> None:
def _pregate_context(
- files: list[dict], *, draft: bool = False, user_type: str = "User", check_runs: list[dict] | None = None
+ files: list[dict],
+ *,
+ draft: bool = False,
+ user_type: str = "User",
+ check_runs: list[dict] | None = None,
+ folder_policies_known: bool = False,
) -> dict:
context = _run_context(files, check_runs)
context["pr"] = {**context["pr"], "draft": draft, "user": {"login": "alice", "type": user_type}}
+ if folder_policies_known:
+ context["folder_policies_known"] = True
return context
@@ -579,53 +587,87 @@ def _lines(filename: str, additions: int) -> dict:
return {"filename": filename, "additions": additions, "deletions": 0, "status": "modified", "patch": "@@"}
+_PENDING_MIGRATION_CHECK = [{"name": "Migration risk", "status": "in_progress", "conclusion": None}]
+
+
@pytest.mark.parametrize(
- "context, expect_final, expect_summary",
+ "context, expect_verdict, expect_summary",
[
- pytest.param(_pregate_context([_api_file("terraform/main.tf")]), True, True, id="deny-list-and-t2"),
- pytest.param(_pregate_context([_api_file("src/app.py")], draft=True), True, True, id="draft-prerequisite"),
- pytest.param(_pregate_context([_api_file("src/app.py")], user_type="Bot"), True, False, id="bot-author"),
+ pytest.param(_pregate_context([_api_file("terraform/main.tf")]), "REFUSED", True, id="deny-list-and-t2"),
+ pytest.param(_pregate_context([_api_file("src/app.py")], draft=True), "REFUSED", True, id="draft-prerequisite"),
+ pytest.param(_pregate_context([_api_file("src/app.py")], user_type="Bot"), "REFUSED", False, id="bot-author"),
pytest.param(
- _pregate_context([_lines(f"src/mod_{i}.py", 5) for i in range(60)]), True, True, id="past-the-file-contract"
+ _pregate_context([_lines(f"src/mod_{i}.py", 5) for i in range(60)]),
+ "REFUSED",
+ True,
+ id="past-the-file-contract",
),
# Between the global ceiling and the delegation contract, a folder AGENT_APPROVALS.md on the PR
# head can lift the size gate, and the pre-check cannot read one.
- pytest.param(_pregate_context([_lines("src/big.py", 900)]), False, False, id="size-a-folder-could-lift"),
+ pytest.param(_pregate_context([_lines("src/big.py", 900)]), None, False, id="size-a-folder-could-lift"),
+ pytest.param(
+ _pregate_context([_lines("src/big.py", 900)], folder_policies_known=True),
+ "REFUSED",
+ True,
+ id="size-with-folder-files-known",
+ ),
# The manifest scripts scan reads git, which the pre-check does not have; running it anyway fails
# closed and would refuse every manifest edit.
- pytest.param(_pregate_context([_api_file("frontend/package.json")]), False, False, id="manifest-scan-skipped"),
+ pytest.param(_pregate_context([_api_file("frontend/package.json")]), None, False, id="manifest-scan-skipped"),
pytest.param(
- _pregate_context([_api_file("posthog/migrations/0999_add_col.py")]),
+ _pregate_context([_api_file("posthog/migrations/0999_add_col.py")], check_runs=_PENDING_MIGRATION_CHECK),
+ None,
False,
+ id="pending-migration-check-without-folder-files",
+ ),
+ pytest.param(
+ _pregate_context(
+ [_api_file("posthog/migrations/0999_add_col.py")],
+ check_runs=_PENDING_MIGRATION_CHECK,
+ folder_policies_known=True,
+ ),
+ "WAIT",
+ False,
+ id="pending-migration-check-waits",
+ ),
+ # A manifest's scripts scan could add a second deny in the sandbox and turn the WAIT into a refusal.
+ pytest.param(
+ _pregate_context(
+ [_api_file("posthog/migrations/0999_add_col.py"), _api_file("frontend/package.json")],
+ check_runs=_PENDING_MIGRATION_CHECK,
+ folder_policies_known=True,
+ ),
+ None,
False,
- id="pending-migration-check-can-wait",
+ id="pending-migration-check-with-a-manifest",
),
- pytest.param(_pregate_context([_api_file("src/app.py")]), False, False, id="clean-t1"),
+ pytest.param(_pregate_context([_api_file("src/app.py")]), None, False, id="clean-t1"),
],
)
-def test_pregate_fast_denies_only_what_the_full_review_refuses(
- monkeypatch, context: dict, expect_final: bool, expect_summary: bool
+def test_pregate_is_final_only_where_the_full_review_agrees(
+ monkeypatch, context: dict, expect_verdict: str | None, expect_summary: bool
) -> None:
- # The server posts a final pre-check deny as the verdict and never makes a sandbox, so a final
- # deny the full review would not also refuse is a wrong refusal nobody gets to overturn.
+ # The server posts a final pre-check result as the verdict and never makes a sandbox, so a final
+ # result the full review would not also reach is a wrong verdict nobody gets to overturn.
monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
monkeypatch.setattr(review_local, "pr_provenance", lambda *a, **k: None)
outcome = review_local.pregate(context)
- assert outcome["final_deny"] is expect_final
+ assert outcome["final"] is (expect_verdict is not None)
assert outcome["needs_summary"] is expect_summary
- if not expect_final:
+ if expect_verdict is None:
assert outcome["result"] is None
+ assert outcome["not_final_reason"]
return
- assert outcome["result"]["final_verdict"] == "REFUSED"
+ assert outcome["result"]["final_verdict"] == expect_verdict
assert outcome["result"]["review_body"]
def approve(self, pr, classification, gate_context, diff_path=None):
return {"verdict": "APPROVE", "reasoning": "ok", "risk": "low", "issues": []}
monkeypatch.setattr(reviewer.Reviewer, "review", approve)
- assert review_local.run(context)["final_verdict"] == "REFUSED"
+ assert review_local.run(context)["final_verdict"] == expect_verdict
def test_pregate_refusal_reasoning_falls_back_to_the_gate_messages(monkeypatch) -> None:
@@ -638,3 +680,26 @@ def test_pregate_refusal_reasoning_falls_back_to_the_gate_messages(monkeypatch)
assert "deny-list: matches: infra_cicd" in fallback["reviewer"]["reasoning"]
assert summarized["reviewer"]["reasoning"] == "Terraform needs a human."
assert summarized["review_body"].startswith("Terraform needs a human.")
+
+
+def test_main_prints_the_result_with_phase_timings_as_its_last_line(monkeypatch, tmp_path, capsys) -> None:
+ # The server parses only the last stdout line, and reads the phase timings from it to split the
+ # sandbox's reviewer step into uv launch, LLM and exit time.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ monkeypatch.setattr(review_local, "pr_provenance", lambda *a, **k: None)
+
+ def approve(self, pr, classification, gate_context, diff_path=None):
+ return {"verdict": "APPROVE", "reasoning": "ok", "risk": "low", "issues": []}
+
+ monkeypatch.setattr(reviewer.Reviewer, "review", approve)
+ context_path = tmp_path / "context.json"
+ context_path.write_text(json.dumps(_run_context([_api_file("src/app.py")])))
+ monkeypatch.setenv(review_local.LAUNCHED_AT_ENV, str(review_local._now_ms() - 1500))
+ monkeypatch.setattr(sys, "argv", ["review_local.py", "--context", str(context_path)])
+
+ review_local.main()
+
+ result = json.loads(capsys.readouterr().out.strip().splitlines()[-1])
+ assert result["final_verdict"] == "APPROVED"
+ assert result["timings_ms"]["launch"] >= 1500
+ assert {"gates", "llm", "flush", "total"} <= set(result["timings_ms"])
diff --git a/products/stamphog/packages/pr-approval-agent/version.py b/products/stamphog/packages/pr-approval-agent/version.py
index 2ae25d0a5621..4237d8760024 100644
--- a/products/stamphog/packages/pr-approval-agent/version.py
+++ b/products/stamphog/packages/pr-approval-agent/version.py
@@ -9,4 +9,4 @@ changes don't need a bump - they are tracked by the policy sha shown next to
the version in the verdict table.
"""
-STAMPHOG_VERSION = "2.1.0"
+STAMPHOG_VERSION = "2.2.0"