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.

55.6 KB
Raw Blame
#!/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
"""AI-assisted PR approval agent.

Usage:
    uv run products/stamphog/packages/pr-approval-agent/review_pr.py <pr_number> [--dry-run] [--output-json path]

Runs deterministic gates (deny-list, ownership, tier classification),
then — if eligible — calls the LLM reviewer for an evidence-bundle review.

Requires `gh` CLI authenticated and OPENAI_API_KEY in env (or ANTHROPIC_API_KEY
with STAMPHOG_REVIEWER_ENGINE=claude for the rollback reviewer).
"""

import os
import json
import time
import uuid
import argparse
import tempfile
import subprocess
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING

from familiarity import AuthorFamiliarity, compute_familiarity, familiarity_evidence
from gates import (
    DENY_EXEMPT_AUTHOR_TEAMS,
    MAX_FILES,
    MAX_LINES,
    POLICY,
    assign_tier,
    build_ownership,
    category_fully_exempt,
    classify_files,
    dependency_manifests_without_lockfile,
    detect_deny_categories,
    detect_ownership,
    detect_title_scrutiny_flags,
    has_ci_workflow_changes,
    has_dependency_changes,
    is_allow_listed_only,
    manifest_basenames,
    parse_conventional_commit,
    scope_breadth,
    substantive_size,
    t1_risk_subclass,
    test_only,
)
from gateway import CLAUDE_ENGINE, analytics_extra_properties, reviewer_engine
from github import (
    CommitProvenance,
    PRData,
    check_team_membership,
    describe_review_evidence,
    fetch_pr,
    is_in_flight_bot_eyes,
    pr_provenance,
    provenance_evidence,
    write_pr_diff,
)
from manifest_risk import manifest_script_changes, manifest_script_changes_from_contents
from migration_risk import migration_check_pending, safe_migration_files
from policy import EffectivePolicy, ScopeBudget, _sanitize_untrusted, repo_root, resolve
from verdict_rule import facts_summary
from version import STAMPHOG_VERSION

if TYPE_CHECKING:
    from reviewer import Reviewer

try:
    import posthoganalytics

    posthoganalytics.api_key = os.environ.get("POSTHOG_API_KEY", "")  # ty: ignore[invalid-assignment]
    posthoganalytics.host = os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com")  # ty: ignore[invalid-assignment]
    _POSTHOG_AVAILABLE = bool(posthoganalytics.api_key)
except ImportError:
    _POSTHOG_AVAILABLE = False


def flush_analytics() -> None:
    """Flush buffered capture events; a no-op without a configured client.

    The capture client batches in a background thread — without an explicit flush,
    events queued near process exit are silently dropped.
    """
    if _POSTHOG_AVAILABLE:
        posthoganalytics.flush()


# ── Repo root detection ──────────────────────────────────────────

REPO_ROOT = repo_root()


def _head_commit_sha() -> str:
    """HEAD sha of the checked-out policy tree, or 'unknown' if git is unavailable."""
    try:
        result = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=REPO_ROOT,
            capture_output=True,
            text=True,
            timeout=10,
        )
    except (OSError, subprocess.SubprocessError):
        return "unknown"
    return result.stdout.strip() if result.returncode == 0 else "unknown"


# ── Terminal formatting ──────────────────────────────────────────


def _ok(msg: str) -> str:
    return f"  \033[32m✓\033[0m {msg}"


def _warn(msg: str) -> str:
    return f"  \033[33m⚠\033[0m {msg}"


def _fail(msg: str) -> str:
    return f"  \033[31m✗\033[0m {msg}"


def _bold(msg: str) -> str:
    return f"\033[1m{msg}\033[0m"


def _dim(msg: str) -> str:
    return f"\033[2m{msg}\033[0m"


# ── Error classification ─────────────────────────────────────────

# Patterns that indicate non-retryable failures (agent limitations, not infra).
_NON_RETRYABLE_PATTERNS = (
    "Reached maximum number of turns",
    "could not produce valid structured output",
    # A retry starts with the same spent budget and fails at once.
    "time budget exhausted",
)


class WorktreeUnavailableError(RuntimeError):
    """The PR head tree required for a stacked review could not be created."""


def _llm_usage_properties(reviewer_output: dict | None) -> dict[str, object]:
    """Token usage the reviewer reported, as event properties, or {} when it reported none.

    Only the OpenAI reviewer reports usage. The Claude reviewer's usage reaches analytics through
    the gateway's $ai_generation events instead.
    """
    usage = (reviewer_output or {}).get("usage")
    if not isinstance(usage, dict):
        return {}
    return {f"stamphog_llm_{name}": value for name, value in usage.items()}


def _is_retryable_error(err_msg: str) -> bool:
    """Return True if the error looks like an infrastructure/transient issue
    that is worth retrying (API timeouts, rate limits, overload).
    Return False for non-retryable errors like turn-limit exhaustion."""
    return not any(pattern in err_msg for pattern in _NON_RETRYABLE_PATTERNS)


# Reviewer bots put 👀 on a PR while reviewing and swap it for a verdict
# reaction within minutes. Stamphog is usually triggered at the same moment
# (label applied at PR open), so an 👀 at fetch time is almost always a race
# with a bot mid-review, not a lasting state — poll until it clears instead
# of refusing. Budget must leave room for the LLM review inside the
# workflow job timeout.
BOT_REVIEW_WAIT_BUDGET_SECONDS = 300
BOT_REVIEW_POLL_SECONDS = 30


# ── Gate result ──────────────────────────────────────────────────


@dataclass
class GateResult:
    gate: str
    passed: bool
    message: str
    details: dict = field(default_factory=dict)


def _describe_deny_category(category: str) -> str:
    """Name a denied category, and for an owner-only one, the teams that stamphog approves there."""
    teams = DENY_EXEMPT_AUTHOR_TEAMS.get(category)
    if not teams:
        return category
    return f"{category} (stamphog approves these paths only for authors on {', '.join(teams)})"


# ── Pipeline ─────────────────────────────────────────────────────


