:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "claude-agent-sdk==0.2.164",
# "anthropic==0.80.0",
# "openai==3.26.0",
# "posthoganalytics==7.20.4",
# "pyyaml==6.0.3",
# ]
# ///
# ruff: noqa: T201
"""Offline PR review entrypoint. The hosted sandbox runs this instead of review_pr.py.
review_pr.py is the manual entrypoint. It fetches everything over the network
(`gh`, GraphQL, git) and posts the verdict. This script runs the SAME engine
(gates, tier classification, git-blame familiarity, the LLM reviewer with the
same prompt and version) against a LOCAL checkout, with NO GitHub access and NO
token. The server holds the token, assembles every GitHub-sourced value that the
engine needs from the API, and passes them in through a `--context` JSON file.
Only one value flows back out: the JSON on the last stdout line, which is the
same `to_dict()` contract that review_pr.py emits with `--output-json`.
This script drives review_pr.Pipeline's own steps (classify, gates, the LLM
review, to_dict), so both entrypoints share one implementation of the engine
logic. It replaces only the steps that touch the network with injected data:
- _fetch (gh) becomes a PRData built from the context.
- The context injects the two `gh` calls that review_pr.py makes inside gate and
familiarity, which are the author-team membership lookup and the author's
merged-PR set. Familiarity's blame math is mirrored here with the injected PR
set (see _familiarity_offline), because Pipeline._compute_familiarity hardcodes
the `gh` fetch that only the networked entrypoint can make. The hosted server
also injects blame and history facts read from GitHub, which replace the git
history reads entirely (see _attach_familiarity).
The engine reads the trusted policy (`.stamphog/policy.yml`,
`.stamphog/review-guidance.md`) from the checkout at import time. The server
overwrites those paths in the checkout with the default-branch versions before
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 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.
`--attest` runs the same gates in the same tree before the server posts an approval (see attest()).
"""
import os
import json
import time
import argparse
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from familiarity import (
AuthorFamiliarity,
_band,
_blame_overlap,
_BlameOverlap,
_files_previously_modified,
_merge_base,
_parse_diff,
_prior_prs_in_paths,
_read_diff,
_select_considered_files,
familiarity_from_facts,
)
from gates import POLICY, assign_tier, dependency_manifests_without_lockfile, substantive_size
from gateway import SUMMARY_MODEL
from github import (
TRUSTED_REACTOR_BOTS,
CommitProvenance,
PRData,
_git_diff_files,
_normalize_discussion_for_prompt,
_normalize_reviews_for_prompt,
_prompt_worthy_author,
_reaction_emoji,
git_touched_paths,
is_bot_author,
pr_provenance,
provenance_from_messages,
)
from migration_risk import migration_check_pending
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.
github._git_diff_files uses git's --name-status letters (A/M/D/R/C); the
GitHub files API spells them out. Only used on the fallback path when the
local `git diff` produced nothing.
"""
return {
"added": "A",
"modified": "M",
"removed": "D",
"renamed": "R",
"copied": "C",
"changed": "M",
}.get(status, "M")
def _convert_api_file(f: dict) -> dict:
"""Convert a get_pr_files object into github._git_diff_files' file dict shape."""
additions = int(f.get("additions", 0) or 0)
deletions = int(f.get("deletions", 0) or 0)
# The files API omits an explicit binary flag; a changed file with no patch
# and no line counts is binary (or too large for GitHub to inline).
is_binary = f.get("patch") is None and additions == 0 and deletions == 0
return {
"filename": f.get("filename", ""),
"additions": additions,
"deletions": deletions,
"binary": is_binary,
"status": _api_file_status(str(f.get("status", "modified"))),
}
def _build_pr_data(context: dict, *, checkout: bool = True) -> PRData:
"""Build the engine's PRData from the injected context.
File stats are recomputed locally with the exact function that review_pr.py
uses (`git diff --numstat` over the PR range), so PRData.files is identical to
a networked run. The hosted server passes the merge base, because its shallow
checkout cannot compute one (see github.diff_range). The context's file list
is only a fallback for an empty local diff, which happens when a sha failed to
fetch. The context also
carries reviews, top-level discussion comments, and head-commit check runs.
Reviews and discussion are normalized with the same helpers that review_pr.py
uses, and check runs are passed through raw the same way. The prerequisite
gate therefore blocks on an active
CHANGES_REQUESTED, the agent sees maintainer discussion, and the migration
gate can see a passing "Migration risk" check. Inline review-thread comments
(a GraphQL-only surface with thread-resolution state) are carried when the
hosted context supplies "review_threads"; only UNRESOLVED threads flow into
the prompt, since an unresolved inline "do not merge" is the blocker the
reviewer must see, and resolved threads are noise. An absent key means an
empty list, which is a clean no-op and never a crash. A local review_pr.py
run does not pass the key.
Reactions on those inline comments are not carried, so they default empty.
``checkout=False`` is the server's gate-only pre-check, which has no git tree, so the file list
comes from the context alone.
"""
pr = context.get("pr") or {}
user = pr.get("user") or {}
base = pr.get("base") or {}
base_sha = context.get("base_sha") or base.get("sha") or ""
head_sha = context.get("head_sha") or (pr.get("head") or {}).get("sha") or ""
merge_base_sha = context.get("merge_base_sha") or ""
# Both feed PRData.stacked (the stacked-PR prompt note). A lean context without them reads as
# non-stacked, matching the Action's default.
default_branch = (base.get("repo") or {}).get("default_branch") or "master"
base_ref = base.get("ref") or default_branch
files = _git_diff_files(base_sha, head_sha, REPO_ROOT, merge_base_sha) if checkout else []
if files:
touched_paths = git_touched_paths(base_sha, head_sha, REPO_ROOT, merge_base_sha)
else:
api_files = context.get("files") or []
files = [_convert_api_file(f) for f in api_files]
touched_paths = [path for f in api_files for path in (f.get("filename"), f.get("previous_filename")) if path]
# Drop only EMPTY COMMENTED reviews from the offline reviews. A bare COMMENTED top-level review
# carries no readable body — yet _summarize_assurance would surface its author as a current-head
# reviewer ("head_commented"), reading as independent assurance. Unseen feedback must reduce to "no
# assurance," never a positive vouch. (Any inline feedback that review left still reaches the prompt
# via review_comments below, so dropping the empty top-level state loses nothing the reviewer needs.)
# A COMMENTED review WITH a body is different: that text is
# a maintainer's visible feedback (possibly a comment-only "hold"), and dropping it would let
# the reviewer approve without ever seeing it — it flows through, body and all.
reviews = [
r for r in (context.get("reviews") or []) if r.get("state") != "COMMENTED" or (r.get("body") or "").strip()
]
# Trusted-bot reactions only. The offline path has no token for the org-membership check that
# the networked reactor predicate performs, and the in-flight wait consumes only allowlisted bot
# 👀 in any case, because the code never waits on human reactions. REST content values
# lowercase-match the mapper.
author_login = user.get("login") or ""
pr_reactions = [
{"user": login, "emoji": _reaction_emoji(r.get("content", "")), "created_at": r.get("created_at")}
for r in context.get("pr_reactions") or []
if (login := r.get("user") or "") and login.lower() in TRUSTED_REACTOR_BOTS and login != author_login
]
# Flatten the injected inline review threads into the review_comments shape the reviewer prompt
# consumes. Only UNRESOLVED threads reach the prompt (see _build_pr_data's docstring); the full
# list stays in the context. Each comment passes the same author-trust gate as reviews and
# discussion — an untrusted external commenter must not plant a fake maintainer hold, and
# stamphog's own prior comments must not feed back as third-party claims. An absent key yields
# an empty list, so a local review_pr.py run, which does not pass the key, is unaffected and the
# prompt renders no inline-comments section.
review_comments: list[dict] = []
for thread in context.get("review_threads") or []:
if thread.get("is_resolved"):
continue
for index, comment in enumerate(thread.get("comments") or []):
if not _prompt_worthy_author(
comment.get("author"), comment.get("author_association"), bool(comment.get("author_is_bot"))
):
continue
# Real reply ids aren't carried in the lean shape; a truthy placeholder on the replies
# only marks reply-ness — the prompt's "(reply)" label and _summarize_assurance's
# "count threads (in_reply_to_id is None), not comments" semantic both key off it.
# Parity with the networked path (github.py): only the TRUE thread root (index 0) may
# carry None. When a filter removes the root (untrusted author, or stamphog's own
# finding), every survivor is a reply, so the thread contributes 0 to
# unresolved_threads. The networked path behaves the same way, because its surviving
# replies keep their real non-None replyTo ids.
review_comments.append(
{
"user": comment.get("author") or "ghost",
"body": comment.get("body", ""),
"path": thread.get("path", ""),
"line": thread.get("line"),
"in_reply_to_id": None if index == 0 else -1,
"is_resolved": False,
"is_outdated": bool(thread.get("is_outdated")),
"reactions": [],
}
)
review_evidence = [item for item in context.get("review_evidence") or [] if isinstance(item, dict)]
return PRData(
number=int(pr.get("number") or 0),
repo=context.get("repo") or "",
title=pr.get("title") or "",
state=pr.get("state") or "",
draft=bool(pr.get("draft")),
mergeable_state=pr.get("mergeable_state") or "unknown",
author=user.get("login") or "",
labels=[label.get("name", "") for label in pr.get("labels") or []],
base_ref=base_ref,
base_sha=base_sha,
head_sha=head_sha,
merge_base_sha=merge_base_sha,
files=files,
touched_paths=touched_paths,
reviews=_normalize_reviews_for_prompt(reviews, head_sha),
review_comments=review_comments,
check_runs=context.get("check_runs") or [],
author_is_bot=is_bot_author(user),
pr_reactions=pr_reactions,
body=pr.get("body") or "",
discussion=_normalize_discussion_for_prompt(context.get("discussion") or []),
default_branch=default_branch,
review_evidence=review_evidence,
)
def _context_provenance(context: dict, pr: PRData) -> CommitProvenance | None:
"""Commit-trailer provenance from the server's commit messages, else from `git log`.
The hosted server always sets ``commit_messages`` (null when GitHub could not list the commits
at the reviewed head), because its shallow checkout holds none of the PR's history. A context
without the key comes from a checkout with history, where `git log` reads the same trailers.
"""
if "commit_messages" in context:
messages = context["commit_messages"]
return None if messages is None else provenance_from_messages([str(m) for m in messages])
return pr_provenance(pr.base_sha, pr.head_sha, REPO_ROOT)
def _author_team_slugs(context: dict) -> set[str]:
"""Every team that the server found the author on, for the pipeline's membership checks.
review_pr.py asks GitHub once per team. The sandbox holds no token, so the server supplies the set.
It decides two things. The reviewer prompt reads `author_on_owning_team` with a default of True,
so the ownership summary must always set it. A deny category's `exempt_author_teams` reads it too.
An unresolvable lookup arrives as an empty set, which yields "not on any owning team" and denies
owner-only paths. review_pr.py fails in the same direction, and that direction is the safe one
for a bot that approves.
"""
return {str(slug) for slug in context.get("author_team_slugs") or []}
def _run_gates_offline(pipeline: Pipeline) -> None:
"""Run the four deterministic gate checks, the same ones that _run_gates runs.
Mirrors Pipeline._run_gates without the console output. Set `pipeline.author_team_slugs` first
(see _author_team_slugs), or the membership checks call `gh`, which the sandbox cannot do.
"""
gates = [
("prerequisites", pipeline._check_prerequisites),
("deny-list", pipeline._check_deny_list),
("size", pipeline._check_size),
("tier", pipeline._check_tier),
]
for name, check in gates:
passed, message = check()
pipeline.gate_results.append(GateResult(name, passed, message))
pipeline._summarize_ownership()
def _familiarity_offline(
author_prs: set[int],
diff_path: Path,
base_sha: str,
head_sha: str,
thresholds: FamiliarityPolicy,
*,
now: float | None = None,
) -> AuthorFamiliarity:
"""Mirror of familiarity.compute_familiarity with the author-PR set injected.
compute_familiarity fetches the author's merged-PR numbers with one `gh`
call, which is impossible in the tokenless sandbox — the server fetches them
and hands them in via the context instead. Everything else (blame overlap,
prior PRs, previously-modified files, banding) is the engine's own bounded
git logic, called here unchanged.
"""
now = time.time() if now is None else now
file_diffs = _parse_diff(_read_diff(diff_path))
considered, capped = _select_considered_files(file_diffs)
considered_paths = [f.path for f in considered if f.path]
blame_sha = _merge_base(base_sha, head_sha, REPO_ROOT)
overlap = (
_blame_overlap(considered, blame_sha, author_prs, REPO_ROOT)
if blame_sha is not None
else _BlameOverlap(owned_lines=0, total_lines=0, incomplete_files=0, top_prior_authors=())
)
blame_overlap_pct = (100.0 * overlap.owned_lines / overlap.total_lines) if overlap.total_lines else 0.0
prior_prs, days_since = _prior_prs_in_paths(considered_paths, author_prs, REPO_ROOT, now)
files_prev_count, files_total = _files_previously_modified(considered, author_prs, REPO_ROOT)
band = _band(blame_overlap_pct, prior_prs, days_since, thresholds)
return AuthorFamiliarity(
band=band,
blame_overlap_pct=blame_overlap_pct,
modified_lines_owned=overlap.owned_lines,
modified_lines_total=overlap.total_lines,
prior_prs_in_paths=prior_prs,
days_since_last_touch=days_since,
files_prev_count=files_prev_count,
files_total=files_total,
capped=capped,
blame_incomplete_files=overlap.incomplete_files,
top_prior_authors=overlap.top_prior_authors,
)
def _attach_familiarity(pipeline: Pipeline, context: dict) -> None:
"""Attach the author-familiarity signal for the T1-agent path only.
Same gating as Pipeline._maybe_compute_familiarity (T0 skips the LLM, T2 is a
deny, so neither benefits).
The hosted server always sets ``familiarity_facts``: the blame and history facts it read
from GitHub, or null when that failed or the run is an inbox review. Null leaves the signal
absent (a one-way ratchet), and never falls back to git, because the hosted checkout does
not carry the history that git blame needs. A context without the key comes from a runtime
that predates the server facts, so it keeps the git path. There, absent injected PR numbers
leave the signal None, exactly as a failed `gh` call would in review_pr.py.
"""
if pipeline.classification.get("tier") != "T1-agent":
return
author_prs = {int(n) for n in context.get("author_pr_numbers") or []}
if "familiarity_facts" in context:
facts = context["familiarity_facts"]
if not facts:
return
source = "server"
else:
if not author_prs:
return
source = "git"
diff_path = pipeline._ensure_diff_path()
try:
if source == "server":
fam = familiarity_from_facts(facts, pipeline.pr.author, author_prs, diff_path, POLICY.familiarity)
else:
fam = _familiarity_offline(
author_prs, diff_path, pipeline.pr.base_sha, pipeline.pr.head_sha, POLICY.familiarity
)
except Exception as exc:
print(f"warning: familiarity computation failed ({exc}); continuing without the signal")
return
# Telemetry reads pipeline.familiarity and the prompt reads the classification, so both are set.
pipeline.familiarity = fam
pipeline.familiarity_source = source
pipeline.classification["familiarity"] = fam
def _blocked_only_by_pending_migration_check(pipeline: Pipeline) -> bool:
"""True when only the unfinished migration analyzer keeps this PR from a review.
`Pipeline._only_pending_migration_check` cannot answer this. It disqualifies the PR on any
failing gate other than the deny-list, and a migrations deny always pulls the tier gate down to
T2-never as well. That method therefore returns False for every migration PR that it exists to
catch.
This function derives the tier again with the migrations deny removed, rather than special-casing
the gate. A PR that is T2 for another reason (breadth, size, a second deny) therefore stays
refused, and does not wait for a check that cannot change the outcome.
"""
pr = pipeline.pr
cl = pipeline.classification
if cl.get("deny_categories") != ["migrations"]:
return False
if not migration_check_pending(pr.check_runs, pr.file_paths):
return False
if any(not gate.passed and gate.gate not in ("deny-list", "tier") for gate in pipeline.gate_results):
return False
tier_without_migrations = assign_tier(
deny_categories=[],
allow_listed_only=bool(cl.get("allow_listed_only")),
is_test_only=bool(cl.get("is_test_only")),
has_new_files=pr.has_new_files,
lines_total=pr.lines_total,
files_changed=len(pr.files),
breadth=cl.get("breadth", ""),
commit_type=cl.get("commit_type"),
)
return tier_without_migrations != "T2-never"
# Gates the pre-check evaluates from the same inputs the sandbox uses, so a failure here is a
# failure there. The size gate is not in this set: see _size_denial_is_final.
_CHECKOUT_FREE_GATES = frozenset({"prerequisites", "deny-list", "tier"})
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.
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")
line_ceiling = max(POLICY.size_gate.max_lines, line_contract.ceiling if line_contract else 0)
file_ceiling = max(POLICY.size_gate.max_files, file_contract.ceiling if file_contract else 0)
return lines > line_ceiling or files > file_ceiling
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). 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, 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:
"""The refusal text when no LLM summary is available: the failing gates' own messages."""
failed = "\n".join(f"- {gate.gate}: {gate.message}" for gate in pipeline.gate_results if not gate.passed)
return (
f"stamphog's deterministic gates refused this PR, so no agent review ran. A human review is needed.\n\n{failed}"
)
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`` 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,
context.get("repo") or "",
self_driving=bool(context.get("self_driving_review")),
review_trigger=str(context.get("review_trigger") or ""),
head_checkout=True,
checkout=False,
)
pipeline.pr = _build_pr_data(context, checkout=False)
# Only the server's commit messages work here, because the pre-check tree is not a git
# repository. Without them, provenance stays null on the fast-path event.
if "commit_messages" in context:
pipeline.provenance = _context_provenance(context, pipeline.pr)
folder_policies_known = context.get("folder_policies_known") is True
outcome = {"final": False, "needs_summary": False, "summary_model": SUMMARY_MODEL, "result": None}
if pipeline.pr.author_is_bot and not pipeline.self_driving:
pipeline._refuse_bot_author()
return {**outcome, "final": True, "result": pipeline.to_dict()}
pipeline.author_team_slugs = _author_team_slugs(context)
pipeline._classify()
_run_gates_offline(pipeline)
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 = {
"verdict": "REFUSE",
"reasoning": str(context.get("refusal_reasoning") or "").strip() or _gate_refusal_reasoning(pipeline),
"risk": "unknown",
"issues": [],
}
pipeline._capture_review_completed("DENIED", "GATES-ONLY")
return {**outcome, "final": True, "needs_summary": True, "result": pipeline.to_dict()}
def attest(context: dict) -> dict:
"""Gate-only check that the hosted server runs before it posts an approval from the sandbox.
The sandbox prints its verdict and its gate results on stdout, and the server cannot authenticate
that output. So the server runs the deterministic gates again on the worker, under the trusted
policy and on the file list it read from GitHub. ``attested`` is True only when this run reaches
every condition that the sandbox needs before it may ask the LLM: no refused bot author, every
gate passed, and no reviewer in flight. ``reason`` names the first condition that failed.
Two inputs come from the checkout in the sandbox, so an unknown value fails the check rather
than guessing. The folder files can lower a size ceiling, so ``folder_policies_known`` must be
set. The manifest scripts scan can add a deny, so each dependency manifest without its lockfile
needs its texts in ``manifest_contents``. Without them the reason is ``dependency_manifest``,
and ``manifests`` names the paths for the server to read and pass in on a second run.
"""
pipeline = Pipeline(
0,
context.get("repo") or "",
self_driving=bool(context.get("self_driving_review")),
review_trigger=str(context.get("review_trigger") or ""),
head_checkout=True,
checkout=False,
)
pipeline.pr = _build_pr_data(context, checkout=False)
def outcome(reason: str) -> dict:
gates = [{"gate": g.gate, "passed": g.passed, "message": g.message} for g in pipeline.gate_results]
return {"attested": not reason, "reason": reason, "gates": gates}
if pipeline.pr.author_is_bot and not pipeline.self_driving:
return outcome("bot_author")
if context.get("folder_policies_known") is not True:
return outcome("folder_policies_unknown")
manifests = dependency_manifests_without_lockfile(pipeline.pr.file_paths)
manifest_contents = context.get("manifest_contents")
if manifests:
if not isinstance(manifest_contents, dict) or any(path not in manifest_contents for path in manifests):
return {**outcome("dependency_manifest"), "manifests": manifests}
pipeline.manifest_contents = manifest_contents
pipeline.author_team_slugs = _author_team_slugs(context)
pipeline._classify()
_run_gates_offline(pipeline)
if any(not gate.passed for gate in pipeline.gate_results):
return outcome("gate_failed")
if pipeline._in_flight_bot_reviewers() or pipeline.pr.pending_review_evidence():
return outcome("review_in_flight")
return outcome("")
def run(context: dict) -> dict:
"""Run the full offline review and return the to_dict() contract."""
# The hosted server sets self_driving_review only for PRs it verified came from a self-driving
# Inbox implementation run. Action contexts never carry it, so bot authors are refused as before.
# head_checkout: the sandbox clones and checks out the PR head before this runs (see the server's
# _clone_pr), so parent-PR symbols already resolve for stacked PRs and no worktree is needed.
pipeline = Pipeline(
0,
context.get("repo") or "",
self_driving=bool(context.get("self_driving_review")),
review_trigger=str(context.get("review_trigger") or ""),
head_checkout=True,
)
pipeline.pr = _build_pr_data(context)
# Without this, the agent-authorship evidence and the stamphog_review_completed provenance
# properties are null for every hosted review.
pipeline.provenance = _context_provenance(context, pipeline.pr)
if pipeline.pr.author_is_bot and not pipeline.self_driving:
pipeline._refuse_bot_author()
return pipeline.to_dict()
try:
with _timed_phase("gates"):
pipeline.author_team_slugs = _author_team_slugs(context)
pipeline._classify()
_run_gates_offline(pipeline)
gate_verdict = pipeline._gate_verdict()
# A `Migration risk` check that has not reported yet is a race with CI, and not a judgment
# on the PR. The deny-list matched only because the engine cannot yet tell a safe migration
# from a risky one. The verdict is WAIT rather than REFUSE because the hosted runtime routes
# every refusal to a ReviewHog handoff and strips the trigger label. A refusal would
# therefore escalate a transient check to a second review agent, and force the author to
# re-request the review that it displaced.
if _blocked_only_by_pending_migration_check(pipeline):
pipeline.final_verdict = "WAIT"
pipeline.reviewer_output = _pending_migration_wait()
pipeline._capture_review_completed(gate_verdict, "PENDING-MIGRATION-CHECK")
return pipeline.to_dict()
# Mirror review_pr.py's in-flight reviewer-bot handling, minus the wait: there is no token in
# the sandbox to poll with, and the SERVER already waited out the race (workflow bot-wait
# loop) and refreshed this snapshot before provisioning. Bots still showing fresh 👀 here
# mean the server's budget expired — WAIT, never approve over an unfinished review. Gate
# denials skip the check, same as review_pr.py: a refusal can't approve over anything.
if gate_verdict != "DENIED" and (in_flight := pipeline._in_flight_bot_reviewers()):
bot_list = ", ".join(f"@{b}" for b in in_flight)
pipeline.final_verdict = "WAIT"
pipeline.reviewer_output = {
"verdict": "WAIT",
"reasoning": (
f"{bot_list} still {'have' if len(in_flight) > 1 else 'has'} a review in flight (👀) — "
"not approving over an unfinished review. The review re-runs on the next push, or "
"re-request one once the reviewer finishes."
),
"risk": "unknown",
"issues": [],
}
return pipeline.to_dict()
# The server waited for these reviews too, so a review still pending here outlasted the
# server's budget. Same answer as an in-flight bot: WAIT, never approve over it.
if gate_verdict != "DENIED" and (pending := pipeline.pr.pending_review_evidence()):
reviewers = " and ".join(str(item.get("reviewer")) for item in pending)
verb = "are" if len(pending) > 1 else "is"
pipeline.final_verdict = "WAIT"
pipeline.reviewer_output = {
"verdict": "WAIT",
"reasoning": (
f"{reviewers} {verb} still reviewing this commit, so stamphog does not approve yet. "
"The review runs again on the next push, or you can re-request it once that review finishes."
),
"risk": "unknown",
"issues": [],
}
return pipeline.to_dict()
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)
return pipeline.to_dict()
def _escalate_result(context: dict, exc: Exception) -> dict:
"""A minimal, parseable escalate outcome for an unexpected internal failure.
Keeps the last-line contract intact so the server parses a defined verdict
(escalate, never a silent approval) rather than choking on a stack trace.
"""
pr = context.get("pr") or {}
return {
"stamphog_version": STAMPHOG_VERSION,
"pr_number": pr.get("number"),
"repo": context.get("repo") or "",
"classification": {},
"gates": [],
"policy": {},
"reviewer": {
"verdict": "ESCALATE",
"reasoning": "The review agent could not complete its analysis — escalating for a human.",
"risk": "high",
"issues": [str(exc)],
},
"review_body": None,
"final_verdict": "ESCALATE",
}
def main() -> None:
parser = argparse.ArgumentParser(description="Offline PR review (sandbox entrypoint)")
parser.add_argument("--context", required=True, help="Path to the review context JSON")
parser.add_argument("--repo-dir", default=None, help="Checkout directory (defaults to cwd)")
parser.add_argument("--pregate", action="store_true", help="Gates only, no checkout and no LLM (server pre-check)")
parser.add_argument(
"--attest", action="store_true", help="Gates only, no checkout and no LLM (server check before an approval)"
)
args = parser.parse_args()
if args.repo_dir:
os.chdir(args.repo_dir)
context = json.loads(Path(args.context).read_text())
if args.pregate:
# No escalate fallback here: a crash exits non-zero, and the server falls through to the full
# review, which is the safe answer for a check that can only shorten the path to a refusal.
pregate_result = pregate(context)
flush_analytics()
print(json.dumps(pregate_result), flush=True)
return
if args.attest:
# A crash exits non-zero, and the server treats that as a failed check and posts no approval.
print(json.dumps(attest(context)), 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
result = _escalate_result(context, exc)
# 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.
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)
if __name__ == "__main__":
main()