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.

feat(stamphog): support stacked PRs (#54933)

Raúl Negrón-Oterof4ed1ce5b029
diff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.yml
index 8f328124f189..6f52e1562cdd 100644
--- a/.github/workflows/pr-approval-agent.yml
+++ b/.github/workflows/pr-approval-agent.yml
@@ -2,14 +2,19 @@ name: PR Approval Agent
on:
pull_request:
- types: [labeled, ready_for_review, synchronize]
+ types: [labeled, ready_for_review, synchronize, edited]
permissions:
contents: read
pull-requests: write
+# `edited` fires on title/body edits too; those runs skip every job but would
+# still cancel an in-flight review via the shared group. Give them a unique
+# throwaway group. Base-change edits (retarget) keep the shared group on
+# purpose: cancelling a review that's mid-flight against the old base is the
+# desired outcome.
concurrency:
- group: pr-approval-${{ github.event.pull_request.number }}
+ group: pr-approval-${{ github.event.pull_request.number }}${{ github.event.action == 'edited' && github.event.changes.base == null && format('-edit-{0}', github.run_id) || '' }}
cancel-in-progress: true
jobs:
@@ -21,7 +26,7 @@ jobs:
# Triggers: explicit `stamphog` label, ready_for_review with the
# label already present, or `synchronize` where decide-delta
# asked for re-review (or itself failed — fail closed for safety).
- needs: [decide-delta, dismiss]
+ needs: [decide-delta, dismiss, dismiss-on-retarget]
# !cancelled() rather than always() so a push that supersedes this run stops the
# LLM review instead of posting a stamphog approval for a commit that is no longer
# HEAD. The explicit decide-delta checks below keep the fail-closed re-review paths.
@@ -36,6 +41,7 @@ jobs:
|| (github.event.action == 'ready_for_review' && contains(github.event.pull_request.labels.*.name, 'stamphog'))
|| needs.decide-delta.outputs.run_review == 'true'
|| needs.decide-delta.result == 'failure'
+ || (github.event.action == 'edited' && github.event.changes.base != null && contains(github.event.pull_request.labels.*.name, 'stamphog'))
)
runs-on: ubuntu-latest
# Budget for the in-flight-bot-review wait (5 min of sleeps plus the
@@ -91,7 +97,7 @@ jobs:
--output-json /tmp/review.json
- name: Post review
- if: always()
+ if: ${{ !cancelled() }}
env:
# Everything stamphog does — the approval, the sticky comment,
# the label strip — posts as the Stamphog app (GH_TOKEN) so it
@@ -110,6 +116,7 @@ jobs:
# bullets + folded gate mechanics); fall back to the bare
# reasoning when the script predates the field.
REASONING=$(jq -r '.review_body // .reviewer.reasoning // ""' /tmp/review.json 2>/dev/null || echo "")
+ REVIEWED_BASE_SHA=$(jq -r '.base_sha // ""' /tmp/review.json 2>/dev/null || echo "")
REVIEWED_SHA=$(jq -r '.head_sha // ""' /tmp/review.json 2>/dev/null || echo "")
# Lock the review to the sha the LLM actually saw — `gh pr
@@ -121,6 +128,15 @@ jobs:
fi
if [ "$VERDICT" = "APPROVED" ]; then
+ # Stacked PRs move under us: re-read the live base/head and
+ # skip the approval if either drifted from what the LLM saw,
+ # so we never stamp a review onto code that has since changed.
+ CURRENT_REFS=$(gh api "repos/$REPO/pulls/$PR" --jq '[.base.sha, .head.sha] | @tsv')
+ IFS=$'\t' read -r CURRENT_BASE_SHA CURRENT_HEAD_SHA <<< "$CURRENT_REFS"
+ if [ "$CURRENT_BASE_SHA" != "$REVIEWED_BASE_SHA" ] || [ "$CURRENT_HEAD_SHA" != "$REVIEWED_SHA" ]; then
+ echo "PR base or head changed after review; skipping stale approval."
+ exit 0
+ fi
# Single Stamphog app approval, carrying the review body.
# Fatal on failure (the step runs under `set -e`): this is
# now the only approval, so if it doesn't post the PR stays
@@ -233,7 +249,7 @@ jobs:
fi
- name: Upload evidence
- if: always()
+ if: ${{ !cancelled() }}
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: review-${{ github.event.pull_request.number }}
@@ -281,8 +297,22 @@ jobs:
filter: blob:none
fetch-depth: 0
- - name: Fetch PR head
- run: git fetch --filter=blob:none origin pull/${{ github.event.pull_request.number }}/head
+ - name: Fetch PR head and base
+ # base.ref is author-controlled, so it goes through an env var
+ # (never interpolated into the command). A stacked PR's base is
+ # its parent branch, which the master checkout doesn't fetch;
+ # dismiss_check needs it to classify merge commits. Best-effort —
+ # a missing base just fails the merge check closed to re-review.
+ env:
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ BASE_REF_NAME: ${{ github.event.pull_request.base.ref }}
+ run: |
+ set -euo pipefail
+ git fetch --filter=blob:none origin "pull/${PR_NUMBER}/head"
+ # Explicit refspec: a bare `git fetch origin <branch>` only
+ # writes FETCH_HEAD, and dismiss_check resolves origin/<branch>.
+ git fetch --filter=blob:none origin \
+ "+refs/heads/${BASE_REF_NAME}:refs/remotes/origin/${BASE_REF_NAME}" || true
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
@@ -348,6 +378,7 @@ jobs:
# of secrets on forks), so gate the whole job to head branches in this repo.
if: >-
always()
+ && !cancelled()
&& github.event.action == 'synchronize'
&& !github.event.pull_request.draft
&& github.event.pull_request.head.repo.full_name == github.repository
@@ -396,6 +427,48 @@ jobs:
-f event=DISMISS
done
+ # A base retarget (Graphite moving a child onto master when its parent
+ # merges) changes the diff without a push, so no `synchronize` fires and a
+ # prior bot approval carries onto the new base under the master ruleset
+ # (dismiss_stale_reviews_on_push=false). Dismiss it; review re-runs against
+ # the new base. Ordered before review via `needs`, so it can't dismiss the
+ # fresh approval that re-review is about to post. See README for the full rationale.
+ dismiss-on-retarget:
+ if: >-
+ github.event.action == 'edited'
+ && github.event.changes.base != null
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+
+ steps:
+ # The dismissal loop below mirrors the `dismiss` job's. Neither job
+ # checks out the repo, so factoring it into a shared script would
+ # force a checkout into both — more cost than the duplication saves.
+ # If you change the stamphog-approval selection, update both
+ # dismissal jobs in lockstep.
+ - name: Dismiss stale bot approvals on base change
+ env:
+ # pull-requests:write dismisses any review regardless of its
+ # author, so github.token clears both the app's approvals
+ # (stamphog[bot]) and any legacy github-actions[bot] ones.
+ GH_TOKEN: ${{ github.token }}
+ PR: ${{ github.event.pull_request.number }}
+ REPO: ${{ github.repository }}
+ run: |
+ set -euo pipefail
+
+ mapfile -t REVIEW_IDS < <(
+ gh api "repos/$REPO/pulls/$PR/reviews" --paginate \
+ --jq '.[] | select((.user.login == "github-actions[bot]" or .user.login == "stamphog[bot]") and .state == "APPROVED") | .id'
+ )
+
+ for id in "${REVIEW_IDS[@]}"; do
+ [ -z "$id" ] && continue
+ gh api -X PUT "repos/$REPO/pulls/$PR/reviews/$id/dismissals" \
+ -f message="Base branch retargeted — stamphog approval dismissed; re-review runs automatically if the label is present." \
+ -f event=DISMISS
+ done
+
# stamphog never reviews bot-authored PRs (dependabot, mendral, other
# agents). A human applying the label can't override this — bot output
# isn't a trusted basis for an auto-approval. review / decide-delta are
@@ -437,9 +510,10 @@ jobs:
run: |
set -euo pipefail
# Explain only on the apply paths (a human just labeled it, or
- # marked the PR ready). On synchronize the note was already
- # posted — or the label predates this gate — so just clean up.
- if [ "$ACTION" != "synchronize" ]; then
+ # marked the PR ready). On synchronize/edited the note was
+ # already posted — or the label predates this gate — so just
+ # clean up.
+ if [ "$ACTION" = "labeled" ] || [ "$ACTION" = "ready_for_review" ]; then
gh pr comment "$PR" --repo "$REPO" \
--body "stamphog does not review bot-authored PRs — removing the \`stamphog\` label. This change needs a human reviewer."
fi
diff --git a/.gitignore b/.gitignore
index 4f1300bde968..af4084a9d3b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,7 @@
# people's OCDs ^_^
.cache
.planning
-.pr-review-diff.patch
+.pr-review-diff*.patch
.qa-frontend/
__emails__
__pycache__/
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 4246be8575fe..f2563bba3d14 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -49,9 +49,8 @@ A newer relevant delivery supersedes older non-terminal runs. Rules that keep th
- Terminal states (`TERMINAL_STATUSES` in `facade/enums.py`) are never rewritten — `mark_review_failed`
must not clobber a delivered outcome, and terminal saves are conditional
(`.exclude(status=SUPERSEDED).update(...)`), never plain `save()`.
-- `post_verdict` guards before ANY GitHub write: superseded status, current head vs run head, and
- a last fresh status read. Losing the final conditional update means dismiss-your-own-approval,
- not "log and return".
+- `post_verdict` guards before ANY GitHub write: superseded status, current head vs run head, current base (ref and SHA) vs the reviewed one (a retarget, or a parent branch moving under a stacked PR, rewrites the diff with the head unchanged, and the retarget delivery can trail the activity), and a last fresh status read.
+ Losing the final conditional update means dismiss-your-own-approval, not "log and return".
- Out-of-order webhook deliveries are dropped by the `payload_updated_at` clock — checked before
the transaction AND re-checked under the row lock, and the descriptive-field refresh is gated on
the same clock inside the UPDATE's WHERE clause.
@@ -76,6 +75,8 @@ add a read-then-act path, pin it; this class of bug has been found on five separ
`STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS`, not code edits.
- Everything posted to GitHub goes through `_scrub_credentials` AND `_neutralize_active_markdown`
(GitHub's camo proxy auto-fetches images — a markdown image URL is an exfiltration channel).
+- The sandbox checkout is the PR head, so the engine's Agent SDK session runs with `setting_sources=[]` + `strict_mcp_config` (reviewer.py): a PR-shipped `.claude/settings.json` hook, `CLAUDE.md`, or `.mcp.json` is readable as untrusted content, never loaded as configuration.
+ Don't reintroduce filesystem settings discovery there.
## The self-driving inbox carve-out (the one exception to the bot-author refusal)
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index cf7bc3eb54df..92a1c7d08daa 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -23,6 +23,15 @@ Each audience resolves to a Slack channel in three steps (`backend/logic/channel
Summaries are written where the diff is. The reviewer emits a one-line `change_summary` alongside its verdict, which is stamped onto the merged PR; the daily run condenses those rather than guessing from PR titles, and for an owning team it also sees which of the changed files are theirs, so a repo-wide sweep that grazed two of them can be dropped as noise.
+## Stacked PRs
+
+A stacked PR targets its parent's branch, not the repo's default branch, and depends on parent code that hasn't merged yet.
+The sandbox clones and checks out the PR head for every review, so the reviewer's Read/Grep/Glob already see the post-stack tree and parent symbols resolve.
+The engine is told the checkout is the head (`head_checkout=True`) so it never builds the Action's separate head worktree, and the prompt flags the PR as stacked (`PRData.stacked`, keyed on the repo's actual default branch).
+The diff stays scoped `base...head`.
+When the parent merges and GitHub retargets the child onto the default branch, the diff changes without a push: the webhook path retracts the standing approval and queues a fresh run, and `post_verdict` rechecks the live base (ref and SHA) against the reviewed one before posting.
+Engine details: [`tools/pr-approval-agent/README.md`](../../tools/pr-approval-agent/README.md#stacked-prs-graphite--git-stacks).
+
## Configuration
Per-repo settings live on `StamphogRepoConfig` (synced via the GitHub App install flow, managed in the Stamphog scene): review on/off, review mode (auto vs trigger label), digest on/off. Review policy (gates, deny-lists, tiers, ownership) is read from `.stamphog/policy.yml` on the repo's **default branch** — never from the PR head — layered over hosted defaults in [`backend/logic/policy_defaults/`](backend/logic/policy_defaults/).
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index dfb550d57f35..080644f3d707 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -671,7 +671,29 @@ def post_verdict(input: StamphogReviewInput) -> dict:
return {"verdict": "skipped_superseded"}
current_pr = client.get_pr(repo, pull_request.pr_number)
current_head = ((current_pr.get("head") or {}).get("sha") or "").strip()
+ # A base retarget (a stacked PR's parent merged, or a manual base switch) rewrites the reviewed
+ # diff with the head SHA unchanged, so the head guard alone can't see it. The retarget delivery
+ # retracts approvals and queues a fresh run, but that delivery can trail this activity. The SHA
+ # is compared too: GitHub pins base.sha at the last PR event rather than tracking the trunk tip,
+ # so it only moves when the PR itself was touched — the diff the sandbox reviewed is stale then.
+ reviewed_base = (output.get("pr") or {}).get("base") or {}
+ current_base = current_pr.get("base") or {}
+ reviewed_base_ref = reviewed_base.get("ref") or ""
+ reviewed_base_sha = reviewed_base.get("sha") or ""
+ current_base_ref = (current_base.get("ref") or "").strip()
+ current_base_sha = (current_base.get("sha") or "").strip()
+ base_ref_moved = bool(reviewed_base_ref and current_base_ref and reviewed_base_ref != current_base_ref)
+ base_sha_moved = bool(reviewed_base_sha and current_base_sha and reviewed_base_sha != current_base_sha)
+ drift: tuple[str, str] | None = None
if current_head and current_head != run.head_sha:
+ drift = ("head_moved", f"head moved {run.head_sha} -> {current_head}")
+ elif base_ref_moved or base_sha_moved:
+ drift = (
+ "base_retargeted",
+ f"base moved {reviewed_base_ref}@{reviewed_base_sha} -> {current_base_ref}@{current_base_sha}",
+ )
+ if drift is not None:
+ kind, detail = drift
# Conditional: a retry after the terminal save already committed (e.g. the trailing digest
# stamp crashed) must not rewrite a delivered COMPLETED outcome to SUPERSEDED — terminal
# states are history. The stale-approval sweep retires that approval on the next delivery.
@@ -680,8 +702,8 @@ def post_verdict(input: StamphogReviewInput) -> dict:
)
if run.verdict != ReviewVerdict.APPROVED:
_dismiss_orphaned_approval(client, run, input.team_id)
- activity.logger.info(f"Skipping verdict for run {run.id}: head moved {run.head_sha} -> {current_head}")
- return {"verdict": "skipped_head_moved"}
+ activity.logger.info(f"Skipping verdict for run {run.id}: {detail}")
+ return {"verdict": f"skipped_{kind}"}
parsed = parse_reviewer_output(raw)
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index d480851278af..cdeda0a99c40 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -948,6 +948,47 @@ def test_retry_after_head_move_never_rewrites_a_terminal_run(team, stamphog_chai
assert [w for w in recorder.github_writes if w["kind"] == "dismiss_review"] == []
+ "live_base",
+ [
+ pytest.param({"sha": "master-tip", "ref": "master"}, id="retargeted-to-master"),
+ pytest.param({"sha": "parent-tip-2", "ref": "feat/parent"}, id="same-ref-parent-moved"),
+ ],
+)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_post_verdict_skips_when_the_base_moved_under_the_run(
+ team, stamphog_chain: StamphogChain, live_base: dict
+) -> None:
+ # A stacked PR's parent merged mid-review (child retargeted to master), or the parent branch
+ # itself moved under the same ref: either rewrites the reviewed diff while the head SHA stays
+ # put. The retarget delivery retracts and re-queues, but it can trail this activity —
+ # post_verdict must recheck the live base itself, or an approval for the old base..head diff
+ # lands on the new one.
+ repo_config = _repo_config(team.id)
+ recorder = stamphog_chain.recorder
+ head_sha = "sha119a"
+ live_pr = _pr_object(119, "devex-dev", head_sha) | {"base": live_base}
+ recorder.register_pr(REPO, 119, live_pr, _pr_files())
+ pull_request = PullRequest.objects.for_team(team.id).create(
+ team_id=team.id, repo_config=repo_config, pr_number=119, author_login="devex-dev"
+ )
+ reviewed_pr = _pr_object(119, "devex-dev", head_sha) | {"base": {"sha": "parent-tip", "ref": "feat/parent"}}
+ run = ReviewRun.objects.for_team(team.id).create(
+ team_id=team.id,
+ pull_request=pull_request,
+ head_sha=head_sha,
+ status=ReviewRunStatus.REVIEWING,
+ output={"pr": reviewed_pr, "reviewer_raw": fakes.approved_engine_output().splitlines()[-1]},
+ )
+
+ result = _run_activity(post_verdict, StamphogReviewInput(review_run_id=str(run.id), team_id=team.id))
+
+ assert result == {"verdict": "skipped_base_retargeted"}
+ assert [w for w in recorder.github_writes if w["kind"] == "approve_review"] == []
+ run.refresh_from_db()
+ assert run.status == ReviewRunStatus.SUPERSEDED
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_bot_eyes_on_a_later_reactions_page_still_counts_as_in_flight(team, stamphog_chain: StamphogChain) -> None:
# Anyone can react on a public PR, so an author could bury the trusted bot's fresh 👀 past the
diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_event_fanout.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_event_fanout.py
index f5554264a2c2..4be2a9d38d15 100644
--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_event_fanout.py
+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/pr_event_fanout.py
@@ -30,7 +30,9 @@ UNBUDGETED_ACTIONS = frozenset({"labeled", "unlabeled"})
PR_EVENT_FANOUT_BUDGET: Mapping[str, int] = {
"closed": 3,
"converted_to_draft": 1,
- "edited": 3,
+ # pr-approval-agent listens for base retargets (`edited` with `changes.base`); title/body
+ # edits skip every job there, but GitHub still counts the dispatch.
+ "edited": 4,
"opened": 28,
"ready_for_review": 11,
"reopened": 24,
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.md
index 884eccf7117d..4515caacfbbb 100644
--- a/tools/pr-approval-agent/README.md
+++ b/tools/pr-approval-agent/README.md
@@ -145,6 +145,36 @@ An approval is posted once, as the Stamphog app (`stamphog[bot]`), carrying the
This identity was confirmed to satisfy branch protection, so the earlier bodyless `github-actions[bot]` fallback approval has been dropped and every stamphog action now runs under the app token.
Every other verdict (REFUSED, ESCALATE, WAIT, ERROR) goes into a single sticky comment that is updated in place on each run, with a counter of how many verdicts the comment has carried (failure notes append without bumping it) — repeated refusals don't stack up as separate review comments on the PR.
+## Stacked PRs (Graphite / git stacks)
+
+A stacked PR targets its parent branch, not the repo's default branch, and depends on code the parent introduces but hasn't merged yet.
+`PRData.stacked` (`base_ref != default_branch`, so repos whose trunk is `main` work too) drives the handling; the reviewer prompt tells the agent it is looking at a stacked PR.
+Two parts make stamphog correct on these:
+
+- **Exploration sees the post-stack tree.**
+ The LLM reviewer's `Read`/`Grep`/`Glob` must run over a tree that already contains the parent PRs' code, so symbols from a not-yet-merged parent resolve and aren't flagged as broken imports.
+ The diff itself is still computed `base_sha...head_sha`, so the review is scoped to exactly this PR's changes.
+ How the head tree is materialized differs per runtime:
+ - **Action:** the workflow checks out master (hardcoded, so a PR can't swap the review script), so the reviewer explores a detached **worktree at the PR head** created just for stacked PRs.
+ If the worktree cannot be created, stamphog returns `ERROR` and retains the label rather than reviewing against the wrong source tree.
+ Symbolic links the PR adds or repoints (relative to the default branch's tree, which already carries trusted ones like `CLAUDE.md`) fail closed, so a PR path cannot resolve outside the worktree.
+ - **Hosted:** the sandbox clones and checks out the PR head for every review, so nothing extra is needed — `review_local.py` runs the pipeline with `head_checkout=True` and no worktree is created.
+ - **Security (both runtimes):** the explored tree is PR-authored content.
+ The reviewer runs the Agent SDK with `setting_sources=[]` (isolation mode) plus `strict_mcp_config`, so it does **not** load `.claude/settings.json` hooks (command execution), `CLAUDE.md` (injected instructions), or `.mcp.json` from the tree.
+ Those files are still readable as untrusted _content_ under the anti-injection notice — never as configuration.
+ The diff scratch file is created with `mkstemp` under an unpredictable name, so a tracked symlink in the tree cannot redirect the write.
+
+- **Base retarget dismisses the stale approval.**
+ When a stack's parent merges, the child PR is retargeted from the parent branch onto master, changing its effective diff **without a push** — so no `synchronize` fires and the normal push-dismiss path is skipped.
+ Under the master ruleset (`dismiss_stale_reviews_on_push=false`), a prior bot approval would silently carry onto the new base.
+ The Action listens for the `edited` event and, when the base changed, dismisses the bot approval and re-reviews against the new base (if the label is still present); the approval step also rechecks the live base and head SHAs right before posting.
+ The hosted runtime does the same from the webhook (`_retract_approvals_on_base_retarget`, then a fresh run) and `post_verdict` rechecks the live base ref and SHA against the reviewed ones.
+
+The base commit of a stacked PR is its parent branch tip, which the Action's master checkout doesn't fetch by default — `github.ensure_commits` and the `decide-delta` job both fetch the base branch so `git diff base_sha...head_sha` and the dismiss-time merge classification resolve it.
+The hosted sandbox fetches the base SHA explicitly during the clone.
+
+Known limitation (both runtimes): a parent branch force-push or rebase without restacking the child emits no child PR event, so the child's approval is only revalidated once the child is restacked or pushed.
+
## Tiers
### T0 — deterministic
diff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.py
index 5cb4c38b2d2b..77d5244d0db4 100644
--- a/tools/pr-approval-agent/github.py
+++ b/tools/pr-approval-agent/github.py
@@ -5,8 +5,10 @@ else (PR metadata, reviews, comments, check runs) from the GitHub API.
Also handles team membership checks for the ownership gate.
"""
+import os
import re
import json
+import tempfile
import subprocess
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -25,6 +27,7 @@ class PRData:
mergeable_state: str
author: str
labels: list[str]
+ base_ref: str
base_sha: str
head_sha: str
files: list[dict]
@@ -35,6 +38,14 @@ class PRData:
pr_reactions: list[dict] = field(default_factory=list)
body: str = ""
discussion: list[dict] = field(default_factory=list)
+ # The repo's default branch, so stacked-ness isn't tied to "master" (the hosted
+ # runtime reviews repos whose trunk is "main").
+ default_branch: str = "master"
+
+ @property
+ def stacked(self) -> bool:
+ """True when the PR targets another PR's branch rather than the repo's trunk."""
+ return self.base_ref != self.default_branch
@property
def file_paths(self) -> list[str]:
@@ -441,13 +452,27 @@ def _git_diff_files(base_sha: str, head_sha: str, repo_root: Path) -> list[dict]
return files
-def write_pr_diff(base_sha: str, head_sha: str, dest: Path, repo_root: Path) -> Path:
- """Write the base...head PR diff to `dest` from the local checkout.
+def new_diff_file(directory: Path) -> Path:
+ """Create a fresh, empty diff file under an unpredictable name inside ``directory``.
+
+ The directory can be PR-authored (the hosted sandbox's head checkout, or
+ the Action's stacked-PR worktree), where a predictable name could be a
+ tracked symlink redirecting the write. ``mkstemp`` creates a new regular
+ file, so PR content cannot redirect it. Callers own the cleanup.
+ """
+ fd, path = tempfile.mkstemp(prefix=".pr-review-diff-", suffix=".patch", dir=directory)
+ os.close(fd)
+ return Path(path)
+
+
+def write_pr_diff(base_sha: str, head_sha: str, repo_root: Path) -> Path:
+ """Write the base...head PR diff to a fresh file in the checkout and return its path.
Shared by the reviewer (feeds the LLM the diff to read) and the familiarity
signal (parses the same diff for base-side modified line ranges), so the
`git diff` invocation lives in one place.
"""
+ dest = new_diff_file(repo_root)
result = subprocess.run(
["git", "diff", f"{base_sha}...{head_sha}"],
capture_output=True,
@@ -459,24 +484,48 @@ def write_pr_diff(base_sha: str, head_sha: str, dest: Path, repo_root: Path) ->
return dest
-def ensure_commits(pr_number: int, head_sha: str, repo_root: Path) -> None:
- """Fetch PR commits if not available locally."""
- result = subprocess.run(
- ["git", "cat-file", "-t", head_sha],
- cwd=repo_root,
- capture_output=True,
- timeout=5,
- )
- if result.returncode == 0:
- return
- subprocess.run(
- ["git", "fetch", "origin", f"pull/{pr_number}/head"],
- cwd=repo_root,
- capture_output=True,
- timeout=30,
+def _have_commit(sha: str, repo_root: Path) -> bool:
+ return (
+ subprocess.run(
+ ["git", "cat-file", "-t", sha],
+ cwd=repo_root,
+ capture_output=True,
+ timeout=5,
+ ).returncode
+ == 0
)
+def ensure_commits(pr_number: int, head_sha: str, base_ref: str, base_sha: str, repo_root: Path) -> None:
+ """Make the PR head and its base commit available locally.
+
+ The workflow checks out master and fetches `pull/<n>/head`, which covers
+ the common case. Two stacked-PR cases need more:
+ - The head: fetched explicitly if the merge commit isn't present.
+ - The base: a stacked PR targets its parent branch, not master, so
+ `base_sha` is the parent's tip. It's usually an ancestor of the head
+ (reachable once the head is fetched), but a rebased/force-pushed stack
+ can leave it unreachable — fetch the base branch by name to be sure.
+ `git diff base_sha...head_sha` (and dismiss_check's ancestry walk)
+ need that object present. Best-effort: a missing base surfaces later
+ as a diff error rather than a silent wrong scope.
+ """
+ if not _have_commit(head_sha, repo_root):
+ subprocess.run(
+ ["git", "fetch", "--filter=blob:none", "origin", f"pull/{pr_number}/head"],
+ cwd=repo_root,
+ capture_output=True,
+ timeout=60,
+ )
+ if not _have_commit(base_sha, repo_root):
+ subprocess.run(
+ ["git", "fetch", "--filter=blob:none", "origin", base_ref],
+ cwd=repo_root,
+ capture_output=True,
+ timeout=60,
+ )
+
+
@dataclass(frozen=True)
class CommitProvenance:
"""Agent-authorship evidence parsed from the PR's commit-message trailers."""
@@ -573,12 +622,14 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
except Exception as exc:
print(f"warning: discussion fetch failed ({exc}); continuing with no discussion context") # noqa: T201
+ base_ref = pr["base"]["ref"]
+ default_branch = pr["base"]["repo"]["default_branch"]
base_sha = pr["base"]["sha"]
head_sha = pr["head"]["sha"]
check_runs_resp = _gh_api(f"repos/{repo}/commits/{head_sha}/check-runs")
git_root = repo_root or Path.cwd()
- ensure_commits(pr_number, head_sha, git_root)
+ ensure_commits(pr_number, head_sha, base_ref, base_sha, git_root)
files = _git_diff_files(base_sha, head_sha, git_root)
review_comments, pr_reactions = _fetch_threads_and_reactions(repo, pr_number, pr["user"]["login"])
@@ -592,6 +643,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
mergeable_state=pr.get("mergeable_state", "unknown"),
author=pr["user"]["login"],
labels=[label["name"] for label in pr.get("labels", [])],
+ base_ref=base_ref,
base_sha=base_sha,
head_sha=head_sha,
files=files,
@@ -602,6 +654,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
pr_reactions=pr_reactions,
body=pr.get("body") or "",
discussion=discussion,
+ default_branch=default_branch,
)
diff --git a/tools/pr-approval-agent/review_local.py b/tools/pr-approval-agent/review_local.py
index 110c4edacef4..74a21c6909ff 100644
--- a/tools/pr-approval-agent/review_local.py
+++ b/tools/pr-approval-agent/review_local.py
@@ -124,8 +124,13 @@ def _build_pr_data(context: dict) -> PRData:
"""
pr = context.get("pr") or {}
user = pr.get("user") or {}
- base_sha = context.get("base_sha") or (pr.get("base") or {}).get("sha") 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 ""
+ # 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)
if not files:
@@ -198,6 +203,7 @@ def _build_pr_data(context: dict) -> PRData:
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,
files=files,
@@ -208,6 +214,7 @@ def _build_pr_data(context: dict) -> PRData:
pr_reactions=pr_reactions,
body=pr.get("body") or "",
discussion=_normalize_discussion_for_prompt(context.get("discussion") or []),
+ default_branch=default_branch,
)
@@ -315,7 +322,11 @@ 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.
- pipeline = Pipeline(0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")))
+ # 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")), head_checkout=True
+ )
pipeline.pr = _build_pr_data(context)
if pipeline.pr.author_is_bot and not pipeline.self_driving:
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.py
index 7568bf78bc2f..e5fda00fbdbf 100644
--- a/tools/pr-approval-agent/review_pr.py
+++ b/tools/pr-approval-agent/review_pr.py
@@ -24,8 +24,11 @@ Requires `gh` CLI authenticated and ANTHROPIC_API_KEY in env.
import os
import json
import time
+import uuid
import argparse
+import tempfile
import subprocess
+from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
@@ -141,6 +144,10 @@ _NON_RETRYABLE_PATTERNS = (
)
+class WorktreeUnavailableError(RuntimeError):
+ """The PR head tree required for a stacked review could not be created."""
+
+
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).
@@ -193,7 +200,14 @@ 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
+ self,
+ pr_number: int,
+ repo: str,
+ *,
+ dry_run: bool = False,
+ verbose: bool = False,
+ self_driving: bool = False,
+ head_checkout: bool = False,
):
self.pr_number = pr_number
self.repo = repo
@@ -203,6 +217,10 @@ class Pipeline:
# implementation run. It relaxes two gates (bot author, draft) and swaps author trust for
# task provenance.
self.self_driving = self_driving
+ # 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
self._wait_refetched_pr = False
self.pr: PRData | None = None
self.provenance: CommitProvenance | None = None
@@ -552,9 +570,7 @@ class Pipeline:
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 / ".pr-review-diff.patch", REPO_ROOT
- )
+ self._diff_path = write_pr_diff(self.pr.base_sha, self.pr.head_sha, REPO_ROOT)
return self._diff_path
def _run_gates(self) -> None:
@@ -695,21 +711,103 @@ class Pipeline:
return True, f"T0 auto-approve: {summary}"
return True, summary
- def _llm_review(self, gate_verdict: str) -> None:
- print(f"\n{_bold('LLM Review')}")
- reviewer = Reviewer(REPO_ROOT, verbose=self.verbose)
- # 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()
+ @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):
+ """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
- gate_context = {
- "gate_verdict": gate_verdict,
- "gates": [{"gate": g.gate, "passed": g.passed, "message": g.message} for g in self.gate_results],
- }
+ 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)}")
- print(_dim(" Calling reviewer..."))
+ 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
- reviewer_unavailable = False
for attempt in range(max_retries):
try:
self.reviewer_output = reviewer.review(
@@ -718,7 +816,7 @@ class Pipeline:
gate_context,
diff_path=diff_path,
)
- break
+ return False
except Exception as e:
err_str = str(e)
is_retryable = _is_retryable_error(err_str)
@@ -728,41 +826,71 @@ class Pipeline:
print(_warn(f"Reviewer failed (attempt {attempt + 1}/{max_retries}): {e}"))
print(_dim(f" Retrying in {wait}s..."))
time.sleep(wait)
- else:
- reviewer_unavailable = True
- 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 STAMPHOG_ANTHROPIC_API_KEY "
- "secret (or local ANTHROPIC_API_KEY)."
- )
+ 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 STAMPHOG_ANTHROPIC_API_KEY "
+ "secret (or local ANTHROPIC_API_KEY)."
)
- 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],
- }
- break
+ )
+ 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 _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 = Reviewer(REPO_ROOT, explore_root=explore_root, verbose=self.verbose)
+ 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}")
@@ -913,6 +1041,7 @@ class Pipeline:
"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(),
diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.py
index f087fe99f9f2..f743f82ec6af 100644
--- a/tools/pr-approval-agent/reviewer.py
+++ b/tools/pr-approval-agent/reviewer.py
@@ -7,6 +7,7 @@ and reach a verdict on whether a PR is safe to auto-approve.
import os
import json
+import shutil
import asyncio
import textwrap
from pathlib import Path
@@ -14,7 +15,7 @@ from pathlib import Path
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from claude_agent_sdk.types import AssistantMessage, ToolUseBlock
from gateway import analytics_extra_properties, gateway_env, resolve_gateway_config
-from github import PRData, write_pr_diff
+from github import PRData, new_diff_file, write_pr_diff
from policy import _sanitize_untrusted, review_guidance_path, steering_path
from version import STAMPHOG_VERSION
@@ -301,8 +302,12 @@ def _apply_gateway_route(gateway: tuple[str, str] | None, attribution: dict[str,
class Reviewer:
"""LLM reviewer using Agent SDK."""
- def __init__(self, repo_root: Path, *, verbose: bool = False):
+ def __init__(self, repo_root: Path, *, explore_root: Path | None = None, verbose: bool = False):
self.repo_root = repo_root
+ # Where the agent's Read/Grep/Glob look. For stacked PRs this is a
+ # worktree at the PR head so imports from not-yet-merged parent PRs
+ # resolve (see review_pr._pr_head_worktree). Falls back to repo_root.
+ self.explore_root = explore_root or repo_root
self.verbose = verbose
def review(self, pr: PRData, classification: dict, gate_context: dict, diff_path: Path | None = None) -> dict:
@@ -313,12 +318,30 @@ class Reviewer:
"""
return asyncio.run(self._review(pr, classification, gate_context, diff_path))
+ def _copy_diff_into_explore_root(self, diff_path: Path) -> Path:
+ """Copy the diff to a runner-created path the agent can read (see new_diff_file)."""
+ copied_diff_path = new_diff_file(self.explore_root)
+ try:
+ shutil.copyfile(diff_path, copied_diff_path)
+ except OSError:
+ copied_diff_path.unlink(missing_ok=True)
+ raise
+ return copied_diff_path
+
async def _review(
self, pr: PRData, classification: dict, gate_context: dict, diff_path: Path | None = None
) -> dict:
owns_diff = diff_path is None
if diff_path is None:
diff_path = self._write_diff_file(pr)
+ original_diff = diff_path
+ copied_diff_path: Path | None = None
+ if self.explore_root != self.repo_root:
+ # The agent's file access is scoped to cwd (explore_root); a diff
+ # sitting in the master checkout would need an out-of-cwd read the
+ # dontAsk permission mode never grants.
+ copied_diff_path = self._copy_diff_into_explore_root(diff_path)
+ diff_path = copied_diff_path
prompt = self._build_review_prompt(pr, classification, gate_context, diff_path)
# Gate denials and trivial PRs don't need deep exploration —
@@ -329,7 +352,27 @@ class Reviewer:
system_prompt=REVIEWER_SYSTEM,
allowed_tools=["Read", "Grep", "Glob"],
disallowed_tools=["Write", "Edit", "NotebookEdit", "Bash", "Agent", "WebFetch", "WebSearch"],
- cwd=str(self.repo_root),
+ cwd=str(self.explore_root),
+ # SECURITY: explore_root holds PR-authored content (a worktree at
+ # the PR head for stacked PRs in the Action; the whole checkout in
+ # the hosted sandbox, which clones the head for every review). With
+ # the default (None) the SDK
+ # loads filesystem settings from cwd like the CLI does — including
+ # .claude/settings.json hooks (arbitrary command execution) and
+ # CLAUDE.md (injected as instructions). A PR could ship either.
+ # [] is SDK isolation mode: no filesystem settings, no hooks, no
+ # CLAUDE.md autoload. The agent can still Read those files, but as
+ # untrusted content under the anti-injection notice, never as
+ # configuration. This is the guardrail that makes pointing cwd at
+ # PR-controlled files safe.
+ setting_sources=[],
+ # setting_sources=[] covers settings.json but not .mcp.json, which
+ # has its own discovery. The CLI's project-trust gate already
+ # refuses an unapproved .mcp.json in headless mode, but pin it:
+ # strict config + empty server map ignore any .mcp.json the PR
+ # ships in the head tree, regardless of CLI defaults.
+ mcp_servers={},
+ strict_mcp_config=True,
max_turns=5 if quick else 20,
model=MODEL,
permission_mode="dontAsk",
@@ -410,34 +453,39 @@ class Reviewer:
active_query = query
structured_output = None
- async for message in active_query(prompt=prompt, options=options, **posthog_kwargs):
- if self.verbose:
- print(f"\033[2m [{type(message).__name__}]\033[0m", flush=True)
- if isinstance(message, ResultMessage):
- if message.subtype == "error_max_structured_output_retries":
- raise RuntimeError("Agent could not produce valid structured output after retries")
- if getattr(message, "is_error", False):
- # An API-level failure (auth, rate limit, overload, quota) surfaces
- # here with subtype "success" and the real HTTP status in
- # api_error_status. Raise with that detail now — otherwise the CLI
- # process exits right after this message and the SDK's read loop
- # replaces it with the generic, status-less "Claude Code returned
- # an error result: success" once the exception reaches us anyway.
- # getattr guards older SDK builds that lack these attributes.
- api_status = getattr(message, "api_error_status", None)
- status = f" (HTTP {api_status})" if api_status else ""
- raise RuntimeError(f"Anthropic API error{status}: {message.result or message.subtype}")
- if message.structured_output:
- structured_output = message.structured_output
- # Stamp the LLM verdict onto the trace properties
- props["stamphog_llm_verdict"] = structured_output.get("verdict", "")
- elif isinstance(message, AssistantMessage):
- for block in message.content:
- if isinstance(block, ToolUseBlock) and self.verbose:
- self._log_tool_call(block)
-
- if owns_diff:
- diff_path.unlink(missing_ok=True)
+ try:
+ async for message in active_query(prompt=prompt, options=options, **posthog_kwargs):
+ if self.verbose:
+ print(f"\033[2m [{type(message).__name__}]\033[0m", flush=True)
+ if isinstance(message, ResultMessage):
+ if message.subtype == "error_max_structured_output_retries":
+ raise RuntimeError("Agent could not produce valid structured output after retries")
+ if getattr(message, "is_error", False):
+ # An API-level failure (auth, rate limit, overload, quota) surfaces
+ # here with subtype "success" and the real HTTP status in
+ # api_error_status. Raise with that detail now — otherwise the CLI
+ # process exits right after this message and the SDK's read loop
+ # replaces it with the generic, status-less "Claude Code returned
+ # an error result: success" once the exception reaches us anyway.
+ # getattr guards older SDK builds that lack these attributes.
+ api_status = getattr(message, "api_error_status", None)
+ status = f" (HTTP {api_status})" if api_status else ""
+ raise RuntimeError(f"Anthropic API error{status}: {message.result or message.subtype}")
+ if message.structured_output:
+ structured_output = message.structured_output
+ # Stamp the LLM verdict onto the trace properties
+ props["stamphog_llm_verdict"] = structured_output.get("verdict", "")
+ elif isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, ToolUseBlock) and self.verbose:
+ self._log_tool_call(block)
+ finally:
+ # Runs on every exit path (API error, cancellation): PR-authored diff copies must not
+ # linger on the runner.
+ if copied_diff_path is not None:
+ copied_diff_path.unlink(missing_ok=True)
+ if owns_diff:
+ original_diff.unlink(missing_ok=True)
if structured_output is None:
raise RuntimeError("Reviewer agent returned no structured output")
@@ -461,8 +509,7 @@ class Reviewer:
def _write_diff_file(self, pr: PRData) -> Path:
"""Write the PR diff to a temp file so the LLM can Read it on demand."""
- diff_path = self.repo_root / ".pr-review-diff.patch"
- return write_pr_diff(pr.base_sha, pr.head_sha, diff_path, self.repo_root)
+ return write_pr_diff(pr.base_sha, pr.head_sha, self.repo_root)
def _build_review_prompt(self, pr: PRData, cl: dict, gate_context: dict, diff_path: Path) -> str:
safe_title = _sanitize_untrusted(pr.title, max_len=200)
@@ -551,6 +598,18 @@ class Reviewer:
"scripts or lifecycle hooks changed."
)
+ # For a stacked PR the working tree is the PR head, so parent-PR symbols
+ # resolve in Read/Grep/Glob though absent from the diff; tell the agent.
+ # The base branch name is author-chosen, so it stays out of this trusted
+ # block; the stacked fact alone is what the agent needs.
+ if pr.stacked:
+ constraint += (
+ f"\nStacked PR: this targets a non-default branch, not `{pr.default_branch}`. The working tree "
+ "reflects the codebase as it will look after the whole stack lands, so symbols defined in "
+ "parent PRs resolve via Read/Grep/Glob even though they're absent from the diff below. Review "
+ "only the diff's changes; do not flag imports or references that resolve in the tree as missing."
+ )
+
file_list = "\n".join(
f" {f['filename']} (+{f['additions']}/-{f['deletions']})" + (" [NEW]" if f.get("status") == "A" else "")
for f in pr.files
diff --git a/tools/pr-approval-agent/test_familiarity.py b/tools/pr-approval-agent/test_familiarity.py
index b1807253d536..a90518f9451c 100644
--- a/tools/pr-approval-agent/test_familiarity.py
+++ b/tools/pr-approval-agent/test_familiarity.py
@@ -315,6 +315,7 @@ def _prompt_fixture() -> tuple[PRData, dict, dict]:
mergeable_state="clean",
author="alice",
labels=[],
+ base_ref="master",
base_sha="base",
head_sha="head",
files=[{"filename": "src/foo.py", "additions": 3, "deletions": 1, "status": "M"}],
diff --git a/tools/pr-approval-agent/test_github.py b/tools/pr-approval-agent/test_github.py
index 83b559b944ba..91ae25604925 100644
--- a/tools/pr-approval-agent/test_github.py
+++ b/tools/pr-approval-agent/test_github.py
@@ -1,6 +1,7 @@
"""Tests for GitHub review normalization used by the PR approval agent."""
import re
+from pathlib import Path
import pytest
@@ -11,6 +12,7 @@ from github import (
_normalize_reviews_for_prompt,
_reaction_emoji,
_trusted_reactor_predicate,
+ ensure_commits,
is_bot_author,
parse_provenance_trailers,
)
@@ -88,6 +90,49 @@ def test_normalize_reviews_filters_by_trust_source(
assert len(normalized) == expected_count
+class _Result:
+ def __init__(self, returncode: int) -> None:
+ self.returncode = returncode
+
+
+ "present, expected_fetches",
+ [
+ pytest.param({"HEAD_SHA", "BASE_SHA"}, [], id="both-present-no-fetch"),
+ pytest.param({"BASE_SHA"}, ["pull/9/head"], id="head-missing-fetches-pr-head"),
+ pytest.param({"HEAD_SHA"}, ["query-validations"], id="base-missing-fetches-base-branch"),
+ pytest.param(set(), ["pull/9/head", "query-validations"], id="both-missing-fetches-both"),
+ ],
+)
+def test_ensure_commits_fetches_missing_head_and_base(
+ monkeypatch: pytest.MonkeyPatch, present: set[str], expected_fetches: list[str]
+) -> None:
+ """Stacked PRs target a parent branch, so the base commit may not be
+ reachable from the master checkout. ensure_commits fetches whatever is
+ missing — head via the pull ref, base via the base branch name."""
+ fetched: list[str] = []
+
+ def fake_run(cmd: list[str], **kwargs: object) -> _Result:
+ if cmd[:3] == ["git", "cat-file", "-t"]:
+ return _Result(0 if cmd[3] in present else 1)
+ if "fetch" in cmd:
+ fetched.append(cmd[-1])
+ return _Result(0)
+ return _Result(0)
+
+ monkeypatch.setattr(github.subprocess, "run", fake_run)
+
+ ensure_commits(
+ pr_number=9,
+ head_sha="HEAD_SHA",
+ base_ref="query-validations",
+ base_sha="BASE_SHA",
+ repo_root=Path("/repo"),
+ )
+
+ assert fetched == expected_fetches
+
+
@pytest.mark.parametrize(
"login,expected_count",
[
diff --git a/tools/pr-approval-agent/test_policy.py b/tools/pr-approval-agent/test_policy.py
index 0d6a71c04ba5..fa09174f698c 100644
--- a/tools/pr-approval-agent/test_policy.py
+++ b/tools/pr-approval-agent/test_policy.py
@@ -404,6 +404,7 @@ def test_size_gate_applies_mixed_leniency(n_global: int, expected_ok: bool) -> N
mergeable_state="clean",
author="alice",
labels=[],
+ base_ref="master",
base_sha="base",
head_sha="head",
files=vr_files + global_files,
@@ -548,6 +549,7 @@ def _body_pipeline(fam) -> "review_pr.Pipeline":
mergeable_state="clean",
author="alice",
labels=[],
+ base_ref="master",
base_sha="base",
head_sha="91c4be2aaaa",
files=[{"filename": "products/visual_review/a.py", "additions": 3, "deletions": 1, "status": "M"}],
diff --git a/tools/pr-approval-agent/test_review_local.py b/tools/pr-approval-agent/test_review_local.py
index c90af4324b7c..ae68d335d587 100644
--- a/tools/pr-approval-agent/test_review_local.py
+++ b/tools/pr-approval-agent/test_review_local.py
@@ -12,6 +12,7 @@ from unittest.mock import MagicMock
sys.modules.setdefault("claude_agent_sdk", MagicMock())
sys.modules.setdefault("claude_agent_sdk.types", MagicMock())
+import review_pr # noqa: E402
import review_local # noqa: E402
from review_pr import Pipeline # noqa: E402
@@ -313,3 +314,67 @@ def test_self_driving_flag_reviews_the_bot_authored_draft(monkeypatch) -> None:
prerequisites = next(g for g in result["gates"] if g["gate"] == "prerequisites")
assert prerequisites["passed"] is True # the draft issue is carved out for this run
assert result["classification"]["self_driving"] is True # provenance rides into the output contract
+
+
+def _stacked_context(base_ref: str, default_branch: str) -> dict:
+ return {
+ "repo": "PostHog/posthog",
+ "head_sha": "abc123",
+ "base_sha": "def456",
+ "pr": {
+ "number": 11,
+ "title": "feat: child of a stack",
+ "state": "OPEN",
+ "draft": False,
+ "user": {"login": "author", "type": "User"},
+ "base": {"ref": base_ref, "sha": "def456", "repo": {"default_branch": default_branch}},
+ },
+ }
+
+
+ "base_ref, default_branch, expect_stacked",
+ [
+ pytest.param("master", "master", False, id="trunk-pr"),
+ pytest.param("feat/parent", "master", True, id="stacked-on-a-parent-branch"),
+ pytest.param("main", "main", False, id="trunk-named-main"),
+ ],
+)
+def test_stacked_detection_follows_the_repo_default_branch(
+ monkeypatch, base_ref: str, default_branch: str, expect_stacked: bool
+) -> None:
+ # The hosted runtime reviews repos whose trunk is "main"; a hardcoded "master" would tag every
+ # PR there as stacked and mis-brief the reviewer.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+
+ pr = review_local._build_pr_data(_stacked_context(base_ref, default_branch))
+
+ assert pr.stacked is expect_stacked
+
+
+def test_hosted_stacked_review_never_creates_a_worktree(monkeypatch) -> None:
+ # The sandbox clones and checks out the PR head before the engine runs, so parent-PR symbols
+ # already resolve. Reviving the Action's stacked-PR worktree here would be a wasted full-tree
+ # checkout per stacked review, plus its symlink-rejection failure mode.
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ real_run = review_pr.subprocess.run
+
+ def guarded_run(cmd, *args, **kwargs):
+ assert "worktree" not in cmd, f"hosted review must not create a worktree: {cmd}"
+ return real_run(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(review_pr.subprocess, "run", guarded_run)
+ seen: dict = {}
+
+ def fake_review(self, pr, classification, gate_context, diff_path=None):
+ seen["explore_root"] = self.explore_root
+ seen["stacked"] = pr.stacked
+ return {"verdict": "APPROVE", "reasoning": "ok", "risk": "low", "issues": []}
+
+ monkeypatch.setattr(review_pr.Reviewer, "review", fake_review)
+
+ result = review_local.run(_stacked_context("feat/parent", "master"))
+
+ assert result["final_verdict"] == "APPROVED"
+ assert seen["stacked"] is True
+ assert seen["explore_root"] == review_pr.REPO_ROOT
diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.py
index 2fe61f131760..4823140cf847 100644
--- a/tools/pr-approval-agent/test_review_pr.py
+++ b/tools/pr-approval-agent/test_review_pr.py
@@ -29,7 +29,7 @@ def _no_live_team_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(review_pr, "compute_familiarity", lambda **_k: None)
-def _fake_pr(head_sha: str) -> PRData:
+def _fake_pr(head_sha: str, base_ref: str = "master", default_branch: str = "master") -> PRData:
return PRData(
number=1,
repo="PostHog/posthog",
@@ -39,12 +39,14 @@ def _fake_pr(head_sha: str) -> PRData:
mergeable_state="clean",
author="alice",
labels=[],
+ base_ref=base_ref,
base_sha="def456",
head_sha=head_sha,
files=[],
reviews=[],
review_comments=[],
check_runs=[],
+ default_branch=default_branch,
)
@@ -81,12 +83,14 @@ def test_summarize_assurance_excludes_author_self_review() -> None:
assert assurance["head_commented_users"] == ["bob"]
-def test_to_dict_includes_head_sha() -> None:
- """The post-review workflow step reads head_sha from the JSON output to
- lock the resulting GitHub review to the sha the LLM actually saw — see
+def test_to_dict_includes_reviewed_base_and_head_shas() -> None:
+ """The post-review workflow step reads base_sha/head_sha from the JSON output
+ to lock the resulting GitHub review to the sha the LLM actually saw and to
+ skip the approval if the PR's base or head changed after review — see
`.github/workflows/pr-approval-agent.yml`'s "Post review" step."""
pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
pipeline.pr = _fake_pr(head_sha="07dfeff14d95be1247e4c8c1065fd958a367389e")
+ pipeline.pr.base_sha = "b5412a26ec97b9d97367c7356cfe9d9b836ae3cb"
pipeline.classification = {"tier": "T1-trivial", "breadth": "narrow"}
pipeline.gate_results = []
pipeline.reviewer_output = None
@@ -94,6 +98,7 @@ def test_to_dict_includes_head_sha() -> None:
output = pipeline.to_dict()
+ assert output["base_sha"] == "b5412a26ec97b9d97367c7356cfe9d9b836ae3cb"
assert output["head_sha"] == "07dfeff14d95be1247e4c8c1065fd958a367389e"
@@ -126,13 +131,16 @@ class _TurnLimitReviewer:
],
)
def test_backend_failure_yields_error_except_when_gates_deny(
- monkeypatch: pytest.MonkeyPatch, gate_verdict: str, expected_final: str
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, gate_verdict: str, expected_final: str
) -> None:
"""A failed LLM call must surface as ERROR (label retained) unless gates
already DENIED — a deterministic denial outranks an unavailable reviewer."""
monkeypatch.setattr(review_pr, "Reviewer", _RaisingReviewer)
monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)
monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ # _llm_review is called directly, so run()'s diff cleanup never happens — keep the scratch
+ # diff out of the real checkout.
+ monkeypatch.setattr(review_pr, "REPO_ROOT", tmp_path)
pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
pipeline.pr = _fake_pr(head_sha="abc123")
@@ -157,7 +165,9 @@ def test_backend_failure_yields_error_except_when_gates_deny(
("DENIED", "REFUSED"),
],
)
-def test_turn_limit_error_not_retried(monkeypatch: pytest.MonkeyPatch, gate_verdict: str, expected_final: str) -> None:
+def test_turn_limit_error_not_retried(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, gate_verdict: str, expected_final: str
+) -> None:
"""A turn-limit error is non-retryable and should give a clear message
about complexity rather than blaming infrastructure. When gates DENIED,
the deterministic denial still outranks the error."""
@@ -173,6 +183,7 @@ def test_turn_limit_error_not_retried(monkeypatch: pytest.MonkeyPatch, gate_verd
monkeypatch.setattr(_TurnLimitReviewer, "review", counting_review)
monkeypatch.setattr(review_pr.time, "sleep", lambda _s: None)
monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_pr, "REPO_ROOT", tmp_path)
pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
pipeline.pr = _fake_pr(head_sha="abc123")
@@ -442,6 +453,164 @@ def test_wait_refetch_reclassifies_before_review(monkeypatch: pytest.MonkeyPatch
assert pipeline.classification["deny_categories"] == ["infra_cicd"]
+class _FakeCompleted:
+ def __init__(self, returncode: int, stderr: str = "", stdout: str = "") -> None:
+ self.returncode = returncode
+ self.stderr = stderr
+ self.stdout = stdout
+
+
+def test_pr_head_worktree_yields_path_and_cleans_up(monkeypatch: pytest.MonkeyPatch) -> None:
+ """On success (stacked PR) the context manager yields the worktree path and removes it on exit."""
+ calls: list[list[str]] = []
+
+ def fake_run(cmd: list[str], **kwargs: object) -> _FakeCompleted:
+ calls.append(cmd)
+ return _FakeCompleted(0)
+
+ monkeypatch.setattr(review_pr.subprocess, "run", fake_run)
+
+ pipeline = Pipeline(pr_number=42, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="cafe123", base_ref="feat/parent-branch")
+
+ with pipeline._pr_head_worktree() as explore_root:
+ assert explore_root is not None
+ assert "pr-review-42-" in explore_root.name
+ add = next(c for c in calls if "add" in c)
+ assert "--detach" in add and "cafe123" in add
+
+ # Cleanup ran with --force after the block exited.
+ remove = next(c for c in calls if "remove" in c)
+ assert "--force" in remove
+
+
+def test_pr_head_worktree_fails_closed_on_creation_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(cmd: list[str], **kwargs: object) -> _FakeCompleted:
+ calls.append(cmd)
+ if "ls-tree" in cmd:
+ return _FakeCompleted(0)
+ return _FakeCompleted(1, stderr="fatal: invalid reference")
+
+ monkeypatch.setattr(review_pr.subprocess, "run", fake_run)
+
+ pipeline = Pipeline(pr_number=7, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="deadbeef", base_ref="feat/parent-branch")
+
+ with pytest.raises(review_pr.WorktreeUnavailableError, match="invalid reference"):
+ with pipeline._pr_head_worktree():
+ pass
+
+ # No worktree was created, so none is removed.
+ assert not any("remove" in c for c in calls)
+
+
+ "head_links, trunk_links, expect_reject",
+ [
+ pytest.param("120000 blob abcdef\tlink\n", "", True, id="pr-adds-symlink"),
+ pytest.param(
+ "120000 blob abcdef\tCLAUDE.md\n", "120000 blob abcdef\tCLAUDE.md\n", False, id="trunk-symlink-kept"
+ ),
+ pytest.param(
+ "120000 blob 000000\tCLAUDE.md\n", "120000 blob abcdef\tCLAUDE.md\n", True, id="pr-retargets-symlink"
+ ),
+ ],
+)
+def test_pr_head_worktree_rejects_only_symlinks_the_pr_adds(
+ monkeypatch: pytest.MonkeyPatch, head_links: str, trunk_links: str, expect_reject: bool
+) -> None:
+ # The trunk carries tracked symlinks (CLAUDE.md -> AGENTS.md and friends); rejecting any symlink
+ # in the head would fail every stacked review closed. Only links the PR adds or repoints,
+ # relative to the default branch, are untrusted.
+ calls: list[list[str]] = []
+
+ def fake_run(cmd: list[str], **kwargs: object) -> _FakeCompleted:
+ calls.append(cmd)
+ if "ls-tree" in cmd:
+ return _FakeCompleted(0, stdout=trunk_links if cmd[-1] == "origin/master" else head_links)
+ if expect_reject:
+ raise AssertionError(f"symlinked PR must not create a worktree: {cmd}")
+ return _FakeCompleted(0)
+
+ monkeypatch.setattr(review_pr.subprocess, "run", fake_run)
+
+ pipeline = Pipeline(pr_number=7, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="deadbeef", base_ref="feat/parent-branch")
+
+ if expect_reject:
+ with pytest.raises(review_pr.WorktreeUnavailableError, match="adds symbolic links"):
+ with pipeline._pr_head_worktree():
+ pass
+ assert len(calls) == 2
+ else:
+ with pipeline._pr_head_worktree() as explore_root:
+ assert explore_root is not None
+
+
+def test_pr_head_worktree_ignores_cleanup_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
+ def fake_run(cmd: list[str], **kwargs: object) -> _FakeCompleted:
+ if "remove" in cmd:
+ raise review_pr.subprocess.TimeoutExpired(cmd, timeout=30)
+ return _FakeCompleted(0)
+
+ monkeypatch.setattr(review_pr.subprocess, "run", fake_run)
+
+ pipeline = Pipeline(pr_number=7, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="cafe123", base_ref="feat/parent-branch")
+
+ with pipeline._pr_head_worktree() as explore_root:
+ assert explore_root is not None
+
+
+def test_stacked_worktree_failure_returns_error(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ @review_pr.contextmanager
+ def unavailable_worktree():
+ raise review_pr.WorktreeUnavailableError("checkout unavailable")
+ yield None
+
+ pipeline = Pipeline(pr_number=7, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="cafe123", base_ref="feat/parent-branch")
+ pipeline.gate_results = []
+ monkeypatch.setattr(pipeline, "_pr_head_worktree", unavailable_worktree)
+ monkeypatch.setattr(pipeline, "_ensure_diff_path", lambda: tmp_path / "diff.patch")
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+
+ pipeline._llm_review("PENDING")
+
+ assert pipeline.final_verdict == "ERROR"
+ assert pipeline.reviewer_output is not None
+ assert pipeline.reviewer_output["issues"] == ["checkout unavailable"]
+
+
+ "base_ref, default_branch, head_checkout",
+ [
+ pytest.param("master", "master", False, id="trunk-is-master"),
+ pytest.param("main", "main", False, id="trunk-is-main"),
+ pytest.param("feat/parent-branch", "master", True, id="hosted-checkout-already-at-head"),
+ ],
+)
+def test_pr_head_worktree_skipped_when_not_needed(
+ monkeypatch: pytest.MonkeyPatch, base_ref: str, default_branch: str, head_checkout: bool
+) -> None:
+ """No worktree — so git is never invoked and the full-tree checkout cost is
+ skipped — for a PR targeting the repo's trunk (whatever it is named), and
+ for a runtime whose checkout already is the PR head (the hosted sandbox)."""
+
+ def fake_run(cmd: list[str], **kwargs: object) -> _FakeCompleted:
+ raise AssertionError(f"must not touch git: {cmd}")
+
+ monkeypatch.setattr(review_pr.subprocess, "run", fake_run)
+
+ pipeline = Pipeline(pr_number=7, repo="PostHog/posthog", head_checkout=head_checkout)
+ pipeline.pr = _fake_pr(head_sha="cafe123", base_ref=base_ref, default_branch=default_branch)
+
+ with pipeline._pr_head_worktree() as explore_root:
+ assert explore_root is None
+
+
@pytest.mark.parametrize(
"tier, expect_in_prompt",
[
diff --git a/tools/pr-approval-agent/test_reviewer.py b/tools/pr-approval-agent/test_reviewer.py
index 7fb98012047d..a49415c246e0 100644
--- a/tools/pr-approval-agent/test_reviewer.py
+++ b/tools/pr-approval-agent/test_reviewer.py
@@ -26,6 +26,7 @@ def _pr(**overrides: object) -> PRData:
"mergeable_state": "clean",
"author": "alice",
"labels": [],
+ "base_ref": "master",
"base_sha": "a",
"head_sha": "h",
"files": [],
@@ -186,6 +187,53 @@ def test_inline_truncation_keeps_unresolved_drops_resolved(
assert line == omission
+def test_explore_root_defaults_to_repo_root() -> None:
+ repo = Path("/repo")
+ assert Reviewer(repo).explore_root == repo
+ other = Path("/tmp/wt")
+ assert Reviewer(repo, explore_root=other).explore_root == other
+
+
+def test_copy_diff_into_explore_root_cannot_follow_pr_symlink(tmp_path: Path) -> None:
+ source_diff = tmp_path / "source.patch"
+ source_diff.write_text("diff --git a/file b/file\n")
+ explore_root = tmp_path / "explore"
+ explore_root.mkdir()
+ outside_target = tmp_path / "outside"
+ outside_target.write_text("unchanged")
+ (explore_root / ".pr-review-diff.patch").symlink_to(outside_target)
+
+ copied_diff = Reviewer(tmp_path, explore_root=explore_root)._copy_diff_into_explore_root(source_diff)
+
+ assert copied_diff.parent == explore_root
+ assert copied_diff.name != ".pr-review-diff.patch"
+ assert copied_diff.read_text() == source_diff.read_text()
+ assert outside_target.read_text() == "unchanged"
+
+
+ "base_ref, default_branch, expect_stack_note",
+ [
+ ("master", "master", False),
+ ("query-validations", "master", True),
+ # Stacked-ness keys off the repo's own trunk, not a hardcoded "master".
+ ("main", "main", False),
+ ("master", "main", True),
+ ],
+)
+def test_prompt_stack_note(base_ref: str, default_branch: str, expect_stack_note: bool) -> None:
+ # A stacked PR (base != the repo's default branch) gets a note telling the
+ # agent that parent-PR symbols resolve in the tree and aren't missing.
+ prompt = _prompt(_pr(base_ref=base_ref, default_branch=default_branch))
+
+ assert ("Stacked PR" in prompt) is expect_stack_note
+ if expect_stack_note:
+ assert f"targets a non-default branch, not `{default_branch}`" in prompt
+ # The author-chosen base branch name must not land in the trusted block.
+ trusted, _, _ = prompt.rpartition("--- BEGIN UNTRUSTED CONTENT ---")
+ assert base_ref not in trusted
+
+
def _fake_stamphog_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, guidance: str) -> Path:
monkeypatch.setattr(policy, "repo_root", lambda: tmp_path)
stamphog_dir = tmp_path / ".stamphog"