:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(stamphog): remove the PR-approval GitHub Action (#85565)
Julian Bezbd558c85822f
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 39f5b1aa0c2f..32696e5b72a7 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -49,7 +49,6 @@ tools/owners/** @PostHog/team-securityCODEOWNERS @PostHog/team-security# PR approval agent — can auto-approve PRs, so changes need review-.github/workflows/pr-approval-agent.yml @PostHog/team-securitytools/pr-approval-agent/** @PostHog/team-security# Ingestion team owns persons migrationsdiff --git a/.github/scripts/minimize-superseded-comments.mjs b/.github/scripts/minimize-superseded-comments.mjsindex 9cff34ce317a..afc36d1a0b5c 100644--- a/.github/scripts/minimize-superseded-comments.mjs+++ b/.github/scripts/minimize-superseded-comments.mjs@@ -21,9 +21,6 @@// rewords its message the group silently stops matching, so the zero-match log below// is the breadcrumb that says a prefix has drifted.const COMMENT_GROUPS = [- // stamphog's per-push "kept your approval" notes ("Note retained approval" step- // in .github/workflows/pr-approval-agent.yml)- { author: 'github-actions', prefix: 'Retaining stamphog approval' },// "branch advanced" skip notices ("Post skip comment" step in// .github/actions/commit-snapshots/action.yml){ author: 'github-actions', prefix: '⏭️ Skipped snapshot commit' },diff --git a/.github/workflows/pr-approval-agent.yml b/.github/workflows/pr-approval-agent.ymldeleted file mode 100644index 6f52e1562cdd..000000000000--- a/.github/workflows/pr-approval-agent.yml+++ /dev/null@@ -1,520 +0,0 @@-name: PR Approval Agent--on:- pull_request:- 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 }}${{ github.event.action == 'edited' && github.event.changes.base == null && format('-edit-{0}', github.run_id) || '' }}- cancel-in-progress: true--jobs:- review:- # Write access is required to apply the stamphog label, so no- # additional author_association check is needed. Bot-authored PRs are- # hard-excluded regardless of who applies the label — see the- # bot-author-skip job, which strips the label and explains why.- # 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, 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.- if: >-- !cancelled()- && !github.event.pull_request.draft- && github.event.pull_request.user.type != 'Bot'- && !contains(github.event.pull_request.user.login, '[bot]')- && github.event.pull_request.user.login != 'posthog-bot'- && (- github.event.label.name == 'stamphog'- || (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- # per-poll refetches, so wall-clock exceeds it) plus the LLM review —- # see BOT_REVIEW_WAIT_BUDGET_SECONDS in review_pr.py. The cap costs- # nothing unless a run hangs; runners bill actual minutes.- timeout-minutes: 20-- steps:- - name: Get app token- id: app-token- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1- with:- client-id: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_APP_ID }}- private-key: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_PRIVATE_KEY }}-- # Always run the approval script from master — hardcoded so a PR- # targeting a non-master branch can't supply a tampered script.- - name: Checkout master (blobless, full history)- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- token: ${{ steps.app-token.outputs.token }}- ref: master- filter: blob:none- fetch-depth: 0-- - name: Fetch PR head ref- run: git fetch --filter=blob:none origin pull/${{ github.event.pull_request.number }}/head-- - name: Install uv- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0- with:- version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit- enable-cache: false-- - name: Run review- env:- # Dedicated key so a rotation of the shared ANTHROPIC_API_KEY- # doesn't break stamphog (and vice versa). The env var name- # stays ANTHROPIC_API_KEY — that's what the Claude Agent SDK reads.- ANTHROPIC_API_KEY: ${{ secrets.STAMPHOG_ANTHROPIC_API_KEY }}- # ai-gateway cutover: when both are set, the review routes through- # the Go ai-gateway (phs_ secret) instead of Anthropic directly.- # Unset = direct path, so setting them is the cutover.- AI_GATEWAY_URL: ${{ secrets.STAMPHOG_AI_GATEWAY_URL }}- AI_GATEWAY_API_KEY: ${{ secrets.STAMPHOG_AI_GATEWAY_API_KEY }}- POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_TOKEN }}- GH_TOKEN: ${{ steps.app-token.outputs.token }}- run: |- uv run tools/pr-approval-agent/review_pr.py \- ${{ github.event.pull_request.number }} \- --repo ${{ github.repository }} \- --output-json /tmp/review.json-- - name: Post review- if: ${{ !cancelled() }}- env:- # Everything stamphog does — the approval, the sticky comment,- # the label strip — posts as the Stamphog app (GH_TOKEN) so it- # all carries the bot's own identity. The app approval was- # confirmed to unblock PRs, so the earlier bodyless- # github-actions[bot] fallback approval has been dropped.- GH_TOKEN: ${{ steps.app-token.outputs.token }}- # Derived from the token step so the sticky-comment author- # filter tracks an app rename instead of failing silent.- BOT_LOGIN: ${{ steps.app-token.outputs.app-slug }}[bot]- run: |- PR=${{ github.event.pull_request.number }}- REPO=${{ github.repository }}- VERDICT=$(jq -r '.final_verdict // ""' /tmp/review.json 2>/dev/null || echo "")- # Prefer the structured comment body (reasoning + judgment- # 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- # review` records against the head at API-call time, which- # drifts mid-LLM-roundtrip if the author force-pushes.- SHA_ARGS=()- if [ -n "$REVIEWED_SHA" ]; then- SHA_ARGS=(-f "commit_id=$REVIEWED_SHA")- 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- # blocked and that must surface as a red run, not a warning.- gh api \- -X POST "repos/$REPO/pulls/$PR/reviews" \- "${SHA_ARGS[@]}" \- -f event=APPROVE \- -f body="$REASONING"- else- # Non-approve verdicts share ONE sticky comment, updated in- # place, instead of a fresh COMMENT review per run. Review- # bodies can't be minimized or deleted, so when an automation- # loop keeps re-applying the label against a deterministic- # denial (e.g. the size gate) the refusals pile up — one PR- # collected 60+ near-identical stamphog reviews.- MARKER='<!-- stamphog-sticky-review -->'- RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"-- # Author + leading-marker filter: on a public repo anyone can- # post a comment containing the marker; without the filter the- # bot would PATCH (clobber) a third-party comment. Slurp so the- # jq runs once over all pages (per-page filtering could emit- # one object per page); gh rejects --slurp combined with --jq,- # so pipe to standalone jq. The || guard keeps a transient- # lookup failure from aborting the step before the label strip- # below (it degrades to posting a fresh comment instead).- EXISTING=$(gh api "repos/$REPO/issues/$PR/comments" --paginate --slurp \- | jq "[.[][] | select(.user.login == \"$BOT_LOGIN\" and (.body | startswith(\"$MARKER\")))][0] // empty" \- || echo "")- COMMENT_ID=""- EXISTING_BODY=""- PREV_COUNT=0- if [ -n "$EXISTING" ]; then- COMMENT_ID=$(jq -r '.id' <<<"$EXISTING")- EXISTING_BODY=$(jq -r '.body' <<<"$EXISTING")- PREV_COUNT=$(jq -r '.body | (match("stamphog-review-count:([0-9]+)").captures[0].string // "0")' <<<"$EXISTING")- fi-- # The append path requires an actual verdict in the prior body —- # a crash-only prior comment goes through the rebuild branch so- # it can't end up claiming "the verdict above" over no verdict.- if [ -z "$REASONING" ] && [ -n "$COMMENT_ID" ] \- && grep -q 'verdict: \*\*' <<<"$EXISTING_BODY"; then- # Verdictless crash with a prior verdict on record: append the- # failure note below it rather than clobbering the reasoning- # the author still needs to act on. The anchored grep dedups- # only the note itself, never verdict reasoning that happens- # to mention review failures.- { grep -v '^> ⚠️ A later review run failed' <<<"$EXISTING_BODY" || true; } > /tmp/stamphog-comment.md- {- echo- echo "> ⚠️ A later review run failed before producing a verdict — check the [workflow run]($RUN_URL). The verdict above is from an earlier run."- } >> /tmp/stamphog-comment.md- else- # The counter tracks verdicts only — a crash rebuild keeps- # the previous count so repeated failures don't inflate it.- if [ -n "$REASONING" ]; then- COUNT=$((PREV_COUNT + 1))- HEADLINE="stamphog reviewed \`${REVIEWED_SHA:-unknown}\` — verdict: **${VERDICT:-unknown}**"- DETAIL="$REASONING"- else- COUNT=$PREV_COUNT- HEADLINE="stamphog review failed before producing a verdict"- DETAIL="Check the [workflow run]($RUN_URL) and re-apply the label to retry."- fi- {- echo "$MARKER"- echo "<!-- stamphog-review-count:$COUNT -->"- echo "> [!NOTE]"- echo "> 🤖 $HEADLINE"- echo- echo "$DETAIL"- if [ -n "$COMMENT_ID" ]; then- echo- [ "$PREV_COUNT" -gt 0 ] \- && echo "_Updated in place — this replaces $PREV_COUNT earlier stamphog review(s) on this PR._" \- || echo "_Updated in place from an earlier stamphog review._"- fi- } > /tmp/stamphog-comment.md- fi-- # A failed PATCH (comment deleted, transient API error) falls- # back to posting fresh, so the only unguarded API call left- # ahead of the label strip is the same single POST the old- # COMMENT-review path had.- if [ -n "$COMMENT_ID" ]; then- gh api -X PATCH "repos/$REPO/issues/comments/$COMMENT_ID" \- -F "body=@/tmp/stamphog-comment.md" || COMMENT_ID=""- fi- if [ -z "$COMMENT_ID" ]; then- gh api -X POST "repos/$REPO/issues/$PR/comments" \- -F "body=@/tmp/stamphog-comment.md"- fi- fi-- # Only the two substantive verdicts strip the label — a- # REFUSE/ESCALATE means the author must address feedback and- # re-apply. Everything else fails toward retention: ERROR- # (LLM backend down), WAIT (reviewer bot mid-review), and an- # empty verdict (script crash / job cancelled before- # review.json was written) are not verdicts on the PR, and- # retention just means the next push retries. An explicit- # strip-list also means future verdicts keep the label by- # default instead of everyone remembering to extend a- # keep-list.- if [ "$VERDICT" = "REFUSED" ] || [ "$VERDICT" = "ESCALATE" ]; then- gh pr edit "$PR" --remove-label stamphog \- --repo "$REPO"- fi-- - name: Upload evidence- if: ${{ !cancelled() }}- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- with:- name: review-${{ github.event.pull_request.number }}- path: /tmp/review.json- retention-days: 30-- # Defense-in-depth: master ruleset has dismiss_stale_reviews_on_push=false- # and require_last_push_approval=false, so a stale bot approval could- # otherwise inherit malicious commits. Two-step gate: decide-delta- # classifies the new commits since the last bot approval, dismiss only- # runs when the delta is non-trivial. Trivial deltas (test/docs/lockfile- # /generated paths and clean merges from the base branch) retain the- # prior approval — a comment on the PR records the reason. The stamphog- # label stays sticky across pushes; the review job's existing- # non-APPROVED label-strip is the auto-loop's escape hatch.- decide-delta:- if: >-- github.event.action == 'synchronize'- && !github.event.pull_request.draft- && github.event.pull_request.user.type != 'Bot'- && !contains(github.event.pull_request.user.login, '[bot]')- && github.event.pull_request.user.login != 'posthog-bot'- && contains(github.event.pull_request.labels.*.name, 'stamphog')- runs-on: ubuntu-latest- timeout-minutes: 5- outputs:- dismiss_approval: ${{ steps.decide.outputs.dismiss_approval }}- run_review: ${{ steps.decide.outputs.run_review }}- reason: ${{ steps.decide.outputs.reason }}- last_approved_sha: ${{ steps.decide.outputs.last_approved_sha }}-- steps:- - name: Get app token- id: app-token- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1- with:- client-id: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_APP_ID }}- private-key: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_PRIVATE_KEY }}-- - name: Checkout master (full history)- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2- with:- token: ${{ steps.app-token.outputs.token }}- ref: master- filter: blob:none- fetch-depth: 0-- - 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- with:- version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit- enable-cache: false-- - name: Decide retain vs dismiss- id: decide- env:- GH_TOKEN: ${{ steps.app-token.outputs.token }}- REPO: ${{ github.repository }}- PR_NUMBER: ${{ github.event.pull_request.number }}- HEAD_SHA: ${{ github.event.pull_request.head.sha }}- BASE_REF: origin/${{ github.event.pull_request.base.ref }}- run: |- set -euo pipefail- decision=$(uv run tools/pr-approval-agent/dismiss_check.py)- echo "$decision"- echo "dismiss_approval=$(echo "$decision" | jq -r .dismiss_approval)" >> "$GITHUB_OUTPUT"- echo "run_review=$(echo "$decision" | jq -r .run_review)" >> "$GITHUB_OUTPUT"- echo "reason=$(echo "$decision" | jq -r .reason)" >> "$GITHUB_OUTPUT"- echo "last_approved_sha=$(echo "$decision" | jq -r '.last_approved_sha // ""')" >> "$GITHUB_OUTPUT"-- # Only post the comment on actual retention reasons — not on- # no_prior_approval (nothing to retain) or empty_delta (HEAD- # didn't move, comment would be noise).- - name: Note retained approval- if: contains(fromJSON('["trivial_paths", "merge_only", "mixed_trivial"]'), steps.decide.outputs.reason)- env:- GH_TOKEN: ${{ steps.app-token.outputs.token }}- PR: ${{ github.event.pull_request.number }}- REPO: ${{ github.repository }}- REASON: ${{ steps.decide.outputs.reason }}- run: |- gh pr comment "$PR" --repo "$REPO" \- --body "Retaining stamphog approval — delta since last review classified as \`$REASON\`."-- # hogli-lint: not-a-required-gate — branches on decide-delta's result to decide- # whether to dismiss a stale approval; it emits no required status check.- dismiss:- needs: decide-delta- # Fail closed on three cases:- # - decide-delta said dismiss (smart path)- # - decide-delta failed (uv install / checkout / fetch timeout)- # - decide-delta was skipped (label removed out-of-band) — mirrors- # the pre-PR unconditional dismiss-on-push behavior so a stale- # bot approval can't outlive the label under master ruleset's- # dismiss_stale_reviews_on_push=false / require_last_push_approval=false- # Explicit synchronize + draft gates stop spurious dismissal on- # labeled / ready_for_review events where decide-delta's result is- # also 'skipped'.- # Bot authors are deliberately NOT excluded here: a bot-authored PR may- # still carry a stale github-actions[bot] approval from before the- # bot-author gate landed, and it must get dismissed on push. decide-delta- # is skipped for bots, which routes here via the 'skipped' fail-closed- # path. This only ever touches github-actions[bot] approvals, so it's a- # no-op when there's nothing to dismiss.- # Same-repo only: forked / Dependabot PRs don't receive the app secrets,- # so the app-token step below would fail on every such synchronize. There- # is nothing to dismiss there anyway, since stamphog can never have- # approved a fork PR (the review job's app-token step is equally starved- # 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- && (- needs.decide-delta.outputs.dismiss_approval == 'true'- || needs.decide-delta.result == 'failure'- || needs.decide-delta.result == 'skipped'- )- runs-on: ubuntu-latest- timeout-minutes: 5-- steps:- - name: Get app token- id: app-token- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1- with:- client-id: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_APP_ID }}- private-key: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_PRIVATE_KEY }}-- - name: Dismiss stale bot approvals- env:- # Act as the Stamphog app for consistency with every other- # write. pull-requests:write can dismiss any review regardless- # of its author, so the app dismisses both its own approvals- # and any legacy github-actions[bot] ones.- GH_TOKEN: ${{ steps.app-token.outputs.token }}- PR: ${{ github.event.pull_request.number }}- REPO: ${{ github.repository }}- REASON: ${{ needs.decide-delta.outputs.reason || (needs.decide-delta.result == 'skipped' && 'label_absent') || 'decide_delta_failed' }}- run: |- set -euo pipefail-- # Dismiss APPROVED reviews from either Stamphog identity —- # github-actions[bot] (bodyless approval) and stamphog[bot]- # (the app approval carrying the review body). Human reviews- # and non-approval reviews are untouched.- 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="New commits pushed (delta classified \`$REASON\`) — stamphog approval dismissed; re-review running automatically." \- -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- # gated to skip bot authors; this job runs instead to strip the label so- # it never lingers. Same bot definition as those job gates, and as the- # review script's defense-in-depth REFUSE.- # Fires on labeled / ready_for_review (the apply paths — comment + strip)- # and on synchronize when the label is still present (a leftover from before- # this gate landed, or a failed earlier strip — clean it up, no comment).- bot-author-skip:- if: >-- !github.event.pull_request.draft- && (- github.event.pull_request.user.type == 'Bot'- || contains(github.event.pull_request.user.login, '[bot]')- || github.event.pull_request.user.login == 'posthog-bot'- )- && (- github.event.label.name == 'stamphog'- || (github.event.action != 'labeled' && contains(github.event.pull_request.labels.*.name, 'stamphog'))- )- runs-on: ubuntu-latest- timeout-minutes: 5-- steps:- - name: Get app token- id: app-token- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1- with:- client-id: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_APP_ID }}- private-key: ${{ secrets.GH_APP_PR_APPROVAL_AGENT_PRIVATE_KEY }}-- - name: Comment and strip label- env:- GH_TOKEN: ${{ steps.app-token.outputs.token }}- PR: ${{ github.event.pull_request.number }}- REPO: ${{ github.repository }}- ACTION: ${{ github.event.action }}- run: |- set -euo pipefail- # Explain only on the apply paths (a human just labeled it, or- # 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- gh pr edit "$PR" --repo "$REPO" --remove-label stamphogdiff --git a/.stamphog/policy.yml b/.stamphog/policy.ymlindex 92ffc002104c..ea1cd1efa2ea 100644--- a/.stamphog/policy.yml+++ b/.stamphog/policy.yml@@ -178,18 +178,6 @@ tiers:max_lines: 300max_files: 15breadth: 'not-cross-cutting'-dismiss:- trivial_extensions:- - '.md'- - '.mdx'- trivial_name_prefixes:- - 'readme'- - 'changelog'- test_regex: '(?:^|/)(?:__tests__|tests?|fixtures)/|(?:^|/)test_[^/]+\.py$|_test\.(py|go)$|\.test\.(ts|tsx|js|jsx)$|\.spec\.(ts|tsx|js|jsx)$|(?:^|/)conftest\.py$'- # The bare-filename alternative is pinned to the one path ci-backend.yml regenerates and- # diffs. A general `(?:^|/)generated\.ts$` would retain an approval for any file a- # contributor chose to name that, and only this path has the drift check behind it.- generated_regex: '(?:^|/)generated/.*\.(ts|tsx|js|jsx|json|md|snap|pyi|txt)$|^services/mcp/src/api/generated\.ts$|\.gen\.(ts|tsx|js|jsx)$|\.generated\.(ts|tsx|js|jsx)$|^frontend/src/queries/schema/'overrides:'size_gate.max_files':ceiling: 50diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex 202118c94215..cc019145ffeb 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -88,8 +88,8 @@ add a read-then-act path, pin it; this class of bug has been found on five separand `include_internal_scopes=False`. Never switch to `include_internal_scopes=True` — thatdrags `task:write` into a sandbox running an LLM over untrusted PR content. The`internal_run:read` marker is what satisfies the gateway route's `requires_server_credential`.-- The raw-Anthropic fallback is for the Action runtime only; hosted runs fail closed without a- gateway. No `ANTHROPIC_API_KEY` may enter the sandbox environment.+- The raw-Anthropic fallback exists for a local `review_pr.py` run only; hosted runs fail closed+ without a gateway. No `ANTHROPIC_API_KEY` may enter the sandbox environment.- Egress is an explicit domain allowlist (`_sandbox_egress_allowlist`). Additions go through`STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS`, not code edits.- Everything posted to GitHub goes through `_scrub_credentials` AND `_neutralize_active_markdown`@@ -99,9 +99,9 @@ add a read-then-act path, pin it; this class of bug has been found on five separ## The self-driving inbox carve-out (the one exception to the bot-author refusal)-Bot-authored PRs are refused at every layer — the webhook pre-filter (`_review_skip_reason`),-the engine (`review_pr.py::_refuse_bot_author`, mirrored by `review_local.py`), and the-Action's job gates — with ONE deliberate exception: a PR **positively linked** to a+Bot-authored PRs are refused at every layer — the webhook pre-filter (`_review_skip_reason`) and+the engine (`review_pr.py::_refuse_bot_author`, called by `review_local.py`) — with ONE deliberate+exception: a PR **positively linked** to aself-driving Inbox implementation run (a signal-report-carrying TaskRun at`ai_stage="implementation"`, matched through the tasks facade), one of whose assigned reviewersopted in via ReviewHog's per-user `stamphog_review_inbox_prs` toggle. Rules that keep the exception@@ -129,8 +129,8 @@ narrow:PR #72680), and a teammate who can edit the _report_ before auto-start still influences whatthe implementation agent builds — that is the product working as designed, reviewed as any PR.- The engine flag (`self_driving_review` in the hosted context JSON →- `Pipeline(self_driving=...)`) defaults closed and the Action never sets it, so Action- behavior is unchanged by construction. It relaxes exactly two gates — the bot-author+ `Pipeline(self_driving=...)`) defaults closed, so a local `review_pr.py` run never turns it on.+ It relaxes exactly two gates — the bot-authorrefusal and the draft prerequisite (the verdict must exist at Inbox triage time, while thePR is still a draft) — and swaps human-author trust context for a TRUSTED provenance blockin the prompt. The hosted server sets the flag exclusively from the run's persisted inbox@@ -181,23 +181,24 @@ narrow:## Engine parity (tools/pr-approval-agent)-`review_local.py` (hosted) must mirror `review_pr.py` (Action) semantics wherever both apply:+`review_local.py` is the entrypoint the sandbox runs. It drives `review_pr.Pipeline`'s own steps, sogate order, review filtering (bare COMMENTED reviews dropped, non-empty ones kept), in-flightbot-reviewer WAIT behavior (`TRUSTED_REACTOR_BOTS` mirrored in `temporal/constants.py`), and-ownership summaries (individual owners count, not just teams). When you change one runtime,-check the other; divergence here has produced real approve-when-should-wait findings.+ownership summaries (individual owners count, not just teams) all come from shared code. `review_pr.py`+remains as the manual entrypoint for reviewing a PR from a local checkout; changing a `Pipeline` method+changes both, and divergence here has produced real approve-when-should-wait findings.-Inputs the Action fetches over the network reach the sandbox through the context JSON instead, and+Inputs `review_pr.py` fetches over the network reach the sandbox through the context JSON instead, anddropping one is a silent behavior change rather than a missing section. `author_team_slugs` feeds`author_on_owning_team`, which the reviewer prompt reads with a default of `True`, so an unset keytells the reviewer that every author owns the code they touched. `pr_provenance` needs no token andis computed in the sandbox from the checkout.-One divergence is deliberate. A pending `Migration risk` check returns WAIT here rather than-falling through to a refusal, because a hosted refusal costs a ReviewHog handoff and a trigger-label-strip over what is a race with CI. It also can't reuse `Pipeline._only_pending_migration_check`: that-method disqualifies on any failing gate other than the deny-list, and a migrations deny always drags-the tier gate to T2-never with it, so it answers False for every PR it exists to catch.+A pending `Migration risk` check returns WAIT rather than falling through to a refusal, because a+refusal costs a ReviewHog handoff and a trigger-label strip over what is a race with CI. It can't+reuse `Pipeline._only_pending_migration_check`: that method disqualifies on any failing gate other+than the deny-list, and a migrations deny always drags the tier gate to T2-never with it, so it+answers False for every PR it exists to catch.## Temporal specificsdiff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 92a1c7d08daa..3851bb5ad638 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -2,12 +2,11 @@Approve-first PR review: an LLM reviewer that runs deterministic gates plus a scoped review over a pull request and, when the policy allows it, posts an actual GitHub **approval** — not just comments. Repos opt in per-repo; everything else stays untouched.-## Two runtimes, one engine+## The engine-The review engine lives in [`tools/pr-approval-agent/`](../../tools/pr-approval-agent/) and runs in two places:--- **GitHub Action** — runs in the repo's own CI with the repo's own secrets (`review_pr.py`).-- **Hosted** (this product) — a GitHub App delivers webhooks here; reviews run in an isolated Modal sandbox with per-run minted credentials (`review_local.py` consumes a pre-fetched context, no GitHub token inside the sandbox).+The review engine lives in [`tools/pr-approval-agent/`](../../tools/pr-approval-agent/).+A GitHub App delivers webhooks here, and reviews run in an isolated Modal sandbox with per-run minted credentials: `review_local.py` consumes a pre-fetched context, with no GitHub token inside the sandbox.+`review_pr.py` in the same directory is the manual entrypoint for reviewing a PR from your own checkout, which fetches over the network instead.Hosted flow: webhook → Celery (`backend/tasks/tasks.py`) → Temporal (`backend/temporal/workflow.py`) → sandboxed engine → verdict posted back (`post_verdict`). The workflow dismisses stale approvals _first_, waits out other in-flight reviewer bots, then reviews.diff --git a/products/stamphog/backend/logic/policy_defaults/policy.yml b/products/stamphog/backend/logic/policy_defaults/policy.ymlindex 17188aa5c082..d921010daa72 100644--- a/products/stamphog/backend/logic/policy_defaults/policy.yml+++ b/products/stamphog/backend/logic/policy_defaults/policy.yml@@ -173,15 +173,6 @@ tiers:max_lines: 300max_files: 15breadth: 'not-cross-cutting'-dismiss:- trivial_extensions:- - '.md'- - '.mdx'- trivial_name_prefixes:- - 'readme'- - 'changelog'- test_regex: '(?:^|/)(?:__tests__|tests?|fixtures)/|(?:^|/)test_[^/]+\.py$|_test\.(py|go)$|\.test\.(ts|tsx|js|jsx)$|\.spec\.(ts|tsx|js|jsx)$|(?:^|/)conftest\.py$'- generated_regex: '(?:^|/)generated/.*\.(ts|tsx|js|jsx|json|md|snap|pyi|txt)$|\.gen\.(ts|tsx|js|jsx)$|\.generated\.(ts|tsx|js|jsx)$'overrides:'size_gate.max_files':ceiling: 50diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.pyindex c8123d7395d7..69f98f43b201 100644--- a/products/stamphog/backend/tasks/tasks.py+++ b/products/stamphog/backend/tasks/tasks.py@@ -609,6 +609,44 @@ def _record_retained_head(run: ReviewRun, head_sha: str) -> None:run.save(update_fields=["output", "updated_at"])+_BOT_AUTHOR_LABEL_MESSAGE = (+ "stamphog does not review bot-authored pull requests, so the trigger label has been removed. "+ "This change needs a human reviewer."+)+++def _clear_trigger_label_from_bot_pr(installation_id: str, repo: str, pr: dict[str, Any], action: str) -> None:+ """Remove the trigger label from a bot-authored PR that somebody labeled.++ Without this removal the label stays on the PR, and every later delivery silently takes the+ bot-author skip. The PR then looks reviewed, but it never is. The comment explains the removal+ only on the paths where a person just acted, because a later synchronize is a cleanup and not a+ response.++ This is best effort. A bot PR that carries a stray label is a cosmetic problem next to the+ review path that runs beside it, so a GitHub failure is logged and not retried.+ """+ pr_number = pr.get("number")+ if pr_number is None:+ return+ try:+ repo_config = _resolve_repo_config(installation_id, repo)+ # LABEL mode only. In other modes the trigger label carries no meaning, and the removal of+ # a label that the repo does not act on would surprise the author rather than clean+ # anything up.+ if repo_config is None or not repo_config.enabled or repo_config.review_mode != ReviewMode.LABEL:+ return+ label_names = {(label or {}).get("name") for label in pr.get("labels") or []}+ if repo_config.trigger_label not in label_names:+ return+ client = StamphogGitHubClient(repo_config.installation_id)+ if action != "synchronize":+ client.upsert_sticky_comment(repo, pr_number, _BOT_AUTHOR_LABEL_MESSAGE)+ client.remove_pr_label(repo, pr_number, repo_config.trigger_label)+ except Exception:+ logger.warning("stamphog_pr_event_bot_label_cleanup_failed", repo=repo, pr_number=pr_number, exc_info=True)++def _retract_stale_approvals_on_skip(repo_config: StamphogRepoConfig, pr: dict[str, Any], message: str) -> None:"""Retract a standing stamphog approval when a head-changing event is skipped before the workflow.@@ -1078,6 +1116,8 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Non"stamphog_pr_event_untrusted_skip_dismiss_failed", delivery_id=delivery_id, error=str(e))raise cast(Any, process_pull_request_event).retry(exc=e)+ if skip_reason == "bot_author":+ _clear_trigger_label_from_bot_pr(installation_id, repo, pr, action)if carve_out_error is not None:# The dismissal above already ran, so the stale-approval invariant holds however many# retries fail. Retry so the carve-out re-review is re-attempted once the failure clears.diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.pyindex 44db328e417a..157f687dd453 100644--- a/products/stamphog/backend/temporal/constants.py+++ b/products/stamphog/backend/temporal/constants.py@@ -13,11 +13,10 @@ from temporalio.common import RetryPolicySTAMPHOG_TASK_QUEUE = "stamphog-task-queue"-# Where the target repo is cloned inside the review sandbox. The Action's review-# engine is shipped into ENGINE_DIR (under the checkout, so its repo-root walk finds-# the checkout and reads the injected trusted policy); the context JSON lands at-# CONTEXT_PATH. Kept here so logic.reviewer.build_reviewer_invocation and-# run_review_in_sandbox agree on paths.+# Where the target repo is cloned inside the review sandbox. The review engine ships into+# ENGINE_DIR, which sits under the checkout, so the engine's repo-root walk finds the checkout and+# reads the injected trusted policy. The context JSON lands at CONTEXT_PATH. These paths stay here+# so that logic.reviewer.build_reviewer_invocation and run_review_in_sandbox agree on them.STAMPHOG_SANDBOX_REPO_DIR = "/tmp/stamphog/target"STAMPHOG_SANDBOX_WORKSPACE_DIR = "/tmp/stamphog/workspace"STAMPHOG_SANDBOX_ENGINE_DIR = f"{STAMPHOG_SANDBOX_REPO_DIR}/tools/pr-approval-agent"@@ -37,7 +36,7 @@ STAMPHOG_TRUSTED_REACTOR_BOTS = frozenset()STAMPHOG_BOT_EYES_MAX_AGE_SECONDS = 45 * 60STAMPHOG_BOT_REVIEW_POLL_SECONDS = 30-STAMPHOG_BOT_REVIEW_MAX_POLLS = 10 # ~300s budget at 30s per poll, matching the Action's wait budget+STAMPHOG_BOT_REVIEW_MAX_POLLS = 10 # ~300s budget at 30s per poll, matching the engine's wait budget# The GitHub label Stamphog adds to hand a refused/escalated PR to ReviewHog. ``review-hog.yml``# routes this label (when applied by stamphog[bot] — the one sanctioned bot exempted from itsdiff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.pyindex 94bb3b52d020..918477c3bf61 100644--- a/products/stamphog/backend/tests/test_tasks.py+++ b/products/stamphog/backend/tests/test_tasks.py@@ -1429,3 +1429,28 @@ def test_retention_needs_a_usable_approved_base_sha(team, repo_config, output):)mock_execute.assert_called_once()++[email protected]_db(databases=PRODUCT_DATABASES)[email protected]("action,expect_comment", [("labeled", True), ("synchronize", False)])+def test_trigger_label_is_taken_back_off_a_bot_pr(team, repo_config, action, expect_comment):+ # A labeled dependabot PR gets an explanation and loses the label again. Without that removal+ # the label stays on the PR while every later delivery silently takes the bot-author skip, so+ # the PR looks reviewed but never is. The explanation is posted only where a person just+ # acted.+ with team_scope(team.id):+ repo_config.review_mode = ReviewMode.LABEL+ repo_config.save()+ payload = _pr_payload(+ action=action,+ author_login="dependabot[bot]",+ user_type="Bot",+ labels=["stamphog"],+ added_label="stamphog",+ )++ client = _run_task(payload, f"delivery-bot-label-{action}", team.id).github+ client.remove_pr_label.assert_called_once_with(REPO, 42, "stamphog")+ assert client.upsert_sticky_comment.called is expect_comment+ with team_scope(team.id):+ assert ReviewRun.objects.count() == 0diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.mdindex 4515caacfbbb..9195e5caed69 100644--- a/tools/pr-approval-agent/README.md+++ b/tools/pr-approval-agent/README.md@@ -10,9 +10,9 @@ Deterministic safety gates first, then Claude reviews for showstoppers.## Usage-Add the `stamphog` label to a non-draft PR.-The GitHub Action runs the agent and posts an approval or comment.-On approval the label stays so it's visible which PRs were stamphog'd.+Reviews run in the hosted stamphog product ([`products/stamphog/`](../../products/stamphog/)): a GitHub App delivers the PR webhook, and the engine runs in an isolated sandbox through `review_local.py`.+A repo either reviews every PR or waits for its trigger label, per its `review_mode`.+On approval a trigger label stays so it's visible which PRs were stamphog'd.Only a substantive non-approval (`REFUSE`/`ESCALATE`) removes the label, so itcan be re-applied once the feedback is addressed; every other outcome —including a crashed run that produced no verdict — keeps the label and retries@@ -21,14 +21,12 @@ If the review agent can't reach its LLM backend (credentials, credit, oroutage) it returns `ERROR` and **keeps** the label — a transient infra failuremust not silently drop labels across every queued PR. The review retries on thenext push, or re-apply the label once the backend recovers.-`WAIT` also keeps the label: it means an allowlisted reviewer bot still had a-review in flight (👀 reaction) after the polling budget — not a verdict on the-PR, so the next push retries automatically. When the whole-fleet of stamphog reviews suddenly returns `ERROR`, suspect the-`STAMPHOG_ANTHROPIC_API_KEY` org secret first (stamphog uses its own dedicated-Anthropic key, separate from the shared `ANTHROPIC_API_KEY`).+`WAIT` also keeps the label. It means either that an allowlisted reviewer bot+still had a review in flight (👀 reaction) after the polling budget, or that the+`Migration risk` check had not reported yet — neither is a verdict on the PR, so+the next push retries automatically.-### Local testing+### Local review```bash# run from anywhere inside the posthog repo@@ -44,6 +42,8 @@ uv run tools/pr-approval-agent/review_pr.py 46594 --output-json /tmp/review.jsonuv run tools/pr-approval-agent/review_pr.py 46594 -v```+`review_pr.py` is the manual entrypoint: it fetches everything over the network with `gh` and reviews a PR from your own checkout.+The hosted runtime never uses it, running `review_local.py` against a pre-fetched context instead, with no GitHub token inside the sandbox.Requires `gh` CLI authenticated and `ANTHROPIC_API_KEY` in your environment.Uses PEP 723 inline metadata so `uv run` handles dependencies automatically.@@ -234,7 +234,7 @@ PostHog's auth system or its billing.The **migrations** deny-list is bypassed when the `Migration risk` check on the head commit concludes `success` (all migrations classified Safe). The check is published by `analyze_migration_risk` in `ci-backend.yml` and is the same signal humans see in the PR's Checks tab. See `tools/pr-approval-agent/migration_risk.py` for how stamphog reads it.-If the check hasn't completed yet when stamphog runs, stamphog refuses with a message asking the user to wait for the `Migration risk` check and re-apply the `stamphog` label. The label-strip on non-approved verdicts breaks the auto-rerun loop, so the next labeling action is the one that triggers a fresh review against the now-classified head commit.+If the check hasn't reported yet when stamphog runs, the hosted runtime returns `WAIT` rather than a verdict: the deny-list only matched because the engine could not tell a safe migration from a risky one, and a refusal would hand the PR to ReviewHog and strip the trigger label over a race with CI. The label is kept and the next push reviews against the now-classified head commit.### Ownership@@ -269,7 +269,7 @@ Every run produces a JSON evidence bundle (`--output-json` locally, uploaded as- Reviewer output (verdict, reasoning, risk, issues)- Final verdict-The GitHub Action uploads this as a build artifact with 30-day retention.+The hosted runtime persists it on the `ReviewRun` row, readable through the stamphog API.## Architecture@@ -277,7 +277,7 @@ The GitHub Action uploads this as a build artifact with 30-day retention.- `gates.py` — deterministic classification and deny-list logic- `github.py` — GitHub data fetching via `gh` CLI- `reviewer.py` — Claude Agent SDK reviewer (showstoppers prompt)-- `.github/workflows/pr-approval-agent.yml` — GitHub Action (label trigger)+- `review_local.py` — offline entrypoint the hosted sandbox runs, consuming a pre-fetched context## Empirical basisdiff --git a/tools/pr-approval-agent/dismiss_check.py b/tools/pr-approval-agent/dismiss_check.pydeleted file mode 100644index 28436e33d75d..000000000000--- a/tools/pr-approval-agent/dismiss_check.py+++ /dev/null@@ -1,233 +0,0 @@-#!/usr/bin/env python3-# /// script-# requires-python = ">=3.11"-# dependencies = [-# "pyyaml",-# ]-# ///-# ruff: noqa: T201-"""Decide what to do with Stamphog's prior approval after a push.--Reads `REPO`, `PR_NUMBER`, `HEAD_SHA`, `BASE_REF`, `GITHUB_WORKSPACE` from-the environment and prints a single-line `Decision` JSON on stdout:-- {"dismiss_approval": bool, "run_review": bool, "reason": "...", "last_approved_sha": "..."}--The two booleans are orthogonal so each downstream workflow job gates on-exactly the question it owns: the `dismiss` job reads `dismiss_approval`,-the `review` job reads `run_review`. Decisions are constructed only via-`Decision.retain`, `Decision.review_only`, `Decision.dismiss_and_review`,-and `Decision.error` — together they cover every legitimate combination,-and the impossible "dismiss the approval but skip re-review" case is-unrepresentable.--Anything ambiguous (force-push, mixed paths, fetch error, foreign-branch-merge) falls through to `Decision.dismiss_and_review`. The bias is-correctness, not retention.-"""--import os-import sys-import json-import subprocess-from dataclasses import asdict, dataclass, replace-from enum import StrEnum-from pathlib import Path--from gates import is_trivial_at_dismiss_time--# Stamphog now approves only as stamphog[bot] (the app), carrying the review-# body. github-actions[bot] is kept here so legacy bodyless approvals from-# before that change still count as a prior bot approval for the delta check.-BOT_LOGINS = {"github-actions[bot]", "stamphog[bot]"}---class Reason(StrEnum):- """Why the decision was made. Plumbed into the dismissal message and PR comment.-- `error:<ExcName>` is constructed dynamically in `Decision.error` for- unhandled exceptions and is intentionally not enumerated here.- """-- TRIVIAL_PATHS = "trivial_paths"- MERGE_ONLY = "merge_only"- MIXED_TRIVIAL = "mixed_trivial"- NON_TRIVIAL_DELTA = "non_trivial_delta"- NON_LINEAR_HISTORY = "non_linear_history"- EMPTY_DELTA = "empty_delta"- NO_PRIOR_APPROVAL = "no_prior_approval"---class CommitClass(StrEnum):- """Per-commit classification used to fold a delta into a single decision."""-- MERGE = "merge"- TRIVIAL = "trivial"- NON_TRIVIAL = "non_trivial"---@dataclass(frozen=True)-class Decision:- """Wire format consumed by .github/workflows/pr-approval-agent.yml.-- Construct only via the four classmethod factories — together they- enumerate every legitimate combination of the two booleans.- """-- dismiss_approval: bool- run_review: bool- reason: str- last_approved_sha: str | None = None-- @classmethod- def retain(cls, reason: Reason) -> "Decision":- """Trivial delta with a prior approval — leave both the approval and the review alone."""- return cls(dismiss_approval=False, run_review=False, reason=reason)-- @classmethod- def dismiss_and_review(cls, reason: Reason | str) -> "Decision":- """Non-trivial delta (or ambiguous fallback) — clear the prior approval and re-run review."""- return cls(dismiss_approval=True, run_review=True, reason=str(reason))-- @classmethod- def review_only(cls, reason: Reason) -> "Decision":- """No prior bot approval to dismiss, but the label is still on and the- agent hasn't approved yet — re-run the review on this push. Covers the- first-run ERROR case (LLM backend was down, so the label was retained- without an approval): the push actually retries the review instead of- leaving the PR labeled but stuck until someone re-applies the label."""- return cls(dismiss_approval=False, run_review=True, reason=reason)-- @classmethod- def error(cls, exc: Exception) -> "Decision":- """Defense-in-depth fallback when the script itself crashes."""- return cls.dismiss_and_review(f"error:{type(exc).__name__}")---def _run(*args: str, cwd: Path | None = None) -> str:- """Run command, return stdout. Raises on non-zero exit."""- return subprocess.run(list(args), cwd=cwd, capture_output=True, text=True, timeout=30, check=True).stdout---def _is_ancestor(ancestor: str, descendant: str, cwd: Path) -> bool:- """`git merge-base --is-ancestor`: rc 0=ancestor, 1=not ancestor, ≥2=error.-- Errors fall through to False so callers treat the relation as- non-linear and dismiss + re-review (fail-closed). The stderr log- distinguishes a real force-push from a git plumbing failure.- """- result = subprocess.run(- ["git", "merge-base", "--is-ancestor", ancestor, descendant],- cwd=cwd,- capture_output=True,- text=True,- timeout=30,- )- if result.returncode not in (0, 1):- print(- f"[dismiss_check] _is_ancestor git error rc={result.returncode}: {result.stderr.strip()}",- file=sys.stderr,- )- return result.returncode == 0---def select_last_bot_approval(reviews: list[dict]) -> str | None:- """Pick the commit SHA of the most recent bot APPROVED review.-- Pure function so the filter+sort behavior can be exercised without- invoking `gh api`. Human reviews and non-APPROVED bot reviews are- excluded; ties are broken by `submitted_at`.- """- bot_approvals = sorted(- (r for r in reviews if r.get("user", {}).get("login") in BOT_LOGINS and r.get("state") == "APPROVED"),- key=lambda r: r.get("submitted_at", ""),- )- return bot_approvals[-1].get("commit_id") if bot_approvals else None---def find_last_approved_sha(repo: str, pr_number: int) -> str | None:- """Commit SHA of the most recent Stamphog-bot APPROVED review."""- reviews = json.loads(_run("gh", "api", f"repos/{repo}/pulls/{pr_number}/reviews", "--paginate"))- return select_last_bot_approval(reviews)---def _is_clean_merge_from_base(sha: str, foreign_parents: list[str], cwd: Path, base_ref: str) -> bool:- """A merge is clean iff it added no manual conflict-resolution edits AND- every non-first parent is already reachable from `base_ref`.-- Without the ancestry check, a clean merge from an arbitrary side branch- would be trusted as if it came from base.- """- cc = _run("git", "show", sha, "--diff-merges=cc", "--format=", "-p", cwd=cwd)- if cc.strip():- return False- return all(_is_ancestor(p, base_ref, cwd) for p in foreign_parents)---def _first_parent_commits_between(from_sha: str, to_sha: str, cwd: Path) -> list[str]:- """Return commits in `(from_sha, to_sha]`, oldest first."""- commit_range = f"{from_sha}..{to_sha}"- output = _run("git", "rev-list", "--reverse", "--first-parent", commit_range, cwd=cwd)- return output.splitlines()---def _classify_commit(sha: str, cwd: Path, base_ref: str) -> CommitClass:- parents = _run("git", "rev-list", "--parents", "-n", "1", sha, cwd=cwd).split()[1:]- if len(parents) >= 2:- return (- CommitClass.MERGE if _is_clean_merge_from_base(sha, parents[1:], cwd, base_ref) else CommitClass.NON_TRIVIAL- )- files = [f for f in _run("git", "diff-tree", "--no-commit-id", "--name-only", "-r", sha, cwd=cwd).splitlines() if f]- return CommitClass.TRIVIAL if all(is_trivial_at_dismiss_time(f) for f in files) else CommitClass.NON_TRIVIAL---def evaluate_delta(last_approved_sha: str, head_sha: str, cwd: Path, base_ref: str = "origin/master") -> Decision:- """Classify the first-parent commit delta from `last_approved_sha` to `head_sha`.-- First-parent walking ensures a merge from base appears as a single- node — without it, the second-parent's commits would surface- individually and almost always classify as non-trivial.- """- if not _is_ancestor(last_approved_sha, head_sha, cwd):- return Decision.dismiss_and_review(Reason.NON_LINEAR_HISTORY)-- commits = _first_parent_commits_between(last_approved_sha, head_sha, cwd)- if not commits:- return Decision.retain(Reason.EMPTY_DELTA)-- classes = [_classify_commit(c, cwd, base_ref) for c in commits]- if CommitClass.NON_TRIVIAL in classes:- return Decision.dismiss_and_review(Reason.NON_TRIVIAL_DELTA)- if CommitClass.MERGE in classes and CommitClass.TRIVIAL in classes:- return Decision.retain(Reason.MIXED_TRIVIAL)- if CommitClass.MERGE in classes:- return Decision.retain(Reason.MERGE_ONLY)- return Decision.retain(Reason.TRIVIAL_PATHS)---def decide(repo: str, pr_number: int, head_sha: str, cwd: Path, base_ref: str = "origin/master") -> Decision:- last_approved_sha = find_last_approved_sha(repo, pr_number)- if last_approved_sha is None:- return Decision.review_only(Reason.NO_PRIOR_APPROVAL)- return replace(- evaluate_delta(last_approved_sha, head_sha, cwd, base_ref),- last_approved_sha=last_approved_sha,- )---def main() -> None:- try:- decision = decide(- repo=os.environ["REPO"],- pr_number=int(os.environ["PR_NUMBER"]),- head_sha=os.environ["HEAD_SHA"],- cwd=Path(os.environ.get("GITHUB_WORKSPACE", ".")),- base_ref=os.environ.get("BASE_REF", "origin/master"),- )- except Exception as e:- decision = Decision.error(e)- print(json.dumps(asdict(decision)))---if __name__ == "__main__":- main()diff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.pyindex 9e2901883e22..ba249428ce29 100644--- a/tools/pr-approval-agent/gates.py+++ b/tools/pr-approval-agent/gates.py@@ -34,9 +34,9 @@ _OWNERS_PKG = Path(__file__).resolve().parents[1] / "owners"# ── Dependency ecosystems ────────────────────────────────────────## Source of truth for how each package ecosystem pairs manifests with-# lockfiles. The deps_toolchain deny patterns, DISMISS_TIME_LOCKFILES, and-# the manifest/lockfile helper sets all derive from this table — add a new-# ecosystem here, not in several places. (requirements*.{txt,in} stays out:+# lockfiles. The deps_toolchain deny patterns and the manifest/lockfile+# helper sets all derive from this table, so add a new ecosystem here, and+# not in several places. (requirements*.{txt,in} stays out:# a pinned requirements.txt is arguably both manifest and lockfile, so# has_dependency_changes recognizes it directly instead of forcing it into# one column of this table.)@@ -50,46 +50,33 @@ _OWNERS_PKG = Path(__file__).resolve().parents[1] / "owners"class Ecosystem:manifests: frozenset[str]lockfiles: frozenset[str]- # Whether this ecosystem's lockfiles are trivially trusted at dismiss- # time (a lockfile-only push retains a prior stamphog approval without- # LLM re-review). Defaults to NOT trusted so a newly added ecosystem- # narrows trust rather than silently widening it — dismiss-time trust- # is an explicit decision made here, not inherited from the deny list.- trusted_at_dismiss: bool = FalseDEPENDENCY_ECOSYSTEMS: dict[str, Ecosystem] = {"node": Ecosystem(manifests=frozenset({"package.json", "pnpm-workspace.yaml"}),lockfiles=frozenset({"pnpm-lock.yaml", "package-lock.json", "yarn.lock", "npm-shrinkwrap.json"}),- trusted_at_dismiss=True,),"python": Ecosystem(# setup.py/setup.cfg execute code at install/build time even though# no lockfile pairs with them in this repo.manifests=frozenset({"pyproject.toml", "setup.py", "setup.cfg", "pipfile"}),lockfiles=frozenset({"uv.lock", "poetry.lock", "pipfile.lock"}),- trusted_at_dismiss=True,),"ruby": Ecosystem(manifests=frozenset({"gemfile"}),lockfiles=frozenset({"gemfile.lock"}),- trusted_at_dismiss=True,),# No composer usage in-repo today; listed so a future composer.json# doesn't arrive ungated."php": Ecosystem(manifests=frozenset({"composer.json"}),lockfiles=frozenset({"composer.lock"}),- trusted_at_dismiss=True,),"rust": Ecosystem(manifests=frozenset({"cargo.toml"}),lockfiles=frozenset({"cargo.lock"}),- trusted_at_dismiss=True,),- # go.sum deliberately stays untrusted at dismiss time: it hashes what- # go.mod names rather than being the sole source of installed code."go": Ecosystem(manifests=frozenset({"go.mod"}),lockfiles=frozenset({"go.sum"}),@@ -291,14 +278,13 @@ def detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> di# ── Policy-sourced data ──────────────────────────────────────────#-# The deny/allow/size/tier/dismiss data lives in .stamphog/policy.yml and is+# The deny/allow/size/tier data lives in .stamphog/policy.yml and is# loaded here at import time, keeping the existing module-level constant names-# populated so importers and tests are unchanged. DEPENDENCY_ECOSYSTEMS (and-# DISMISS_TIME_LOCKFILES below) stay code-derived; the loader splices the-# lockfile names into the deps_toolchain deny paths and validates the declared-# ownership formats against OWNERSHIP_FORMATS. A malformed policy raises at-# import - fail closed, the tool crashes rather than gating on a half-loaded-# policy.+# populated so importers and tests are unchanged. DEPENDENCY_ECOSYSTEMS stays+# code-derived; the loader splices the lockfile names into the deps_toolchain+# deny paths and validates the declared ownership formats against+# OWNERSHIP_FORMATS. A malformed policy raises at import. The tool fails+# closed, and crashes rather than gating on a half-loaded policy.POLICY = load_policy(lockfile_names=_ALL_LOCKFILE_NAMES, ownership_formats=OWNERSHIP_FORMAT_LOCATORS)_DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = POLICY.deny_pattern_defs()@@ -353,77 +339,10 @@ def _compile_patterns(DENY_PATTERNS = _compile_patterns(_DENY_PATTERN_DEFS)-# Compiled path patterns for stamphog's own policy/engine files. A dismiss-time-# guard consults these so a retained approval can't silently absorb a policy-# edit - .md is otherwise blanket-trivial and AGENT_APPROVALS.md would slip in.-_STAMPHOG_POLICY_PATH_PATTERNS = DENY_PATTERNS["stamphog_policy"]["paths"]-ALLOW_ONLY_EXTENSIONS = set(POLICY.allow_extensions)ALLOW_PATH_PATTERNS = list(POLICY.allow_path_patterns)-# ── Dismiss-time allow-list ──────────────────────────────────────-#-# Stricter than ALLOW_PATH_PATTERNS / ALLOW_ONLY_EXTENSIONS. Used by-# dismiss_check.py to decide whether to retain Stamphog's prior approval-# after new commits land on a PR. At approve time the LLM also reviews;-# at dismiss time the path alone is the only signal, so this list excludes-# anything that could carry executable code into CI, prod, or the build-# pipeline (workflows, configs, build files) even though those paths may-# be allow-listed at approve time.--# Derived from the ecosystems that explicitly opted in via trusted_at_dismiss-# — dismiss-time trust is a per-ecosystem decision made in the table, never a-# default a new deny-list entry inherits. See the field's comment on Ecosystem.-DISMISS_TIME_LOCKFILES: frozenset[str] = frozenset().union(- *(spec.lockfiles for spec in DEPENDENCY_ECOSYSTEMS.values() if spec.trusted_at_dismiss)-)--_DISMISS_TIME_TEST_RE = re.compile(POLICY.dismiss.test_regex, re.IGNORECASE)--# Non-executable-at-dismiss-time on purpose: at dismiss time the path is-# the only signal, so generated files in runnable backend languages-# (.py, .go) trigger re-review even though the LLM accepted them at-# approve time. Type stubs (.pyi) are read by type checkers, not runtime.-# Real-world cost in this repo: proto regen under-# posthog/personhog_client/proto/generated/ falls through to re-review,-# which is rare and cheap.-_DISMISS_TIME_GENERATED_RE = re.compile(POLICY.dismiss.generated_regex, re.IGNORECASE)---def is_trivial_at_dismiss_time(path: str) -> bool:- """Return True if `path` alone is safe enough to retain a prior approval.-- Strictly narrower than `is_allow_listed_only`: excludes `.github/**`,- bare `*.yaml`/`*.json` configs, `Dockerfile*`, `*.sh`, `Makefile`, and- anything else that can execute or alter build/CI behavior.- """- # Stamphog's own policy/engine files are never trivial at dismiss time -- # otherwise a retained approval would let a post-approval policy edit land- # unreviewed (AGENT_APPROVALS.md is .md, which is blanket-trivial below).- if any(rx.search(path) for rx in _STAMPHOG_POLICY_PATH_PATTERNS):- return False-- name = Path(path).name- name_lower = name.lower()- if name_lower in DISMISS_TIME_LOCKFILES:- return True-- suffix = Path(path).suffix.lower()- if suffix in POLICY.dismiss.trivial_extensions:- return True- if name_lower.startswith(POLICY.dismiss.trivial_name_prefixes):- return True- if path.startswith("docs/") or "/docs/" in path:- return True- if "/__snapshots__/" in path or path.startswith("__snapshots__/"):- return True- if _DISMISS_TIME_TEST_RE.search(path):- return True- if _DISMISS_TIME_GENERATED_RE.search(path):- return True- return False-CONVENTIONAL_RE = re.compile(r"^(\w+)(?:\(([^)]*)\))?!?:\s*(.+)")diff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.pyindex 77d5244d0db4..dcda6609e906 100644--- a/tools/pr-approval-agent/github.py+++ b/tools/pr-approval-agent/github.py@@ -92,7 +92,7 @@ def is_bot_author(user: dict) -> bool:GitHub Apps (dependabot, mendral, other agents) report user.type == "Bot";machine users like posthog-bot are type "User", so match them by login.- Mirrors the bot definition gating the jobs in pr-approval-agent.yml.+ Mirrors the bot definition the hosted webhook pre-filter uses (_is_bot_authored)."""if user.get("type") == "Bot":return Truediff --git a/tools/pr-approval-agent/policy.py b/tools/pr-approval-agent/policy.pyindex 39ce5a9a932f..fa9d947a86a4 100644--- a/tools/pr-approval-agent/policy.py+++ b/tools/pr-approval-agent/policy.py@@ -1,6 +1,6 @@"""Declarative merge-gate policy: loader, resolver, and prompt sanitizer.-The engine's deny/allow/size/tier/dismiss data lives in `.stamphog/policy.yml`+The engine's deny/allow/size/tier data lives in `.stamphog/policy.yml`(global, trusted) and optional per-folder `AGENT_APPROVALS.md` overrides(untrusted, positive allow-list). This module loads and validates the globalpolicy, resolves the effective policy for a given set of changed files, and@@ -114,14 +114,6 @@ class T1Subclass:breadth: str-@dataclass(frozen=True)-class DismissData:- trivial_extensions: frozenset[str]- trivial_name_prefixes: tuple[str, ...]- test_regex: str- generated_regex: str--@dataclass(frozen=True)class OverrideContract:ceiling: int@@ -177,7 +169,6 @@ class Policy:allow_extensions: frozenset[str]size_gate: SizeGatet1_subclasses: dict[str, T1Subclass]- dismiss: DismissDataoverrides: dict[str, OverrideContract]familiarity: FamiliarityPolicyownership: tuple[OwnershipSource, ...]@@ -227,16 +218,19 @@ class PolicyError(ValueError):# ── Global policy loading + validation ───────────────────────────-_TOP_LEVEL_KEYS = {"version", "deny", "allow", "size_gate", "tiers", "dismiss", "overrides", "familiarity", "ownership"}-# Keys the hosted server owns and parses itself (products/stamphog/backend/logic/digest_config.py),-# not the engine. Allowed at the top level so a repo declaring one doesn't hard-fail every review, but-# never required and never read here — the engine ignores their contents.-_SERVER_ONLY_TOP_LEVEL_KEYS = {"digest"}+_TOP_LEVEL_KEYS = {"version", "deny", "allow", "size_gate", "tiers", "overrides", "familiarity", "ownership"}+# Keys that the hosted server owns and parses itself, and that the engine does not. The top level+# allows them, so a repo that declares one does not hard-fail every review. They are never required,+# and the engine never reads their contents. `digest` is read by logic/digest_config.py. `dismiss`+# is tolerated for policies that still declare it, and nothing reads it: the server decides whether+# a push may retain a standing approval (logic/approval_retention.py). A repo that could widen those+# rules could keep an approval standing across arbitrary code pushes.+_SERVER_ONLY_TOP_LEVEL_KEYS = {"digest", "dismiss"}_DENY_SCOPES = {"any", "titles", "paths"}_BREADTH_RULES = {"single-area", "not-cross-cutting"}# The delegation contract's only delegable key. Everything else (deny, allow,-# dismiss, tiers, size_gate.max_lines) is non-delegable by construction.+# tiers, size_gate.max_lines) is non-delegable by construction._DELEGABLE_KEYS = {"size_gate.max_files"}# Invariant 7: self-governance deny must cover these path families so a future@@ -352,26 +346,6 @@ def _parse_tiers(raw: Any) -> dict[str, T1Subclass]:return subclasses-def _parse_dismiss(raw: Any) -> DismissData:- _require(isinstance(raw, dict), "dismiss: must be a mapping")- extensions = raw.get("trivial_extensions")- prefixes = raw.get("trivial_name_prefixes")- test_regex = raw.get("test_regex")- generated_regex = raw.get("generated_regex")- _require(isinstance(extensions, list) and bool(extensions), "dismiss.trivial_extensions: must be a non-empty list")- _require(isinstance(prefixes, list) and bool(prefixes), "dismiss.trivial_name_prefixes: must be a non-empty list")- _require(isinstance(test_regex, str), "dismiss.test_regex: must be a string")- _require(isinstance(generated_regex, str), "dismiss.generated_regex: must be a string")- _compile_or_raise(test_regex, "dismiss.test_regex")- _compile_or_raise(generated_regex, "dismiss.generated_regex")- return DismissData(- trivial_extensions=frozenset(str(e) for e in extensions),- trivial_name_prefixes=tuple(str(p) for p in prefixes),- test_regex=test_regex,- generated_regex=generated_regex,- )--def _parse_overrides(raw: Any) -> dict[str, OverrideContract]:_require(isinstance(raw, dict), "overrides: must be a mapping")overrides: dict[str, OverrideContract] = {}@@ -510,7 +484,6 @@ def load_policy(allow_extensions=extensions,size_gate=_parse_size_gate(raw["size_gate"]),t1_subclasses=_parse_tiers(raw["tiers"]),- dismiss=_parse_dismiss(raw["dismiss"]),overrides=_parse_overrides(raw["overrides"]),familiarity=_parse_familiarity(raw["familiarity"]),ownership=_parse_ownership(raw["ownership"], ownership_formats),diff --git a/tools/pr-approval-agent/review_local.py b/tools/pr-approval-agent/review_local.pyindex 3f02b6ccc313..1537eae12224 100644--- a/tools/pr-approval-agent/review_local.py+++ b/tools/pr-approval-agent/review_local.py@@ -9,32 +9,32 @@# ]# ///# ruff: noqa: T201-"""Offline PR review entrypoint — the sandbox runs this instead of review_pr.py.--review_pr.py fetches everything over the network (`gh`, GraphQL, git) and posts-the verdict. This script runs the SAME engine (gates, tier classification,-git-blame familiarity, the LLM reviewer with the same prompt/version) against a-LOCAL checkout, with NO GitHub access and NO token. All GitHub-sourced data the-engine needs is handed in via a `--context` JSON file that the server (which-holds the token) assembles from the API; the only thing that flows back out is-the JSON on the last stdout line — the same `to_dict()` contract review_pr.py-emits with `--output-json`.--Reuse: it drives review_pr.Pipeline's own steps (classify, gates, the LLM-review, to_dict) so the engine logic stays byte-identical to the Action. Only-the two steps that touch the network are replaced with injected data:-- _fetch (gh) → a PRData built from the context.-- the two `gh` calls the Action makes inside gate/familiarity — the author-team- membership lookup (advisory ownership enrichment) and the author's merged-PR- set — are skipped / injected. Familiarity's blame math is mirrored here with- the injected PR set (see _familiarity_offline) because Pipeline._compute_familiarity- hardcodes the `gh` fetch and must not be modified (the Action stays additive-only).--Trusted policy (`.stamphog/policy.yml`, `.stamphog/review-guidance.md`) is read-by the engine from the checkout at import time; the server overwrites those paths-in the checkout with the default-branch versions before this runs, so a PR head-can't substitute its own gate. The reviewer key comes from the environment-(ANTHROPIC_API_KEY), same as before.+"""Offline PR review entrypoint. The hosted sandbox runs this instead of review_pr.py.++review_pr.py is the manual entrypoint. It fetches everything over the network+(`gh`, GraphQL, git) and posts the verdict. This script runs the SAME engine+(gates, tier classification, git-blame familiarity, the LLM reviewer with the+same prompt and version) against a LOCAL checkout, with NO GitHub access and NO+token. The server holds the token, assembles every GitHub-sourced value that the+engine needs from the API, and passes them in through a `--context` JSON file.+Only one value flows back out: the JSON on the last stdout line, which is the+same `to_dict()` contract that review_pr.py emits with `--output-json`.++This script drives review_pr.Pipeline's own steps (classify, gates, the LLM+review, to_dict), so both entrypoints share one implementation of the engine+logic. It replaces only the steps that touch the network with injected data:+- _fetch (gh) becomes a PRData built from the context.+- The context injects the two `gh` calls that review_pr.py makes inside gate and+ familiarity, which are the author-team membership lookup and the author's+ merged-PR set. Familiarity's blame math is mirrored here with the injected PR+ set (see _familiarity_offline), because Pipeline._compute_familiarity hardcodes+ the `gh` fetch that only the networked entrypoint can make.++The engine reads the trusted policy (`.stamphog/policy.yml`,+`.stamphog/review-guidance.md`) from the checkout at import time. The server+overwrites those paths in the checkout with the default-branch versions before+this script runs, so a PR head cannot substitute its own gate. The reviewer key+comes from the environment (ANTHROPIC_API_KEY)."""import os@@ -108,20 +108,22 @@ def _convert_api_file(f: dict) -> dict:def _build_pr_data(context: dict) -> PRData:"""Build the engine's PRData from the injected context.- File stats are recomputed locally with the exact function the Action uses- (`git diff --numstat` over base...head) so PRData.files is identical to a- real run; the context's file list is only a fallback if the local diff is- empty (e.g. a sha failed to fetch). Reviews, top-level discussion comments,- and head-commit check runs are carried in the context (reviews/discussion- normalized with the same helpers the Action uses, check runs passed through- raw as the Action does) — so the prerequisite gate blocks on an active+ File stats are recomputed locally with the exact function that review_pr.py+ uses (`git diff --numstat` over base...head), so PRData.files is identical to+ a networked run. The context's file list is only a fallback for an empty+ local diff, which happens when a sha failed to fetch. The context also+ carries reviews, top-level discussion comments, and head-commit check runs.+ Reviews and discussion are normalized with the same helpers that review_pr.py+ uses, and check runs are passed through raw the same way. The prerequisite+ gate therefore blocks on an activeCHANGES_REQUESTED, the agent sees maintainer discussion, and the migrationgate can see a passing "Migration risk" check. Inline review-thread comments(a GraphQL-only surface with thread-resolution state) are carried when thehosted context supplies "review_threads"; only UNRESOLVED threads flow intothe prompt, since an unresolved inline "do not merge" is the blocker the- reviewer must see and resolved threads are noise. An absent key (the Action- runtime doesn't pass it) means an empty list — a clean no-op, never a crash.+ reviewer must see, and resolved threads are noise. An absent key means an+ empty list, which is a clean no-op and never a crash. A local review_pr.py+ run does not pass the key.Reactions on those inline comments are not carried, so they default empty."""pr = context.get("pr") or {}@@ -150,9 +152,10 @@ def _build_pr_data(context: dict) -> PRData:r for r in (context.get("reviews") or []) if r.get("state") != "COMMENTED" or (r.get("body") or "").strip()]- # Trusted-bot reactions only: the offline path has no token for the org-membership check the- # Action's reactor predicate performs, and the in-flight wait consumes only allowlisted bot 👀- # anyway — human reactions are never waited on. REST content values lowercase-match the mapper.+ # Trusted-bot reactions only. The offline path has no token for the org-membership check that+ # the networked reactor predicate performs, and the in-flight wait consumes only allowlisted bot+ # 👀 in any case, because the code never waits on human reactions. REST content values+ # lowercase-match the mapper.author_login = user.get("login") or ""pr_reactions = [{"user": login, "emoji": _reaction_emoji(r.get("content", "")), "created_at": r.get("created_at")}@@ -164,9 +167,9 @@ def _build_pr_data(context: dict) -> PRData:# consumes. Only UNRESOLVED threads reach the prompt (see _build_pr_data's docstring); the full# list stays in the context. Each comment passes the same author-trust gate as reviews and# discussion — an untrusted external commenter must not plant a fake maintainer hold, and- # stamphog's own prior comments must not feed back as third-party claims. Absent key -> empty, so- # the Action runtime (which doesn't pass it) is unaffected and the prompt renders no- # inline-comments section, exactly as before.+ # stamphog's own prior comments must not feed back as third-party claims. An absent key yields+ # an empty list, so a local review_pr.py run, which does not pass the key, is unaffected and the+ # prompt renders no inline-comments section.review_comments: list[dict] = []for thread in context.get("review_threads") or []:if thread.get("is_resolved"):@@ -179,10 +182,11 @@ def _build_pr_data(context: dict) -> PRData:# Real reply ids aren't carried in the lean shape; a truthy placeholder on the replies# only marks reply-ness — the prompt's "(reply)" label and _summarize_assurance's# "count threads (in_reply_to_id is None), not comments" semantic both key off it.- # Parity with the Action (github.py): only the TRUE thread root (index 0) may carry None.- # When the root is filtered (untrusted author, or stamphog's own finding), every survivor- # is a reply, so the thread contributes 0 to unresolved_threads — exactly like the Action,- # whose surviving replies keep their real non-None replyTo ids.+ # Parity with the networked path (github.py): only the TRUE thread root (index 0) may+ # carry None. When a filter removes the root (untrusted author, or stamphog's own+ # finding), every survivor is a reply, so the thread contributes 0 to+ # unresolved_threads. The networked path behaves the same way, because its surviving+ # replies keep their real non-None replyTo ids.review_comments.append({"user": comment.get("author") or "ghost",@@ -223,14 +227,14 @@ def _build_pr_data(context: dict) -> PRData:def _apply_ownership_summary(pipeline: Pipeline, author_team_slugs: set[str]) -> None:"""Mirror Pipeline._summarize_ownership with team membership injected instead of fetched.- The Action resolves membership with one `gh` call per owning team. The sandbox holds no token,- so the server supplies every team that the author belongs to, and this function does the+ review_pr.py resolves membership with one `gh` call per owning team. The sandbox holds no+ token, so the server supplies every team that the author belongs to, and this function does theintersection.`author_on_owning_team` matters beyond the summary text. The reviewer prompt reads that key witha default of True, so an unset key tells the reviewer that the author owns the code, whoeveropened the PR. An unresolvable lookup arrives as an empty set and yields "not on any owning- team". The Action fails in the same direction, and that direction is the safe one for a bot that+ team". review_pr.py fails in the same direction, and that direction is the safe one for a bot thatapproves."""cl = pipeline.classification@@ -296,7 +300,7 @@ def _familiarity_offline(compute_familiarity fetches the author's merged-PR numbers with one `gh`call, which is impossible in the tokenless sandbox — the server fetches themand hands them in via the context instead. Everything else (blame overlap,- prior PRs, previously-modified files, banding) is the Action's own bounded+ prior PRs, previously-modified files, banding) is the engine's own boundedgit logic, called here unchanged."""now = time.time() if now is None else now@@ -334,7 +338,7 @@ def _attach_familiarity(pipeline: Pipeline, context: dict) -> None:Same gating as Pipeline._maybe_compute_familiarity (T0 skips the LLM, T2 is adeny, so neither benefits). Absent injected PR numbers leaves the signal None,- exactly as a failed `gh` call would in the Action — a one-way ratchet.+ exactly as a failed `gh` call would in review_pr.py — a one-way ratchet."""if pipeline.classification.get("tier") != "T1-agent":return@@ -394,10 +398,10 @@ def run(context: dict) -> dict:0, context.get("repo") or "", self_driving=bool(context.get("self_driving_review")), head_checkout=True)pipeline.pr = _build_pr_data(context)- # Reads commit trailers with `git log base..head` against the checkout, so it needs no token- # and runs here exactly as it runs in the Action. Without this call, the agent-authorship- # evidence and the stamphog_review_completed provenance properties are null for every hosted- # review.+ # Reads commit trailers with `git log base..head` against the checkout, so it needs no token,+ # and it behaves here exactly as it does on a networked run. Without this call, the+ # agent-authorship evidence and the stamphog_review_completed provenance properties are null for+ # every hosted review.pipeline.provenance = pr_provenance(pipeline.pr.base_sha, pipeline.pr.head_sha, REPO_ROOT)if pipeline.pr.author_is_bot and not pipeline.self_driving:@@ -430,11 +434,11 @@ def run(context: dict) -> dict:pipeline._capture_review_completed(gate_verdict, "PENDING-MIGRATION-CHECK")return pipeline.to_dict()- # Mirror the Action's in-flight reviewer-bot handling, minus the wait: there is no token in+ # Mirror review_pr.py's in-flight reviewer-bot handling, minus the wait: there is no token in# the sandbox to poll with, and the SERVER already waited out the race (workflow bot-wait# loop) and refreshed this snapshot before provisioning. Bots still showing fresh 👀 here# mean the server's budget expired — WAIT, never approve over an unfinished review. Gate- # denials skip the check, same as the Action: a refusal can't approve over anything.+ # denials skip the check, same as review_pr.py: a refusal can't approve over anything.if gate_verdict != "DENIED" and (in_flight := pipeline._in_flight_bot_reviewers()):bot_list = ", ".join(f"@{b}" for b in in_flight)pipeline.final_verdict = "WAIT"diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex e5fda00fbdbf..9b8736eee66d 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -938,9 +938,9 @@ class Pipeline:posthoganalytics.capture(distinct_id=pr.author,event="stamphog_review_completed",- # Extras first so the base props win on collision: the hosted server stamps its- # runtime/team context through this hook; absent in the Action, so Action events- # are unchanged (no prop = action runtime).+ # 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",diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.pyindex f743f82ec6af..586bb9ae4096 100644--- a/tools/pr-approval-agent/reviewer.py+++ b/tools/pr-approval-agent/reviewer.py@@ -381,10 +381,10 @@ class Reviewer:extra_args={"no-session-persistence": None},)- # Shared by both routes; the full set is always on the separate- # stamphog_review_completed event. Extras first so the base props win:- # the hosted server stamps runtime/team context via STAMPHOG_EXTRA_PROPERTIES,- # absent in the Action.+ # Shared by both routes. The full set is always on the separate+ # stamphog_review_completed event. Extras first, so the base props win.+ # The hosted server stamps runtime and team context through+ # STAMPHOG_EXTRA_PROPERTIES, and a local run sets no such variable.attribution = {**analytics_extra_properties(),"stamphog_pr_number": pr.number,diff --git a/tools/pr-approval-agent/test_dismiss_check.py b/tools/pr-approval-agent/test_dismiss_check.pydeleted file mode 100644index bec4834293b8..000000000000--- a/tools/pr-approval-agent/test_dismiss_check.py+++ /dev/null@@ -1,475 +0,0 @@-"""Tests for the Stamphog dismiss-decision logic."""--import os-import subprocess-from pathlib import Path--import pytest--import dismiss_check-from dismiss_check import Decision, decide, evaluate_delta, select_last_bot_approval-from gates import is_trivial_at_dismiss_time--_GIT_ENV = {- "GIT_AUTHOR_NAME": "test",- "GIT_AUTHOR_EMAIL": "t@t",- "GIT_COMMITTER_NAME": "test",- "GIT_COMMITTER_EMAIL": "t@t",-}---def _git(*args: str, cwd: Path, check: bool = True) -> subprocess.CompletedProcess[str]:- env = {**os.environ, **_GIT_ENV}- return subprocess.run(- ["git", *args],- cwd=cwd,- env=env,- capture_output=True,- text=True,- timeout=30,- check=check,- )---def _write(repo: Path, path: str, content: str = "x") -> None:- p = repo / path- p.parent.mkdir(parents=True, exist_ok=True)- p.write_text(content)---def _commit(repo: Path, message: str) -> str:- _git("add", "-A", cwd=repo)- _git("commit", "-m", message, cwd=repo)- return _git("rev-parse", "HEAD", cwd=repo).stdout.strip()---def _head(repo: Path) -> str:- return _git("rev-parse", "HEAD", cwd=repo).stdout.strip()---def _assert_decision(d: Decision, *, dismiss: bool, review: bool, reason: str) -> None:- assert d.dismiss_approval is dismiss- assert d.run_review is review- assert d.reason == reason---def repo(tmp_path: Path) -> Path:- """Empty repo with one initial commit on master."""- _git("init", "--initial-branch=master", cwd=tmp_path)- _write(tmp_path, "README.md", "init")- _commit(tmp_path, "init")- return tmp_path---# ── is_trivial_at_dismiss_time unit tests ────────────────────────--- "path,expected",- [- # Tests- ("frontend/src/foo.test.ts", True),- ("frontend/src/foo.test.tsx", True),- ("frontend/src/foo.spec.ts", True),- ("posthog/test_views.py", True),- ("posthog/api/test/foo.py", True),- ("tests/test_foo.py", True),- ("foo/__tests__/bar.ts", True),- ("conftest.py", True),- ("posthog/conftest.py", True),- ("internal_test.go", True),- ("posthog/fixtures/foo.json", True),- # Snapshots — only the canonical __snapshots__/ directory; bare- # .snap suffix anywhere is no longer trusted.- ("foo/__snapshots__/bar.snap", True),- ("__snapshots__/bar.snap", True),- ("scripts/deploy.snap", False),- ("foo.snap", False),- # Docs- ("README.md", True),- ("CHANGELOG.md", True),- ("docs/foo.md", True),- ("foo.mdx", True),- # Lockfiles (matched case-insensitively)- ("package-lock.json", True),- ("pnpm-lock.yaml", True),- ("frontend/yarn.lock", True),- ("uv.lock", True),- ("Cargo.lock", True),- ("CARGO.LOCK", True),- ("Gemfile.lock", True),- ("Pipfile.LOCK", True),- # Generated — frontend TS / JS / JSON / md / snap / type-stubs only.- # Backend executable code (.py, .go) under generated/ is NOT trivial- # because at dismiss time the path is the only signal.- ("frontend/src/generated/core/api.ts", True),- ("products/foo/frontend/generated/api.ts", True),- ("nodejs/src/generated/foo.ts", True),- ("services/mcp/src/generated/foo.ts", True),- ("frontend/src/queries/schema/general.ts", True),- ("foo.gen.ts", True),- ("foo.generated.ts", True),- ("services/mcp/src/ui-apps/generated/foo.txt", True),- # Backend code under generated/ — must dismiss- ("posthog/generated/evil.py", False),- ("posthog/personhog_client/proto/generated/foo.py", False),- ("services/foo/generated/handler.go", False),- ("foo.gen.py", False),- ("foo.generated.py", False),- ("foo.gen.go", False),- ("foo.generated.go", False),- # NOT allowed- (".github/workflows/foo.yml", False),- (".github/CODEOWNERS", False),- ("Dockerfile", False),- ("scripts/deploy.sh", False),- ("Makefile", False),- ("pyproject.toml", False),- ("tsconfig.json", False),- ("frontend/src/foo.ts", False),- ("posthog/api/foo.py", False),- ("requirements.txt", False),- ("package.json", False),- ],-)-def test_is_trivial_at_dismiss_time(path: str, expected: bool) -> None:- assert is_trivial_at_dismiss_time(path) is expected---# ── _is_ancestor unit tests ──────────────────────────────────────---def test_is_ancestor_returns_true_when_ancestor(repo: Path) -> None:- base = _head(repo)- _write(repo, "a.ts", "a")- head = _commit(repo, "feat a")- assert dismiss_check._is_ancestor(base, head, repo) is True---def test_is_ancestor_returns_false_when_not_ancestor(repo: Path) -> None:- _write(repo, "a.ts", "a")- a = _commit(repo, "feat a")- _git("reset", "--hard", "HEAD~1", cwd=repo)- _write(repo, "b.ts", "b")- b = _commit(repo, "feat b")- assert dismiss_check._is_ancestor(a, b, repo) is False---def test_is_ancestor_returns_false_on_git_error(repo: Path, capsys: pytest.CaptureFixture[str]) -> None:- bogus = "0" * 40- assert dismiss_check._is_ancestor(bogus, _head(repo), repo) is False- assert "_is_ancestor git error" in capsys.readouterr().err---# ── evaluate_delta scenarios ─────────────────────────────────────---def test_test_only_delta_retains(repo: Path) -> None:- base = _head(repo)- _write(repo, "tests/test_foo.py", "def test_foo(): pass")- _commit(repo, "test only")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=False, review=False, reason="trivial_paths")---def test_lockfile_only_delta_retains(repo: Path) -> None:- base = _head(repo)- _write(repo, "package-lock.json", "{}")- _commit(repo, "lock")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=False, review=False, reason="trivial_paths")---def test_workflow_change_dismisses(repo: Path) -> None:- base = _head(repo)- _write(repo, ".github/workflows/foo.yml", "name: x")- _commit(repo, "workflow")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=True, review=True, reason="non_trivial_delta")---def test_prod_file_dismisses(repo: Path) -> None:- base = _head(repo)- _write(repo, "frontend/src/foo.ts", "export const x = 1")- _commit(repo, "prod")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=True, review=True, reason="non_trivial_delta")---def test_generated_file_only_retains(repo: Path) -> None:- base = _head(repo)- _write(repo, "frontend/src/generated/core/api.ts", "export const x = 1")- _commit(repo, "regen")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=False, review=False, reason="trivial_paths")---def test_mixed_test_plus_prod_dismisses(repo: Path) -> None:- base = _head(repo)- _write(repo, "frontend/src/foo.test.ts", "test('x', () => {})")- _write(repo, "frontend/src/foo.ts", "export const x = 1")- _commit(repo, "mixed")- _assert_decision(evaluate_delta(base, _head(repo), repo), dismiss=True, review=True, reason="non_trivial_delta")---def test_clean_merge_from_master_retains(repo: Path) -> None:- # Branch off and commit on feat- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "feat.ts", "feat")- feat_sha = _commit(repo, "feat")-- # Advance master with a non-overlapping change- _git("checkout", "master", cwd=repo)- _write(repo, "main.ts", "main")- _commit(repo, "main change")-- # Merge master into feat (no conflicts)- _git("checkout", "feat", cwd=repo)- _git("merge", "--no-ff", "master", "-m", "merge master", cwd=repo)-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo, base_ref="master"),- dismiss=False,- review=False,- reason="merge_only",- )---def test_merge_with_conflict_resolution_dismisses(repo: Path) -> None:- # Both branches modify the same file → manual resolution- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "shared.ts", "feat version")- feat_sha = _commit(repo, "feat shared")-- _git("checkout", "master", cwd=repo)- _write(repo, "shared.ts", "main version")- _commit(repo, "main shared")-- _git("checkout", "feat", cwd=repo)- # Merge will conflict; resolve manually- _git("merge", "--no-ff", "--no-commit", "master", cwd=repo, check=False)- _write(repo, "shared.ts", "manually resolved")- _git("add", "shared.ts", cwd=repo)- _git("commit", "--no-edit", cwd=repo)-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo, base_ref="master"),- dismiss=True,- review=True,- reason="non_trivial_delta",- )---def test_clean_merge_plus_test_commit_retains(repo: Path) -> None:- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "feat.ts", "feat")- feat_sha = _commit(repo, "feat")-- _git("checkout", "master", cwd=repo)- _write(repo, "main.ts", "main")- _commit(repo, "main change")-- _git("checkout", "feat", cwd=repo)- _git("merge", "--no-ff", "master", "-m", "merge master", cwd=repo)- # Then add a test- _write(repo, "tests/test_feat.py", "def test_feat(): pass")- _commit(repo, "tests")-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo, base_ref="master"),- dismiss=False,- review=False,- reason="mixed_trivial",- )---def test_clean_merge_plus_prod_commit_dismisses(repo: Path) -> None:- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "feat.ts", "feat")- feat_sha = _commit(repo, "feat")-- _git("checkout", "master", cwd=repo)- _write(repo, "main.ts", "main")- _commit(repo, "main change")-- _git("checkout", "feat", cwd=repo)- _git("merge", "--no-ff", "master", "-m", "merge master", cwd=repo)- _write(repo, "feat.ts", "feat updated")- _commit(repo, "prod tweak")-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo, base_ref="master"),- dismiss=True,- review=True,- reason="non_trivial_delta",- )---def test_non_linear_history_dismisses(repo: Path) -> None:- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "a.ts", "a")- feat_sha = _commit(repo, "feat a")-- # Simulate force-push: reset and create a divergent commit- _git("reset", "--hard", "HEAD~1", cwd=repo)- _write(repo, "a.ts", "different a")- _commit(repo, "rebased a")-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo), dismiss=True, review=True, reason="non_linear_history"- )---def test_empty_delta_retains(repo: Path) -> None:- head = _head(repo)- _assert_decision(evaluate_delta(head, head, repo), dismiss=False, review=False, reason="empty_delta")---# ── edge cases ───────────────────────────────────────────────────---def test_empty_commit_retains(repo: Path) -> None:- base = _head(repo)- _git("commit", "--allow-empty", "-m", "empty", cwd=repo)- _assert_decision(- evaluate_delta(base, _head(repo), repo, base_ref="master"),- dismiss=False,- review=False,- reason="trivial_paths",- )---def test_merge_from_non_base_branch_dismisses(repo: Path) -> None:- # PR branch- _git("checkout", "-b", "feat", cwd=repo)- _write(repo, "feat.ts", "feat")- feat_sha = _commit(repo, "feat")-- # Side branch off master with a prod commit, never landed on master- _git("checkout", "-b", "side", "master", cwd=repo)- _write(repo, "side.ts", "side")- _commit(repo, "side prod change")-- # Merge side into feat (clean merge, but side isn't in master history)- _git("checkout", "feat", cwd=repo)- _git("merge", "--no-ff", "side", "-m", "merge side", cwd=repo)-- _assert_decision(- evaluate_delta(feat_sha, _head(repo), repo, base_ref="master"),- dismiss=True,- review=True,- reason="non_trivial_delta",- )---# ── decide() with mocked GitHub API ──────────────────────────────---def test_decide_no_prior_approval(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:- # No prior bot approval, but the label is still on (decide-delta only runs- # when it is) and the agent hasn't approved — re-run the review on this- # push so the first-run ERROR case (LLM backend down, label retained)- # actually retries instead of staying labeled but stuck.- monkeypatch.setattr(dismiss_check, "find_last_approved_sha", lambda *_: None)- result = decide("PostHog/posthog", 1, _head(repo), repo)- _assert_decision(result, dismiss=False, review=True, reason="no_prior_approval")- assert result.last_approved_sha is None---def test_decide_returns_last_approved_sha(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:- base = _head(repo)- _write(repo, "tests/test_foo.py", "def test_foo(): pass")- _commit(repo, "test")-- monkeypatch.setattr(dismiss_check, "find_last_approved_sha", lambda *_: base)- result = decide("PostHog/posthog", 1, _head(repo), repo)- _assert_decision(result, dismiss=False, review=False, reason="trivial_paths")- assert result.last_approved_sha == base---def test_decide_dismiss_path_includes_last_approved_sha(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:- base = _head(repo)- _write(repo, "frontend/src/foo.ts", "export const x = 1")- _commit(repo, "prod")-- monkeypatch.setattr(dismiss_check, "find_last_approved_sha", lambda *_: base)- result = decide("PostHog/posthog", 1, _head(repo), repo)- _assert_decision(result, dismiss=True, review=True, reason="non_trivial_delta")- assert result.last_approved_sha == base---# ── select_last_bot_approval (filter + sort) ─────────────────────---def _review(login: str, state: str, commit_id: str, submitted_at: str) -> dict:- return {- "user": {"login": login},- "state": state,- "commit_id": commit_id,- "submitted_at": submitted_at,- }---def test_select_last_bot_approval_empty_list() -> None:- assert select_last_bot_approval([]) is None---def test_select_last_bot_approval_no_bot_reviews() -> None:- reviews = [_review("alice", "APPROVED", "sha1", "2026-01-01T00:00:00Z")]- assert select_last_bot_approval(reviews) is None---def test_select_last_bot_approval_no_approved_state() -> None:- reviews = [- _review("github-actions[bot]", "COMMENTED", "sha1", "2026-01-01T00:00:00Z"),- _review("github-actions[bot]", "CHANGES_REQUESTED", "sha2", "2026-01-02T00:00:00Z"),- ]- assert select_last_bot_approval(reviews) is None---def test_select_last_bot_approval_picks_latest() -> None:- reviews = [- _review("github-actions[bot]", "APPROVED", "sha-old", "2026-01-01T00:00:00Z"),- _review("github-actions[bot]", "APPROVED", "sha-new", "2026-02-01T00:00:00Z"),- _review("github-actions[bot]", "APPROVED", "sha-mid", "2026-01-15T00:00:00Z"),- ]- assert select_last_bot_approval(reviews) == "sha-new"---def test_select_last_bot_approval_ignores_human_approvals() -> None:- reviews = [- _review("github-actions[bot]", "APPROVED", "sha-bot", "2026-01-01T00:00:00Z"),- _review("alice", "APPROVED", "sha-human", "2026-02-01T00:00:00Z"),- ]- assert select_last_bot_approval(reviews) == "sha-bot"---def test_select_last_bot_approval_ignores_bot_non_approval_states() -> None:- reviews = [- _review("github-actions[bot]", "APPROVED", "sha-approved", "2026-01-01T00:00:00Z"),- _review("github-actions[bot]", "CHANGES_REQUESTED", "sha-changes", "2026-02-01T00:00:00Z"),- ]- assert select_last_bot_approval(reviews) == "sha-approved"---def test_select_last_bot_approval_recognizes_app_identity() -> None:- # The Stamphog app posts the body-carrying approval as stamphog[bot]; it- # must count as a prior bot approval so dismiss-on-push can find its SHA.- reviews = [_review("stamphog[bot]", "APPROVED", "sha-app", "2026-01-01T00:00:00Z")]- assert select_last_bot_approval(reviews) == "sha-app"---# ── main() error path ────────────────────────────────────────────---def test_main_missing_env_emits_dismiss(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:- # REPO is the first env var read in main(); leaving it unset triggers KeyError.- for key in ("REPO", "PR_NUMBER", "HEAD_SHA"):- monkeypatch.delenv(key, raising=False)-- dismiss_check.main()- out = capsys.readouterr().out.strip()-- import json as _json-- decision = _json.loads(out)- assert decision["dismiss_approval"] is True- assert decision["run_review"] is True- assert decision["reason"].startswith("error:")- assert decision["last_approved_sha"] is Nonediff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.pyindex da758ffdfa78..f2662636aa69 100644--- a/tools/pr-approval-agent/test_gates.py+++ b/tools/pr-approval-agent/test_gates.py@@ -6,7 +6,6 @@ import pytestfrom gates import (DEPENDENCY_ECOSYSTEMS,- DISMISS_TIME_LOCKFILES,build_ownership,dependency_manifests_without_lockfile,detect_deny_categories,@@ -505,16 +504,6 @@ def test_has_dependency_changes_recognizes_uncurated_manifests_and_lockfiles(patassert has_dependency_changes([path]) is True-def test_dismiss_time_trust_is_opt_in_per_ecosystem() -> None:- # Dismiss-time trust must be an explicit per-ecosystem decision: go.sum- # (trusted_at_dismiss unset) stays out even though it is a deny-listed- # lockfile, while node's lockfiles — including npm-shrinkwrap.json — opt- # in. Catches a revert to deriving trust from the whole lockfile set.- assert "go.sum" not in DISMISS_TIME_LOCKFILES- assert "pnpm-lock.yaml" in DISMISS_TIME_LOCKFILES- assert "npm-shrinkwrap.json" in DISMISS_TIME_LOCKFILES--# ── Ownership sources ────────────────────────────────────────────_HOGLI_RESOLVER = (OwnershipSource(format="hogli-resolver", path="."),)diff --git a/tools/pr-approval-agent/test_policy.py b/tools/pr-approval-agent/test_policy.pyindex fa09174f698c..a2368c63a55b 100644--- a/tools/pr-approval-agent/test_policy.py+++ b/tools/pr-approval-agent/test_policy.py@@ -152,8 +152,6 @@ OLD_ALLOW_PATH_PATTERNS = []OLD_MAX_LINES = 800OLD_MAX_FILES = 30-OLD_DISMISS_TEST_RE = "(?:^|/)(?:__tests__|tests?|fixtures)/|(?:^|/)test_[^/]+\\.py$|_test\\.(py|go)$|\\.test\\.(ts|tsx|js|jsx)$|\\.spec\\.(ts|tsx|js|jsx)$|(?:^|/)conftest\\.py$"-OLD_DISMISS_GENERATED_RE = "(?:^|/)generated/.*\\.(ts|tsx|js|jsx|json|md|snap|pyi|txt)$|^services/mcp/src/api/generated\\.ts$|\\.gen\\.(ts|tsx|js|jsx)$|\\.generated\\.(ts|tsx|js|jsx)$|^frontend/src/queries/schema/"# ── 1. Equality snapshot: loaded policy matches pre-extraction literals ──@@ -163,13 +161,11 @@ def test_deny_defs_equal_pre_extraction_excluding_stamphog_policy() -> None:assert live == OLD_DENY_PATTERN_DEFS-def test_allow_size_and_dismiss_equal_pre_extraction() -> None:+def test_allow_and_size_equal_pre_extraction() -> None:assert set(gates.ALLOW_ONLY_EXTENSIONS) == OLD_ALLOW_ONLY_EXTENSIONSassert list(gates.ALLOW_PATH_PATTERNS) == OLD_ALLOW_PATH_PATTERNSassert gates.MAX_LINES == OLD_MAX_LINESassert gates.MAX_FILES == OLD_MAX_FILES- assert gates._DISMISS_TIME_TEST_RE.pattern == OLD_DISMISS_TEST_RE- assert gates._DISMISS_TIME_GENERATED_RE.pattern == OLD_DISMISS_GENERATED_RE@pytest.mark.parametrize(@@ -513,18 +509,7 @@ def test_reviewer_system_composes_guidance_and_scaffold() -> None:assert "Verdicts:" in reviewer._REVIEWER_SCAFFOLD_TAIL-# ── 6. Stamphog policy files are not trivial at dismiss time ──--- "path",- ["products/visual_review/AGENT_APPROVALS.md", ".stamphog/policy.yml", "tools/pr-approval-agent/gates.py"],-)-def test_policy_paths_not_trivial_at_dismiss_time(path: str) -> None:- assert gates.is_trivial_at_dismiss_time(path) is False---# ── 7. Folder prose is sanitized and capped ──+# ── 6. Folder prose is sanitized and capped ──def test_folder_prose_stripped_of_control_chars() -> None:diff --git a/tools/pr-approval-agent/test_review_local.py b/tools/pr-approval-agent/test_review_local.pyindex ce7af8a90d54..843fd0cafee9 100644--- a/tools/pr-approval-agent/test_review_local.py+++ b/tools/pr-approval-agent/test_review_local.py@@ -295,10 +295,11 @@ def test_multi_comment_thread_counts_as_one_unresolved_thread(monkeypatch) -> Nodef test_filtered_root_thread_counts_zero_unresolved_threads(monkeypatch) -> None:- # Parity with the Action: when the true thread root is filtered (untrusted author, or stamphog's- # own inline finding), the survivors are replies — the thread contributes 0 to unresolved_threads,- # exactly as the Action's real replyTo ids make it. Treating the first survivor as a root would- # make hosted stricter than the Action on every maintainer reply to a stamphog finding.+ # Parity with the networked path. When a filter removes the true thread root (untrusted author,+ # or stamphog's own inline finding), the survivors are replies, so the thread contributes 0 to+ # unresolved_threads. The networked path's real replyTo ids produce the same count. Treatment of+ # the first survivor as a root would make the sandbox stricter on every maintainer reply to a+ # stamphog finding.monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])context = _thread_context([@@ -326,8 +327,8 @@ def test_filtered_root_thread_counts_zero_unresolved_threads(monkeypatch) -> Nondef test_absent_review_threads_key_is_a_clean_no_op(monkeypatch) -> None:- # The Action runtime doesn't pass review_threads yet, so a context without the key must default to- # no inline comments rather than crash — the engine parity contract.+ # A local review_pr.py run does not pass review_threads, so a context without the key must+ # default to no inline comments rather than crash. That is the engine parity contract.monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])context = {"repo": "PostHog/posthog",diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.pyindex 4823140cf847..4b3b2df1841c 100644--- a/tools/pr-approval-agent/test_review_pr.py+++ b/tools/pr-approval-agent/test_review_pr.py@@ -84,10 +84,9 @@ def test_summarize_assurance_excludes_author_self_review() -> None: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."""+ # The verdict is posted against the base_sha and head_sha from the JSON output. This locks+ # the GitHub review to the diff the LLM actually saw, and skips the approval when the base+ # or the head changed after the review.pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")pipeline.pr = _fake_pr(head_sha="07dfeff14d95be1247e4c8c1065fd958a367389e")pipeline.pr.base_sha = "b5412a26ec97b9d97367c7356cfe9d9b836ae3cb"diff --git a/tools/pr-approval-agent/test_reviewer.py b/tools/pr-approval-agent/test_reviewer.pyindex a49415c246e0..6d3b531b1060 100644--- a/tools/pr-approval-agent/test_reviewer.py+++ b/tools/pr-approval-agent/test_reviewer.py@@ -254,7 +254,7 @@ def test_guidance_appends_steering_under_marked_section(tmp_path: Path, monkeypadef test_guidance_unchanged_without_steering(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- # No steering.md must mean a byte-identical prompt — the Action's existing repos see no change.+ # No steering.md must mean a byte-identical prompt, so existing repos see no change._fake_stamphog_dir(tmp_path, monkeypatch, "norms prose\n")assert _load_review_guidance() == "norms prose\n"