class Pipeline:
    """Orchestrates the full PR review: fetch → classify → gates → LLM review."""

    def __init__(
        self,
        pr_number: int,
        repo: str,
        *,
        dry_run: bool = False,
        verbose: bool = False,
        self_driving: bool = False,
        review_trigger: str = "",
        head_checkout: bool = False,
        checkout: bool = True,
    ) -> None:
        self.pr_number = pr_number
        self.repo = repo
        self.dry_run = dry_run
        self.verbose = verbose
        # Set only by the hosted runtime, for PRs it verified came from a self-driving Inbox
        # implementation run. It relaxes two gates (bot author, draft) and swaps author trust for
        # task provenance.
        self.self_driving = self_driving
        # Why the hosted runtime is reviewing this PR: "label", "all" or "self_driving". Descriptive
        # only. It reaches the prompt as one line and gates nothing, unlike self_driving above.
        # Empty for a local run, which has no trigger to report.
        self.review_trigger = review_trigger
        # True when REPO_ROOT already holds the PR head (the hosted sandbox clones and checks out
        # the head for every review). The Action reviews from a trunk checkout, so a stacked PR
        # needs a separate head worktree there — see _pr_head_worktree.
        self.head_checkout = head_checkout
        # False only for the hosted server's gate-only pre-check, which runs on the PR context with no
        # git tree. The manifest scripts scan reads file text from git, so it is skipped there. That
        # can only miss a deny, never add one, and the sandbox review runs the scan again.
        self.checkout = checkout
        # Manifest texts at the merge base and the head, keyed by path, which the server's gate check
        # reads from GitHub so that it can run the scripts scan without a checkout.
        self.manifest_contents: dict[str, dict[str, str]] | None = None
        # Every GitHub team the author is on, set by the hosted runtime because the sandbox holds no
        # token. None means a local run, which asks GitHub per team instead.
        self.author_team_slugs: set[str] | None = None
        self._wait_refetched_pr = False
        self.pr: PRData | None = None
        self.provenance: CommitProvenance | None = None
        self.familiarity: AuthorFamiliarity | None = None
        # Where the familiarity signal came from: "git" (local history), "server" (GitHub facts the
        # hosted server injected), or "absent". Telemetry only, so a band shift can be traced to
        # its source.
        self.familiarity_source = "absent"
        self.classification: dict = {}
        self.effective_policy: EffectivePolicy | None = None
        self._diff_path: Path | None = None
        self.gate_results: list[GateResult] = []
        self.reviewer_output: dict | None = None
        # Empty until an LLM reviewer starts, so a gate-only verdict names no engine.
        self.reviewer_engine = ""
        self.final_verdict: str = ""

    def run(self) -> str:
        """Run the full pipeline, return final verdict string."""
        self._fetch()

        if self.pr.author_is_bot and not self.self_driving:
            return self._refuse_bot_author()

        gate_verdict = self._classify_and_gate()

        if self._only_pending_migration_check():
            return self._refuse_pending_migration_check()

        if self.dry_run:
            self.final_verdict = "DRY-RUN"
            return self.final_verdict

        # Gate denials skip the wait: a refusal can't approve over an
        # in-flight review, so waiting would only burn runner minutes before
        # the inevitable REFUSE. The wait refetches the PR, so on the paths
        # that did wait, re-derive classification and gates from fresh data.
        if gate_verdict != "DENIED":
            wait_verdict = self._handle_in_flight_bot_reviews()
            if wait_verdict:
                return wait_verdict
            if self._wait_refetched_pr:
                gate_verdict = self._classify_and_gate()
                if self._only_pending_migration_check():
                    return self._refuse_pending_migration_check()

        try:
            self._maybe_compute_familiarity()
            self._llm_review(gate_verdict)
        finally:
            if self._diff_path is not None:
                self._diff_path.unlink(missing_ok=True)
        return self.final_verdict

    def _classify_and_gate(self) -> str:
        self.gate_results = []
        self._classify()
        self._run_gates()
        return self._gate_verdict()

    def _only_pending_migration_check(self) -> bool:
        """True when the only thing blocking approval is a pending Migration risk check.

        Lets us emit a specific deny reason ("wait for the check, re-label")
        instead of the generic deny-list one. Other denies (auth, crypto) or
        gate failures (size, prerequisites) won't clear when the analyzer
        finishes, so we shouldn't promise a re-label will help.
        """
        if self.classification.get("deny_categories", []) != ["migrations"]:
            return False
        if any(not r.passed and r.gate != "deny-list" for r in self.gate_results):
            return False
        return migration_check_pending(self.pr.check_runs, self.pr.file_paths)

    def _refuse_bot_author(self) -> str:
        """Hard gate: stamphog never reviews bot-authored PRs.

        A human applying the stamphog label can't override this — bot output
        isn't a trusted basis for an auto-approval. The workflow already gates
        the review job on a non-bot author; this is the defense-in-depth layer
        for any manual or out-of-band invocation.
        """
        self.final_verdict = "REFUSED"
        self.reviewer_output = {
            "verdict": "REFUSE",
            "reasoning": (
                f"@{self.pr.author} is a bot — stamphog does not review "
                "bot-authored PRs. This change needs a human reviewer."
            ),
            "risk": "unknown",
            "issues": [],
        }
        print(f"\n{_fail('REFUSED')} — bot author (@{self.pr.author}); stamphog skips bot-authored PRs")
        self._capture_review_completed("DENIED", "BOT-AUTHOR")
        return self.final_verdict

    def _in_flight_bot_reviewers(self) -> list[str]:
        """Allowlisted reviewer bots with a fresh 👀 reaction on the PR."""
        return sorted({r["user"] for r in self.pr.pr_reactions if is_in_flight_bot_eyes(r)})

    def _handle_in_flight_bot_reviews(self) -> str | None:
        """Wait out the reviewer-bot 👀 race; WAIT if a bot is still reviewing.

        Returns None when no bot review is (or remains) in flight. Human 👀
        reactions are not waited on — humans take longer than any polling
        budget, and the LLM refuses over them with a clear message instead.
        The WAIT verdict keeps the stamphog label (like ERROR) so the review
        retries on the next push rather than demanding a human re-label.
        """
        bots = self._in_flight_bot_reviewers()
        if not bots:
            return None

        deadline = time.monotonic() + BOT_REVIEW_WAIT_BUDGET_SECONDS
        while time.monotonic() < deadline:
            print(_warn(f"in-flight bot review ({', '.join(bots)}) — waiting {BOT_REVIEW_POLL_SECONDS}s"))
            time.sleep(BOT_REVIEW_POLL_SECONDS)
            try:
                self._fetch()
            except Exception as exc:
                print(_warn(f"refetch failed ({exc}); treating as still in flight"))
                continue
            self._wait_refetched_pr = True
            bots = self._in_flight_bot_reviewers()
            if not bots:
                return None

        bot_list = ", ".join(f"@{b}" for b in bots)
        self.final_verdict = "WAIT"
        self.reviewer_output = {
            "verdict": "WAIT",
            "reasoning": (
                f"{bot_list} still {'have' if len(bots) > 1 else 'has'} a review in flight (👀) after "
                f"{BOT_REVIEW_WAIT_BUDGET_SECONDS // 60} minutes — not approving over an "
                "unfinished review. The `stamphog` label has been kept; the review re-runs "
                "on the next push, or remove and re-apply the label once the reviewer finishes."
            ),
            "risk": "unknown",
            "issues": [],
        }
        print(f"\n{_warn('WAIT')} — bot review still in flight ({bot_list}); label retained for retry")
        self._capture_review_completed("SKIPPED", "WAIT")
        return self.final_verdict

    def _refuse_pending_migration_check(self) -> str:
        self.final_verdict = "REFUSED"
        self.reviewer_output = {
            "verdict": "REFUSE",
            "reasoning": (
                "The `Migration risk` check has not completed for this commit. "
                "Wait for it to finish (visible in the PR's Checks tab), then "
                "re-apply the `stamphog` label to retry."
            ),
            "risk": "unknown",
            "issues": [],
        }
        print(f"\n{_warn('REFUSED')} — Migration risk check pending; re-label after it completes")
        self._capture_review_completed("DENIED", "PENDING-MIGRATION-CHECK")
        return self.final_verdict

    def _gate_verdict(self) -> str:
        """Determine what gates say — this is authoritative."""
        if self._any_gate_denied():
            return "DENIED"
        if self.classification["tier"] == "T0-deterministic":
            return "AUTO-APPROVED"
        return "PENDING"

    # ── Steps ────────────────────────────────────────────────────

    def _fetch(self) -> None:
        print(_dim("Fetching PR data..."))
        self.pr = fetch_pr(self.pr_number, self.repo, repo_root=REPO_ROOT)
        self.provenance = pr_provenance(self.pr.base_sha, self.pr.head_sha, REPO_ROOT)
        print(_dim(f"  {self.pr.title}"))
        print(
            _dim(
                f"  by @{self.pr.author} | {self.pr.state} | {len(self.pr.files)} files | {len(self.pr.review_comments)} comments"
            )
        )
        print()

    def _classify(self) -> None:
        pr = self.pr
        file_paths = pr.file_paths
        file_info = classify_files(file_paths)
        categories = file_info["categories"]
        top_dirs = file_info["top_dirs"]
        breadth = scope_breadth(top_dirs)
        cc = parse_conventional_commit(pr.title)
        safe_migrations = safe_migration_files(pr.check_runs, file_paths)
        deny = detect_deny_categories(pr.deny_paths, ignored_files=safe_migrations)
        exception_lifted = bool(POLICY.deny_exceptions) and (
            detect_deny_categories(pr.deny_paths, ignored_files=safe_migrations, apply_exceptions=False) != deny
        )
        dep_manifests = dependency_manifests_without_lockfile(file_paths)
        # Deterministic first line for the manifest scripts risk: an edit to
        # scripts/lifecycle/build keys hard-denies rather than resting solely
        # on the reviewer prompt's REFUSE instruction.
        if not dep_manifests:
            risky_manifests = []
        elif self.checkout:
            risky_manifests = manifest_script_changes(
                dep_manifests, pr.base_sha, pr.head_sha, REPO_ROOT, pr.merge_base_sha
            )
        elif self.manifest_contents is not None:
            risky_manifests = manifest_script_changes_from_contents(dep_manifests, self.manifest_contents)
        else:
            risky_manifests = []
        if risky_manifests and "deps_toolchain" not in deny:
            deny = sorted([*deny, "deps_toolchain"])
        denied_before_exemptions = len(deny)
        deny = [
            category
            for category in deny
            if not any(self._author_on_team(team) for team in DENY_EXEMPT_AUTHOR_TEAMS.get(category, ()))
        ]
        owner_exempted = len(deny) < denied_before_exemptions
        title_flags = [
            c
            for c in detect_title_scrutiny_flags(pr.title)
            if c not in deny and not category_fully_exempt(c, file_paths)
        ]
        # Dependency manifests are .json/.toml/.cfg so they'd otherwise ride
        # the allow-list into the T0 fast path — but manifest scripts execute
        # in CI, so they get full T1 scrutiny even though they no longer deny.
        # Both checks matter: has_dependency_changes catches lockfile-paired
        # manifests, dependency_manifests_without_lockfile catches the rest
        # (tsconfig, setup.py/.cfg) that the reviewer's scripts guard covers.
        # An owner-only exemption lifts the deny, not the review: a workflow is .yml,
        # so without this it rides the allow-list to a T0 approval with no reviewer.
        allow_only = (
            is_allow_listed_only(file_paths)
            and not has_dependency_changes(file_paths)
            and not dep_manifests
            and not owner_exempted
            and not exception_lifted
        )
        is_test = test_only(categories) and not owner_exempted and not exception_lifted
        ownership_resolvers = build_ownership(REPO_ROOT, POLICY.ownership)
        ownership = detect_ownership(file_paths, ownership_resolvers)

        tier = assign_tier(
            deny_categories=deny,
            allow_listed_only=allow_only,
            is_test_only=is_test,
            has_new_files=pr.has_new_files,
            lines_total=pr.lines_total,
            files_changed=len(file_paths),
            breadth=breadth,
            commit_type=cc["type"],
        )
        subclass = ""
        if tier == "T1-agent":
            subclass = t1_risk_subclass(
                lines_total=pr.lines_total,
                files_changed=len(file_paths),
                breadth=breadth,
            )

        # Resolve any per-folder override for this PR's file set once. Its
        # effective size gate feeds _check_size; its advisory prose (untrusted)
        # is threaded to the reviewer prompt; its provenance goes in the bundle.
        self.effective_policy = resolve(POLICY, file_paths)

        self.classification = {
            "tier": tier,
            "t1_subclass": subclass,
            "breadth": breadth,
            "commit_type": cc["type"],
            "commit_scope": cc["scope"],
            "categories": categories,
            "deny_categories": deny,
            "title_scrutiny_flags": title_flags,
            "safe_migration_files": sorted(safe_migrations),
            "allow_listed_only": allow_only,
            "is_test_only": is_test,
            "has_dep_changes": has_dependency_changes(file_paths),
            "dep_manifests_without_lockfile": dep_manifests,
            "manifest_script_changes": risky_manifests,
            "has_ci_changes": has_ci_workflow_changes(file_paths),
            "ownership": ownership,
            "folder_policy_prose": self.effective_policy.folder_prose,
            "assurance": self._summarize_assurance(),
            # Judgment-layer signal for the reviewer prompt, attached later on
            # the T1-agent path only (see _maybe_compute_familiarity). None here
            # keeps the other paths' prompts byte-identical to before.
            "familiarity": None,
            # False renders the provenance block empty, leaving every other prompt unchanged.
            # True swaps the author trust context for task provenance.
            "self_driving": self.self_driving,
            "review_trigger": self.review_trigger,
        }

    def _author_on_team(self, team_slug: str) -> bool:
        if self.author_team_slugs is not None:
            return team_slug in self.author_team_slugs
        return check_team_membership(self.repo.split("/")[0], self.pr.author, team_slug)

    def _summarize_assurance(self) -> dict:
        """Deterministic pre-digest of review state for the TRUSTED prompt block.

        Derived only from GitHub review metadata (states, head-ness) and the
        hosted server's external review evidence — never author-controlled text —
        so the reviewer gets a trustworthy at-a-glance summary of who has
        actually vouched for the current head.
        """
        pr = self.pr
        # Exclude the author's own reviews: an author commenting on or replying
        # within their own PR records a COMMENTED review at head, which would
        # otherwise surface as "<author> reviewed the current head." Self-review
        # is never independent assurance, so it must not read as a vouch — to the
        # human in the review body or to the LLM in the trusted prompt block.
        head_approvals = sorted(
            {
                r["user"]
                for r in pr.reviews
                if r.get("is_current_head") and r.get("state") == "APPROVED" and r["user"] != pr.author
            }
        )
        head_commented_users = sorted(
            {
                r["user"]
                for r in pr.reviews
                if r.get("is_current_head") and r.get("state") == "COMMENTED" and r["user"] != pr.author
            }
        )
        # Count unresolved conversations, not flattened comments: replies inherit
        # the thread's resolution state, so a single 4-reply thread must read as
        # one unresolved thread, not five unresolved comments.
        unresolved_threads = sum(
            1
            for c in pr.review_comments
            if c.get("in_reply_to_id") is None and not c.get("is_resolved") and not c.get("is_outdated")
        )
        return {
            "head_approvals": head_approvals,
            "head_commented_users": head_commented_users,
            "head_commented": len(head_commented_users),
            "unresolved_threads": unresolved_threads,
            "discussion": len(pr.discussion),
            # A completed external review of this head counts like a current-head review. Its
            # published findings are review threads, so unresolved_threads above already holds them.
            "head_review_evidence": pr.completed_review_evidence(),
        }

    def _maybe_compute_familiarity(self) -> None:
        """Compute the author-familiarity signal on every LLM-reviewed run.

        Judgment layer only - never touches gates, and any failure leaves the
        signal absent (None). The reviewer prompt receives it on the T1-agent
        path only (T0 auto-approves and T2 is a deny, so their prompts stay
        unchanged); telemetry captures it from every run so familiarity can be
        trended per subsystem, not just where the reviewer consumes it.
        """
        self.familiarity = self._compute_familiarity()
        if self.familiarity is not None:
            self.familiarity_source = "git"
        if self.classification.get("tier") == "T1-agent":
            self.classification["familiarity"] = self.familiarity

    def _compute_familiarity(self) -> AuthorFamiliarity | None:
        pr = self.pr
        try:
            return compute_familiarity(
                author_login=pr.author,
                diff_path=self._ensure_diff_path(),
                base_sha=pr.base_sha,
                head_sha=pr.head_sha,
                repo=self.repo,
                repo_root=REPO_ROOT,
                thresholds=POLICY.familiarity,
            )
        except Exception as exc:
            print(_warn(f"familiarity computation failed ({exc}); continuing without the signal"))
            return None

    def _ensure_diff_path(self) -> Path:
        """Write the PR diff once per run; familiarity and the reviewer share it.

        One producer keeps the two consumers grading the same diff. run() owns
        cleanup so the file never lingers in the repo working tree.
        """
        if self._diff_path is None:
            self._diff_path = write_pr_diff(self.pr.base_sha, self.pr.head_sha, REPO_ROOT, self.pr.merge_base_sha)
        return self._diff_path

    def _run_gates(self) -> None:
        print(_bold("Gates"))
        gates = [
            ("prerequisites", self._check_prerequisites),
            ("deny-list", self._check_deny_list),
            ("size", self._check_size),
            ("tier", self._check_tier),
        ]
        for name, check in gates:
            passed, message = check()
            result = GateResult(name, passed, message)
            self.gate_results.append(result)
            print(_ok(f"{name}: {message}") if passed else _fail(f"{name}: {message}"))

        ownership = self._summarize_ownership()
        print(_dim(f"  ownership: {ownership}"))

    def _any_gate_denied(self) -> bool:
        return any(not r.passed for r in self.gate_results)

    def _check_prerequisites(self) -> tuple[bool, str]:
        pr = self.pr
        issues = []
        # Self-driving PRs are reviewed while still draft so the verdict is ready at Inbox triage
        # time. The approval is pinned to the head SHA, so it holds when the PR flips to ready.
        if pr.draft and not self.self_driving:
            issues.append("PR is still in draft")
        if pr.mergeable_state == "dirty":
            issues.append("merge conflicts present")

        latest_review_per_user: dict[str, str] = {}
        for r in pr.reviews:
            latest_review_per_user[r["user"]] = r["state"]
        changes_requested = [u for u, s in latest_review_per_user.items() if s == "CHANGES_REQUESTED"]
        if changes_requested:
            issues.append(f"changes requested by: {', '.join(changes_requested)}")

        # CI failures are not a hard gate — CI is its own gate and the
        # agent is often triggered before all checks finish.

        if issues:
            return False, "; ".join(issues)
        return True, "all clear"

    def _check_deny_list(self) -> tuple[bool, str]:
        deny = self.classification["deny_categories"]
        matches = ", ".join(_describe_deny_category(c) for c in deny)
        risky = self.classification.get("manifest_script_changes", [])
        if risky:
            risky_names = ", ".join(manifest_basenames(risky))
            return False, f"matches: {matches} (scripts/hooks changed in {risky_names})"
        if deny:
            return False, f"matches: {matches}"
        return True, "no deny categories matched"

    def _summarize_ownership(self) -> str:
        """Build ownership context for the LLM (not a hard gate)."""
        ownership = self.classification["ownership"]
        individuals = ownership.get("individuals", [])
        if ownership["team_count"] == 0 and not individuals:
            self.classification["ownership_summary"] = "no owned paths touched"
            return self.classification["ownership_summary"]

        teams = ownership["teams"]
        author = self.pr.author
        author_teams = []
        for team_raw in teams:
            if self._author_on_team(team_raw.split("/")[-1]):
                author_teams.append(team_raw)

        parts = []
        if teams:
            parts.append(f"touches {', '.join(teams)}")
        if individuals:
            # Individuals never enter the membership check — the author simply
            # is or isn't one of them.
            suffix = f" (author {author} is one of them)" if f"@{author}" in individuals else ""
            parts.append(f"individually owned by {', '.join(individuals)}{suffix}")
        if author_teams:
            parts.append(f"author {author} is on {', '.join(author_teams)}")
        elif teams:
            parts.append(f"author {author} is not on any owning team")
        if ownership.get("cross_team"):
            parts.append("cross-team change")

        self.classification["ownership_summary"] = "; ".join(parts)
        self.classification["author_on_owning_team"] = len(author_teams) > 0
        return self.classification["ownership_summary"]

    def _check_size(self) -> tuple[bool, str]:
        lines, files = substantive_size(self.pr.files)
        binary_count = sum(1 for f in self.pr.files if f.get("binary"))
        exempt_files = len(self.pr.files) - files
        suffix_parts = []
        if binary_count:
            suffix_parts.append(f"{binary_count} binary")
        if exempt_files:
            suffix_parts.append(f"{self.pr.lines_total}L/{len(self.pr.files)}F incl. docs/generated/snapshots")
        suffix = (", " + "; ".join(suffix_parts)) if suffix_parts else ""
        # Mixed PRs get mixed leniency: each file counts against the budget of
        # the scope governing it for a given ceiling (a folder override or the
        # global pool), so a folder's higher ceiling covers its own files and
        # nothing else. Lines and files partition independently, so a folder
        # that raises one ceiling keeps the global one for the other. Each
        # ceiling then has a roof over the PR total, so scope budgets cannot sum
        # without bound as more folders grant.
        budgets = self._size_budgets()
        for scope in budgets.line_scopes:
            scope_lines, _ = substantive_size(self._files_in(scope))
            if scope_lines > scope.ceiling:
                return (
                    False,
                    f"too large for auto-review ({scope_lines}L substantive in {scope.path or 'global'} — "
                    f"ceiling is {scope.ceiling}L; {lines}L, {files}F total{suffix})",
                )
        for scope in budgets.file_scopes:
            _, scope_files = substantive_size(self._files_in(scope))
            if scope_files > scope.ceiling:
                return (
                    False,
                    f"too large for auto-review ({scope_files}F substantive in {scope.path or 'global'} — "
                    f"ceiling is {scope.ceiling}F; {lines}L, {files}F total{suffix})",
                )
        if lines > budgets.line_roof:
            return (
                False,
                f"too large for auto-review ({lines}L, {files}F substantive across the whole PR — "
                f"roof is {budgets.line_roof}L{suffix})",
            )
        if files > budgets.file_roof:
            return (
                False,
                f"too large for auto-review ({lines}L, {files}F substantive across the whole PR — "
                f"roof is {budgets.file_roof}F{suffix})",
            )
        return True, f"{lines}L, {files}F substantive{suffix} — within ceiling"

    def _files_in(self, scope: ScopeBudget) -> list[dict]:
        in_scope = set(scope.files)
        return [f for f in self.pr.files if f["filename"] in in_scope]

    def _size_budgets(self) -> EffectivePolicy:
        """The PR's resolved size budgets, or global-only ones when resolution did not run."""
        if self.effective_policy is not None:
            return self.effective_policy
        all_files = tuple(f["filename"] for f in self.pr.files)
        return EffectivePolicy(
            file_scopes=(ScopeBudget(path=None, ceiling=MAX_FILES, files=all_files),),
            line_scopes=(ScopeBudget(path=None, ceiling=MAX_LINES, files=all_files),),
        )

    def _check_tier(self) -> tuple[bool, str]:
        cl = self.classification
        tier_label = cl["tier"]
        if cl["t1_subclass"]:
            tier_label += f" / {cl['t1_subclass']}"
        summary = f"{tier_label} ({self.pr.lines_total}L, {len(self.pr.files)}F, {cl['breadth']}, {cl['commit_type'] or 'unknown'})"

        if cl["tier"] == "T2-never":
            return False, f"classified as T2-never: {summary}"
        if cl["tier"] == "T0-deterministic":
            return True, f"T0 auto-approve: {summary}"
        return True, summary

    @staticmethod
    def _tracked_symlinks(rev: str) -> dict[str, str]:
        """Symlinks tracked at ``rev`` as path -> blob; the same blob means the same target."""
        try:
            listing = subprocess.run(
                ["git", "ls-tree", "-r", "--full-tree", rev],
                capture_output=True,
                text=True,
                timeout=30,
                cwd=REPO_ROOT,
            )
        except subprocess.TimeoutExpired as exc:
            raise WorktreeUnavailableError(f"symlink check timed out for {rev}") from exc
        if listing.returncode != 0:
            raise WorktreeUnavailableError(f"symlink check failed for {rev}: {listing.stderr.strip()}")
        links: dict[str, str] = {}
        for line in listing.stdout.splitlines():
            if not line.startswith("120000 "):
                continue
            meta, path = line.split("\t", 1)
            links[path] = meta.split()[2]
        return links

    @contextmanager
    def _pr_head_worktree(self) -> Iterator[Path | None]:
        """Yield a detached worktree at the PR head, or None when none is needed.

        Only stacked PRs reviewed from a trunk checkout need this: their head
        contains code from parent PRs that aren't on the base branch yet, so
        without materializing the head tree those parents' symbols look like
        broken imports and the reviewer false-refuses. A non-stacked PR reviews
        from the trunk checkout exactly as before, and a runtime whose checkout
        already IS the head (hosted sandbox, head_checkout=True) needs nothing
        extra — both yield None and skip the full-tree checkout. In the Action
        the main checkout stays master (the workflow hardcodes that so a PR
        can't swap the review script), so the worktree is the only place the
        head tree is materialized. Cleaned up on exit; stacked PRs fail closed
        if creation fails rather than reviewing against the wrong source tree.

        SECURITY: the worktree is PR-authored content; isolation from it as
        *configuration* is enforced by setting_sources=[] in Reviewer.
        """
        if self.head_checkout or not self.pr.stacked:
            yield None
            return

        worktree_dir = Path(tempfile.gettempdir()) / f"pr-review-{self.pr_number}-{uuid.uuid4().hex[:8]}"
        # A symlink in the head tree can point outside the worktree, and the agent's Read follows
        # it — so only symlinks the trunk already carries (same path, same target) are trusted; a
        # stacked PR's base is PR-authored too, so the baseline is the default branch, not the base.
        trusted_links = self._tracked_symlinks(f"origin/{self.pr.default_branch}")
        added_links = sorted(
            path for path, blob in self._tracked_symlinks(self.pr.head_sha).items() if trusted_links.get(path) != blob
        )
        if added_links:
            raise WorktreeUnavailableError(f"PR head adds symbolic links: {', '.join(added_links)}")

        try:
            result = subprocess.run(
                ["git", "worktree", "add", "--detach", str(worktree_dir), self.pr.head_sha],
                capture_output=True,
                text=True,
                timeout=120,
                cwd=REPO_ROOT,
            )
        except subprocess.TimeoutExpired as exc:
            raise WorktreeUnavailableError("worktree creation timed out") from exc
        if result.returncode != 0:
            raise WorktreeUnavailableError(f"worktree creation failed: {result.stderr.strip()}")

        print(_dim(f"  Exploring PR head in worktree: {worktree_dir}"))

        try:
            yield worktree_dir
        finally:
            try:
                cleanup = subprocess.run(
                    ["git", "worktree", "remove", "--force", str(worktree_dir)],
                    capture_output=True,
                    text=True,
                    timeout=30,
                    cwd=REPO_ROOT,
                )
                if cleanup.returncode != 0:
                    print(_warn(f"Worktree cleanup failed (ignored): {cleanup.stderr.strip()}"))
            except (OSError, subprocess.TimeoutExpired) as exc:
                print(_warn(f"Worktree cleanup failed (ignored): {exc}"))

    def _run_reviewer_with_retries(self, reviewer: "Reviewer", gate_context: dict, diff_path: Path) -> bool:
        """Call the reviewer with backoff; set self.reviewer_output.

        Returns True when the reviewer never produced a verdict (an ERROR
        stand-in was synthesized instead) so the caller retains the label.
        Retryable failures (LLM backend) back off; non-retryable ones (e.g.
        turn-limit) fail immediately with a distinct message.
        """
        max_retries = 3
        for attempt in range(max_retries):
            try:
                self.reviewer_output = reviewer.review(
                    self.pr,
                    self.classification,
                    gate_context,
                    diff_path=diff_path,
                )
                return False
            except Exception as e:
                err_str = str(e)
                is_retryable = _is_retryable_error(err_str)

                if is_retryable and attempt < max_retries - 1:
                    wait = 2 ** (attempt + 1)
                    print(_warn(f"Reviewer failed (attempt {attempt + 1}/{max_retries}): {e}"))
                    print(_dim(f"  Retrying in {wait}s..."))
                    time.sleep(wait)
                    continue

                if is_retryable:
                    print(_fail(f"Reviewer failed after {max_retries} attempts: {e}"))
                    print(
                        _warn(
                            "  This is an LLM backend failure (credentials, credit, or outage), "
                            "not a verdict on the PR. Check the ai-gateway token and the reviewer "
                            "model's allowlist (or the local OPENAI_API_KEY, or ANTHROPIC_API_KEY "
                            "with STAMPHOG_REVIEWER_ENGINE=claude)."
                        )
                    )
                    self.reviewer_output = {
                        "verdict": "ERROR",
                        "reasoning": (
                            "The review agent couldn't reach its LLM backend — an infrastructure "
                            "or credentials issue, not a problem with this PR. The `stamphog` label "
                            "has been kept; the review retries automatically on the next push, or "
                            "re-apply the label once the backend recovers."
                        ),
                        "risk": "unknown",
                        "issues": [err_str],
                    }
                else:
                    print(_fail(f"Reviewer hit a non-retryable error: {e}"))
                    self.reviewer_output = {
                        "verdict": "ERROR",
                        "reasoning": (
                            "The review agent could not complete its analysis for this PR "
                            "(likely too complex for the allocated turn budget). "
                            "The `stamphog` label has been kept; a human review is needed."
                        ),
                        "risk": "unknown",
                        "issues": [err_str],
                    }
                return True

        raise AssertionError("review retry loop exhausted without a verdict")

    def _new_reviewer(self, explore_root: Path | None) -> "Reviewer":
        self.reviewer_engine = reviewer_engine()
        # Deferred so the gate-only pre-check can import this module where the LLM SDKs are absent.
        if self.reviewer_engine == CLAUDE_ENGINE:
            from reviewer import Reviewer  # noqa: PLC0415 — keeps the heavy dep off the import path

            return Reviewer(REPO_ROOT, explore_root=explore_root, verbose=self.verbose)
        from openai_reviewer import OpenAIReviewer  # noqa: PLC0415 — keeps the heavy dep off the import path

        return OpenAIReviewer(REPO_ROOT, explore_root=explore_root, verbose=self.verbose)

    def _llm_review(self, gate_verdict: str) -> None:
        print(f"\n{_bold('LLM Review')}")
        # Outside the retry loop: a diff-write hiccup must not masquerade as a
        # retryable reviewer failure and burn the backoff budget.
        diff_path = self._ensure_diff_path()

        gate_context = {
            "gate_verdict": gate_verdict,
            "gates": [{"gate": g.gate, "passed": g.passed, "message": g.message} for g in self.gate_results],
        }

        print(_dim("  Calling reviewer..."))

        try:
            with self._pr_head_worktree() as explore_root:
                reviewer = self._new_reviewer(explore_root)
                reviewer_unavailable = self._run_reviewer_with_retries(reviewer, gate_context, diff_path)
        except WorktreeUnavailableError as exc:
            reviewer_unavailable = True
            self.reviewer_output = {
                "verdict": "ERROR",
                "reasoning": (
                    "The review agent could not create the isolated worktree required to review this stacked PR. "
                    "The `stamphog` label has been kept; retry after the checkout issue is resolved."
                ),
                "risk": "unknown",
                "issues": [str(exc)],
            }

        llm_verdict = self.reviewer_output.get("verdict", "UNKNOWN")
        print(f"  Verdict: {llm_verdict}")
        print(f"  Reasoning: {self.reviewer_output.get('reasoning', '?')}")

        issues = self.reviewer_output.get("issues", [])
        for issue in issues:
            print(_warn(f"  {issue}"))

        # Gates are authoritative — LLM can tighten but never loosen. A real
        # gate denial outranks an unavailable reviewer: still REFUSE (and let
        # the label strip), because the deny is deterministic and actionable.
        if gate_verdict == "DENIED":
            self.final_verdict = "REFUSED"
            print(f"\n{_fail('REFUSED')} — gates denied")
        elif reviewer_unavailable:
            # Distinct from a substantive REFUSE/ESCALATE: the workflow keeps
            # the label so a transient outage doesn't drop it across every PR.
            self.final_verdict = "ERROR"
            print(f"\n{_warn('ERROR')} — review agent unavailable; label retained for retry")
        elif gate_verdict == "AUTO-APPROVED" and llm_verdict in ("REFUSE", "ESCALATE"):
            self.final_verdict = "ESCALATE"
            print(f"\n{_warn('ESCALATE')} — gates auto-approved but LLM disagrees")
        elif llm_verdict == "APPROVE":
            self.final_verdict = "APPROVED"
            print(f"\n{_ok('APPROVED')}")
        elif llm_verdict == "REFUSE":
            self.final_verdict = "REFUSED"
            print(f"\n{_fail('REFUSED')}")
        else:
            self.final_verdict = "ESCALATE"
            print(f"\n{_warn('ESCALATE')} — needs human review")

        self._capture_review_completed(gate_verdict, llm_verdict)

    def _capture_review_completed(self, gate_verdict: str, llm_verdict: str) -> None:
        """Send a stamphog_review_completed event with all verdict data."""
        if not _POSTHOG_AVAILABLE:
            return

        cl = self.classification
        pr = self.pr
        fam = self.familiarity
        prov = self.provenance
        posthoganalytics.capture(
            distinct_id=pr.author,
            event="stamphog_review_completed",
            # Extras first, so the base props win on a collision. The hosted server stamps its
            # runtime and team context through this hook. A local run has no such hook, so its
            # events are unchanged, and a missing prop means a local runtime.
            properties={
                **analytics_extra_properties(),
                "ai_product": "stamphog",
                "stamphog_version": STAMPHOG_VERSION,
                "stamphog_commit": _head_commit_sha(),
                "stamphog_pr_number": pr.number,
                "stamphog_repo": pr.repo,
                "stamphog_author": pr.author,
                "stamphog_pr_title": pr.title,
                "stamphog_tier": cl.get("tier", ""),
                "stamphog_t1_subclass": cl.get("t1_subclass", ""),
                "stamphog_breadth": cl.get("breadth", ""),
                "stamphog_commit_type": cl.get("commit_type") or "",
                "stamphog_files_changed": len(pr.files),
                "stamphog_lines_total": pr.lines_total,
                "stamphog_pr_reactions_count": len(pr.pr_reactions),
                "stamphog_title_scrutiny_flags": cl.get("title_scrutiny_flags", []),
                "stamphog_owner_teams": (cl.get("ownership") or {}).get("teams", []),
                "stamphog_familiarity_band": fam.band if fam else "",
                "stamphog_familiarity_blame_overlap_pct": round(fam.blame_overlap_pct, 1) if fam else None,
                "stamphog_familiarity_prior_prs_in_paths": fam.prior_prs_in_paths if fam else None,
                "stamphog_familiarity_days_since_last_touch": fam.days_since_last_touch if fam else None,
                "stamphog_familiarity_source": self.familiarity_source,
                "stamphog_agent_authored": prov.agent_authored if prov else None,
                "stamphog_agent_commit_count": prov.agent_commit_count if prov else None,
                "stamphog_commit_count": prov.commit_count if prov else None,
                "stamphog_generated_by": list(prov.generated_by) if prov else [],
                "stamphog_task_ids": list(prov.task_ids) if prov else [],
                "stamphog_gate_verdict": gate_verdict,
                "stamphog_llm_verdict": llm_verdict,
                "stamphog_final_verdict": self.final_verdict,
                # Empty on a local run: only the hosted runtime knows why the review started.
                "stamphog_review_trigger": self.review_trigger,
                "stamphog_llm_reasoning": (self.reviewer_output or {}).get("reasoning", ""),
                "stamphog_llm_risk": (self.reviewer_output or {}).get("risk", ""),
                "stamphog_llm_issues": (self.reviewer_output or {}).get("issues", []),
                "stamphog_llm_facts_summary": facts_summary((self.reviewer_output or {}).get("facts")),
                "stamphog_reviewer_engine": self.reviewer_engine,
                **_llm_usage_properties(self.reviewer_output),
            },
        )

    # ── Output ───────────────────────────────────────────────────

    def _render_review_body(self) -> str | None:
        """The verdict comment body: reasoning first, judgment bullets, mechanics folded.

        Judgment leads and the gate mechanics (budgets, tier, policy version)
        stay inside a collapsed details block. Built only from GFM constructs a
        GitHub comment actually renders.
        """
        if self.reviewer_output is None:
            return None
        reasoning = str(self.reviewer_output.get("reasoning", "")).strip()

        bullets: list[str] = []
        fam = self.classification.get("familiarity")
        if fam is not None and fam.band in ("STRONG", "MODERATE"):
            bullets.append(
                f"Author wrote {fam.blame_overlap_pct:.0f}% of the modified lines and has "
                f"{fam.prior_prs_in_paths} merged PRs in these paths (familiarity {fam.band})."
            )
        # Reuse the assurance digest's head-reviewer derivation rather than
        # re-deriving it here. classification is empty {} on early-exit paths
        # (bot-author REFUSE), so guard with .get and skip the bullet then.
        assurance = self.classification.get("assurance") or {}
        head_reviewers = sorted(
            _sanitize_untrusted(u, max_len=50)
            for u in {*assurance.get("head_approvals", []), *assurance.get("head_commented_users", [])}
        )
        thumbs = sorted(
            {_sanitize_untrusted(r["user"], max_len=50) for r in self.pr.pr_reactions if r.get("emoji") == "👍"}
        )
        for completed_review in assurance.get("head_review_evidence") or []:
            bullets.append(f"{describe_review_evidence(completed_review)}.")
        if head_reviewers:
            bullets.append(f"{', '.join(head_reviewers)} reviewed the current head.")
        elif thumbs:
            bullets.append(f"👍 on the PR from {', '.join(thumbs)}.")
        if self.effective_policy is not None:
            for path, governed in self.effective_policy.governed_file_counts():
                bullets.append(f"{governed} of the {len(self.pr.files)} changed files are governed by `{path}`.")
        bullets.extend(str(issue) for issue in (self.reviewer_output.get("issues") or [])[:3])

        rows = [f"| {g.gate} | {'✓' if g.passed else '✗'} | {g.message} |" for g in self.gate_results if g]
        rows.append(
            f"| stamphog {STAMPHOG_VERSION} |  | `.stamphog/policy.yml` @ `{_head_commit_sha()[:7]}`"
            f" · reviewed head `{self.pr.head_sha[:7]}` |"
        )
        details = (
            "<details>\n<summary>Gate mechanics and policy version</summary>\n\n"
            "| Gate |  | Result |\n|---|---|---|\n" + "\n".join(rows) + "\n\n</details>"
        )

        parts = [part for part in (reasoning, "\n".join(f"- {b}" for b in bullets) if bullets else "") if part]
        parts.append(details)
        return "\n\n".join(parts)

    def to_dict(self) -> dict:
        return {
            "stamphog_version": STAMPHOG_VERSION,
            "pr_number": self.pr.number,
            "repo": self.pr.repo,
            "title": self.pr.title,
            "author": self.pr.author,
            "base_sha": self.pr.base_sha,
            "head_sha": self.pr.head_sha,
            "classification": {
                # .get() not [] — the bot-author REFUSE returns before _classify(),
                # so classification is empty {} on that path; --output-json must
                # still serialize cleanly rather than KeyError.
                "tier": self.classification.get("tier", ""),
                "t1_subclass": self.classification.get("t1_subclass", ""),
                "lines_total": self.pr.lines_total,
                "files_changed": len(self.pr.files),
                "breadth": self.classification.get("breadth", ""),
                "commit_type": self.classification.get("commit_type"),
                "deny_categories": self.classification.get("deny_categories", []),
                "title_scrutiny_flags": self.classification.get("title_scrutiny_flags", []),
                "safe_migration_files": self.classification.get("safe_migration_files", []),
                "ownership": self.classification.get("ownership", {}),
                "familiarity": familiarity_evidence(self.familiarity),
                # Audit trail: records that this review ran with the gates relaxed (see __init__).
                "self_driving": self.self_driving,
                # Audit trail: what the reviewer was told about why it was asked.
                "review_trigger": self.review_trigger,
            },
            "provenance": provenance_evidence(self.provenance),
            "gates": [
                {"gate": g.gate, "passed": g.passed, "message": g.message} for g in self.gate_results if g is not None
            ],
            "policy": {
                "commit_sha": _head_commit_sha(),
                "policy_file": ".stamphog/policy.yml",
                "scopes": (
                    [
                        {"path": s.path, "key": key, "ceiling": s.ceiling, "files": len(s.files)}
                        for key, scopes in (
                            ("max_lines", self.effective_policy.line_scopes),
                            ("max_files", self.effective_policy.file_scopes),
                        )
                        for s in scopes
                    ]
                    if self.effective_policy
                    else []
                ),
                "invalid_folder_files": (
                    list(self.effective_policy.invalid_folder_files) if self.effective_policy else []
                ),
            },
            "reviewer": self.reviewer_output,
            "review_body": self._render_review_body(),
            "final_verdict": self.final_verdict,
        }

    def save_json(self, path: str) -> None:
        with open(path, "w") as f:
            json.dump(self.to_dict(), f, indent=2)
        print(_dim(f"\nSaved to {path}"))


