Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

chore(agent): add repo-local PR delivery skill (#1213)

Call Whited349cf3000d9
diff --git a/.agents/skills/pr-delivery-loop/SKILL.md b/.agents/skills/pr-delivery-loop/SKILL.md
new file mode 100644
index 000000000..1a92f1128
--- /dev/null
+++ b/.agents/skills/pr-delivery-loop/SKILL.md
@@ -0,0 +1,436 @@
+---
+name: pr-delivery-loop
+description: The implementation-lane standard for delivering a PR across the Avibe repositories (avibe, avibe-backend, avibe-docs, avault, and vault-sandbox) — branch/scope rules, contracts, Codex-bot review-loop discipline, and close-out criteria. Use this skill for every implementation task in these repos, regardless of agent backend.
+---
+
+# PR Delivery Loop — implementation-lane standard
+
+## Distribution
+
+- The canonical maintained copy lives in the Avibe repository at
+ `.agents/skills/pr-delivery-loop/SKILL.md`.
+- Every other applicable repository carries a byte-for-byte copy of this skill
+ directory at the same repo-relative path, including its bundled watcher
+ scripts, so a standalone clone has the complete workflow.
+- The bundled watcher set is `scripts/wait_pr.py`,
+ `scripts/wait_action.py`, and `scripts/_github_wait_common.py`; keep these
+ files synchronized with the skill text.
+- This PR deliberately maintains only the repo-local bundle under
+ `.agents/skills/pr-delivery-loop/scripts/`. The existing
+ `skills/background-watch-hook/scripts/` copy remains a separate distribution
+ surface; document its relationship and any differences in the PR body, and
+ leave unification to a separate orchestrator decision.
+- In the multi-repo workspace, the project-level skill entry is a symlink to
+ the Avibe copy. Update the canonical copy first, then sync every repository
+ copy in the same change.
+
+## Roles & authority
+
+- Your **orchestrator** is the agent session responsible for integration and
+ scope decisions. For a delegated lane, it is the dispatching session (your
+ run's callback target). In a user-started working session, the current agent
+ is the orchestrator; the user remains the owner and highest authority, not
+ the default decision engine.
+- Authority order: **user > orchestrator > this standard.** An explicit
+ instruction from the user or your orchestrator overrides any rule below —
+ verify the mechanical gates, then carry it out yourself.
+- Never spawn another agent to act as orchestrator, final reviewer, or
+ merge-approver. Review authority cannot be conjured by a delegated lane:
+ report decisions to its assigned orchestrator. When the current session is
+ the orchestrator, decide independently; ask the owner only for a major
+ trade-off, irreversible risk, or genuinely ambiguous direction.
+
+## 0. Scope & branch
+
+- If the owner or orchestrator gives you an existing branch or worktree, treat
+ it as the assigned task context and continue there after verifying its head;
+ do not create a fresh default-branch lane that abandons or duplicates it.
+- Otherwise branch from the **latest** origin default branch (`git fetch
+ origin` first). In avibe, use a task worktree under the workspace's
+ `.worktrees/avibe/<branch>` directory, or the equivalent sibling worktree
+ directory in a standalone clone.
+- Stay inside your assigned file scope. A cross-lane interface gap is a
+ **report to the orchestrator**, never an edit to the other lane's files.
+- No stacked PRs. If you depend on an unmerged PR, build against its documented
+ shapes from the default branch and declare the dependency in your PR body.
+- **A unique identifier you allocate is a cross-lane contract, even though git
+ treats it as a private file.** Two lanes each add
+ `storage/alembic/versions/<date>_00NN_*.py` picking the same next number; the
+ filenames differ, so git merges both silently into a duplicate revision and a
+ forked head, and the one textual conflict — the shared `HEAD_REVISION` line in
+ `tests/test_sqlite_state_migration.py` — resolves mechanically ("same string,
+ keep it") and erases the evidence. Before final rebase, re-diff your
+ `revision` / `down_revision` against the default branch's newest revision;
+ renumber and re-chain rather than keeping siblings.
+ Same shape for any allocated-id namespace: route paths, feature-flag keys,
+ fixture ids. `git merge-tree --write-tree` will not find it.
+- **`DIRTY` + zero CI checks is one symptom, not two.** A conflicted PR cannot
+ produce the `refs/pull/N/merge` ref that `pull_request` workflows run
+ against, so no workflow starts at all. Before waiting on a slow queue, check
+ `gh pr view --json mergeStateStatus`.
+- **A cancel-and-reroute is not a handover.** `vibe runs cancel` is
+ asynchronous and can lose the race, so a brief rerouted to a fresh agent can
+ leave two agents live on one branch. The run table shows nothing wrong; the
+ symptom is commits the current agent did not author and a PR head ahead of its
+ own record. Whoever reroutes owes one of two things: confirmation that the
+ original is dead before the fork starts, or an explicit statement to each side
+ — the fork is told which session it replaces, the original is told it has been
+ superseded. Whoever inherits a branch reads `git log` for authors other than
+ itself before editing, and treats an unexplained commit as a live peer rather
+ than as its own forgotten work.
+
+## 1. Contracts before code (multi-lane work)
+
+- Interface shapes live in files both lanes can read (types, example payloads,
+ endpoint lists, or a spec section explicitly named as the contract) — never
+ only in prose. Field names are exact (case included). **Commit them to the
+ base branch before the lanes fork**: a contract that lands after the fork is
+ not a shared reference, it is two divergent copies.
+- **An untracked contract draft in the main checkout is a defect with a delayed
+ cost.** No lane can read it from `origin/<base>`, and it blocks the
+ post-merge fast-forward of that checkout — which matters because regression
+ deploys the local commit, so the checkout that cannot fast-forward is exactly
+ the one that ships stale code. Commit the contract, or keep it out of the
+ checkout entirely.
+- **Freeze behavior contracts, not just field shapes.** For every
+ cross-boundary flow, the contract states per field: who produces it, who
+ consumes it, what a signature covers, and — for any handshake/attestation —
+ which side must supply what. A shape-only contract passes both sides' unit
+ tests while the behavior silently disagrees.
+- Orchestrator duty: before dispatching multi-lane work, walk each end-to-end
+ flow across all boundaries and enumerate every field's
+ produce/consume/sign/supply, surfacing every misalignment at once. On any
+ live integration failure, audit the whole remaining chain in one pass — each
+ fix can mask the next layer.
+- Require a real end-to-end test that pierces every boundary with real data
+ (including non-ASCII) — two isolated unit suites with the peer mocked prove
+ nothing about the boundary.
+- Deviating from the contract requires orchestrator sign-off first.
+- Orchestrator-owned spec/contract files you were given by absolute path live
+ OUTSIDE your branch (often uncommitted). If your PR needs them in-repo, sync
+ the AUTHORITATIVE current content at final rebase (confirm the path with the
+ orchestrator) — never commit the possibly-stale copy you read at kickoff:
+ amendments accumulate while you work.
+
+## 1a. State criteria and tests as invariants, never as enumerations
+
+- Every acceptance criterion and every test states the property that must hold,
+ never the list of cases that must not happen. A list reads as complete and
+ never is: the case nobody thought of is, by construction, absent from it.
+- The mechanical form: seed one row of every shape that already exists, run the
+ change, and assert the rows are unchanged — never list which shapes are
+ skipped. A test naming the skipped ones passes forever while the one shape it
+ never named is silently rewritten; seeding is complete by construction, so a
+ shape added later is covered without editing the test. For a migration, assert
+ after upgrade **and** after downgrade.
+- Same rule for spec criteria: name the property and let the tests enumerate. An
+ enumeration written into a spec becomes the definition of done, so whatever is
+ missing from it falls out of scope by accident rather than by decision.
+
+## 2. Pre-PR checks
+
+- Run the smallest relevant local validation: focused tests for what you
+ touched, lint on changed files, the build gate (`npm run build` for UI work),
+ and a read-only smoke test of any bundled watcher script you changed.
+ Self-review your own diff once (`git diff origin/<default>...HEAD`) for scope
+ strays and leftovers.
+- The GitHub Codex bot review (§4) is the review gate.
+
+## 3. Opening the PR
+
+- Non-draft (drafts don't trigger review). Title `type(scope): summary`.
+- Pass the repository's default branch explicitly with `gh pr create
+ --base <default-branch>`; derive it from GitHub rather than trusting a local
+ `branch.<name>.gh-merge-base` setting. After creation, read the PR back and
+ verify `baseRefName` is that default branch before treating the PR as open.
+- Body must include: the changed capability; affected scenario IDs when a
+ catalog exists; evidence layers (unit / contract / scenario / residual manual
+ checks); explicit dependencies ("requires #NNN merged first"); and a
+ **Known-by-design ledger** (§4) when applicable.
+
+## 3a. Turn-final text = a delivered status line
+
+When you run as an async lane (`vibe agent run`), the FINAL TEXT of every turn
+you end is delivered to your orchestrator's conversation as an at-least-once
+callback. It is a report surface, not scratch space: include a stable PR/head
+or Run identifier so duplicate callback delivery can be deduplicated, and end
+every turn with a short, meaningful status line — e.g. `PR #921 head 41c088c5:
+review triggered (👀 confirmed); watch armed` — never a step narration ("Push
+branch, confirm repo"), a thinking fragment, or a bare next-action note. If a
+turn ends because you armed a watch and are waiting, say exactly that.
+
+## 4. Review-loop discipline
+
+- The Codex bot usually auto-reviews new pushes, but not reliably. After every
+ push, confirm a review of the new head is in flight within a few minutes; if
+ none appears, comment `@codex review`.
+- A trigger only counts once the bot reacts 👀 (`eyes`) to that comment — but
+ **the bot withdraws the reaction when the review completes**, so 👀 is
+ evidence only inside its own window. Capture the URL returned by
+ `gh pr comment <pr> --body '@codex review'`, extract that comment's ID, and
+ query `repos/<o>/<r>/issues/comments/<comment-id>/reactions` directly within ~2
+ minutes. Require a reaction with `content == "eyes"` whose `user.login` is
+ `chatgpt-codex-connector` or `chatgpt-codex-connector[bot]`; aggregate counts or
+ reactions from other users do not prove pickup. Before retriggering because
+ 👀 is absent, check for a current-head Codex verdict or another in-flight
+ review signal; a completed review may already have withdrawn 👀. Never use
+ `issues/<pr>/comments --jq '.[-1]'` to identify the trigger.
+ Outside that window every historical trigger reads 0 including the ones that
+ were reviewed, so never infer "it never started" from a reaction count after
+ the fact — look for a current-head verdict instead.
+- Liveness invariant: at every pause there is either a pending bot review of
+ the current head, or one you just triggered. Never wait on nothing.
+- Watches: use the bundled
+ `.agents/skills/pr-delivery-loop/scripts/wait_pr.py` with `python3`; it is
+ self-contained with `_github_wait_common.py`. Use one-shot watches per phase,
+ re-arm after each round with the same watch ID, and never `--forever`. Update
+ its command or message when needed, then always run `vibe watch resume <id>`;
+ update alone does not re-enable a completed one-shot watch. When CI is the sole
+ remaining merge gate, the lane **must switch** its one live watch to the bundled
+ `wait_action.py` and stop re-arming the PR waiter; PR activity cannot wake on a
+ check-only transition. Every GitHub operation in both waiters crosses
+ one shared request taxonomy: only network failures and retryable HTTP statuses
+ may remain inside the bounded one-shot timeout. GraphQL `errors` payloads,
+ malformed protocol responses, non-retryable HTTP statuses, and unexpected
+ failures are terminal and exit explicitly; call sites do not keep local catch-all
+ retry paths. Initial transient requests get three attempts with exponential
+ backoff, and exhausting that budget is also an explicit terminal error.
+- The PR waiter filters your own reviews and comments by the authenticated
+ GitHub viewer login. It must resolve that identity before polling; if `/user`
+ is unavailable for `--pr`, fail closed or explicitly pass
+ `--include-self-comments` and account for those events in the cursor plan.
+ `--new-prs` does not require a viewer lookup because it has no PR-local
+ self-comment filter.
+- The one-watch invariant is scoped by owner and concern: one live lane/fix
+ watch per PR, plus one independent orchestrator gate watch when the work is
+ delegated. Give each concern its own cursor path, for example
+ `<tmp>/pr-<N>-lane.json` and `<tmp>/pr-<N>-gate.json`; never share a natural
+ per-PR cursor file across concurrent watches. Verify the watch name, target
+ session, command, cursor path, and `--pr <N>` together with `vibe watch show`
+ and a live `wait_pr.py` process; never count unrelated global monitors as the
+ lane watch.
+- Every managed waiter must pass an owner/concern-specific `--state-file
+ <path>`. The state file records the repository, PR/filter, and watch
+ identity; resolve PR viewer identity before claiming it, claim it under a lock,
+ and treat a foreign, corrupt, or unwritable file as terminal. A PR state also
+ persists the head SHA, review/comment fingerprints, the full review-thread
+ resolution map, and one normalized gate snapshot. The snapshot contains full
+ current review, comment, pass-reaction, thread, status, and head state after
+ reporting filters, but omits timestamps and other volatile fields. Each detected
+ batch stages its rendered output together with the next cursors under one pending record, then
+ promotes both only after `AVIBE_WATCH_LAST_DELIVERY` changes. An unchanged
+ delivery stamp replays the stored output before GitHub polling or viewer
+ authentication, so deleted activity or changed credentials cannot erase a
+ notification; a head change is itself review-loop activity.
+- A first managed cycle with an unseeded state file must explicitly use
+ `--catch-up` or fail closed; the normal PR-delivery path seeds the complete
+ cursor baseline before pushing, then starts the post-push waiter from that
+ file so a review that lands during the handoff cannot become the baseline.
+- A resumed PR state without the normalized snapshot, persisted `head_sha`, or
+ any review/comment fingerprint map is also treated as an unseeded baseline; pass `--catch-up`
+ explicitly to establish every baseline rather than silently skipping an
+ upgrade-era push or edit.
+- Both modes load saved cursors before deriving their initial baseline:
+ `--new-prs` reads `pr_cursor` before limiting the first pagination, and
+ `--pr` restores the saved review/comment/reaction cursors before polling.
+ Use `--settle 20` for review batches so a Codex review envelope and its inline
+ comments are observed together when GitHub writes them in separate requests.
+ Every settle candidate is computed from the same committed cursor and
+ normalized snapshot; only the final candidate updates the next state.
+- Authenticated PR polling fetches every review-thread page through GraphQL
+ `endCursor` and fetches complete mutable REST collections rather than `since`
+ slices. The sole wake condition is inequality between the current normalized
+ snapshot and the committed snapshot. Per-field checks only describe that
+ difference, so additions, edits, removals, resolution changes, reactions,
+ status changes, and head changes cannot be silently omitted by an incomplete
+ trigger list.
+- Arm the fresh watch only AFTER your reply-then-resolve batch is pushed and
+ settled: your own thread resolutions count as "review activity" to a watch
+ armed earlier in the round, so it self-consumes on YOUR close-out actions and
+ the real next review lands with nobody watching. End every round by
+ objectively verifying the invariant with **two independent pieces of
+ evidence**: `vibe watch list` shows exactly one armed (non-completed) watch
+ for the PR, AND `ps aux | grep "[w]ait_pr.py"` shows a live process carrying
+ both `--repo <owner/name>` and `--pr <N>` for this repository. Never trust
+ that you armed one earlier in the turn, and never read
+ `run_definitions.enabled` — that column is bookkeeping and it drifts both
+ ways: long-removed watches keep `enabled=1` while `vibe watch show` returns
+ null for them, and a watch reported as armed from a remembered id can be
+ `enabled=0` with no waiter behind it. Both errors are silent and look
+ identical on a dashboard, so a brief must never ask a lane to "self-certify
+ enabled" — that phrase prescribes exactly the unsound check.
+- Preserve the watch ID when re-arming: update the existing definition when its
+ command or message changed, then resume that same ID so its owner stamp remains
+ compatible with the persisted state file and the one-shot is enabled. If an
+ ownership handoff is unavoidable, rotate to a fresh state path and seed it
+ before starting the replacement. A watch you delete on purpose is not a
+ liveness break while you are mid-run: the running turn *is* the liveness.
+ Re-arm after the push, then verify both ways.
+- For whoever gates the PR: a lane run that ended `succeeded` proves nothing
+ about the loop. A watch-triggered run can finish clean having pushed nothing
+ and armed nothing, leaving the PR with new findings and no watcher on either
+ side. When your gate watch fires on a findings review, check for a live
+ `wait_pr.py` on that PR number before concluding the lane has it handled.
+- The bot has three verdict shapes. A PASS is either (a) a plain issue comment
+ by the Codex bot (`chatgpt-codex-connector` in the API; often displayed as
+ `chatgpt-codex-connector[bot]`) whose body says
+ "Codex Review: Didn't find any major issues" and names
+ `Reviewed commit: <sha>` equal to the current head, or (b) a `+1` reaction
+ from that bot on the PR body. Findings arrive as a review with inline
+ threads. A contributor comment that quotes the pass text is never a verdict.
+- The CI waiter matches every distinct Actions run ID for each requested
+ workflow name at the exact SHA and branch. A workflow name is not a unique
+ run identity; do not declare CI complete while a second matching run is
+ pending or failed.
+- A `+1` reaction carries no commit sha by itself. Immediately before pushing a
+ new head, ensure the managed waiter's state file contains the last
+ acknowledged activity baseline. Start the post-push waiter with that same
+ `--state-file`, and do not push another head while the new review is pending.
+ Accept the reaction only when it is new after that baseline, the Codex review
+ for the prior head was already terminal before the push, and the PR head is
+ still unchanged. If prior-review completion cannot be established, require
+ the bot-authored pass comment instead of accepting a reaction-only pass. The
+ waiter's `pr_reaction` output is the durable evidence for this phase, so it
+ must never be omitted by `--event-limit` even in a large review batch.
+- Keep reaction meanings distinct: 👀 only says a trigger was picked up; the
+ Codex bot's PR-body `+1` says the review completed without comments. Reactions
+ from other authors or on other comments are not verdicts.
+- Do not treat `Reviewed commit:` alone as a pass signal. A findings verdict is
+ a `COMMENTED` review whose body also opens
+ `### 💡 Codex Review … **Reviewed commit:** <sha>`, so a gate that merely
+ greps for the sha merges over live findings. For a comment-shaped pass, match
+ the bot author, pass phrase, and exact head together; for a reaction-shaped
+ pass, require the head-bound waiter evidence above. In both cases, also gate
+ on every unresolved thread on the PR, including threads opened on earlier or
+ outdated heads.
+- A review attributed to the repo owner with an **empty body** is a phantom, not
+ a review: replying to a review thread creates a `COMMENTED` review under your
+ own account, stamped with the current head's `commit_id`. Any check that
+ selects reviews by head sha will count it as "the bot has started". Filter it
+ out by author and empty body.
+- A 0-finding review is not clean. The bot double-passes commits; close-out
+ requires zero unresolved threads across the entire PR, including threads
+ opened on earlier or outdated heads, not a quiet latest review.
+- Resolve every thread you address (reply, then resolve). For intentional
+ non-changes the bot keeps re-flagging: keep a **Known-by-design ledger** in
+ the PR body and answer re-flags by linking the entry.
+- Same-theme findings = stop patching. The trigger is not a round count, it is
+ whether you can **name the class**: the moment you can enumerate the members
+ the reviewer has not reached yet ("it flagged the projected definition name,
+ and the projection also carries session title, session label, and the
+ callback session"), close the class now — one shared declaration plus a test
+ that asserts the enumeration, so a member added later fails a test instead of
+ costing a review round. Waiting for a third round is paying for a review you
+ have already predicted. Can't name the class? A delegated lane escalates the
+ inventory to its orchestrator; the orchestrator diagnoses whether the closure
+ belongs in a local path, chokepoint, contract, or data model.
+- The circuit breaker is mechanical, not discretionary. Before editing any
+ findings review, fetch every paginated thread and record the reviewed head,
+ number of findings, and root-cause classes in the status delivered to the
+ orchestrator. If a class appears on a second reviewed head, stop before the
+ next edit or push. After an architecture or data-model rewrite, the third
+ findings-bearing head also stops the lane even when no class has repeated.
+ A delegated lane delivers the complete inventory and waits for its
+ orchestrator. The orchestrator diagnoses the full inventory, records the
+ scope decision, and continues independently when the smallest complete action
+ is clear, reversible, and contract-preserving; it asks the owner only for a
+ major trade-off, irreversible risk, or genuinely ambiguous direction. Local
+ tests, CI, and resolved old threads cannot waive the diagnosis.
+- Searchable-list invariant, learned the expensive way on #1023 (three rounds):
+ **every string a row displays must remain a substring of a column the search
+ predicate covers.** A projected field the predicate forgot breaks it; so does
+ a display-side transform that produces a string no column contains
+ (whitespace collapsing, ellipsizing, reformatting). Deleting the transform is
+ not always available: HTML collapses runs of whitespace when it renders, so a
+ row can differ from its column even with no JS touching it. When the rendering
+ layer itself normalizes, make the **matcher** tolerant at the single
+ chokepoint that builds the pattern — never mirror the transform field by
+ field, which puts every future display tweak on a treadmill. Assert the
+ invariant over the enumerated title/label cases, not one example.
+- **Every claim about code you did not write names the sha it was read at.**
+ Read another lane's file from `origin/<their-branch>`, never at your own
+ merge-base: a merge-base snapshot ages the moment they push, and reading one
+ is how a lane escalates a defect the sibling fixed minutes earlier. Name the
+ sha in the escalation so the reader can tell a live read from a stale one.
+- A review finding — and any ruling derived from it — is pinned to the head the
+ review ran on, so name that head when you act on it. If the branch has moved
+ since, reconcile the finding against the current head rather than re-doing the
+ fix; the work may already be there.
+- An escalation only counts when it is **delivered to the orchestrator**:
+ a watch-triggered run must send the escalation directly to the orchestrator's
+ session with `vibe agent run --session-id <orchestrator> --no-callback`, then
+ verify that send succeeded. Merely finishing the watch-triggered run leaves
+ the result in the lane session and notifies nobody. While blocked, the PR
+ waiter observes GitHub activity only; it does not observe Session decisions.
+ The orchestrator must deliver the circuit-breaker decision explicitly to the
+ lane session (for example with `vibe agent run --session-id <lane-session>
+ --message-file <decision> --no-callback`). Keep the GitHub watch armed and
+ state exactly which decision the lane needs.
+
+## 5. Close-out — all conditions, then stop
+
+1. Bot review of the current head with no real findings;
+2. CI fully green: the repository's expected check set is present (unless the
+ repository explicitly defines no CI), every applicable check is terminal,
+ and none is failing, cancelled, timed out, action-required, or pending;
+3. Zero unresolved review threads across the entire PR, regardless of the head
+ on which each thread was opened;
+4. Post the final report: PR URL, what shipped, evidence layers, residual
+ manual checks (state what end-to-end verification is deferred to the
+ orchestrator's integration pass);
+ **Delivery rule (same as escalations):** the final report must be
+ DELIVERED to the orchestrator — send it to the orchestrator's session (or
+ finish the run the orchestrator dispatched with it as the result). When
+ sending via `vibe agent run --session-id <orchestrator>`, pass
+ `--no-callback` — otherwise the orchestrator's next user-facing reply is
+ auto-queued back into YOUR session as a stray instruction. A
+ watch-triggered run's result text stays in your own session and notifies
+ NOBODY; ending your close-out round there means the orchestrator never
+ learns you finished. Verify the send succeeded before stopping.
+ **Tripwire:** the round where the clean pass finally lands is exactly the
+ round where lanes forget this and stop after tidying watches. When you notice
+ conditions 1–3 are already true at the start of a watch-triggered round, SEND
+ THE FINAL REPORT FIRST, then do cleanup;
+5. Remove your watches only after report delivery is verified (nothing
+ dangles, and a failed delivery still has recovery liveness);
+6. **Do not merge on your own initiative** — hand back; the orchestrator does
+ the final review and merge. If the user or your orchestrator explicitly
+ tells you to merge, that instruction IS the final review: check the
+ mechanical gate yourself in one guarded shell conditional that evaluates
+ every condition together — either a bot-authored pass-phrase issue comment
+ naming the current head or a head-bound Codex `+1` captured by the current
+ phase's waiter, zero unresolved threads across the entire PR, the expected
+ CI check set is present and fully successful, and
+ `gh pr view --json mergeStateStatus` == `CLEAN` — so that a check which
+ errors, returns empty, or omits an expected check reads as *do not merge*.
+ Then merge with `gh pr merge --match-head-commit <validated-head-sha>` — no
+ re-review, no spawning anyone. If the gate is not CLEAN, report exactly
+ what's missing instead of refusing by role.
+
+## 6. While waiting, don't idle
+
+Bot rounds take 5–20 minutes. Use the gaps to prepare integration assets: the
+user-facing acceptance checklist, regression/deploy prep notes, contract notes
+for dependent lanes, and your final-report draft.
+
+## 7. Orchestrator counterpart (for dispatchers, not lanes)
+
+- Do not rely on lane terminal reports alone: arm your OWN one-shot gate watch
+ per PR (the repo-local bundled `wait_pr.py`, follow-up in your session) with
+ the merge-gate instructions in the message. Lanes go silent at exactly the
+ moment that matters (§5.5 failure mode); your gate watch is the insurance.
+- One waiter per concern still holds: the lane's watch drives its fix loop;
+ your watch drives the merge gate. Two watches on one PR, two concerns — fine.
+- Every time a findings review lands, independently paginate the threads and
+ update the head/class counts before allowing another fix push. On each round,
+ inspect at least one claimed root-cause fix in the diff and one consuming test;
+ do not accept "all tests green" or the lane's classification as a substitute.
+ Enforce the circuit breaker above: a repeated class on the second reviewed
+ head, or a third findings-bearing head after a model rewrite, pauses the lane
+ and requires the orchestrator to make and record a whole-model decision before
+ work resumes.
+- At gate: verify pass-on-current-head + all expected CI green + zero unresolved
+ across the entire PR + CLEAN yourself from GitHub, re-scan the final diff
+ against the granted file scope (plus any ratified extensions), confirm the
+ lane session is quiesced (no running or queued runs), then merge in dependency
+ order and ff your local default branch before any deploy.
diff --git a/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.py b/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.py
new file mode 100644
index 000000000..5804c54df
--- /dev/null
+++ b/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+"""Shared helpers for GitHub polling waiters."""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+from dataclasses import dataclass
+from typing import Any, Callable, Generic, TypeVar
+
+
+RETRY_EXIT_CODE = 75
+# Cycle completed, nothing worth waking the Agent for. `vibe watch` records the
+# cycle and ends or re-arms without creating a follow-up run.
+#
+# The code alone is not enough: 64 is BSD `sysexits` EX_USAGE, so a watched command
+# that rejects its own arguments exits with it and must keep failing loudly. `vibe
+# watch` reads a quiet cycle only when the marker is on the waiter's output too, so
+# always exit through `no_event()` rather than returning the bare code.
+NO_EVENT_EXIT_CODE = 64
+NO_EVENT_MARKER = "avibe-watch: no-event"
+# `vibe watch` names the watch a waiter is a cycle of here. A waiter that keeps
+# per-watch state on disk should own that state by this id, so two identically
+# configured watches cannot silently share one file. Absent for a manual run.
+WATCH_ID_ENV = "AVIBE_WATCH_ID"
+# How many event reports from this watch `vibe watch` has durably queued as a
+# follow-up, or empty for none. Flushing stdout proves nothing: the supervisor only
+# sees the output once the process has exited, so a waiter that stages the cursors
+# covering a reported event records this value with them and a later cycle promotes
+# them only if the value has since CHANGED. Treat it as opaque and compare it, nothing
+# more. The supervisor bumps it in the same transaction as the follow-up and keeps it
+# out of the lifecycle fields a resume resets, so the answer is still there after a
+# restart, or when a `once` watch is resumed long after its one report. Absent for a
+# manual run, where printing IS the delivery.
+LAST_DELIVERY_ENV = "AVIBE_WATCH_LAST_DELIVERY"
+# Socket timeout for one GitHub request. Callers that have their own deadline need
+# this to size a request budget: a waiter with 20s left cannot afford a fetch that
+# is allowed to block for 30.
+REQUEST_TIMEOUT_SECONDS = 30
+RETRYABLE_HTTP_STATUS_CODES = {408, 429, 500, 502, 503, 504}
+INITIAL_REQUEST_MAX_ATTEMPTS = 3
+INITIAL_REQUEST_BACKOFF_SECONDS = 1.0
+NOT_MODIFIED_STATUS = 304
+
+_MISSING = object()
+_T = TypeVar("_T")
+
+
+class GitHubRequestError(RuntimeError):
+ """Base class for failures classified at the GitHub request boundary."""
+
+ retryable = False
+
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+class GitHubTransientError(GitHubRequestError):
+ """A network or retryable HTTP failure that a bounded waiter may retry."""
+
+ retryable = True
+
+
+class GitHubTerminalError(GitHubRequestError):
+ """A terminal GitHub failure that must stop the waiter."""
+
+
+class GitHubProtocolError(GitHubTerminalError):
+ """A successful HTTP response that violates the expected GitHub contract."""
+
+
+class InitialRequestRetriesExhausted(GitHubTerminalError):
+ """A bounded initial GitHub request exhausted its transient retries."""
+
+
+@dataclass(frozen=True)
+class GitHubRequestResult(Generic[_T]):
+ """One classified request outcome; callers never catch request exceptions."""
+
+ value: _T | None = None
+ error: GitHubRequestError | None = None
+
+ @property
+ def succeeded(self) -> bool:
+ return self.error is None
+
+
+def _classify_github_exception(
+ err: Exception,
+ *,
+ unauthenticated: bool = False,
+) -> GitHubRequestError:
+ if isinstance(err, GitHubRequestError):
+ return err
+ if isinstance(err, urllib.error.HTTPError):
+ code = int(err.code)
+ reason = str(err.reason)
+ if unauthenticated and code in {403, 429}:
+ return GitHubTerminalError(
+ "GitHub unauthenticated polling hit a rate limit; authenticate with "
+ "'gh auth login' or GITHUB_TOKEN/GH_TOKEN",
+ status_code=code,
+ )
+ error_type = GitHubTransientError if code in RETRYABLE_HTTP_STATUS_CODES else GitHubTerminalError
+ return error_type(f"GitHub HTTP {code} {reason}", status_code=code)
+ if isinstance(err, (urllib.error.URLError, TimeoutError, ConnectionError, OSError)):
+ reason = str(getattr(err, "reason", err))
+ return GitHubTransientError(f"GitHub network failure: {reason}")
+ return GitHubTerminalError(
+ f"Unexpected GitHub request failure ({type(err).__name__}): {err}"
+ )
+
+
+def github_request(operation: Callable[[], _T]) -> GitHubRequestResult[_T]:
+ """Run one GitHub operation through the sole transient/terminal taxonomy."""
+
+ try:
+ return GitHubRequestResult(value=operation())
+ except Exception as err: # noqa: BLE001 - this is the classification boundary
+ return GitHubRequestResult(error=_classify_github_exception(err))
+
+
+def retry_initial_request(
+ operation: Callable[[], _T],
+ *,
+ description: str,
+) -> GitHubRequestResult[_T]:
+ """Retry initial network/5xx failures with a bounded exponential backoff."""
+
+ for attempt in range(1, INITIAL_REQUEST_MAX_ATTEMPTS + 1):
+ result = github_request(operation)
+ if result.succeeded or result.error is None or not result.error.retryable:
+ return result
+ failure = str(result.error)
+
+ if attempt == INITIAL_REQUEST_MAX_ATTEMPTS:
+ return GitHubRequestResult(
+ error=InitialRequestRetriesExhausted(
+ f"{description} failed after {INITIAL_REQUEST_MAX_ATTEMPTS} attempts: {failure}"
+ )
+ )
+ delay = INITIAL_REQUEST_BACKOFF_SECONDS * (2 ** (attempt - 1))
+ print(
+ f"Transient {description} failure on attempt {attempt}/{INITIAL_REQUEST_MAX_ATTEMPTS}: "
+ f"{failure}; retrying in {delay:.1f}s",
+ file=sys.stderr,
+ )
+ time.sleep(delay)
+
+ return GitHubRequestResult(error=GitHubTerminalError("unreachable request state"))
+
+
+def no_event(summary: str = "") -> int:
+ """End the cycle with nothing to report, and say so where the watch can see it.
+
+ The summary goes to stderr so it stays in the watch log: it is the only record
+ of what the waiter saw and chose not to forward, and no Agent turn carries it.
+ """
+
+ if summary:
+ print(summary, file=sys.stderr)
+ print(NO_EVENT_MARKER, file=sys.stderr)
+ return NO_EVENT_EXIT_CODE
+
+
+def get_token() -> str | None:
+ for env_name in ("GH_TOKEN", "GITHUB_TOKEN"):
+ value = os.environ.get(env_name)
+ if value:
+ return value
+
+ gh_path = shutil.which("gh")
+ if not gh_path:
+ return None
+
+ try:
+ result = subprocess.run(
+ [gh_path, "auth", "token"],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except (OSError, subprocess.CalledProcessError):
+ return None
+ token = result.stdout.strip()
+ return token or None
+
+
+def min_interval_for_unauthenticated(
+ requests_per_poll: int,
+ *,
+ bootstrap_requests: int = 0,
+) -> float:
+ recurring_requests = max(requests_per_poll, 1)
+ hourly_budget = max(1, 60 - max(bootstrap_requests, 0))
+ return float(max(60, math.ceil((3600 * recurring_requests) / hourly_budget)))
+
+
+class ResponseCache:
+ """Per-URL ETag cache so an unchanged page costs nothing to re-check.
+
+ GitHub answers a revalidated conditional request with 304 and does not charge
+ it against the rate limit, so a waiter that sits on a quiet PR can keep
+ polling indefinitely for free instead of re-downloading its whole history
+ every interval.
+
+ The cache lives for one waiter process. A 304 is only useful while the body it
+ stands for is still in memory, so it is deliberately not persisted. PR polling
+ still requests complete collections because deletion detection requires them;
+ ETag revalidation keeps unchanged pages free of rate-limit cost.
+ """
+
+ __slots__ = ("_entries", "revalidated", "downloaded")
+
+ def __init__(self) -> None:
+ self._entries: dict[str, tuple[str, Any]] = {}
+ self.revalidated = 0
+ self.downloaded = 0
+
+ def etag_for(self, url: str) -> str | None:
+ entry = self._entries.get(url)
+ return entry[0] if entry is not None else None
+
+ def store(self, url: str, etag: str, payload: Any) -> None:
+ self._entries[url] = (etag, payload)
+
+ def payload_for(self, url: str) -> Any:
+ entry = self._entries.get(url)
+ return _MISSING if entry is None else entry[1]
+
+ def summary(self) -> str:
+ total = self.revalidated + self.downloaded
+ if not total:
+ return "no GitHub requests issued"
+ return (
+ f"{total} GitHub request(s): {self.revalidated} revalidated as 304 "
+ f"(free of rate limit), {self.downloaded} downloaded"
+ )
+
+
+def _read_github_json(
+ request: urllib.request.Request,
+ *,
+ token: str | None,
+ cache: ResponseCache | None = None,
+ cache_key: str | None = None,
+) -> Any:
+ """Read one response and translate every failure through the taxonomy."""
+
+ try:
+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ if cache is not None:
+ cache.downloaded += 1
+ response_etag = response.headers.get("ETag")
+ if response_etag and cache_key is not None:
+ cache.store(cache_key, response_etag, payload)
+ return payload
+ except urllib.error.HTTPError as err:
+ if err.code == NOT_MODIFIED_STATUS and cache is not None and cache_key is not None:
+ payload = cache.payload_for(cache_key)
+ if payload is not _MISSING:
+ cache.revalidated += 1
+ return payload
+ raise _classify_github_exception(
+ err,
+ unauthenticated=token is None,
+ ) from err
+ except Exception as err: # noqa: BLE001 - this is the raw HTTP boundary
+ raise _classify_github_exception(err) from err
+
+
+def github_get(url: str, token: str | None, *, cache: ResponseCache | None = None) -> Any:
+ request = urllib.request.Request(url)
+ request.add_header("Accept", "application/vnd.github+json")
+ request.add_header("User-Agent", "background-watch-hook/0.1.0")
+ if token:
+ request.add_header("Authorization", f"Bearer {token}")
+ etag = cache.etag_for(url) if cache is not None else None
+ if etag:
+ request.add_header("If-None-Match", etag)
+ return _read_github_json(request, token=token, cache=cache, cache_key=url)
+
+
+def github_graphql(query: str, variables: dict[str, Any], token: str) -> dict[str, Any]:
+ request = urllib.request.Request(
+ "https://api.github.com/graphql",
+ data=json.dumps({"query": query, "variables": variables}).encode("utf-8"),
+ method="POST",
+ )
+ request.add_header("Accept", "application/vnd.github+json")
+ request.add_header("Content-Type", "application/json")
+ request.add_header("User-Agent", "background-watch-hook/0.1.0")
+ request.add_header("Authorization", f"Bearer {token}")
+ payload = _read_github_json(request, token=token)
+ if not isinstance(payload, dict):
+ raise GitHubProtocolError("GitHub GraphQL returned an unexpected payload")
+ errors = payload.get("errors")
+ if errors:
+ raise GitHubProtocolError(f"GitHub GraphQL error: {errors}")
+ data = payload.get("data")
+ if not isinstance(data, dict):
+ raise GitHubProtocolError("GitHub GraphQL response has no data object")
+ return data
+
+
+def resolve_authenticated_login(token: str | None) -> str | None:
+ """Resolve the viewer identity without hiding an authenticated lookup failure."""
+
+ if not token:
+ return None
+ payload = github_get("https://api.github.com/user", token)
+ if not isinstance(payload, dict):
+ raise GitHubProtocolError("GitHub /user returned an unexpected payload")
+ login = payload.get("login")
+ if not isinstance(login, str) or not login:
+ raise GitHubProtocolError("GitHub /user did not return a viewer login")
+ return login
+
+
+def list_paginated(
+ base_url: str,
+ token: str | None,
+ *,
+ cache: ResponseCache | None = None,
+) -> list[dict[str, Any]]:
+ items, _request_count = list_paginated_with_count(base_url, token, cache=cache)
+ return items
+
+
+def list_paginated_with_count(
+ base_url: str,
+ token: str | None,
+ *,
+ stop_after_id: int | None = None,
+ max_pages: int | None = None,
+ cache: ResponseCache | None = None,
+) -> tuple[list[dict[str, Any]], int]:
+ items: list[dict[str, Any]] = []
+ page = 1
+ request_count = 0
+ while True:
+ separator = "&" if "?" in base_url else "?"
+ url = f"{base_url}{separator}per_page=100&page={page}"
+ payload = github_get(url, token, cache=cache)
+ request_count += 1
+ if not isinstance(payload, list):
+ raise GitHubProtocolError(f"Expected a JSON list from {url}")
+ if not payload:
+ break
+ page_items = [item for item in payload if isinstance(item, dict)]
+ items.extend(page_items)
+ if stop_after_id is not None and stop_after_id > 0:
+ if any(isinstance(item.get("id"), int) and int(item["id"]) <= stop_after_id for item in page_items):
+ break
+ if max_pages is not None and page >= max_pages:
+ break
+ if len(payload) < 100:
+ break
+ page += 1
+ return items, request_count
+
+
+def squash(text: str | None, *, limit: int = 140) -> str:
+ compact = " ".join((text or "").split())
+ if len(compact) <= limit:
+ return compact
+ return compact[: limit - 1].rstrip() + "…"
+
+
+def max_id(items: list[dict[str, Any]]) -> int:
+ values = [int(item["id"]) for item in items if isinstance(item.get("id"), int)]
+ return max(values, default=0)
+
+
+def filter_new(items: list[dict[str, Any]], since_id: int) -> list[dict[str, Any]]:
+ return sorted(
+ [item for item in items if isinstance(item.get("id"), int) and int(item["id"]) > since_id],
+ key=lambda item: (str(item.get("created_at") or ""), int(item["id"])),
+ )
+
+
+def requests_per_poll(*collections: list[dict[str, Any]]) -> int:
+ requests = 0
+ for items in collections:
+ requests += max(1, (len(items) // 100) + 1)
+ return requests
diff --git a/.agents/skills/pr-delivery-loop/scripts/wait_action.py b/.agents/skills/pr-delivery-loop/scripts/wait_action.py
new file mode 100755
index 000000000..b4440604c
--- /dev/null
+++ b/.agents/skills/pr-delivery-loop/scripts/wait_action.py
@@ -0,0 +1,364 @@
+#!/usr/bin/env python3
+"""Wait until selected GitHub Actions workflow runs finish for a commit."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import time
+import urllib.parse
+from pathlib import Path
+from typing import Any
+
+SCRIPT_DIR = Path(__file__).resolve().parent
+if str(SCRIPT_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPT_DIR))
+
+from _github_wait_common import ( # noqa: E402
+ GitHubProtocolError,
+ NO_EVENT_EXIT_CODE,
+ NO_EVENT_MARKER,
+ get_token,
+ github_get,
+ github_request,
+ min_interval_for_unauthenticated,
+ no_event,
+ retry_initial_request,
+)
+
+DEFAULT_SUCCESS_CONCLUSIONS = {"success", "skipped", "neutral"}
+TERMINAL_STATUS = "completed"
+
+
+def _fetch_workflow_runs(
+ repo: str,
+ token: str | None,
+ *,
+ branch: str | None = None,
+ head_sha: str | None = None,
+ max_pages: int = 3,
+) -> tuple[list[dict[str, Any]], int]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ query: dict[str, str | int] = {"per_page": 100}
+ if branch:
+ query["branch"] = branch
+ if head_sha:
+ query["head_sha"] = head_sha
+
+ runs: list[dict[str, Any]] = []
+ request_count = 0
+ for page in range(1, max(max_pages, 1) + 1):
+ query["page"] = page
+ url = f"https://api.github.com/repos/{encoded_repo}/actions/runs?{urllib.parse.urlencode(query)}"
+ payload = github_get(url, token)
+ request_count += 1
+ if not isinstance(payload, dict):
+ raise GitHubProtocolError(f"Expected a JSON object from {url}")
+ page_runs = payload.get("workflow_runs")
+ if not isinstance(page_runs, list):
+ raise GitHubProtocolError(f"Expected workflow_runs list from {url}")
+ runs.extend(run for run in page_runs if isinstance(run, dict))
+ if len(page_runs) < 100:
+ break
+ return runs, request_count
+
+
+def _workflow_name(run: dict[str, Any]) -> str:
+ return str(run.get("name") or run.get("workflowName") or "")
+
+
+def _run_sort_key(run: dict[str, Any]) -> tuple[str, int]:
+ timestamp = str(run.get("run_started_at") or run.get("created_at") or "")
+ run_id = int(run["id"]) if isinstance(run.get("id"), int) else 0
+ return timestamp, run_id
+
+
+def _select_latest_runs_by_workflow(
+ runs: list[dict[str, Any]],
+ *,
+ workflows: list[str],
+ branch: str | None,
+ head_sha: str,
+) -> dict[str, list[dict[str, Any]]]:
+ workflow_set = set(workflows)
+ result: dict[str, list[dict[str, Any]]] = {workflow: [] for workflow in workflows}
+ normalized_sha = head_sha.casefold()
+ seen_ids: dict[str, set[int]] = {workflow: set() for workflow in workflows}
+
+ for run in sorted(runs, key=_run_sort_key):
+ name = _workflow_name(run)
+ if name not in workflow_set:
+ continue
+ if str(run.get("head_sha") or "").casefold() != normalized_sha:
+ continue
+ if branch and str(run.get("head_branch") or "") != branch:
+ continue
+ run_id = run.get("id")
+ if not isinstance(run_id, int) or run_id in seen_ids[name]:
+ continue
+ seen_ids[name].add(run_id)
+ result[name].append(run)
+
+ return result
+
+
+def _format_run(run: dict[str, Any]) -> str:
+ name = _workflow_name(run) or "unknown"
+ status = str(run.get("status") or "unknown")
+ conclusion = str(run.get("conclusion") or "none")
+ url = str(run.get("html_url") or run.get("url") or "")
+ title = str(run.get("display_title") or "")
+ details = f" - {title}" if title else ""
+ return f"- {name}: status={status} conclusion={conclusion}{details}\n {url}"
+
+
+def _render_actions_result(
+ *,
+ repo: str,
+ branch: str | None,
+ head_sha: str,
+ selected: dict[str, list[dict[str, Any]]],
+ success_conclusions: set[str],
+) -> tuple[str | None, bool]:
+ missing = [workflow for workflow, runs in selected.items() if not runs]
+ running = [
+ workflow
+ for workflow, runs in selected.items()
+ if any(str(run.get("status") or "") != TERMINAL_STATUS for run in runs)
+ ]
+ if missing or running:
+ return None, False
+
+ failed = [
+ workflow
+ for workflow, runs in selected.items()
+ if any(str(run.get("conclusion") or "") not in success_conclusions for run in runs)
+ ]
+ result = "failure" if failed else "success"
+ short_sha = head_sha[:12]
+ branch_label = f" on {branch}" if branch else ""
+ lines = [f"GitHub Actions {result} for {repo}@{short_sha}{branch_label}"]
+ for workflow in selected:
+ for run in selected[workflow]:
+ lines.append(_format_run(run))
+ if failed:
+ lines.append(f"Failed workflow(s): {', '.join(failed)}")
+ return "\n".join(lines), bool(failed)
+
+
+def _write_cursor_output(path: str | None, *, selected: dict[str, list[dict[str, Any]]]) -> None:
+ if not path:
+ return
+
+ payload = {
+ workflow: {
+ "runs": [
+ {
+ "id": run.get("id"),
+ "status": run.get("status"),
+ "conclusion": run.get("conclusion"),
+ "html_url": run.get("html_url"),
+ }
+ for run in runs
+ ],
+ }
+ for workflow, runs in selected.items()
+ if runs
+ }
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle)
+
+
+def _parse_success_conclusions(values: list[str] | None) -> set[str]:
+ if not values:
+ return set(DEFAULT_SUCCESS_CONCLUSIONS)
+ result: set[str] = set()
+ for value in values:
+ result.update(item.strip() for item in value.split(",") if item.strip())
+ return result
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", required=True, help="GitHub repo in owner/name form")
+ parser.add_argument("--branch", help="Branch name to match, e.g. main")
+ parser.add_argument("--sha", required=True, help="Exact head commit SHA to match")
+ parser.add_argument("--workflow", action="append", required=True, help="Workflow name to wait for; repeatable")
+ parser.add_argument("--interval", type=float, default=45.0, help="Polling interval in seconds")
+ parser.add_argument(
+ "--timeout",
+ type=float,
+ default=21600.0,
+ help="Overall timeout in seconds; default 21600 (6 hours), 0 means forever",
+ )
+ parser.add_argument("--max-pages", type=int, default=3, help="Maximum Actions run-list pages to inspect per poll")
+ parser.add_argument(
+ "--success-conclusion",
+ action="append",
+ help=(
+ "Conclusion treated as successful; repeatable or comma-separated. "
+ "Defaults to success,skipped,neutral."
+ ),
+ )
+ parser.add_argument(
+ "--only-on-failure",
+ action="store_true",
+ help=(
+ "Do not wake the Agent when every watched workflow succeeded; exit with the "
+ f"no-event code {NO_EVENT_EXIT_CODE} and the '{NO_EVENT_MARKER}' marker instead. "
+ "Failures still exit 0 with the full report."
+ ),
+ )
+ parser.add_argument("--cursor-output", help=argparse.SUPPRESS)
+ parser.add_argument(
+ "--allow-unauthenticated",
+ action="store_true",
+ help="Allow polling without GitHub auth; the interval will be clamped to a safer minimum",
+ )
+ args = parser.parse_args()
+
+ token = get_token()
+ if token is None and not args.allow_unauthenticated:
+ print(
+ (
+ "GitHub authentication is required for reliable polling. "
+ "Set GITHUB_TOKEN/GH_TOKEN, run 'gh auth login', or pass "
+ "--allow-unauthenticated for a throttled best-effort run."
+ ),
+ file=sys.stderr,
+ )
+ return 2
+
+ base_interval = max(args.interval, 1.0)
+ effective_interval = base_interval
+ success_conclusions = _parse_success_conclusions(args.success_conclusion)
+ start = time.monotonic()
+ selected: dict[str, list[dict[str, Any]]] = {workflow: [] for workflow in args.workflow}
+ first_successful_fetch = True
+
+ print(
+ (
+ "Watching GitHub Actions for %s sha=%s branch=%s workflows=%s"
+ % (args.repo, args.sha, args.branch or "-", ",".join(args.workflow))
+ ),
+ file=sys.stderr,
+ )
+
+ poll_attempt = 0
+ while True:
+ first_poll = poll_attempt == 0
+ poll_attempt += 1
+ if first_poll:
+ request_result = retry_initial_request(
+ lambda: _fetch_workflow_runs(
+ args.repo,
+ token,
+ branch=args.branch,
+ head_sha=args.sha,
+ max_pages=args.max_pages,
+ ),
+ description="initial GitHub Actions request",
+ )
+ else:
+ request_result = github_request(
+ lambda: _fetch_workflow_runs(
+ args.repo,
+ token,
+ branch=args.branch,
+ head_sha=args.sha,
+ max_pages=args.max_pages,
+ )
+ )
+
+ if request_result.error is not None:
+ print(str(request_result.error), file=sys.stderr)
+ if first_poll or not request_result.error.retryable:
+ return 1
+ print(
+ "Retryable GitHub request failure during polling; continuing in this watch",
+ file=sys.stderr,
+ )
+ runs = []
+ request_count = 0
+ else:
+ if request_result.value is None:
+ print("GitHub request completed without a result", file=sys.stderr)
+ return 1
+ runs, request_count = request_result.value
+
+ if token is None and request_count > 0:
+ bootstrap_requests = request_count if first_successful_fetch else 0
+ unauthenticated_min = min_interval_for_unauthenticated(
+ request_count,
+ bootstrap_requests=bootstrap_requests,
+ )
+ target_interval = max(base_interval, unauthenticated_min)
+ if target_interval != effective_interval:
+ direction = "increasing" if target_interval > effective_interval else "reducing"
+ print(
+ (
+ "GitHub unauthenticated polling uses %s request(s) per poll plus "
+ "%s bootstrap request(s); %s interval from %.1fs to %.1fs."
+ )
+ % (
+ request_count,
+ bootstrap_requests,
+ direction,
+ effective_interval,
+ target_interval,
+ ),
+ file=sys.stderr,
+ )
+ effective_interval = target_interval
+ first_successful_fetch = False
+
+ if runs:
+ selected = _select_latest_runs_by_workflow(
+ runs,
+ workflows=args.workflow,
+ branch=args.branch,
+ head_sha=args.sha,
+ )
+ output, has_failed_workflow = _render_actions_result(
+ repo=args.repo,
+ branch=args.branch,
+ head_sha=args.sha,
+ selected=selected,
+ success_conclusions=success_conclusions,
+ )
+ if output is not None:
+ _write_cursor_output(args.cursor_output, selected=selected)
+ if args.only_on_failure and not has_failed_workflow:
+ # The interesting outcome is a broken build. Reporting a green one
+ # costs a full Agent turn to say "nothing to do", so keep the
+ # summary on stderr where it stays inspectable via the watch log.
+ print(output, file=sys.stderr)
+ return no_event(
+ "All watched workflows succeeded; exiting without an Agent follow-up "
+ "because --only-on-failure is set."
+ )
+ print(output)
+ return 0
+
+ missing = [workflow for workflow, runs in selected.items() if not runs]
+ running = [
+ workflow
+ for workflow, runs in selected.items()
+ if any(str(run.get("status") or "") != TERMINAL_STATUS for run in runs)
+ ]
+ print(f"Waiting for GitHub Actions: missing={missing or '-'} running={running or '-'}", file=sys.stderr)
+
+ sleep_seconds = effective_interval
+ if args.timeout > 0:
+ remaining_timeout = args.timeout - (time.monotonic() - start)
+ if remaining_timeout <= 0:
+ print("Timed out while waiting for GitHub Actions", file=sys.stderr)
+ return 124
+ sleep_seconds = min(sleep_seconds, remaining_timeout)
+
+ time.sleep(sleep_seconds)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.agents/skills/pr-delivery-loop/scripts/wait_pr.py b/.agents/skills/pr-delivery-loop/scripts/wait_pr.py
new file mode 100755
index 000000000..07ae82d0e
--- /dev/null
+++ b/.agents/skills/pr-delivery-loop/scripts/wait_pr.py
@@ -0,0 +1,2344 @@
+#!/usr/bin/env python3
+"""Wait until a GitHub pull request or repository receives new PR activity."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import sys
+import tempfile
+import time
+import urllib.parse
+from contextlib import contextmanager
+from functools import partial
+from pathlib import Path
+from typing import Any, Iterator
+
+try: # POSIX only, which is every platform `vibe` runs the waiter on.
+ import fcntl
+except ImportError: # pragma: no cover - Windows has no flock
+ fcntl = None # type: ignore[assignment]
+
+SCRIPT_DIR = Path(__file__).resolve().parent
+if str(SCRIPT_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPT_DIR))
+
+from _github_wait_common import ( # noqa: E402
+ filter_new,
+ get_token,
+ GitHubProtocolError,
+ GitHubRequestResult,
+ github_get,
+ github_graphql,
+ github_request,
+ LAST_DELIVERY_ENV,
+ list_paginated,
+ list_paginated_with_count,
+ max_id,
+ min_interval_for_unauthenticated,
+ REQUEST_TIMEOUT_SECONDS,
+ requests_per_poll,
+ resolve_authenticated_login,
+ ResponseCache,
+ retry_initial_request,
+ squash,
+ WATCH_ID_ENV,
+)
+
+CODEX_REVIEW_PASS_REACTION_USERS = frozenset(
+ {"chatgpt-codex-connector", "chatgpt-codex-connector[bot]"}
+)
+CODEX_REVIEW_PASS_REACTION_CONTENT = "+1"
+
+# Comments that only drive the review loop rather than report its result. On a
+# busy PR these outnumber the real findings, and each one costs a full Agent turn.
+# Anchored at BOTH ends: a trigger comment is only the command. "@codex review" is
+# noise; "@author fix the timeout handling" is a person asking for work and must
+# survive, because suppressing it still advances the cursor and the request would be
+# lost for good rather than merely delayed.
+DEFAULT_NOISE_COMMENT_PATTERNS = (
+ r"^@[\w\[\]-]+\s+(review|fix|rebase|merge)\s*$",
+ r"^/[\w-]+\s*$",
+)
+# Lifecycle transitions worth interrupting for. Draft toggles are usually the
+# Agent's own doing, so they are noise in --actionable-only mode.
+ACTIONABLE_PR_STATUSES = frozenset({"merged", "closed"})
+STATE_FILE_VERSION = 1
+# Cursors that cover a REPORTED event, held here instead of committed, next to the
+# supervisor's last-delivery stamp as it read at report time. A waiter cannot see its
+# own delivery -- the supervisor reads its output only after the process exits -- so
+# committing them at report time loses the event whenever the service stops in
+# between. A later cycle that reads a different stamp knows the report was delivered
+# and promotes them; an unchanged stamp replays the report.
+STAGED_KEY = "pending"
+STATE_CURSOR_KEYS = (
+ "review_cursor",
+ "review_comment_cursor",
+ "issue_comment_cursor",
+ "reaction_cursor",
+)
+REVIEW_FINGERPRINTS_KEY = "review_fingerprints"
+REVIEW_COMMENT_FINGERPRINTS_KEY = "review_comment_fingerprints"
+ISSUE_COMMENT_FINGERPRINTS_KEY = "issue_comment_fingerprints"
+REVIEW_THREAD_STATES_KEY = "review_thread_states"
+PR_SNAPSHOT_KEY = "snapshot"
+PR_FINGERPRINT_KEYS = (
+ REVIEW_FINGERPRINTS_KEY,
+ REVIEW_COMMENT_FINGERPRINTS_KEY,
+ ISSUE_COMMENT_FINGERPRINTS_KEY,
+)
+# A bot review lands as a burst of inline comments plus an envelope. Re-polling a
+# few times while the burst is still arriving turns it into one Agent turn instead
+# of one turn per fragment that happened to cross a poll boundary.
+SETTLE_MAX_ROUNDS = 3
+REVIEW_THREADS_QUERY = """
+query($owner: String!, $repo: String!, $number: Int!, $endCursor: String) {
+ repository(owner: $owner, name: $repo) {
+ pullRequest(number: $number) {
+ reviewThreads(first: 100, after: $endCursor) {
+ nodes { id isResolved }
+ pageInfo { hasNextPage endCursor }
+ }
+ }
+ }
+}
+"""
+
+
+class StateFileError(RuntimeError):
+ """The requested ``--state-file`` cannot do the job it was asked to do.
+
+ Raised rather than warned about because a forever watch that keeps polling
+ without usable cursors loses activity instead of reporting it, and does so
+ silently: every fresh cycle re-baselines from the current PR.
+ """
+
+
+class StatePersistenceError(StateFileError):
+ """The cursors an explicit ``--state-file`` promised could not be saved."""
+
+
+class StateFileUnusableError(StateFileError):
+ """An existing ``--state-file`` cannot be read, so its cursors are unknown.
+
+ Not recoverable by starting over: re-baselining from the current PR skips
+ everything that arrived after the last cursor this file did hold, and then
+ overwrites the evidence. The corrupt file has to be removed deliberately.
+ """
+
+
+class StateFileOwnershipError(StateFileError):
+ """The state file at this path belongs to a different PR, or a different watch.
+
+ Two watches pointed at one file is a configuration error, not a state to
+ recover from: each would read the other's cursors as absent, re-baseline, and
+ then overwrite them, so both watches keep missing activity between cycles.
+ """
+
+
+def _format_review(review: dict[str, Any]) -> str:
+ review_id = review.get("id")
+ author = ((review.get("user") or {}).get("login")) or "unknown"
+ state = str(review.get("state") or "commented").lower()
+ body = squash(review.get("body") or state)
+ url = review.get("html_url") or ""
+ return f"- review #{review_id} by {author} ({state})\n {body}\n {url}"
+
+
+def _format_review_comment(comment: dict[str, Any]) -> str:
+ comment_id = comment.get("id")
+ author = ((comment.get("user") or {}).get("login")) or "unknown"
+ path = comment.get("path") or "unknown-path"
+ body = squash(comment.get("body"))
+ url = comment.get("html_url") or ""
+ return f"- review_comment #{comment_id} by {author} on {path}\n {body}\n {url}"
+
+
+def _format_issue_comment(comment: dict[str, Any]) -> str:
+ comment_id = comment.get("id")
+ author = ((comment.get("user") or {}).get("login")) or "unknown"
+ body = squash(comment.get("body"))
+ url = comment.get("html_url") or ""
+ return f"- issue_comment #{comment_id} by {author}\n {body}\n {url}"
+
+
+def _is_self_authored_comment(comment: dict[str, Any], viewer_login: str | None) -> bool:
+ if not viewer_login:
+ return False
+ author = ((comment.get("user") or {}).get("login")) or ""
+ return str(author).casefold() == viewer_login.casefold()
+
+
+def _compile_ignore_patterns(values: list[str] | None, *, actionable_only: bool) -> list[re.Pattern[str]]:
+ patterns = list(DEFAULT_NOISE_COMMENT_PATTERNS) if actionable_only else []
+ patterns.extend(values or [])
+ return [re.compile(pattern, re.IGNORECASE) for pattern in patterns]
+
+
+def _normalize_authors(values: list[str] | None) -> set[str]:
+ return {value.strip().casefold() for value in (values or []) if value.strip()}
+
+
+def _is_ignored_author(item: dict[str, Any], ignored_authors: set[str]) -> bool:
+ if not ignored_authors:
+ return False
+ author = ((item.get("user") or {}).get("login")) or ""
+ return str(author).casefold() in ignored_authors
+
+
+def _matches_ignored_pattern(item: dict[str, Any], patterns: list[re.Pattern[str]]) -> bool:
+ if not patterns:
+ return False
+ text = squash(item.get("body"), limit=1000)
+ if not text:
+ return False
+ return any(pattern.search(text) for pattern in patterns)
+
+
+def _is_actionable_review(review: dict[str, Any]) -> bool:
+ """A review carries a verdict, or a body worth reading.
+
+ A bodyless ``COMMENTED`` review is the envelope GitHub wraps around inline
+ comments; those comments are reported on their own, so the envelope adds a
+ turn and no information.
+ """
+
+ state = str(review.get("state") or "").lower()
+ if state in {"changes_requested", "approved", "dismissed"}:
+ return True
+ return bool(squash(review.get("body")))
+
+
+def _keep_item(
+ item: dict[str, Any],
+ *,
+ ignored_authors: set[str],
+ ignore_patterns: list[re.Pattern[str]],
+) -> bool:
+ return not _is_ignored_author(item, ignored_authors) and not _matches_ignored_pattern(item, ignore_patterns)
+
+
+def _visible_activity_items(
+ items: list[dict[str, Any]],
+ *,
+ viewer_login: str | None,
+ ignore_self_comments: bool,
+ ignored_authors: set[str],
+ ignore_patterns: list[re.Pattern[str]],
+) -> list[dict[str, Any]]:
+ kept = (
+ items
+ if not ignore_self_comments
+ else [item for item in items if not _is_self_authored_comment(item, viewer_login)]
+ )
+ return [
+ item
+ for item in kept
+ if _keep_item(item, ignored_authors=ignored_authors, ignore_patterns=ignore_patterns)
+ ]
+
+
+def _is_codex_pass_reaction(reaction: dict[str, Any]) -> bool:
+ author = ((reaction.get("user") or {}).get("login")) or ""
+ content = str(reaction.get("content") or "")
+ return author in CODEX_REVIEW_PASS_REACTION_USERS and content == CODEX_REVIEW_PASS_REACTION_CONTENT
+
+
+def _format_reaction(reaction: dict[str, Any]) -> str:
+ reaction_id = reaction.get("id")
+ author = ((reaction.get("user") or {}).get("login")) or "unknown"
+ content = str(reaction.get("content") or "")
+ created_at = str(reaction.get("created_at") or "")
+ return (
+ f"- pr_reaction #{reaction_id} by {author} ({content})\n"
+ f" Codex review completed without comments and reacted on the PR body at {created_at}."
+ )
+
+
+def _current_pr_status(pr: dict[str, Any] | None) -> str:
+ if not isinstance(pr, dict):
+ return "unknown"
+ if pr.get("merged_at"):
+ return "merged"
+ state = str(pr.get("state") or "").lower()
+ if state == "closed":
+ return "closed"
+ if pr.get("draft") is True:
+ return "draft"
+ if state == "open":
+ return state
+ return state or "unknown"
+
+
+def _current_pr_head_sha(pr: dict[str, Any] | None) -> str:
+ if not isinstance(pr, dict):
+ return "unknown"
+ head = pr.get("head")
+ if not isinstance(head, dict):
+ return "unknown"
+ sha = str(head.get("sha") or "").strip()
+ return sha or "unknown"
+
+
+def _describe_pr_status_change(previous_status: str, current_status: str) -> str:
+ if previous_status == "draft" and current_status == "open":
+ return "Pull request is ready for review."
+ if previous_status == "open" and current_status == "draft":
+ return "Pull request was converted to draft."
+ if current_status == "merged":
+ return "Pull request was merged."
+ if current_status == "closed":
+ return "Pull request was closed without merge."
+ if current_status == "open":
+ return "Pull request was reopened."
+ return f"Pull request status changed from {previous_status} to {current_status}."
+
+
+def _format_pr_status_event(pr: dict[str, Any], previous_status: str, current_status: str) -> str:
+ pr_number = pr.get("number")
+ url = pr.get("html_url") or ""
+ return (
+ f"- pr_status #{pr_number} {previous_status} -> {current_status}\n"
+ f" {_describe_pr_status_change(previous_status, current_status)}\n"
+ f" {url}"
+ )
+
+
+def _format_pr_head_event(pr: dict[str, Any], previous_head: str, current_head: str) -> str:
+ pr_number = pr.get("number")
+ url = pr.get("html_url") or ""
+ return (
+ f"- pr_head #{pr_number} {previous_head} -> {current_head}\n"
+ " Pull request head changed; confirm or trigger Codex review for the new exact head.\n"
+ f" {url}"
+ )
+
+
+def _format_review_thread_event(
+ pr: dict[str, Any],
+ thread_id: str,
+ previous_resolved: bool | None,
+ current_resolved: bool | None,
+) -> str:
+ url = pr.get("html_url") or ""
+
+ def _label(value: bool | None) -> str:
+ if value is None:
+ return "absent"
+ return "resolved" if value else "unresolved"
+
+ previous = _label(previous_resolved)
+ current = _label(current_resolved)
+ return (
+ f"- review_thread {thread_id} {previous} -> {current}\n"
+ " Review thread state changed; re-evaluate unresolved threads across the entire PR.\n"
+ f" {url}"
+ )
+
+
+def _format_pull_request(pr: dict[str, Any]) -> str:
+ pr_number = pr.get("number")
+ author = ((pr.get("user") or {}).get("login")) or "unknown"
+ state = str(pr.get("state") or "open").lower()
+ title = squash(pr.get("title") or "")
+ url = pr.get("html_url") or ""
+ return f"- pull_request #{pr_number} by {author} ({state})\n {title}\n {url}"
+
+
+def _fetch_review_threads(
+ repo: str,
+ pr_number: int,
+ token: str | None,
+) -> tuple[list[dict[str, Any]], int]:
+ if token is None:
+ return [], 0
+ try:
+ owner, repo_name = repo.split("/", 1)
+ except ValueError as err:
+ raise RuntimeError(f"Invalid repository name: {repo}") from err
+
+ threads: list[dict[str, Any]] = []
+ end_cursor: str | None = None
+ request_count = 0
+ while True:
+ data = github_graphql(
+ REVIEW_THREADS_QUERY,
+ {
+ "owner": owner,
+ "repo": repo_name,
+ "number": pr_number,
+ "endCursor": end_cursor,
+ },
+ token,
+ )
+ request_count += 1
+ repository = data.get("repository")
+ pull_request = repository.get("pullRequest") if isinstance(repository, dict) else None
+ connection = pull_request.get("reviewThreads") if isinstance(pull_request, dict) else None
+ if not isinstance(connection, dict):
+ raise GitHubProtocolError("GitHub GraphQL response has no reviewThreads connection")
+ nodes = connection.get("nodes")
+ if not isinstance(nodes, list):
+ raise GitHubProtocolError("GitHub GraphQL reviewThreads response has no nodes list")
+ threads.extend(node for node in nodes if isinstance(node, dict))
+ page_info = connection.get("pageInfo")
+ if not isinstance(page_info, dict) or page_info.get("hasNextPage") is not True:
+ break
+ next_cursor = page_info.get("endCursor")
+ if not isinstance(next_cursor, str) or not next_cursor:
+ raise GitHubProtocolError("GitHub GraphQL reviewThreads page has no endCursor")
+ end_cursor = next_cursor
+ return threads, request_count
+
+
+def _fetch_state(
+ repo: str,
+ pr_number: int,
+ token: str | None,
+ *,
+ cache: ResponseCache | None = None,
+) -> tuple[dict[str, Any], int]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ base_url = f"https://api.github.com/repos/{encoded_repo}"
+ pull_request = github_get(f"{base_url}/pulls/{pr_number}", token, cache=cache)
+ # The reviews endpoint ignores sort/direction (verified against api.github.com:
+ # direction=desc returns the same ascending ids), so there is no way to page it
+ # newest-first and no `since` support either. An unchanged review list stays
+ # cheap by revalidating to 304 rather than by fetching less.
+ reviews, review_requests = list_paginated_with_count(
+ f"{base_url}/pulls/{pr_number}/reviews",
+ token,
+ cache=cache,
+ )
+ # Snapshot equality is the wake gate, so every mutable collection must be a
+ # complete current view. A `since` slice cannot prove that an older item was
+ # removed and would turn the normalized snapshot into an append-only cache.
+ review_comments, review_comment_requests = list_paginated_with_count(
+ f"{base_url}/pulls/{pr_number}/comments",
+ token,
+ cache=cache,
+ )
+ issue_comments, issue_comment_requests = list_paginated_with_count(
+ f"{base_url}/issues/{pr_number}/comments",
+ token,
+ cache=cache,
+ )
+ # Only the Codex pass reaction is ever reported, and this endpoint filters by
+ # content server-side, so every other reaction on the PR body stays home.
+ reactions, reaction_requests = list_paginated_with_count(
+ f"{base_url}/issues/{pr_number}/reactions"
+ f"?content={urllib.parse.quote(CODEX_REVIEW_PASS_REACTION_CONTENT)}",
+ token,
+ cache=cache,
+ )
+ review_threads, review_thread_requests = _fetch_review_threads(repo, pr_number, token)
+ return (
+ {
+ "pull_request": pull_request,
+ "reviews": reviews,
+ "review_comments": review_comments,
+ "issue_comments": issue_comments,
+ "reactions": reactions,
+ "review_threads": review_threads,
+ },
+ (
+ 1
+ + review_requests
+ + review_comment_requests
+ + issue_comment_requests
+ + reaction_requests
+ + review_thread_requests
+ ),
+ )
+
+
+def _fetch_new_pr_state(
+ repo: str,
+ token: str | None,
+ *,
+ stop_after_id: int | None = None,
+ max_pages: int | None = None,
+ cache: ResponseCache | None = None,
+) -> tuple[dict[str, list[dict[str, Any]]], int]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ pull_requests, request_count = list_paginated_with_count(
+ f"https://api.github.com/repos/{encoded_repo}/pulls?state=all&sort=created&direction=desc",
+ token,
+ stop_after_id=stop_after_id,
+ max_pages=max_pages,
+ cache=cache,
+ )
+ return {"pull_requests": pull_requests}, request_count
+
+
+def _validate_target(
+ repo: str,
+ pr_number: int | None,
+ token: str | None,
+ *,
+ cache: ResponseCache | None = None,
+) -> int:
+ """Validate the remote target before a managed run claims local state."""
+
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ url = f"https://api.github.com/repos/{encoded_repo}"
+ if pr_number is not None:
+ url = f"{url}/pulls/{pr_number}"
+ payload = github_get(url, token, cache=cache)
+ if not isinstance(payload, dict):
+ raise GitHubProtocolError(f"Expected a GitHub target object from {url}")
+ return 1
+
+
+def _render_activity(
+ *,
+ repo: str,
+ pr_number: int,
+ state: dict[str, Any],
+ review_cursor: int,
+ review_comment_cursor: int,
+ issue_comment_cursor: int,
+ reaction_cursor: int,
+ pr_status: str,
+ head_sha: str,
+ snapshot: dict[str, Any],
+ event_limit: int,
+ viewer_login: str | None = None,
+ ignore_self_comments: bool = True,
+ actionable_only: bool = False,
+ ignored_authors: set[str] | None = None,
+ ignore_patterns: list[re.Pattern[str]] | None = None,
+ review_fingerprints: dict[str, str] | None = None,
+ review_comment_fingerprints: dict[str, str] | None = None,
+ issue_comment_fingerprints: dict[str, str] | None = None,
+ review_thread_states: dict[str, bool] | None = None,
+ review_threads_available: bool = True,
+) -> tuple[str | None, int, int, int, int, str, str, dict[str, Any]]:
+ ignored_authors = ignored_authors or set()
+ ignore_patterns = ignore_patterns or []
+ current_snapshot = _normalized_pr_snapshot(
+ state,
+ viewer_login=viewer_login,
+ ignore_self_comments=ignore_self_comments,
+ actionable_only=actionable_only,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ committed_snapshot=snapshot,
+ review_threads_available=review_threads_available,
+ )
+ current_pr_status = _current_pr_status(state.get("pull_request"))
+ current_head_sha = _current_pr_head_sha(state.get("pull_request"))
+ review_threads = state.get("review_threads")
+ if review_threads_available:
+ current_review_thread_states = _review_thread_state_map(
+ review_threads if isinstance(review_threads, list) else []
+ )
+ else:
+ current_review_thread_states = dict(review_thread_states or {})
+ review_thread_changes = _review_thread_state_changes(
+ current_review_thread_states,
+ review_thread_states or {},
+ )
+ new_reviews = _filter_review_changes(state["reviews"], review_cursor, review_fingerprints or {})
+ new_review_comments = _filter_comment_changes(
+ state["review_comments"],
+ review_comment_cursor,
+ review_comment_fingerprints or {},
+ )
+ new_issue_comments = _filter_comment_changes(
+ state["issue_comments"],
+ issue_comment_cursor,
+ issue_comment_fingerprints or {},
+ )
+
+ def _visible(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return _visible_activity_items(
+ items,
+ viewer_login=viewer_login,
+ ignore_self_comments=ignore_self_comments,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ )
+
+ visible_reviews = _visible(new_reviews)
+ if actionable_only:
+ visible_reviews = [review for review in visible_reviews if _is_actionable_review(review)]
+ visible_review_comments = _visible(new_review_comments)
+ visible_issue_comments = _visible(new_issue_comments)
+ new_reactions = [
+ reaction
+ for reaction in filter_new(state["reactions"], reaction_cursor)
+ if _is_codex_pass_reaction(reaction)
+ ]
+ has_pr_status_event = current_pr_status != pr_status
+ has_head_event = current_head_sha != head_sha
+
+ next_review_cursor = max(review_cursor, max_id(state["reviews"]))
+ next_review_comment_cursor = max(review_comment_cursor, max_id(state["review_comments"]))
+ next_issue_comment_cursor = max(issue_comment_cursor, max_id(state["issue_comments"]))
+ next_reaction_cursor = max(reaction_cursor, max_id(state["reactions"]))
+ next_pr_status = current_pr_status
+ next_head_sha = current_head_sha
+
+ # This is the only wake decision. Per-field comparisons below are descriptors:
+ # they explain a changed canonical snapshot but cannot suppress one or create a
+ # wake on their own.
+ if current_snapshot == snapshot:
+ return (
+ None,
+ next_review_cursor,
+ next_review_comment_cursor,
+ next_issue_comment_cursor,
+ next_reaction_cursor,
+ next_pr_status,
+ next_head_sha,
+ current_snapshot,
+ )
+
+ render_pr_status_event = has_pr_status_event and (
+ not actionable_only or current_pr_status in ACTIONABLE_PR_STATUSES
+ )
+
+ required_events: list[str] = []
+ if has_head_event and isinstance(state.get("pull_request"), dict):
+ required_events.append(_format_pr_head_event(state["pull_request"], head_sha, current_head_sha))
+ if render_pr_status_event and isinstance(state.get("pull_request"), dict):
+ required_events.append(_format_pr_status_event(state["pull_request"], pr_status, current_pr_status))
+ # A Codex +1 is durable pass evidence, not just another activity line. It must
+ # survive a small --event-limit even when a large review batch lands with it.
+ required_events.extend(_format_reaction(reaction) for reaction in new_reactions)
+ if isinstance(state.get("pull_request"), dict):
+ required_events.extend(
+ _format_review_thread_event(state["pull_request"], *change)
+ for change in review_thread_changes
+ )
+ optional_events = [_format_review(review) for review in visible_reviews]
+ optional_events.extend(_format_review_comment(comment) for comment in visible_review_comments)
+ optional_events.extend(_format_issue_comment(comment) for comment in visible_issue_comments)
+
+ if not (required_events or optional_events):
+ required_events.append(
+ "- pr_snapshot changed\n"
+ " Gate-relevant PR state changed; re-evaluate the exact head, review verdict, "
+ "and all unresolved threads."
+ )
+
+ lines = [f"GitHub PR activity detected for {repo}#{pr_number}"]
+
+ visible_limit = max(event_limit, len(required_events), 1)
+ visible_optional = optional_events[: max(0, visible_limit - len(required_events))]
+ selected_events = [*required_events, *visible_optional]
+ for entry in selected_events:
+ lines.append(entry)
+
+ total_events = len(required_events) + len(optional_events)
+ if total_events > len(selected_events):
+ lines.append(f"- {total_events - len(selected_events)} additional event(s) omitted")
+
+ return (
+ "\n".join(lines),
+ next_review_cursor,
+ next_review_comment_cursor,
+ next_issue_comment_cursor,
+ next_reaction_cursor,
+ next_pr_status,
+ next_head_sha,
+ current_snapshot,
+ )
+
+
+def _render_new_pull_requests(
+ *,
+ repo: str,
+ state: dict[str, list[dict[str, Any]]],
+ pr_cursor: int,
+ event_limit: int,
+) -> tuple[str | None, int]:
+ new_pull_requests = filter_new(state["pull_requests"], pr_cursor)
+ if not new_pull_requests:
+ return None, pr_cursor
+
+ next_pr_cursor = max(pr_cursor, max_id(new_pull_requests))
+ lines = [f"GitHub new pull request activity detected for {repo}"]
+ rendered_events = [_format_pull_request(pr) for pr in new_pull_requests]
+
+ visible_limit = max(event_limit, 1)
+ for entry in rendered_events[:visible_limit]:
+ lines.append(entry)
+
+ total_events = len(rendered_events)
+ if total_events > visible_limit:
+ lines.append(f"- {total_events - visible_limit} additional event(s) omitted")
+
+ return "\n".join(lines), next_pr_cursor
+
+
+def _write_cursor_output(
+ path: str | None,
+ *,
+ review_cursor: int,
+ review_comment_cursor: int,
+ issue_comment_cursor: int,
+ reaction_cursor: int,
+ pr_status: str,
+ head_sha: str,
+) -> None:
+ if not path:
+ return
+
+ payload = {
+ "review_cursor": review_cursor,
+ "review_comment_cursor": review_comment_cursor,
+ "issue_comment_cursor": issue_comment_cursor,
+ "reaction_cursor": reaction_cursor,
+ "pr_status": pr_status,
+ "head_sha": head_sha,
+ }
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle)
+
+
+def _review_fingerprint(review: dict[str, Any]) -> str:
+ """Capture fields GitHub can update without allocating a new review id."""
+
+ return "|".join(
+ str(review.get(field) or "")
+ for field in ("state", "updated_at", "submitted_at", "body")
+ )
+
+
+def _review_fingerprint_map(reviews: list[dict[str, Any]]) -> dict[str, str]:
+ return {
+ str(review["id"]): _review_fingerprint(review)
+ for review in reviews
+ if isinstance(review.get("id"), int) and not isinstance(review.get("id"), bool)
+ }
+
+
+def _comment_fingerprint(comment: dict[str, Any]) -> str:
+ """Capture fields GitHub can edit without changing a comment id."""
+
+ return "|".join(str(comment.get(field) or "") for field in ("updated_at", "body"))
+
+
+def _comment_fingerprint_map(comments: list[dict[str, Any]]) -> dict[str, str]:
+ return {
+ str(comment["id"]): _comment_fingerprint(comment)
+ for comment in comments
+ if isinstance(comment.get("id"), int) and not isinstance(comment.get("id"), bool)
+ }
+
+
+def _review_thread_state_map(threads: list[dict[str, Any]]) -> dict[str, bool]:
+ return {
+ str(thread["id"]): bool(thread["isResolved"])
+ for thread in threads
+ if isinstance(thread.get("id"), str) and isinstance(thread.get("isResolved"), bool)
+ }
+
+
+def _normalized_item_map(
+ items: list[dict[str, Any]],
+ *,
+ fields: tuple[str, ...],
+) -> dict[str, dict[str, Any]]:
+ normalized: dict[str, dict[str, Any]] = {}
+ for item in items:
+ item_id = item.get("id")
+ if not isinstance(item_id, (int, str)) or isinstance(item_id, bool):
+ continue
+ author = ((item.get("user") or {}).get("login")) or ""
+ normalized[str(item_id)] = {
+ "author": str(author),
+ **{field: item.get(field) for field in fields},
+ }
+ return normalized
+
+
+def _normalized_pr_snapshot(
+ state: dict[str, Any],
+ *,
+ viewer_login: str | None = None,
+ ignore_self_comments: bool = True,
+ actionable_only: bool = False,
+ ignored_authors: set[str] | None = None,
+ ignore_patterns: list[re.Pattern[str]] | None = None,
+ committed_snapshot: dict[str, Any] | None = None,
+ review_threads_available: bool = True,
+) -> dict[str, Any]:
+ """Return the complete gate-relevant PR snapshot without volatile fields."""
+
+ ignored_authors = ignored_authors or set()
+ ignore_patterns = ignore_patterns or []
+
+ def _visible(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return _visible_activity_items(
+ items,
+ viewer_login=viewer_login,
+ ignore_self_comments=ignore_self_comments,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ )
+
+ reviews = _visible(state["reviews"])
+ if actionable_only:
+ reviews = [review for review in reviews if _is_actionable_review(review)]
+ review_comments = _visible(state["review_comments"])
+ issue_comments = _visible(state["issue_comments"])
+ reactions = [reaction for reaction in state["reactions"] if _is_codex_pass_reaction(reaction)]
+ normalized_reactions = _normalized_item_map(reactions, fields=("content",))
+ for reaction in normalized_reactions.values():
+ reaction["author"] = "chatgpt-codex-connector"
+
+ if review_threads_available:
+ review_threads = _review_thread_state_map(state["review_threads"])
+ else:
+ saved_threads = (committed_snapshot or {}).get("review_threads")
+ review_threads = saved_threads if isinstance(saved_threads, dict) else {}
+ pr_status = _current_pr_status(state.get("pull_request"))
+ if actionable_only and pr_status not in ACTIONABLE_PR_STATUSES:
+ pr_status = "open"
+
+ return {
+ "pull_request": {
+ "status": pr_status,
+ "head_sha": _current_pr_head_sha(state.get("pull_request")),
+ },
+ "reviews": _normalized_item_map(
+ reviews,
+ fields=("state", "body", "commit_id"),
+ ),
+ "review_comments": _normalized_item_map(
+ review_comments,
+ fields=("body", "path"),
+ ),
+ "issue_comments": _normalized_item_map(issue_comments, fields=("body",)),
+ "reactions": normalized_reactions,
+ "review_threads": review_threads,
+ }
+
+
+def _review_thread_state_changes(
+ current: dict[str, bool],
+ baseline: dict[str, bool],
+) -> list[tuple[str, bool | None, bool | None]]:
+ return [
+ (thread_id, baseline.get(thread_id), current.get(thread_id))
+ for thread_id in sorted(current.keys() | baseline.keys())
+ if baseline.get(thread_id) != current.get(thread_id)
+ ]
+
+
+def _filter_review_changes(
+ reviews: list[dict[str, Any]],
+ cursor: int,
+ fingerprints: dict[str, str],
+) -> list[dict[str, Any]]:
+ """Return new reviews and updates to reviews already covered by the id cursor."""
+
+ changed: list[dict[str, Any]] = []
+ for review in reviews:
+ review_id = review.get("id")
+ if not isinstance(review_id, int) or isinstance(review_id, bool):
+ continue
+ saved_fingerprint = fingerprints.get(str(review_id))
+ if review_id > cursor or (saved_fingerprint is not None and saved_fingerprint != _review_fingerprint(review)):
+ changed.append(review)
+ return changed
+
+
+def _filter_comment_changes(
+ comments: list[dict[str, Any]],
+ cursor: int,
+ fingerprints: dict[str, str],
+) -> list[dict[str, Any]]:
+ """Return new comments and edits to comments already covered by the id cursor."""
+
+ changed: list[dict[str, Any]] = []
+ for comment in comments:
+ comment_id = comment.get("id")
+ if not isinstance(comment_id, int) or isinstance(comment_id, bool):
+ continue
+ saved_fingerprint = fingerprints.get(str(comment_id))
+ if comment_id > cursor or (
+ saved_fingerprint is not None and saved_fingerprint != _comment_fingerprint(comment)
+ ):
+ changed.append(comment)
+ return changed
+
+
+def _write_new_pr_cursor_output(path: str | None, *, pr_cursor: int) -> None:
+ if not path:
+ return
+
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump({"pr_cursor": pr_cursor}, handle)
+
+
+def _watch_identity(args: argparse.Namespace) -> str:
+ """A stable digest of the options that decide what this watch reports.
+
+ Ownership by repo and PR alone cannot tell two watches on the same PR apart --
+ one ``--actionable-only``, one meant to report everything -- and a shared state
+ file then lets whichever polls first advance the cursors past an event the other
+ would have reported. That event is gone for good rather than merely late, so the
+ filters belong in the identity.
+
+ Only the report-shaping options are in here. ``--interval``, ``--timeout`` and
+ ``--settle`` change pacing, not which activity counts, and two watches differing
+ only in those can share cursors without losing anything.
+ """
+
+ material = json.dumps(
+ {
+ "mode": "new-prs" if args.new_prs else "pr",
+ "actionable_only": bool(args.actionable_only),
+ "include_self_comments": bool(args.include_self_comments),
+ "ignore_authors": sorted(_normalize_authors(args.ignore_author)),
+ "ignore_comment_patterns": sorted(set(args.ignore_comment_pattern or [])),
+ },
+ sort_keys=True,
+ )
+ return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{material}".encode()).hexdigest()[:16]
+
+
+def _managed_watch_id() -> str | None:
+ """The id of the ``vibe watch`` this waiter is a cycle of, when there is one.
+
+ Two separately managed watches on the same PR with the same filters are
+ indistinguishable by configuration alone, and sharing a state file means
+ whichever polls first advances the cursors past events the other never
+ reported. The supervisor hands the id down, so the owner can be exact. A manual
+ run has none, which is not a conflict -- only proof of one is.
+ """
+
+ value = os.environ.get(WATCH_ID_ENV, "").strip()
+ return value or None
+
+
+def _owner_conflict(
+ owner: tuple[Any, Any, Any, Any] | None,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None,
+ watch_id: str | None,
+ allow_cursorless_watch_identity_change: bool = False,
+) -> str | None:
+ """Why ``owner`` is somebody else's claim on the path, or ``None`` when it is ours.
+
+ A state file written before identities existed carries no owner, and an absent
+ owner is compatible with every run -- that is the file a managed watch adopts.
+
+ A file that DOES name an owner is the opposite: the burden is on this run to
+ prove it is that owner, and a manual run cannot. Letting it through would be
+ silent data loss rather than a mere sharing of the path -- the manual run polls,
+ reports to a terminal nobody is reading, and ``_write_state_file`` stamps
+ ``owner: null`` over the managed claim while advancing the cursors past that
+ activity. The managed watch then adopts its own file back as ownerless and
+ resumes from cursors covering events its Agent follow-up never received.
+ """
+
+ if owner is None:
+ return None
+ saved_repo, saved_pr, saved_watch, saved_owner = owner
+ if saved_repo != repo or saved_pr != pr_number:
+ return f"belongs to {saved_repo}#{saved_pr}, not {repo}#{pr_number}"
+ if saved_watch is not None and watch_identity is not None and saved_watch != watch_identity:
+ if allow_cursorless_watch_identity_change and saved_owner == watch_id:
+ return None
+ return (
+ f"belongs to another watch on {saved_repo}#{saved_pr} with different "
+ "reporting filters"
+ )
+ if saved_owner is not None and saved_owner != watch_id:
+ if watch_id is None:
+ return (
+ f"belongs to watch {saved_owner}; this run is not managed by that "
+ "watch. Use a different --state-file."
+ )
+ return f"belongs to watch {saved_owner}, not watch {watch_id}"
+ return None
+
+
+def _cursorless_state_file(path: Path) -> bool:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return False
+ if not isinstance(payload, dict):
+ return False
+ return not any(
+ key in payload
+ for key in (
+ *STATE_CURSOR_KEYS,
+ "pr_cursor",
+ "pr_status",
+ "head_sha",
+ *PR_FINGERPRINT_KEYS,
+ REVIEW_THREAD_STATES_KEY,
+ PR_SNAPSHOT_KEY,
+ STAGED_KEY,
+ )
+ )
+
+
+def _load_state_file(
+ path: str | None,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None = None,
+ watch_id: str | None = None,
+) -> dict[str, Any]:
+ """Read cursors left behind by an earlier run of this same waiter.
+
+ A `--forever` watch runs the waiter once per cycle, so without this the next
+ cycle re-baselines from whatever the PR looks like at startup and silently
+ swallows everything that arrived between the previous cycle's exit and that
+ snapshot.
+ """
+
+ if not path:
+ return {}
+
+ try:
+ raw = Path(path).read_text(encoding="utf-8")
+ except FileNotFoundError:
+ return {}
+ except OSError as err:
+ raise StateFileUnusableError(f"State file {path} cannot be read: {err}") from err
+
+ # An empty file is the claim below caught between its exclusive create and its
+ # first write, so no cursor was ever recorded in it and there is none to lose.
+ # Anything else that will not parse HAD cursors, and how far they reached is now
+ # unknown -- which is why this is terminal rather than a fresh baseline.
+ if not raw.strip():
+ return {}
+ try:
+ payload = json.loads(raw)
+ except ValueError as err:
+ raise StateFileUnusableError(f"State file {path} is corrupt: {err}") from err
+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:
+ raise StateFileUnusableError(f"State file {path} is not in a recognised format")
+ # Resuming from somebody else's cursors would skip the history they cover, and
+ # carrying on would overwrite them on the first cursor advance -- so this is
+ # terminal rather than a fresh baseline. A file left behind by another watch has
+ # to be removed, or that watch given its own path, deliberately.
+ conflict = _owner_conflict(
+ (payload.get("repo"), payload.get("pr"), payload.get("watch"), payload.get("owner")),
+ repo=repo,
+ pr_number=pr_number,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ allow_cursorless_watch_identity_change=_cursorless_state_file(Path(path)) if path else False,
+ )
+ if conflict is not None:
+ raise StateFileOwnershipError(f"State file {path} {conflict}")
+ return payload
+
+
+def _state_file_scratch(target: Path) -> tuple[int, str]:
+ """An exclusively created scratch file beside ``target``.
+
+ ``mkstemp`` rather than a derived name such as ``<state-file>.tmp``: this runs
+ in a directory of persisted user state, and a deterministic path both
+ truncates whatever already occupies it and lets two waiters sharing a
+ directory scribble over each other's half-written file.
+ """
+
+ return tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp")
+
+
+def _state_file_owner(target: Path) -> tuple[Any, Any, Any, Any] | None:
+ """Which watch the file at ``target`` currently claims, or ``None`` if it says nothing.
+
+ Missing and unusable files both answer ``None``, matching ``_load_state_file``:
+ there is no owner to respect, so the caller may take the path.
+ """
+
+ try:
+ with target.open(encoding="utf-8") as handle:
+ payload = json.load(handle)
+ except (OSError, ValueError):
+ return None
+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:
+ return None
+ return payload.get("repo"), payload.get("pr"), payload.get("watch"), payload.get("owner")
+
+
+def _claim_state_file(
+ target: Path,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None = None,
+ watch_id: str | None = None,
+) -> bool:
+ """Take a currently missing state file for this PR, atomically.
+
+ ``O_EXCL`` is the whole point: two waiters starting together both see no file,
+ and exactly one of them creates it. The loser reads the winner's claim and stops
+ on the ownership check instead of quietly sharing the path and overwriting the
+ winner's cursors on its next advance -- a silent gap in the review loop.
+
+ Returns False when somebody else got there first; the caller then treats the path
+ as pre-existing and lets ``_load_state_file`` judge the owner.
+ """
+
+ try:
+ handle = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except FileExistsError:
+ return False
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err
+
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(
+ {
+ "version": STATE_FILE_VERSION,
+ "repo": repo,
+ "pr": pr_number,
+ "watch": watch_identity,
+ "owner": watch_id,
+ },
+ stream,
+ )
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err
+ return True
+
+
+@contextmanager
+def _state_file_lock(target: Path) -> Iterator[None]:
+ """Serialize the ownership decision on ``target`` across processes.
+
+ Deciding who owns a state file is read-then-write, and two managed watches that
+ interleave those halves both conclude the path is theirs. A sidecar lock file
+ makes the decision one step. It is a separate file precisely because the state
+ file itself is replaced rather than rewritten: a lock held on an inode that has
+ since been renamed away guards nothing.
+
+ Best effort by design. A filesystem without working locks, or a directory that
+ refuses the lock file, must not stop the watch -- the write probe and the
+ ownership re-check on every replace still stand.
+ """
+
+ if fcntl is None:
+ yield
+ return
+
+ handle = None
+ try:
+ handle = os.open(target.with_name(f"{target.name}.lock"), os.O_RDWR | os.O_CREAT, 0o600)
+ fcntl.flock(handle, fcntl.LOCK_EX)
+ except OSError:
+ if handle is not None:
+ os.close(handle)
+ yield
+ return
+
+ try:
+ yield
+ finally:
+ try:
+ fcntl.flock(handle, fcntl.LOCK_UN)
+ finally:
+ os.close(handle)
+
+
+def _adopt_state_file(
+ target: Path,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_id: str,
+ watch_identity: str | None,
+) -> bool:
+ """Stamp this managed watch onto an ownerless state file, keeping its cursors.
+
+ A file written before owners existed, or by a manual run, names no owner -- and an
+ absent owner is compatible with every managed watch. Two of them would therefore
+ both adopt the same path, poll, and overwrite each other's cursors, skipping
+ activity for good. Claiming the name here, under the lock and before any polling,
+ turns that into a conflict the loser sees while it can still be told about it.
+
+ An EMPTY file is the same hazard wearing different clothes: it is a claim caught
+ between its exclusive create and its first write, so ``_load_state_file`` reads it
+ as a fresh baseline with no cursors to lose. Left as it is, it names no owner
+ either, and two managed watches pointed at that path both clear this preflight and
+ poll -- so finish the claim the interrupted run started rather than falling through
+ to a byte-for-byte rewrite that preserves the emptiness and the ambiguity with it.
+
+ Returns False when the file says nothing usable, leaving it to the caller's probe.
+ """
+
+ try:
+ raw = target.read_text(encoding="utf-8")
+ except OSError:
+ return False
+
+ if not raw.strip():
+ payload: dict[str, Any] = {
+ "version": STATE_FILE_VERSION,
+ "repo": repo,
+ "pr": pr_number,
+ }
+ else:
+ try:
+ payload = json.loads(raw)
+ except ValueError:
+ return False
+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:
+ return False
+
+ payload["owner"] = watch_id
+ if payload.get("watch") is None and watch_identity is not None:
+ payload["watch"] = watch_identity
+
+ scratch = None
+ try:
+ handle, scratch = _state_file_scratch(target)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(payload, stream)
+ os.replace(scratch, target)
+ scratch = None
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err
+ finally:
+ if scratch is not None:
+ try:
+ os.unlink(scratch)
+ except OSError:
+ pass
+ return True
+
+
+def _verify_state_file_writable(
+ path: str | None,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None = None,
+ watch_id: str | None = None,
+) -> None:
+ """Claim the requested state file, and fail before the first poll if it is unusable.
+
+ A forever watch only discovers a read-only parent directory when the cycle it
+ spent minutes on tries to save its cursors, and by then the activity that
+ cycle observed is already unrecoverable.
+
+ A missing state file is created here holding nothing but this PR's ownership, so
+ the path is owned before any polling starts rather than after the first cursor
+ advance. A managed first cycle must then pass ``--catch-up`` or seed a complete
+ cursor set before polling; it must never silently baseline from the current PR.
+
+ An existing file that names no owner is adopted here too, cursors intact, because
+ an absent owner is compatible with every managed watch and would otherwise let two
+ of them share the path. Both steps happen under a lock on the path, so the
+ read-then-write that decides ownership cannot interleave with another waiter's.
+
+ A file that belongs to somebody else is left untouched and unprobed, and this
+ returns without writing anything -- see the conflict branch below.
+
+ For a file that already exists the probe is the whole write, ``os.replace``
+ included, because that is the step persistence actually depends on and the step a
+ sibling-creation check cannot speak for: a target that is a directory, or one in a
+ sticky-bit directory owned by somebody else, accepts new siblings all day and
+ still refuses the rename. It is rewritten with the bytes it already holds, so a
+ watch resuming from good cursors keeps them either way.
+ """
+
+ if not path:
+ return
+
+ target = Path(path)
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err
+
+ with _state_file_lock(target):
+ try:
+ exists = target.exists()
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err
+
+ if not exists and _claim_state_file(
+ target,
+ repo=repo,
+ pr_number=pr_number,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ ):
+ # Creating the real file in the real directory is the write probe, and the
+ # rename in later cycles lands on a file this process owns.
+ return
+
+ # Somebody else's file is not ours to touch AT ALL -- not to adopt, and not to
+ # probe. The probe below is an ``os.replace`` of bytes read a moment earlier,
+ # and the owner's own cursor writes do NOT take this lock, so probing a foreign
+ # path can land stale bytes over a cursor it has just advanced or a ``pending``
+ # handoff it is mid-way through, making the owning watch replay or lose
+ # activity. Returning here costs nothing: ``_load_state_file`` refuses the same
+ # file moments later, with the same conflict, before a single poll.
+ conflict = _owner_conflict(
+ _state_file_owner(target),
+ repo=repo,
+ pr_number=pr_number,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ allow_cursorless_watch_identity_change=watch_id is not None and _cursorless_state_file(target),
+ )
+ if conflict is not None:
+ return
+
+ # An ownerless file is adopted, not merely accepted: taking the name is what
+ # makes a second managed watch on the same path fail instead of sharing it.
+ if watch_id is not None and _adopt_state_file(
+ target,
+ repo=repo,
+ pr_number=pr_number,
+ watch_id=watch_id,
+ watch_identity=watch_identity,
+ ):
+ # Rewriting the real file is the write probe, as the claim is above.
+ return
+
+ try:
+ existing = target.read_bytes()
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err
+
+ scratch = None
+ try:
+ handle, scratch = _state_file_scratch(target)
+ with os.fdopen(handle, "wb") as stream:
+ stream.write(existing)
+ os.replace(scratch, target)
+ scratch = None
+ except OSError as err:
+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err
+ finally:
+ if scratch is not None:
+ try:
+ os.unlink(scratch)
+ except OSError:
+ pass
+
+
+def _write_state_file(
+ path: str | None,
+ *,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None = None,
+ watch_id: str | None = None,
+ **fields: Any,
+) -> None:
+ if not path:
+ return
+
+ payload = {
+ "version": STATE_FILE_VERSION,
+ "repo": repo,
+ "pr": pr_number,
+ "watch": watch_identity,
+ "owner": watch_id,
+ **fields,
+ }
+ target = Path(path)
+ scratch = None
+ # Re-checked on every replace, not just at startup: the claim can lose a race with
+ # a waiter that created the file in the same instant, or a person can point another
+ # watch at the same path mid-run. Clobbering that watch's cursors would make it
+ # re-baseline and skip real activity, so hand the path back and stop instead.
+ conflict = _owner_conflict(
+ _state_file_owner(target),
+ repo=repo,
+ pr_number=pr_number,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ allow_cursorless_watch_identity_change=watch_id is not None and _cursorless_state_file(target),
+ )
+ if conflict is not None:
+ raise StateFileOwnershipError(f"State file {path} now {conflict}")
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ # Written aside and moved into place: a cycle killed mid-write must not
+ # leave a truncated file that the next cycle has to discard.
+ handle, scratch = _state_file_scratch(target)
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(payload, stream)
+ os.replace(scratch, target)
+ scratch = None
+ except OSError as err:
+ # Terminal, not a warning. The caller asked for cursors that survive the
+ # process; continuing without them lets the next cycle re-baseline from the
+ # current PR and silently drop everything that arrived in between, which is
+ # the exact loss ``--state-file`` exists to prevent.
+ raise StatePersistenceError(f"Could not write state file {path}: {err}") from err
+ finally:
+ # A failed write must not leave its scratch file behind in the state dir.
+ if scratch is not None:
+ try:
+ os.unlink(scratch)
+ except OSError:
+ pass
+
+
+def _token_fingerprint(token: str | None) -> str | None:
+ """Which credentials a cached ``viewer_login`` was resolved under.
+
+ A one-way digest, never the token itself: the state file lives on disk next to
+ the cursors and has no business holding a credential. It exists so a resumed
+ cycle can tell "same account, reuse the saved login" from "the token now
+ belongs to someone else", which otherwise filtered the wrong author's
+ comments out of the review loop.
+ """
+
+ if not token:
+ return None
+ return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{token}".encode()).hexdigest()[:16]
+
+
+def _saved_int(saved: dict[str, Any], key: str) -> int | None:
+ value = saved.get(key)
+ return int(value) if isinstance(value, int) and not isinstance(value, bool) else None
+
+
+def _saved_str(saved: dict[str, Any], key: str) -> str | None:
+ value = saved.get(key)
+ return value if isinstance(value, str) and value else None
+
+
+def _saved_fingerprints(saved: dict[str, Any], key: str) -> dict[str, str]:
+ value = saved.get(key)
+ if not isinstance(value, dict):
+ return {}
+ return {str(item_key): item for item_key, item in value.items() if isinstance(item, str)}
+
+
+def _saved_review_thread_states(saved: dict[str, Any]) -> dict[str, bool]:
+ value = saved.get(REVIEW_THREAD_STATES_KEY)
+ if not isinstance(value, dict):
+ return {}
+ return {
+ str(item_key): item
+ for item_key, item in value.items()
+ if isinstance(item, bool)
+ }
+
+
+def _saved_snapshot(saved: dict[str, Any]) -> dict[str, Any]:
+ value = saved.get(PR_SNAPSHOT_KEY)
+ return value if isinstance(value, dict) else {}
+
+
+def _missing_pr_baselines(saved: dict[str, Any]) -> list[str]:
+ missing = []
+ if _saved_str(saved, "head_sha") is None:
+ missing.append("head_sha")
+ for key in PR_FINGERPRINT_KEYS:
+ value = saved.get(key)
+ if not isinstance(value, dict) or any(not isinstance(item, str) for item in value.values()):
+ missing.append(key)
+ thread_states = saved.get(REVIEW_THREAD_STATES_KEY)
+ if not isinstance(thread_states, dict) or any(
+ not isinstance(item, bool) for item in thread_states.values()
+ ):
+ missing.append(REVIEW_THREAD_STATES_KEY)
+ if not isinstance(saved.get(PR_SNAPSHOT_KEY), dict):
+ missing.append(PR_SNAPSHOT_KEY)
+ return missing
+
+
+def _last_delivery() -> str | None:
+ """When the supervisor last queued a report from this watch, as it sees it.
+
+ ``None`` for a manual run, which has no supervisor -- and needs none, because
+ there printing the report IS delivering it and nothing is ever staged.
+ """
+
+ return os.environ.get(LAST_DELIVERY_ENV, "").strip() or None
+
+
+def _staged_replay_output(saved: dict[str, Any], delivery: str | None) -> str | None:
+ staged = saved.get(STAGED_KEY)
+ if not isinstance(staged, dict):
+ return None
+ if not isinstance(staged.get("cursors"), dict):
+ raise StateFileUnusableError("Pending waiter transaction has no usable cursor state")
+ output = staged.get("output")
+ if staged.get("delivered_after") == delivery and isinstance(output, str) and output:
+ return output
+ return None
+
+
+def _resolve_staged_state(
+ path: str | None,
+ saved: dict[str, Any],
+ *,
+ delivery: str | None,
+ repo: str,
+ pr_number: int | None,
+ watch_identity: str | None,
+ watch_id: str | None,
+) -> tuple[dict[str, Any], str | None]:
+ """Promote an acknowledged transaction or replay its persisted output.
+
+ Promoted when the supervisor's last-delivery stamp has moved since the report was
+ staged: the report was queued, so polling may start after it. When the stamp is
+ unchanged, return the stored rendered report without touching the pending block.
+ Persisting both halves makes replay independent of mutable GitHub objects.
+ """
+
+ staged = saved.get(STAGED_KEY)
+ if not isinstance(staged, dict):
+ return saved, None
+ cursors = staged.get("cursors")
+ if not isinstance(cursors, dict):
+ raise StateFileUnusableError("Pending waiter transaction has no usable cursor state")
+ replay_output = _staged_replay_output(saved, delivery)
+ delivered = staged.get("delivered_after") != delivery
+
+ if replay_output is not None:
+ print("An earlier report was never delivered; replaying its persisted output.", file=sys.stderr)
+ return saved, replay_output
+
+ resolved = {key: value for key, value in saved.items() if key != STAGED_KEY}
+ if delivered:
+ resolved.update(cursors)
+ print(
+ (
+ "An earlier report was delivered; advancing past it."
+ if delivered
+ else "Legacy pending state has no report payload; reconstructing from committed cursors."
+ ),
+ file=sys.stderr,
+ )
+ fields = {
+ key: value
+ for key, value in resolved.items()
+ if key not in {"version", "repo", "pr", "watch", "owner"}
+ }
+ _write_state_file(
+ path,
+ repo=repo,
+ pr_number=pr_number,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ **fields,
+ )
+ return resolved, None
+
+
+def _deliver(output: str) -> None:
+ """Hand the report to the supervisor, and make sure it has left this process.
+
+ The cursors covering a reported event are committed only after this returns, so
+ the report must be out of our own buffers first.
+ """
+
+ print(output)
+ sys.stdout.flush()
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ """The waiter's CLI surface, separate from main() so it can be inspected directly."""
+
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", required=True, help="GitHub repo in owner/name form")
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--pr", type=int, help="Pull request number")
+ mode.add_argument("--new-prs", action="store_true", help="Watch for new pull requests in the repository")
+ parser.add_argument("--interval", type=float, default=45.0, help="Polling interval in seconds")
+ parser.add_argument(
+ "--timeout",
+ type=float,
+ default=21600.0,
+ help="Overall timeout in seconds; default 21600 (6 hours), 0 means forever",
+ )
+ parser.add_argument("--since-review-id", type=int, default=None, help="Existing review cursor")
+ parser.add_argument("--since-review-comment-id", type=int, default=None, help="Existing review comment cursor")
+ parser.add_argument("--since-issue-comment-id", type=int, default=None, help="Existing PR conversation comment cursor")
+ parser.add_argument("--since-reaction-id", type=int, default=None, help="Existing PR-body reaction cursor")
+ parser.add_argument("--since-pr-status", help=argparse.SUPPRESS)
+ parser.add_argument("--since-pr-id", type=int, default=None, help="Existing repository pull request cursor")
+ parser.add_argument("--cursor-output", help=argparse.SUPPRESS)
+ parser.add_argument(
+ "--state-file",
+ help=(
+ "Path to a JSON file holding this watch's cursors between runs. Strongly recommended for "
+ "--forever watches: each cycle resumes where the previous one stopped instead of "
+ "re-baselining, so activity arriving between cycles is not lost and the next cycle can "
+ "compare a complete ETag-revalidated gate snapshot."
+ ),
+ )
+ parser.add_argument(
+ "--settle",
+ type=float,
+ default=0.0,
+ help=(
+ "Seconds to wait after the first new activity before reporting, re-polling until the set "
+ f"stops growing (at most {SETTLE_MAX_ROUNDS} extra polls). A batched review that straddles "
+ "a poll boundary then costs one Agent turn instead of one per fragment. 0 disables it."
+ ),
+ )
+ parser.add_argument("--event-limit", type=int, default=8, help="Maximum number of new events to include in stdout")
+ parser.add_argument(
+ "--include-self-comments",
+ action="store_true",
+ help="Include reviews and comments authored by the current authenticated GitHub user",
+ )
+ parser.add_argument(
+ "--actionable-only",
+ action="store_true",
+ help=(
+ "Only wake the Agent for review activity that needs a response: reviews carrying a "
+ "verdict or a body, inline review comments, the Codex pass reaction, and merged/closed "
+ "transitions. Drops bodyless COMMENTED review envelopes, bot trigger comments such as "
+ "'@codex review', and draft toggles."
+ ),
+ )
+ parser.add_argument(
+ "--ignore-author",
+ action="append",
+ help="GitHub login whose reviews and comments never trigger a follow-up; repeatable",
+ )
+ parser.add_argument(
+ "--ignore-comment-pattern",
+ action="append",
+ help="Case-insensitive regex; matching review/comment bodies never trigger a follow-up. Repeatable",
+ )
+ parser.add_argument(
+ "--catch-up",
+ action="store_true",
+ help="Treat current existing activity as pending when no explicit cursor is provided",
+ )
+ parser.add_argument(
+ "--allow-unauthenticated",
+ action="store_true",
+ help="Allow polling without GitHub auth; the interval will be clamped to a safer minimum",
+ )
+ return parser
+
+
+def main() -> int:
+ args = _build_parser().parse_args()
+
+ token = get_token()
+ cache = ResponseCache()
+ # Everything that can reject the arguments runs BEFORE any state is claimed. A
+ # bad --ignore-comment-pattern used to leave a claimed state file behind on its
+ # way to exit 2, and fixing the regex changes the watch identity, so the very
+ # next run was refused as another watch's until the file was deleted by hand.
+ ignored_authors = _normalize_authors(args.ignore_author)
+ try:
+ ignore_patterns = _compile_ignore_patterns(
+ args.ignore_comment_pattern,
+ actionable_only=args.actionable_only,
+ )
+ except re.error as err:
+ print(f"Invalid --ignore-comment-pattern: {err}", file=sys.stderr)
+ return 2
+ watch_identity = _watch_identity(args)
+ watch_id = _managed_watch_id()
+ delivery_stamp = _last_delivery()
+ # Only a managed run has a next cycle to promote staged cursors, and only it gets
+ # told whether the report was queued. A manual run is one process whose stdout is
+ # the delivery, so staging there would leave cursors nobody ever promotes.
+ two_phase = watch_id is not None
+ if two_phase and not args.state_file:
+ print(
+ "Managed PR watchers require an owner-specific --state-file; refusing to poll without durable cursors.",
+ file=sys.stderr,
+ )
+ return 2
+ # Read-only state may supply the cached viewer login, but no path is claimed
+ # until every authentication precondition below has passed.
+ saved = _load_state_file(
+ args.state_file,
+ repo=args.repo,
+ pr_number=args.pr,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ )
+ replay_output = _staged_replay_output(saved, delivery_stamp)
+ if replay_output is not None:
+ print(
+ "An earlier report was never delivered; replaying it before GitHub polling preflight.",
+ file=sys.stderr,
+ )
+ _deliver(replay_output)
+ return 0
+ if token is None and not args.allow_unauthenticated:
+ print(
+ (
+ "GitHub authentication is required for reliable polling. "
+ "Set GITHUB_TOKEN/GH_TOKEN, run 'gh auth login', or pass "
+ "--allow-unauthenticated for a throttled best-effort run."
+ ),
+ file=sys.stderr,
+ )
+ return 2
+ if args.pr is not None and token is None and not args.include_self_comments:
+ print(
+ "Unauthenticated PR watches require --include-self-comments because viewer identity cannot be resolved.",
+ file=sys.stderr,
+ )
+ return 2
+ token_fingerprint = _token_fingerprint(token)
+ base_interval = max(args.interval, 1.0)
+ start = time.monotonic()
+ viewer_login = None
+ if args.pr is not None and not args.include_self_comments:
+ # The stored login spares a /user request on every cycle of a forever watch,
+ # but only while the token still belongs to the account it was resolved for.
+ # A rotated or swapped credential would otherwise keep filtering out the old
+ # account's comments and let the new account's own comments wake the Agent.
+ if token_fingerprint is not None and _saved_str(saved, "token_fingerprint") == token_fingerprint:
+ viewer_login = _saved_str(saved, "viewer_login")
+ if viewer_login is None:
+ viewer_result = retry_initial_request(
+ lambda: resolve_authenticated_login(token),
+ description="GitHub viewer lookup",
+ )
+ if viewer_result.error is not None:
+ print(f"GitHub viewer lookup failed: {viewer_result.error}", file=sys.stderr)
+ return 1
+ viewer_login = viewer_result.value
+ if not viewer_login:
+ print(
+ "GitHub viewer identity could not be resolved; pass --include-self-comments explicitly to continue.",
+ file=sys.stderr,
+ )
+ return 1
+
+ target_result = retry_initial_request(
+ lambda: _validate_target(args.repo, args.pr, token, cache=cache),
+ description="GitHub target validation",
+ )
+ if target_result.error is not None:
+ print(f"GitHub target validation failed: {target_result.error}", file=sys.stderr)
+ return 1
+ if target_result.value is None:
+ print("GitHub target validation completed without a result", file=sys.stderr)
+ return 1
+ target_validation_requests = target_result.value
+
+ _verify_state_file_writable(
+ args.state_file,
+ repo=args.repo,
+ pr_number=args.pr,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ )
+ # Reload after the atomic claim/adoption so the cycle starts from the state
+ # that actually owns the path, not the read-only preflight snapshot.
+ saved = _load_state_file(
+ args.state_file,
+ repo=args.repo,
+ pr_number=args.pr,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ )
+ saved, replay_output = _resolve_staged_state(
+ args.state_file,
+ saved,
+ delivery=delivery_stamp,
+ repo=args.repo,
+ pr_number=args.pr,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ )
+ if replay_output is not None:
+ _deliver(replay_output)
+ return 0
+
+ effective_interval = base_interval
+ settle_seconds = max(args.settle, 0.0)
+
+ # Resume only from a complete cursor set. A partial one would leave some
+ # baseline to be derived from a `since`-narrowed fetch, which no longer
+ # contains the PR's full history.
+ resume_cursors = {key: _saved_int(saved, key) for key in STATE_CURSOR_KEYS}
+ resumed = not args.catch_up and all(value is not None for value in resume_cursors.values())
+ missing_baselines = _missing_pr_baselines(saved) if resumed else []
+ if args.pr is not None and args.state_file and missing_baselines:
+ print(
+ (
+ "Saved PR state lacks required baseline(s): %s; pass --catch-up "
+ "to seed them explicitly before resuming."
+ )
+ % ", ".join(missing_baselines),
+ file=sys.stderr,
+ )
+ return 2
+ if two_phase and not args.catch_up:
+ seeded = _saved_int(saved, "pr_cursor") is not None if args.new_prs else resumed
+ if not seeded:
+ print(
+ "Managed first watch requires --catch-up or a pre-seeded complete state file; refusing to rebaseline.",
+ file=sys.stderr,
+ )
+ return 2
+ # --catch-up asks for existing activity to count as pending, and it already
+ # overrides the saved cursors above. The new-PR cursor follows the same rule:
+ # inheriting it would filter the fully fetched history right back down to what
+ # the last cycle had already seen, which is the opposite of what was asked for.
+ # An explicit --since-pr-id names a replay point and still wins.
+ saved_pr_cursor = None if args.catch_up else _saved_int(saved, "pr_cursor")
+ since_pr_id = args.since_pr_id if args.since_pr_id is not None else saved_pr_cursor
+
+ if args.pr is not None:
+ initial_request = retry_initial_request(
+ lambda: _fetch_state(args.repo, args.pr, token, cache=cache),
+ description="initial GitHub PR state request",
+ )
+ else:
+ initial_pr_stop_after_id = None
+ initial_pr_max_pages = None
+ if since_pr_id is not None and not args.catch_up:
+ initial_pr_stop_after_id = since_pr_id
+ elif not args.catch_up:
+ initial_pr_max_pages = 1
+ initial_request = retry_initial_request(
+ lambda: _fetch_new_pr_state(
+ args.repo,
+ token,
+ stop_after_id=initial_pr_stop_after_id,
+ max_pages=initial_pr_max_pages,
+ cache=cache,
+ ),
+ description="initial GitHub pull-request list request",
+ )
+ if initial_request.error is not None:
+ print(f"Failed to fetch initial PR state: {initial_request.error}", file=sys.stderr)
+ return 1
+ if initial_request.value is None:
+ print("Initial GitHub request completed without a result", file=sys.stderr)
+ return 1
+ state, requests_per_poll_count = initial_request.value
+
+ if token is None:
+ bootstrap_requests = requests_per_poll_count + target_validation_requests
+ unauthenticated_min = min_interval_for_unauthenticated(
+ requests_per_poll_count,
+ bootstrap_requests=bootstrap_requests,
+ )
+ startup_interval = max(base_interval, unauthenticated_min)
+ if effective_interval < startup_interval:
+ print(
+ (
+ "No GitHub token detected; clamping polling interval from %.1fs to %.1fs "
+ "for %s request(s) per poll plus %s bootstrap request(s) to avoid "
+ "unauthenticated rate-limit lockout."
+ )
+ % (effective_interval, startup_interval, requests_per_poll_count, bootstrap_requests),
+ file=sys.stderr,
+ )
+ effective_interval = startup_interval
+ else:
+ bootstrap_requests = 0
+
+ if args.pr is not None:
+
+ def _initial_cursor(flag_value: int | None, saved_key: str, items_key: str) -> int:
+ if flag_value is not None:
+ return flag_value
+ if resumed:
+ return resume_cursors[saved_key] or 0
+ return 0 if args.catch_up else max_id(state[items_key])
+
+ review_cursor = _initial_cursor(args.since_review_id, "review_cursor", "reviews")
+ review_comment_cursor = _initial_cursor(
+ args.since_review_comment_id, "review_comment_cursor", "review_comments"
+ )
+ issue_comment_cursor = _initial_cursor(
+ args.since_issue_comment_id, "issue_comment_cursor", "issue_comments"
+ )
+ reaction_cursor = _initial_cursor(args.since_reaction_id, "reaction_cursor", "reactions")
+ review_fingerprints = _saved_fingerprints(saved, REVIEW_FINGERPRINTS_KEY)
+ review_comment_fingerprints = _saved_fingerprints(
+ saved,
+ REVIEW_COMMENT_FINGERPRINTS_KEY,
+ )
+ issue_comment_fingerprints = _saved_fingerprints(
+ saved,
+ ISSUE_COMMENT_FINGERPRINTS_KEY,
+ )
+ review_thread_states = _saved_review_thread_states(saved)
+ pr_status = (
+ args.since_pr_status
+ or (_saved_str(saved, "pr_status") if resumed else None)
+ or _current_pr_status(state.get("pull_request"))
+ )
+ head_sha = (
+ (_saved_str(saved, "head_sha") if resumed else None)
+ or _current_pr_head_sha(state.get("pull_request"))
+ )
+ explicit_replay = any(
+ value is not None
+ for value in (
+ args.since_review_id,
+ args.since_review_comment_id,
+ args.since_issue_comment_id,
+ args.since_reaction_id,
+ args.since_pr_status,
+ )
+ )
+ if args.catch_up or explicit_replay:
+ snapshot = {}
+ elif resumed:
+ snapshot = _saved_snapshot(saved)
+ else:
+ snapshot = _normalized_pr_snapshot(
+ state,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ actionable_only=args.actionable_only,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ review_threads_available=token is not None,
+ )
+
+ print(
+ (
+ "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s reaction=%s pr_status=%s head=%s catch_up=%s resumed=%s"
+ % (
+ args.repo,
+ args.pr,
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ pr_status,
+ head_sha,
+ args.catch_up,
+ resumed,
+ )
+ ),
+ file=sys.stderr,
+ )
+
+ def _render(
+ cursors: tuple[int, int, int, int, str, str, dict[str, Any]],
+ ) -> tuple[str | None, int, int, int, int, str, str, dict[str, Any]]:
+ return _render_activity(
+ repo=args.repo,
+ pr_number=args.pr,
+ state=state,
+ review_cursor=cursors[0],
+ review_comment_cursor=cursors[1],
+ issue_comment_cursor=cursors[2],
+ reaction_cursor=cursors[3],
+ pr_status=cursors[4],
+ head_sha=cursors[5],
+ snapshot=cursors[6],
+ event_limit=args.event_limit,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ actionable_only=args.actionable_only,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ review_fingerprints=review_fingerprints,
+ review_comment_fingerprints=review_comment_fingerprints,
+ issue_comment_fingerprints=issue_comment_fingerprints,
+ review_thread_states=review_thread_states,
+ review_threads_available=token is not None,
+ )
+
+ def _pr_state_fields() -> dict[str, Any]:
+ return {
+ "review_cursor": review_cursor,
+ "review_comment_cursor": review_comment_cursor,
+ "issue_comment_cursor": issue_comment_cursor,
+ "reaction_cursor": reaction_cursor,
+ "pr_status": pr_status,
+ "head_sha": head_sha,
+ REVIEW_FINGERPRINTS_KEY: review_fingerprints,
+ REVIEW_COMMENT_FINGERPRINTS_KEY: review_comment_fingerprints,
+ ISSUE_COMMENT_FINGERPRINTS_KEY: issue_comment_fingerprints,
+ REVIEW_THREAD_STATES_KEY: review_thread_states,
+ PR_SNAPSHOT_KEY: snapshot,
+ "viewer_login": viewer_login,
+ "token_fingerprint": token_fingerprint,
+ }
+
+ def _persist_pr_state(
+ *,
+ previous: dict[str, Any] | None = None,
+ output: str | None = None,
+ ) -> None:
+ fields = _pr_state_fields()
+ if previous is not None:
+ # Committed state stays where the reported event is still unseen; the
+ # cursors past it wait under STAGED_KEY, stamped with the delivery this
+ # waiter started from so a later cycle can tell whether it has moved.
+ fields = {
+ **previous,
+ STAGED_KEY: {
+ "delivered_after": delivery_stamp,
+ "output": output,
+ "cursors": fields,
+ },
+ }
+ _write_state_file(
+ args.state_file,
+ repo=args.repo,
+ pr_number=args.pr,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ **fields,
+ )
+
+ def _report_pr(output: str, previous: dict[str, Any]) -> None:
+ """Hand one report to the supervisor, staging or committing to match.
+
+ Under ``vibe watch`` the cursors covering the event are staged first, so a
+ crash before the supervisor queues the follow-up replays the report instead
+ of skipping it. A manual run has no next cycle to promote anything, and
+ printing there is the delivery, so it commits straight after.
+ """
+
+ if two_phase:
+ _persist_pr_state(previous=previous, output=output)
+ _deliver(output)
+ return
+ _deliver(output)
+ _persist_pr_state()
+
+ def _settle(
+ first: tuple[str | None, int, int, int, int, str, str, dict[str, Any]],
+ pending: tuple[int, int, int, int, str, str, dict[str, Any]],
+ ) -> GitHubRequestResult[
+ tuple[str | None, int, int, int, int, str, str, dict[str, Any]]
+ ]:
+ """Re-poll while a batch is still landing so it costs one Agent turn."""
+
+ nonlocal state
+ if settle_seconds <= 0:
+ return GitHubRequestResult(value=first)
+
+ best = first
+ for _round in range(SETTLE_MAX_ROUNDS):
+ # The batch is already worth a turn, so waiting for the rest of it must
+ # not push the waiter past its own deadline: `vibe watch` kills the
+ # process on timeout and the report would be lost with it. The sleep is
+ # only half the cost — the re-poll behind it is several sequential
+ # requests, each free to block for REQUEST_TIMEOUT_SECONDS — so both
+ # have to fit in what is left, not just the sleep.
+ if args.timeout > 0:
+ remaining = args.timeout - (time.monotonic() - start)
+ repoll_budget = max(1, requests_per_poll_count) * REQUEST_TIMEOUT_SECONDS
+ if remaining <= settle_seconds + repoll_budget:
+ print(
+ "Settle window plus its re-poll would outlast --timeout; "
+ "reporting the batch seen so far.",
+ file=sys.stderr,
+ )
+ return GitHubRequestResult(value=best)
+ time.sleep(settle_seconds)
+ settle_request = github_request(
+ lambda: _fetch_state(
+ args.repo,
+ args.pr,
+ token,
+ cache=cache,
+ )
+ )
+ if settle_request.error is not None:
+ print(
+ f"Settle re-poll failed: {settle_request.error}",
+ file=sys.stderr,
+ )
+ if settle_request.error.retryable:
+ continue
+ return GitHubRequestResult(error=settle_request.error)
+ if settle_request.value is None:
+ return GitHubRequestResult(
+ error=GitHubProtocolError(
+ "Settle GitHub request completed without a result"
+ )
+ )
+ state, _count = settle_request.value
+ # Rendered from the same cursors as the first hit, so the result is a
+ # superset rather than a second, partial report.
+ candidate = _render(pending)
+ if candidate[0] is None:
+ return GitHubRequestResult(value=best)
+ if candidate[1:] == best[1:]:
+ return GitHubRequestResult(value=candidate)
+ best = candidate
+ return GitHubRequestResult(value=best)
+
+ pending_cursors = (
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ pr_status,
+ head_sha,
+ snapshot,
+ )
+ pre_event_fields = _pr_state_fields()
+ initial_result = _render(pending_cursors)
+ if initial_result[0] is not None and not args.catch_up:
+ settle_result = _settle(initial_result, pending_cursors)
+ if settle_result.error is not None:
+ return 1
+ if settle_result.value is None:
+ print("Settle request completed without a result", file=sys.stderr)
+ return 1
+ initial_result = settle_result.value
+ review_fingerprints = _review_fingerprint_map(state["reviews"])
+ review_comment_fingerprints = _comment_fingerprint_map(state["review_comments"])
+ issue_comment_fingerprints = _comment_fingerprint_map(state["issue_comments"])
+ if token is not None:
+ review_thread_states = _review_thread_state_map(state["review_threads"])
+ (
+ initial_output,
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ pr_status,
+ head_sha,
+ snapshot,
+ ) = initial_result
+ if initial_output is None:
+ # Persisted even with nothing to report: the baseline this cycle
+ # established is exactly what the next cycle must resume from.
+ _persist_pr_state()
+ else:
+ _write_cursor_output(
+ args.cursor_output,
+ review_cursor=review_cursor,
+ review_comment_cursor=review_comment_cursor,
+ issue_comment_cursor=issue_comment_cursor,
+ reaction_cursor=reaction_cursor,
+ pr_status=pr_status,
+ head_sha=head_sha,
+ )
+ _report_pr(initial_output, pre_event_fields)
+ return 0
+ else:
+ pr_cursor = since_pr_id if since_pr_id is not None else (0 if args.catch_up else max_id(state["pull_requests"]))
+ print(
+ f"Watching GitHub new PRs in {args.repo} from cursor: pr={pr_cursor} catch_up={args.catch_up}",
+ file=sys.stderr,
+ )
+ pre_event_pr_cursor = pr_cursor
+ initial_output, pr_cursor = _render_new_pull_requests(
+ repo=args.repo,
+ state=state,
+ pr_cursor=pr_cursor,
+ event_limit=args.event_limit,
+ )
+ def _persist_new_pr_state(
+ *,
+ previous: int | None = None,
+ output: str | None = None,
+ ) -> None:
+ fields: dict[str, Any] = {"pr_cursor": pr_cursor}
+ if previous is not None:
+ fields = {
+ "pr_cursor": previous,
+ STAGED_KEY: {
+ "delivered_after": delivery_stamp,
+ "output": output,
+ "cursors": {"pr_cursor": pr_cursor},
+ },
+ }
+ _write_state_file(
+ args.state_file,
+ repo=args.repo,
+ pr_number=None,
+ watch_identity=watch_identity,
+ watch_id=watch_id,
+ **fields,
+ )
+
+ def _report_new_pr(output: str, previous: int) -> None:
+ """Same staging contract as ``_report_pr``, over the single new-PR cursor."""
+
+ if two_phase:
+ _persist_new_pr_state(previous=previous, output=output)
+ _deliver(output)
+ return
+ _deliver(output)
+ _persist_new_pr_state()
+
+ if initial_output is None:
+ _persist_new_pr_state()
+ else:
+ _write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)
+ _report_new_pr(initial_output, pre_event_pr_cursor)
+ return 0
+
+ while True:
+ sleep_seconds = effective_interval
+ if args.timeout > 0:
+ remaining_timeout = args.timeout - (time.monotonic() - start)
+ if remaining_timeout <= 0:
+ print("Timed out while waiting for GitHub PR activity", file=sys.stderr)
+ print(cache.summary(), file=sys.stderr)
+ return 124
+ sleep_seconds = min(sleep_seconds, remaining_timeout)
+
+ time.sleep(sleep_seconds)
+
+ if args.pr is not None:
+ poll_request = github_request(
+ lambda: _fetch_state(
+ args.repo,
+ args.pr,
+ token,
+ cache=cache,
+ )
+ )
+ else:
+ poll_request = github_request(
+ lambda: _fetch_new_pr_state(
+ args.repo,
+ token,
+ stop_after_id=pr_cursor if pr_cursor > 0 else None,
+ cache=cache,
+ )
+ )
+ if poll_request.error is not None:
+ print(f"GitHub polling failed: {poll_request.error}", file=sys.stderr)
+ if poll_request.error.retryable:
+ print(
+ "Retryable GitHub request failure; continuing in this watch",
+ file=sys.stderr,
+ )
+ continue
+ return 1
+ if poll_request.value is None:
+ print("GitHub polling completed without a result", file=sys.stderr)
+ return 1
+ state, requests_per_poll_count = poll_request.value
+
+ if token is None:
+ unauthenticated_min = min_interval_for_unauthenticated(requests_per_poll_count)
+ target_interval = max(base_interval, unauthenticated_min)
+ if target_interval != effective_interval:
+ if target_interval > effective_interval:
+ print(
+ (
+ "GitHub unauthenticated polling now needs %.1fs minimum for %s request(s) "
+ "per poll; increasing interval."
+ )
+ % (target_interval, requests_per_poll_count),
+ file=sys.stderr,
+ )
+ else:
+ print(
+ (
+ "GitHub unauthenticated polling now needs only %.1fs minimum for %s request(s) "
+ "per poll; reducing interval."
+ )
+ % (target_interval, requests_per_poll_count),
+ file=sys.stderr,
+ )
+ effective_interval = target_interval
+
+ if args.pr is not None:
+ pending_cursors = (
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ pr_status,
+ head_sha,
+ snapshot,
+ )
+ pre_event_fields = _pr_state_fields()
+ result = _render(pending_cursors)
+ if result[0] is not None:
+ settle_result = _settle(result, pending_cursors)
+ if settle_result.error is not None:
+ return 1
+ if settle_result.value is None:
+ print("Settle request completed without a result", file=sys.stderr)
+ return 1
+ result = settle_result.value
+ review_fingerprints = _review_fingerprint_map(state["reviews"])
+ review_comment_fingerprints = _comment_fingerprint_map(state["review_comments"])
+ issue_comment_fingerprints = _comment_fingerprint_map(state["issue_comments"])
+ if token is not None:
+ review_thread_states = _review_thread_state_map(state["review_threads"])
+ (
+ output,
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ pr_status,
+ head_sha,
+ snapshot,
+ ) = result
+ if output is None:
+ # Cursors also move when everything new was filtered out, and that
+ # progress has to survive the cycle or the next one re-examines it.
+ # Nothing is being reported, so there is no delivery to wait for.
+ _persist_pr_state()
+ continue
+
+ _write_cursor_output(
+ args.cursor_output,
+ review_cursor=review_cursor,
+ review_comment_cursor=review_comment_cursor,
+ issue_comment_cursor=issue_comment_cursor,
+ reaction_cursor=reaction_cursor,
+ pr_status=pr_status,
+ head_sha=head_sha,
+ )
+ report = partial(_report_pr, previous=pre_event_fields)
+ else:
+ pre_event_pr_cursor = pr_cursor
+ output, pr_cursor = _render_new_pull_requests(
+ repo=args.repo,
+ state=state,
+ pr_cursor=pr_cursor,
+ event_limit=args.event_limit,
+ )
+ if output is None:
+ _persist_new_pr_state()
+ continue
+ _write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)
+ report = partial(_report_new_pr, previous=pre_event_pr_cursor)
+
+ print(cache.summary(), file=sys.stderr)
+ report(output)
+ return 0
+
+
+def run_cli() -> int:
+ """``main`` plus the terminal handling of an unusable ``--state-file``.
+
+ Exit 1 and not the retryable 75: a directory that cannot be written to, a path
+ already owned by another PR, and a file whose cursors cannot be read do not start
+ working on the next cycle, and a forever watch retrying into one would poll
+ indefinitely while losing the activity it saw.
+ """
+
+ try:
+ return main()
+ except StateFileError as err:
+ print(
+ f"{err}. Give this watch its own --state-file path (or fix or remove "
+ "this one), then recreate the watch.",
+ file=sys.stderr,
+ )
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli())
diff --git a/.agents/skills/pr-delivery-loop/tests/test_wait_pr.py b/.agents/skills/pr-delivery-loop/tests/test_wait_pr.py
new file mode 100644
index 000000000..f174dda6a
--- /dev/null
+++ b/.agents/skills/pr-delivery-loop/tests/test_wait_pr.py
@@ -0,0 +1,1071 @@
+"""Behavior evidence for the repo-local PR waiter transaction boundary."""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import json
+import sys
+import urllib.error
+from pathlib import Path
+
+import pytest
+
+SCRIPT = Path(__file__).parents[1] / "scripts" / "wait_pr.py"
+SPEC = importlib.util.spec_from_file_location("repo_local_wait_pr", SCRIPT)
+assert SPEC and SPEC.loader
+wait_pr = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = wait_pr
+SPEC.loader.exec_module(wait_pr)
+
+ACTION_SCRIPT = Path(__file__).parents[1] / "scripts" / "wait_action.py"
+COMMON_SCRIPT = Path(__file__).parents[1] / "scripts" / "_github_wait_common.py"
+ACTION_SPEC = importlib.util.spec_from_file_location("repo_local_wait_action", ACTION_SCRIPT)
+assert ACTION_SPEC and ACTION_SPEC.loader
+wait_action = importlib.util.module_from_spec(ACTION_SPEC)
+sys.modules[ACTION_SPEC.name] = wait_action
+ACTION_SPEC.loader.exec_module(wait_action)
+github_wait_common = sys.modules["_github_wait_common"]
+
+
[email protected](autouse=True)
+def _stub_remote_target_validation(monkeypatch):
+ monkeypatch.setattr(wait_pr, "_validate_target", lambda *_args, **_kwargs: 1)
+
+
+def _pr_state(
+ *,
+ reviews=None,
+ review_comments=None,
+ issue_comments=None,
+ reactions=None,
+ review_threads=None,
+ head="head",
+ status="open",
+ draft=False,
+):
+ return {
+ "pull_request": {
+ "number": 1213,
+ "state": status,
+ "draft": draft,
+ "merged_at": "2026-08-10T00:00:00Z" if status == "merged" else None,
+ "head": {"sha": head},
+ "html_url": "https://github.com/avibe-bot/avibe/pull/1213",
+ },
+ "reviews": list(reviews or []),
+ "review_comments": list(review_comments or []),
+ "issue_comments": list(issue_comments or []),
+ "reactions": list(reactions or []),
+ "review_threads": list(review_threads or []),
+ }
+
+
+def _snapshot(state, **options):
+ return wait_pr._normalized_pr_snapshot(
+ state,
+ ignore_self_comments=False,
+ **options,
+ )
+
+
+def _seeded_state(path: Path, *, review_fingerprints=None, head="head", snapshot=None):
+ path.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo": "avibe-bot/avibe",
+ "pr": 1213,
+ "watch": None,
+ "owner": None,
+ "review_cursor": 7,
+ "review_comment_cursor": 10,
+ "issue_comment_cursor": 10,
+ "reaction_cursor": 0,
+ "pr_status": "open",
+ "head_sha": head,
+ "review_fingerprints": review_fingerprints or {},
+ "review_comment_fingerprints": {},
+ "issue_comment_fingerprints": {},
+ "review_thread_states": {},
+ "snapshot": snapshot or {},
+ }
+ )
+ )
+
+
+def _include_self_watch_identity():
+ return wait_pr._watch_identity(
+ wait_pr._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "1213", "--include-self-comments"]
+ )
+ )
+
+
+def test_token_precedence_matches_github_cli(monkeypatch):
+ monkeypatch.setenv("GH_TOKEN", "preferred")
+ monkeypatch.setenv("GITHUB_TOKEN", "stale")
+
+ assert wait_pr.get_token() == "preferred"
+
+
+def test_settle_keeps_one_review_baseline_for_every_candidate(monkeypatch, tmp_path, capsys):
+ old_review = {
+ "id": 7,
+ "state": "APPROVED",
+ "updated_at": "2026-08-10T00:00:00Z",
+ "submitted_at": "2026-08-09T23:00:00Z",
+ "body": "",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/review/7",
+ }
+ changed_review = {**old_review, "updated_at": "2026-08-10T00:01:00Z", "state": "DISMISSED"}
+ initial = _pr_state(reviews=[changed_review])
+ settled = _pr_state(
+ reviews=[changed_review],
+ issue_comments=[
+ {
+ "id": 11,
+ "body": "The review was dismissed.",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/comment/11",
+ }
+ ],
+ )
+ state_file = tmp_path / "state.json"
+ _seeded_state(state_file, review_fingerprints={"7": wait_pr._review_fingerprint(old_review)})
+ calls = iter([initial, settled, settled])
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", lambda *args, **kwargs: (next(calls), 1))
+ monkeypatch.setattr(wait_pr.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(wait_pr, "REQUEST_TIMEOUT_SECONDS", 0.001)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--state-file",
+ str(state_file),
+ "--settle",
+ "0.001",
+ "--timeout",
+ "30",
+ "--event-limit",
+ "20",
+ ],
+ )
+
+ assert wait_pr.main() == 0
+ output = capsys.readouterr().out
+ assert "review #7" in output
+ assert "issue_comment #11" in output
+
+
+def test_undelivered_staged_report_replays_payload_without_github(tmp_path):
+ state_file = tmp_path / "state.json"
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo": "avibe-bot/avibe",
+ "pr": 1213,
+ "watch": "watch-1",
+ "owner": "watch-1",
+ "review_cursor": 1,
+ "pending": {
+ "delivered_after": "delivery-1",
+ "output": "persisted report",
+ "cursors": {"review_cursor": 2},
+ },
+ }
+ )
+ )
+
+ saved = json.loads(state_file.read_text())
+ resolved, replay = wait_pr._resolve_staged_state(
+ str(state_file),
+ saved,
+ delivery="delivery-1",
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ watch_identity=None,
+ watch_id="watch-1",
+ )
+ assert resolved["pending"]["output"] == "persisted report"
+ assert replay == "persisted report"
+ assert json.loads(state_file.read_text())["pending"]["output"] == "persisted report"
+
+ resolved, replay = wait_pr._resolve_staged_state(
+ str(state_file),
+ json.loads(state_file.read_text()),
+ delivery="delivery-2",
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ watch_identity=None,
+ watch_id="watch-1",
+ )
+ assert replay is None
+ assert resolved["review_cursor"] == 2
+ assert "pending" not in json.loads(state_file.read_text())
+
+
+def test_pending_report_replays_before_authentication_preflight(monkeypatch, tmp_path, capsys):
+ state_file = tmp_path / "state.json"
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo": "avibe-bot/avibe",
+ "pr": 1213,
+ "watch": _include_self_watch_identity(),
+ "owner": "watch-1",
+ "pending": {
+ "delivered_after": None,
+ "output": "persisted report",
+ "cursors": {"review_cursor": 2},
+ },
+ }
+ )
+ )
+ monkeypatch.setenv("AVIBE_WATCH_ID", "watch-1")
+ monkeypatch.delenv(wait_pr.LAST_DELIVERY_ENV, raising=False)
+ monkeypatch.setattr(wait_pr, "get_token", lambda: None)
+ monkeypatch.setattr(
+ wait_pr,
+ "_verify_state_file_writable",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError()),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--state-file",
+ str(state_file),
+ ],
+ )
+
+ assert wait_pr.main() == 0
+ assert "persisted report" in capsys.readouterr().out
+
+
+def test_viewer_failure_does_not_claim_state_file(monkeypatch, tmp_path):
+ state_file = tmp_path / "state.json"
+ monkeypatch.delenv("AVIBE_WATCH_ID", raising=False)
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(
+ wait_pr,
+ "resolve_authenticated_login",
+ lambda _token: (_ for _ in ()).throw(RuntimeError("viewer unavailable")),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--state-file",
+ str(state_file),
+ "--timeout",
+ "1",
+ ],
+ )
+
+ assert wait_pr.main() == 1
+ assert not state_file.exists()
+
+
+def test_target_failure_does_not_claim_state_file(monkeypatch, tmp_path):
+ state_file = tmp_path / "state.json"
+ monkeypatch.delenv("AVIBE_WATCH_ID", raising=False)
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(
+ wait_pr,
+ "_validate_target",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(
+ github_wait_common.GitHubProtocolError("target unavailable")
+ ),
+ )
+ monkeypatch.setattr(
+ wait_pr,
+ "_verify_state_file_writable",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError()),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "999999",
+ "--include-self-comments",
+ "--state-file",
+ str(state_file),
+ ],
+ )
+
+ assert wait_pr.main() == 1
+ assert not state_file.exists()
+
+
+def test_cursorless_state_allows_same_watch_to_change_filters(tmp_path):
+ state_file = tmp_path / "state.json"
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo": "avibe-bot/avibe",
+ "pr": 1213,
+ "watch": "old-filter-identity",
+ "owner": "watch-1",
+ }
+ )
+ )
+
+ saved = wait_pr._load_state_file(
+ str(state_file),
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ watch_identity="new-filter-identity",
+ watch_id="watch-1",
+ )
+ assert saved["owner"] == "watch-1"
+
+
+def test_resume_requires_all_persisted_activity_baselines(monkeypatch, tmp_path):
+ state_file = tmp_path / "state.json"
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo": "avibe-bot/avibe",
+ "pr": 1213,
+ "watch": _include_self_watch_identity(),
+ "owner": "watch-1",
+ "review_cursor": 1,
+ "review_comment_cursor": 2,
+ "issue_comment_cursor": 3,
+ "reaction_cursor": 4,
+ "pr_status": "open",
+ }
+ )
+ )
+ monkeypatch.setenv("AVIBE_WATCH_ID", "watch-1")
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError()))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--state-file",
+ str(state_file),
+ ],
+ )
+
+ assert wait_pr.main() == 2
+ missing = wait_pr._missing_pr_baselines(json.loads(state_file.read_text()))
+ assert set(missing) == {
+ "head_sha",
+ "review_fingerprints",
+ "review_comment_fingerprints",
+ "issue_comment_fingerprints",
+ "review_thread_states",
+ "snapshot",
+ }
+
+
+def test_cursor_covered_comment_edits_are_reported():
+ old_review_comment = {
+ "id": 5,
+ "updated_at": "2026-08-10T00:00:00Z",
+ "body": "old inline request",
+ "path": "wait_pr.py",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/review-comment/5",
+ }
+ old_issue_comment = {
+ "id": 6,
+ "updated_at": "2026-08-10T00:00:00Z",
+ "body": "old conversation request",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/issue-comment/6",
+ }
+ changed_review_comment = {
+ **old_review_comment,
+ "updated_at": "2026-08-10T00:01:00Z",
+ "body": "new inline request",
+ }
+ changed_issue_comment = {
+ **old_issue_comment,
+ "updated_at": "2026-08-10T00:01:00Z",
+ "body": "new conversation request",
+ }
+ old_state = _pr_state(
+ review_comments=[old_review_comment],
+ issue_comments=[old_issue_comment],
+ )
+
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(
+ review_comments=[changed_review_comment],
+ issue_comments=[changed_issue_comment],
+ ),
+ review_cursor=0,
+ review_comment_cursor=5,
+ issue_comment_cursor=6,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(old_state),
+ event_limit=10,
+ ignore_self_comments=False,
+ review_comment_fingerprints={"5": wait_pr._comment_fingerprint(old_review_comment)},
+ issue_comment_fingerprints={"6": wait_pr._comment_fingerprint(old_issue_comment)},
+ )
+
+ assert "review_comment #5" in result[0]
+ assert "issue_comment #6" in result[0]
+
+
+def test_event_limit_never_omits_codex_pass_reaction():
+ issue_comments = [
+ {
+ "id": comment_id,
+ "body": f"comment {comment_id}",
+ "user": {"login": "reviewer"},
+ "html_url": f"https://example.invalid/comment/{comment_id}",
+ }
+ for comment_id in (1, 2)
+ ]
+ reaction = {
+ "id": 9,
+ "content": "+1",
+ "created_at": "2026-08-10T00:00:00Z",
+ "user": {"login": "chatgpt-codex-connector[bot]"},
+ }
+
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(issue_comments=issue_comments, reactions=[reaction]),
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(_pr_state()),
+ event_limit=1,
+ ignore_self_comments=False,
+ )
+
+ assert "pr_reaction #9" in result[0]
+ assert "2 additional event(s) omitted" in result[0]
+
+
+def test_codex_pass_reaction_accepts_both_api_login_forms_only():
+ for login in ("chatgpt-codex-connector", "chatgpt-codex-connector[bot]"):
+ assert wait_pr._is_codex_pass_reaction(
+ {"content": "+1", "user": {"login": login}}
+ )
+
+ assert not wait_pr._is_codex_pass_reaction(
+ {"content": "+1", "user": {"login": "another-reviewer"}}
+ )
+
+
+def test_review_thread_state_changes_are_paginated_and_reported(monkeypatch):
+ cursors = []
+
+ def _graphql(_query, variables, _token):
+ cursors.append(variables["endCursor"])
+ if variables["endCursor"] is None:
+ nodes = [{"id": "thread-1", "isResolved": True}]
+ page_info = {"hasNextPage": True, "endCursor": "cursor-1"}
+ else:
+ nodes = [{"id": "thread-2", "isResolved": False}]
+ page_info = {"hasNextPage": False, "endCursor": "cursor-2"}
+ return {
+ "repository": {
+ "pullRequest": {
+ "reviewThreads": {"nodes": nodes, "pageInfo": page_info},
+ }
+ }
+ }
+
+ monkeypatch.setattr(wait_pr, "github_graphql", _graphql)
+ threads, request_count = wait_pr._fetch_review_threads("avibe-bot/avibe", 1213, "token")
+
+ assert request_count == 2
+ assert cursors == [None, "cursor-1"]
+ assert [thread["id"] for thread in threads] == ["thread-1", "thread-2"]
+
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(review_threads=threads),
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(
+ _pr_state(
+ review_threads=[
+ {"id": "thread-1", "isResolved": False},
+ {"id": "thread-2", "isResolved": False},
+ ]
+ )
+ ),
+ event_limit=1,
+ ignore_self_comments=False,
+ review_thread_states={"thread-1": False, "thread-2": False},
+ )
+
+ assert "review_thread thread-1 unresolved -> resolved" in result[0]
+
+
+def test_head_change_is_reported_as_pr_activity():
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(head="new-head"),
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="old-head",
+ snapshot=_snapshot(_pr_state(head="old-head")),
+ event_limit=10,
+ ignore_self_comments=False,
+ )
+
+ assert result[0] is not None
+ assert "pr_head #1213 old-head -> new-head" in result[0]
+ assert result[6] == "new-head"
+
+
+def test_snapshot_diff_wakes_on_review_edit():
+ review = {
+ "id": 1,
+ "state": "COMMENTED",
+ "body": "please fix",
+ "commit_id": "head",
+ "user": {"login": "reviewer"},
+ }
+
+ assert _snapshot(_pr_state(reviews=[review])) != _snapshot(
+ _pr_state(reviews=[{**review, "state": "DISMISSED"}])
+ )
+
+
+def test_snapshot_diff_wakes_on_inline_and_conversation_comment_edits():
+ inline = {
+ "id": 2,
+ "body": "old inline request",
+ "path": "wait_pr.py",
+ "user": {"login": "reviewer"},
+ }
+ conversation = {
+ "id": 3,
+ "body": "old conversation request",
+ "user": {"login": "reviewer"},
+ }
+ baseline = _snapshot(
+ _pr_state(review_comments=[inline], issue_comments=[conversation])
+ )
+
+ assert baseline != _snapshot(
+ _pr_state(
+ review_comments=[{**inline, "body": "new inline request"}],
+ issue_comments=[conversation],
+ )
+ )
+ assert baseline != _snapshot(
+ _pr_state(
+ review_comments=[inline],
+ issue_comments=[{**conversation, "body": "new conversation request"}],
+ )
+ )
+
+
+def test_snapshot_diff_wakes_on_codex_pass_reaction():
+ reaction = {
+ "id": 4,
+ "content": "+1",
+ "user": {"login": "chatgpt-codex-connector"},
+ }
+
+ assert _snapshot(_pr_state()) != _snapshot(_pr_state(reactions=[reaction]))
+
+
+def test_snapshot_diff_wakes_on_every_review_thread_transition():
+ absent = _snapshot(_pr_state())
+ unresolved = _snapshot(
+ _pr_state(review_threads=[{"id": "thread-1", "isResolved": False}])
+ )
+ resolved = _snapshot(
+ _pr_state(review_threads=[{"id": "thread-1", "isResolved": True}])
+ )
+
+ assert absent != unresolved # added
+ assert unresolved != resolved # resolved
+ assert resolved != unresolved # reopened
+ assert unresolved != absent # removed
+
+
+def test_removed_review_thread_wakes_with_a_descriptor():
+ baseline_state = _pr_state(
+ review_threads=[{"id": "thread-1", "isResolved": False}]
+ )
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(),
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(baseline_state),
+ event_limit=10,
+ ignore_self_comments=False,
+ review_thread_states={"thread-1": False},
+ )
+
+ assert result[0] is not None
+ assert "review_thread thread-1 unresolved -> absent" in result[0]
+
+
+def test_unavailable_graphql_preserves_thread_descriptors():
+ baseline_state = _pr_state(
+ review_threads=[{"id": "thread-1", "isResolved": False}]
+ )
+ current_state = _pr_state(
+ issue_comments=[
+ {
+ "id": 7,
+ "body": "REST-visible request",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/comment/7",
+ }
+ ]
+ )
+
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=current_state,
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(baseline_state),
+ event_limit=10,
+ ignore_self_comments=False,
+ review_thread_states={"thread-1": False},
+ review_threads_available=False,
+ )
+
+ assert "issue_comment #7" in result[0]
+ assert "review_thread" not in result[0]
+
+
+def test_snapshot_diff_wakes_on_pr_status_change():
+ assert _snapshot(_pr_state()) != _snapshot(_pr_state(draft=True))
+
+
+def test_timestamp_only_changes_are_silent():
+ old_comment = {
+ "id": 5,
+ "body": "unchanged",
+ "updated_at": "2026-08-10T00:00:00Z",
+ "user": {"login": "reviewer"},
+ }
+ changed_timestamp = {**old_comment, "updated_at": "2026-08-10T00:01:00Z"}
+ baseline_state = _pr_state(issue_comments=[old_comment])
+ result = wait_pr._render_activity(
+ repo="avibe-bot/avibe",
+ pr_number=1213,
+ state=_pr_state(issue_comments=[changed_timestamp]),
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=5,
+ reaction_cursor=0,
+ pr_status="open",
+ head_sha="head",
+ snapshot=_snapshot(baseline_state),
+ event_limit=10,
+ ignore_self_comments=False,
+ issue_comment_fingerprints={"5": wait_pr._comment_fingerprint(old_comment)},
+ )
+
+ assert result[0] is None
+
+
+def test_actionable_snapshot_ignores_trigger_envelopes_and_draft_toggles():
+ patterns = wait_pr._compile_ignore_patterns(None, actionable_only=True)
+ baseline = _snapshot(
+ _pr_state(),
+ actionable_only=True,
+ ignore_patterns=patterns,
+ )
+ noise = _pr_state(
+ draft=True,
+ reviews=[
+ {
+ "id": 6,
+ "state": "COMMENTED",
+ "body": "",
+ "user": {"login": "chatgpt-codex-connector[bot]"},
+ }
+ ],
+ issue_comments=[
+ {
+ "id": 7,
+ "body": "@codex review",
+ "user": {"login": "maintainer"},
+ }
+ ],
+ )
+
+ assert baseline == _snapshot(
+ noise,
+ actionable_only=True,
+ ignore_patterns=patterns,
+ )
+
+
+def test_explicit_replay_clears_the_committed_snapshot(monkeypatch, tmp_path, capsys):
+ review = {
+ "id": 7,
+ "state": "COMMENTED",
+ "body": "historical request",
+ "commit_id": "head",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/review/7",
+ }
+ state = _pr_state(reviews=[review])
+ state_file = tmp_path / "state.json"
+ _seeded_state(
+ state_file,
+ review_fingerprints={"7": wait_pr._review_fingerprint(review)},
+ snapshot=_snapshot(state),
+ )
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", lambda *_args, **_kwargs: (state, 1))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--since-review-id",
+ "0",
+ "--state-file",
+ str(state_file),
+ "--settle",
+ "0",
+ ],
+ )
+
+ assert wait_pr.main() == 0
+ assert "review #7" in capsys.readouterr().out
+
+
+def test_skill_requires_actions_waiter_when_ci_is_the_only_gate():
+ skill = (Path(__file__).parents[1] / "SKILL.md").read_text()
+
+ assert "When CI is the sole" in skill
+ assert "must switch" in skill
+ assert "`wait_action.py`" in skill
+
+
+def test_initial_pr_request_retries_transient_timeout_then_succeeds(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ attempts = 0
+ activity = _pr_state(
+ issue_comments=[
+ {
+ "id": 1,
+ "body": "actionable",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/comment/1",
+ }
+ ]
+ )
+
+ def _fetch(*_args, **_kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise TimeoutError("socket timed out")
+ if attempts == 2:
+ raise urllib.error.HTTPError(
+ "https://api.github.com",
+ 503,
+ "Service Unavailable",
+ None,
+ None,
+ )
+ return activity, 1
+
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", _fetch)
+ monkeypatch.setattr(wait_pr.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--catch-up",
+ "--state-file",
+ str(tmp_path / "state.json"),
+ ],
+ )
+
+ assert wait_pr.main() == 0
+ assert attempts == github_wait_common.INITIAL_REQUEST_MAX_ATTEMPTS
+ assert "issue_comment #1" in capsys.readouterr().out
+
+
+def test_initial_action_request_exits_after_transient_retry_budget(monkeypatch, capsys):
+ attempts = 0
+
+ def _fetch(*_args, **_kwargs):
+ nonlocal attempts
+ attempts += 1
+ raise TimeoutError("socket timed out")
+
+ monkeypatch.setattr(wait_action, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_action, "_fetch_workflow_runs", _fetch)
+ monkeypatch.setattr(wait_action.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(ACTION_SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--sha",
+ "head",
+ "--workflow",
+ "lint",
+ ],
+ )
+
+ assert wait_action.main() == 1
+ assert attempts == github_wait_common.INITIAL_REQUEST_MAX_ATTEMPTS
+ assert "failed after 3 attempts" in capsys.readouterr().err
+
+
+def test_terminal_graphql_errors_exit_after_one_response(monkeypatch, tmp_path, capsys):
+ fetches = 0
+ responses = 0
+
+ class _Response:
+ headers = {}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def read(self):
+ nonlocal responses
+ responses += 1
+ return json.dumps({"errors": [{"message": "forbidden"}]}).encode()
+
+ def _fetch(*_args, **_kwargs):
+ nonlocal fetches
+ fetches += 1
+ if fetches == 1:
+ return _pr_state(), 1
+ github_wait_common.github_graphql("query", {}, "token")
+ raise AssertionError("terminal GraphQL response did not stop the fetch")
+
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", _fetch)
+ monkeypatch.setattr(wait_pr.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(github_wait_common.urllib.request, "urlopen", lambda *_args, **_kwargs: _Response())
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--state-file",
+ str(tmp_path / "state.json"),
+ "--settle",
+ "0",
+ ],
+ )
+
+ assert wait_pr.main() == 1
+ assert fetches == 2
+ assert responses == 1
+ assert "GitHub GraphQL error" in capsys.readouterr().err
+
+
+def test_transient_polling_failure_recovers(monkeypatch, tmp_path, capsys):
+ fetches = 0
+ activity = _pr_state(
+ issue_comments=[
+ {
+ "id": 1,
+ "body": "actionable",
+ "user": {"login": "reviewer"},
+ "html_url": "https://example.invalid/comment/1",
+ }
+ ]
+ )
+
+ def _fetch(*_args, **_kwargs):
+ nonlocal fetches
+ fetches += 1
+ if fetches == 1:
+ return _pr_state(), 1
+ if fetches == 2:
+ raise TimeoutError("socket timed out")
+ return activity, 1
+
+ monkeypatch.setattr(wait_pr, "get_token", lambda: "token")
+ monkeypatch.setattr(wait_pr, "_fetch_state", _fetch)
+ monkeypatch.setattr(wait_pr.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ str(SCRIPT),
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "1213",
+ "--include-self-comments",
+ "--state-file",
+ str(tmp_path / "state.json"),
+ "--settle",
+ "0",
+ ],
+ )
+
+ assert wait_pr.main() == 0
+ assert fetches == 3
+ captured = capsys.readouterr()
+ assert "Retryable GitHub request failure" in captured.err
+ assert "issue_comment #1" in captured.out
+
+
+def _call_name(node):
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ prefix = _call_name(node.value)
+ return f"{prefix}.{node.attr}" if prefix else node.attr
+ return ""
+
+
+def test_github_request_taxonomy_is_the_only_exception_boundary():
+ scripts = (COMMON_SCRIPT, SCRIPT, ACTION_SCRIPT)
+ allowed_broad_handlers = {"github_request", "_read_github_json"}
+ operation_names = {
+ "_fetch_new_pr_state",
+ "_fetch_state",
+ "_fetch_workflow_runs",
+ "_validate_target",
+ "resolve_authenticated_login",
+ }
+ policy_names = {"github_request", "retry_initial_request"}
+ raw_request_names = {"github_get", "github_graphql"}
+ violations = []
+ urlopen_sites = []
+
+ for path in scripts:
+ tree = ast.parse(path.read_text())
+ parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
+
+ def _ancestor_function(node):
+ current = parents.get(node)
+ while current is not None:
+ if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ return current.name
+ current = parents.get(current)
+ return None
+
+ def _has_policy_ancestor(node):
+ current = parents.get(node)
+ while current is not None:
+ if isinstance(current, ast.Call) and _call_name(current.func) in policy_names:
+ return True
+ current = parents.get(current)
+ return False
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ExceptHandler):
+ caught = _call_name(node.type) if node.type is not None else "bare"
+ if caught in {"bare", "Exception", "BaseException"}:
+ owner = _ancestor_function(node)
+ if owner not in allowed_broad_handlers:
+ violations.append(f"{path.name}:{node.lineno} broad catch in {owner}")
+ if not isinstance(node, ast.Call):
+ continue
+ name = _call_name(node.func)
+ if name.endswith("urlopen"):
+ urlopen_sites.append((path.name, _ancestor_function(node)))
+ if name in operation_names and not _has_policy_ancestor(node):
+ violations.append(f"{path.name}:{node.lineno} {name} bypasses request policy")
+ if name in raw_request_names:
+ current = parents.get(node)
+ while current is not None and not isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if isinstance(current, ast.Try):
+ violations.append(f"{path.name}:{node.lineno} {name} has a local except")
+ break
+ current = parents.get(current)
+
+ assert violations == []
+ assert urlopen_sites == [(COMMON_SCRIPT.name, "_read_github_json")]
diff --git a/AGENTS.md b/AGENTS.md
index 32a23a176..e0dccff55 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -175,22 +175,23 @@ Source-of-truth rule:
### Review Loop for PRs
-- the rules in this section are the self-sufficient baseline for every PR; a
- fuller implementation-lane standard (roles and authority, contracts,
- close-out details) lives in the multi-repo workspace at
- `~/vibe-remote-project/.agents/skills/pr-delivery-loop/SKILL.md` — follow it
- whenever that workspace file is available in your environment
+- the rules in this section are the self-sufficient baseline for every PR; use
+ the `pr-delivery-loop` skill for every implementation task to apply the fuller
+ standard for roles, authority, contracts, and close-out
- open PRs non-draft; draft PRs do not trigger the Codex bot review
- the GitHub Codex bot is the review gate: after every push confirm a review
of the new head starts, comment `@codex review` if none appears, and treat a
trigger as accepted only once the bot reacts 👀 to that comment
-- a bot pass is a plain issue comment naming the reviewed commit; close-out
- requires zero unresolved review threads on the current head, not just a
- 0-finding latest review
-- after opening a PR, use the `background-watch-hook` skill to keep a
- review-fix loop running until the review passes; use its bundled
- `wait_pr.py` / `wait_action.py`, never hand-rolled waiters, and create the
- watch immediately without waiting to be reminded
+- a bot pass is either an authenticated Codex-bot issue comment with the pass
+ phrase and exact reviewed commit, or a head-bound Codex-bot `+1` captured as
+ new waiter activity after the prior review was terminal; close-out requires
+ zero unresolved review threads across the entire PR, including earlier and
+ outdated heads, not just a 0-finding latest review
+- after opening a PR, use the repo-local `pr-delivery-loop` waiter to keep a
+ review-fix loop running until the review passes; use
+ `.agents/skills/pr-delivery-loop/scripts/wait_pr.py` /
+ `.agents/skills/pr-delivery-loop/scripts/wait_action.py`, never hand-rolled
+ waiters, and create the watch immediately without waiting to be reminded
- PR descriptions must name the changed capability, list affected scenario IDs
when a catalog exists, and state which evidence layers were updated: unit,
contract, scenario, and residual manual checks