# ── CLI ──────────────────────────────────────────────────────────


def main() -> None:
    parser = argparse.ArgumentParser(description="AI PR approval agent")
    parser.add_argument("pr_number", type=int, help="PR number to review")
    parser.add_argument("--repo", default="PostHog/posthog", help="GitHub repo (owner/name)")
    parser.add_argument("--dry-run", action="store_true", help="Run gates only, skip LLM calls")
    parser.add_argument("--output-json", type=str, help="Save full result to JSON file")
    parser.add_argument("-v", "--verbose", action="store_true", help="Show agent tool calls during review")
    args = parser.parse_args()

    print(_bold(f"\nReviewing PR #{args.pr_number} ({args.repo})\n"))

    pipeline = Pipeline(args.pr_number, args.repo, dry_run=args.dry_run, verbose=args.verbose)
    verdict = pipeline.run()

    if verdict == "DRY-RUN":
        print(f"\n{_dim('DRY RUN — would proceed to LLM review')}")

    # Show the comment exactly as it would be posted (the workflow posts
    # review_body verbatim), gate-mechanics table included.
    review_body = pipeline._render_review_body()
    if review_body:
        print(f"\n{_bold('Review comment (as posted)')}")
        print(_dim("─" * 60))
        print(review_body)
        print(_dim("─" * 60))

    if args.output_json:
        pipeline.save_json(args.output_json)

    flush_analytics()


if __name__ == "__main__":
    main()