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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
chore(agent): separate PR policy from background watchers (#1285)
Call White6e0ac9d9d4af
diff --git a/.agents/skills/pr-delivery-loop/SKILL.md b/.agents/skills/pr-delivery-loop/SKILL.mdindex 1a92f1128..868e1e443 100644--- a/.agents/skills/pr-delivery-loop/SKILL.md+++ b/.agents/skills/pr-delivery-loop/SKILL.md@@ -10,19 +10,24 @@ description: The implementation-lane standard for delivering a PR across the Avi- 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.+ file at the same repo-relative path. Do not copy watcher implementations or+ their tests into this skill.- In the multi-repo workspace, the project-level skill entry is a symlink tothe Avibe copy. Update the canonical copy first, then sync every repository- copy in the same change.+ copy only after the canonical Avibe change passes review.++## Dependency boundary++- Use the `background-watch-hook` skill for every managed wait. It owns the+ reusable `vibe watch` workflow and the GitHub PR, issue, and Actions waiter+ implementations.+- This skill owns Avibe-specific delivery policy: branch and scope rules,+ review and CI gates, thread resolution, circuit breaking, authority, and+ close-out criteria.+- Refer to the dependency by skill name. Do not hard-code an installation path,+ vendor its scripts here, or hand-roll a replacement waiter. If+ `background-watch-hook` is unavailable, install or enable it before starting+ a review loop, or report the missing dependency as a blocker.## Roles & authority@@ -131,9 +136,8 @@ description: The implementation-lane standard for delivering a PR across the Avi- Run the smallest relevant local validation: focused tests for what youtouched, 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.+ and any repository-specific required checks. 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@@ -180,97 +184,41 @@ turn ends because you armed a watch and are waiting, say exactly that.the fact — look for a current-head verdict instead.- Liveness invariant: at every pause there is either a pending bot review ofthe 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.+- Use `background-watch-hook` to create a one-shot PR watch for each review+ phase; never use `--forever` for a delivery loop. Re-arm after every round.+ When CI is the only remaining gate, replace the PR-activity watch with an+ exact-head Actions watch because PR activity cannot wake on a check-only+ transition.- 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+ watch per PR, plus one independent orchestrator gate watch when work is+ delegated. Each concern needs independent waiter state. Never share cursor+ state between concurrent watches or count unrelated global monitors as thelane 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.+- Follow `background-watch-hook` for waiter commands, state, baseline seeding,+ catch-up,+ filtering, settling, retries, and delivery acknowledgement. Those mechanics+ belong to the reusable skill; this policy only constrains when and why the+ watch is armed.- Arm the fresh watch only AFTER your reply-then-resolve batch is pushed andsettled: your own thread resolutions count as "review activity" to a watcharmed 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.+ the real next review lands with nobody watching. End every round by using the+ `background-watch-hook` management commands to verify exactly one live watch+ for this owner, concern, repository, and PR. Do not rely on a remembered watch+ ID or one bookkeeping field as proof that its waiter is live.+- Before a push or review trigger, use `background-watch-hook` to seed a complete+ owner-specific state file. Arm the post-action watch with that same file so+ activity that lands during the handoff is delivered. Use catch-up only when+ deliberately processing historical activity; a first-poll baseline after the+ action is not a valid review-loop handoff.+- A watch you remove while handling its event is not a liveness break: the+ running turn owns progress until the replacement is armed. Re-arm after the+ push and close-out actions, then verify the invariant again.- For whoever gates the PR: a lane run that ended `succeeded` proves nothingabout the loop. A watch-triggered run can finish clean having pushed nothingand 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.+ side. When your gate watch fires on a findings review, verify the lane still+ has a live PR watch before concluding it has the round handled.- The bot has three verdict shapes. A PASS is either (a) a plain issue commentby the Codex bot (`chatgpt-codex-connector` in the API; often displayed as`chatgpt-codex-connector[bot]`) whose body says@@ -283,15 +231,12 @@ turn ends because you armed a watch and are waiting, say exactly that.run identity; do not declare CI complete while a second matching run ispending 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.+ new head, establish the current activity baseline through+ `background-watch-hook`, and do not push another head while the new review is+ pending. Accept the reaction only when that watch reports it as new for the+ current review phase, the prior-head review was already terminal, and the PR+ head is unchanged. If those facts cannot be established, require the+ bot-authored exact-head pass comment instead.- Keep reaction meanings distinct: 👀 only says a trigger was picked up; theCodex bot's PR-body `+1` says the review completed without comments. Reactionsfrom other authors or on other comments are not verdicts.@@ -416,9 +361,9 @@ 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.+ per PR through `background-watch-hook`, with the follow-up in your session and+ 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 anddiff --git a/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.py b/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.pydeleted file mode 100644index 5804c54df..000000000--- a/.agents/skills/pr-delivery-loop/scripts/_github_wait_common.py+++ /dev/null@@ -1,395 +0,0 @@-#!/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 requestsdiff --git a/.agents/skills/pr-delivery-loop/scripts/wait_action.py b/.agents/skills/pr-delivery-loop/scripts/wait_action.pydeleted file mode 100755index b4440604c..000000000--- a/.agents/skills/pr-delivery-loop/scripts/wait_action.py+++ /dev/null@@ -1,364 +0,0 @@-#!/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.pydeleted file mode 100755index 07ae82d0e..000000000--- a/.agents/skills/pr-delivery-loop/scripts/wait_pr.py+++ /dev/null@@ -1,2344 +0,0 @@-#!/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.pydeleted file mode 100644index f174dda6a..000000000--- a/.agents/skills/pr-delivery-loop/tests/test_wait_pr.py+++ /dev/null@@ -1,1071 +0,0 @@-"""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.mdindex e0dccff55..45345d169 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -187,11 +187,10 @@ Source-of-truth rule:new waiter activity after the prior review was terminal; close-out requireszero unresolved review threads across the entire PR, including earlier andoutdated 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+- after opening a PR, use the `background-watch-hook` skill to keep a+ review-fix loop running until the review passes; use that skill's bundled PR+ and Actions waiters rather than hand-rolling one, and create the watch+ immediately without waiting to be reminded- PR descriptions must name the changed capability, list affected scenario IDswhen a catalog exists, and state which evidence layers were updated: unit,contract, scenario, and residual manual checksdiff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdindex a4371c176..f525eb0f3 100644--- a/skills/background-watch-hook/SKILL.md+++ b/skills/background-watch-hook/SKILL.md@@ -2,7 +2,7 @@name: background-watch-hookslug: background-watch-hookdescription: Use `vibe watch` to run a managed Harness waiter that returns to the same conversation later. Best for reviews, CI, files, logs, and other wait-now-continue-later workflows.-version: 0.11.7+version: 0.13.0---# Background Watch Hook@@ -177,7 +177,40 @@ This skill ships bundled GitHub waiters:Use bundled waiters as examples or as ready-to-run building blocks. The main skill is still `vibe watch`; the waiter is only the thing that blocks until the condition is met.When running a bundled script through `uv`, prefer `uv run --no-project ...` so the script does not accidentally attach itself to an unrelated parent project.-Bundled GitHub waiters use exit code `75` for retryable startup errors such as temporary network failures or GitHub `408/429/5xx` responses, and exit code `64` with the `avibe-watch: no-event` marker when a cycle finished with nothing worth an Agent turn.+Bundled GitHub waiters classify temporary network failures and GitHub+`408/429/5xx` responses as retryable. The one-shot PR and Actions waiters retry+those failures inside the same process so the managed watch stays alive. A+cycle-oriented waiter may use exit code `75` only when its supervisor explicitly+opts into retrying that code. Exit code `64` with the+`avibe-watch: no-event` marker means a cycle finished with nothing worth an Agent+turn.++The waiter is distributed with this skill, not with the caller's repository.+Resolve the active skill directory before constructing a watch command:++```bash+BACKGROUND_WATCH_HOOK_SKILL_FILE="${BACKGROUND_WATCH_HOOK_SKILL_FILE:-}"+if [ -z "$BACKGROUND_WATCH_HOOK_SKILL_FILE" ]; then+ REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"+ for SKILL_FILE in \+ "$REPO_ROOT/skills/background-watch-hook/SKILL.md" \+ "$REPO_ROOT/.agents/skills/background-watch-hook/SKILL.md"; do+ if [ -f "$SKILL_FILE" ]; then+ BACKGROUND_WATCH_HOOK_SKILL_FILE="$SKILL_FILE"+ break+ fi+ done+fi+if [ -z "$BACKGROUND_WATCH_HOOK_SKILL_FILE" ]; then+ for SKILL_ROOT in "${CODEX_HOME:-$HOME/.codex}/skills" "${AGENTS_HOME:-$HOME/.agents}/skills"; do+ [ -d "$SKILL_ROOT" ] || continue+ BACKGROUND_WATCH_HOOK_SKILL_FILE="$(find "$SKILL_ROOT" -path '*/background-watch-hook/SKILL.md' -print -quit)"+ [ -n "$BACKGROUND_WATCH_HOOK_SKILL_FILE" ] && break+ done+fi+test -f "$BACKGROUND_WATCH_HOOK_SKILL_FILE"+BACKGROUND_WATCH_HOOK_DIR="$(dirname "$BACKGROUND_WATCH_HOOK_SKILL_FILE")"+```## GitHub Example Waiter@@ -186,18 +219,31 @@ Use the bundled GitHub waiter only when the watched thing is PR review activity.One-shot watch:```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state++# Push or post the review trigger only after the baseline is durable.vibe watch add \--name "Watch PR 151 reviews" \--message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \-- \- uv run --no-project scripts/wait_pr.py \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \--repo avibe-bot/avibe \--pr 151 \--actionable-only \--settle 20 \+ --state-file "$STATE_FILE" \--interval 60```+Before a push or review trigger, seed an owner-specific state file from the+current complete PR snapshot. Arm the post-action watch with that exact file so+activity that lands during the handoff remains visible.++Use `--catch-up` only when deliberately processing historical activity. It is+not a substitute for the pre-action baseline in a review loop.+Prefer `--actionable-only` for review loops. Without it the waiter wakes the Agentfor every comment on the PR, including the `@codex review` triggers the loop itselfposts and the bodyless `COMMENTED` review envelope GitHub wraps around inline@@ -207,7 +253,10 @@ is everything the review loop needs to make progress or close out.Narrow it further with `--ignore-author <login>` and `--ignore-comment-pattern <regex>`(both repeatable). Filtered items still advance the cursors, so they are examined-once and never re-reported.+once and never re-reported. These filters suppress review/comment payloads, not+review-thread status. A thread becoming unresolved or resolved remains an+independent wake signal because thread state is a separate mutable resource and+may later be changed by a different actor.`--settle <seconds>` is worth setting on any review loop. A bot review arrives as aburst of inline comments plus an envelope, so the poll that happens to catch the@@ -222,19 +271,25 @@ lost to the timeout kill. Keep `--settle` well under `--timeout`.Catch up on existing activity first:```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-catch-up.json"vibe watch add \--name "Catch up PR 151 reviews" \--message "PR #151 already has review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \-- \- uv run --no-project scripts/wait_pr.py \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \--repo avibe-bot/avibe \--pr 151 \+ --state-file "$STATE_FILE" \--catch-up```Stay armed for future activity:```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-forever.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state+vibe watch add \--name "Monitor PR 151 reviews" \--forever \@@ -242,28 +297,37 @@ vibe watch add \--lifetime-timeout 86400 \--message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \-- \- uv run --no-project scripts/wait_pr.py \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \--repo avibe-bot/avibe \--pr 151 \--actionable-only \--settle 20 \- --state-file ~/.avibe/state/watch-cursors/pr-151.json \+ --state-file "$STATE_FILE" \--interval 60```Always pass `--state-file` to a `--forever` watch. Each cycle is a fresh waiterprocess, so without it the next cycle re-snapshots the PR as its baseline andanything that arrived between the previous cycle's exit and that snapshot is lost.-The file also carries the `since` filters and the resolved GitHub login forward, so-a resumed cycle asks GitHub only for what is new instead of re-reading the whole PR.+The file carries the resolved GitHub login and the complete mutable PR baseline+forward. PR cycles reread complete review/comment/thread collections because+edits, deletions, and thread-resolution changes are wake-worthy state.+For an ordinary wait, that normalized complete snapshot is the single wake/no-wake+decision. Numeric cursors, fingerprints, and the thread map only describe a detected+change; they cannot wake independently. `--catch-up` and explicit `--since-*-id`+flags are the deliberate replay modes and therefore remain cursor-driven. A legacy+state file with cursors but no complete snapshot is rejected until it is deliberately+caught up or reseeded, rather than silently absorbing mutable changes.The login is reused only while the token still fingerprints to the account it was-resolved for, and an explicit `--since-review-comment-id` /-`--since-issue-comment-id` drops the matching saved `since` so the replay it asks-for is not narrowed away. It is written on every cursor advance and on timeout,-replaced atomically. Cursors that cover a reported event are not committed by the+resolved for. Explicit cursor flags still request a replay from that cursor, while+the complete PR collections remain the source of truth for edits and removals. The+state also records the last observed PR head, review/comment fingerprints, and every+review-thread resolution state, so a pushed head, edited object, deletion, or thread+transition is activity even when no new numeric ID exists. Cursors that cover a reported event are not committed by thecycle that reports it. A waiter cannot observe its own delivery — `vibe watch` readsits stdout only after the process exits — so those cursors are staged under `pending`-while the committed ones stay before the event, together with the value of+while the committed ones stay before the event, together with the rendered report+and the value of`AVIBE_WATCH_LAST_DELIVERY` the cycle started from. That variable is when this watchlast had a report durably queued, stamped in the same transaction as the follow-up, soany later cycle that reads a *different* value knows the report was delivered and@@ -314,32 +378,43 @@ GitHub-specific notes:- `--catch-up` reports activity that already exists at startup, and overrides savedcursors when a state file is present; an explicit `--since-*-id` still wins- without `--catch-up` or a `--state-file`, the waiter snapshots current PR activity as the baseline-- polling is cheap by design: comment fetches are filtered server-side with `since`,- reactions with `content=+1`, and unchanged pages revalidate to `304`, which GitHub- does not charge against the rate limit — an idle watch can poll for hours for free-- PR activity also includes the special case where `chatgpt-codex-connector[bot]` leaves a `+1` reaction on the PR body instead of posting a comment+- polling is cheap by design: mutable review/comment collections are fetched in full+ so edits and deletions remain observable, reactions are filtered server-side with+ `content=+1`, and unchanged pages revalidate to `304`, which GitHub does not charge+ against the rate limit — an idle watch can poll for hours for free+- PR activity also includes the special case where `chatgpt-codex-connector` or+ `chatgpt-codex-connector[bot]` leaves a `+1` reaction on the PR body instead of+ posting a comment; pass reactions remain visible even when `--event-limit` is+ reached- PR activity also includes lifecycle changes on the PR itself, for example draft/ready, closed, reopened, or merged transitions+- a changed PR head is reported as activity so a new push cannot leave the review+ loop asleep- self-authored comments are ignored by default when the current authenticated GitHub user can be resolved; pass `--include-self-comments` to keep them- authentication is preferred; unauthenticated polling is slower and more fragileNew PRs in a repository:```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/new-prs-avibe.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --new-prs --state-file "$STATE_FILE" --seed-state+vibe watch add \--name "Watch new PRs" \--message "The repository has new pull requests. Review the new PRs and continue as needed." \-- \- uv run --no-project scripts/wait_pr.py \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \--repo avibe-bot/avibe \--new-prs \+ --state-file "$STATE_FILE" \--interval 60```New issues or issue comments:```bash-uv run --no-project scripts/wait_issue.py --repo avibe-bot/avibe --new-issues --interval 60-uv run --no-project scripts/wait_issue.py --repo avibe-bot/avibe --issue 157 --interval 60+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --new-issues --interval 60+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --issue 157 --interval 60```GitHub Actions for a pushed commit:@@ -349,23 +424,20 @@ vibe watch add \--name "Watch CI" \--message "GitHub Actions failed. Inspect the result below and fix the failures. Then summarise the round here in one or two lines -- what failed and what you changed. Save a longer message for the build going green, the loop being blocked, or a decision that needs the user." \-- \- uv run --no-project scripts/wait_action.py \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_action.py" \--repo cyhhao/sub2api \--branch main \--sha "$HEAD_SHA" \--workflow CI \--workflow "Security Scan" \- --only-on-failure \--interval 60```-`--only-on-failure` exits `64` with the no-event marker when every watched workflow succeeded, so a green-build ends the watch silently instead of spending an Agent turn to say so. The-full summary still goes to `stderr`, which the supervisor records in the Avibe log-(`~/.avibe/logs/vibe_remote.log`) beside the watch id; `vibe watch show` reports-that the cycle ran and found nothing, not the summary itself.-Drop the flag when the follow-up should also run on success, for example when a-green build is supposed to trigger a deploy.+For a merge gate, omit `--only-on-failure`: a successful exact-head build must+wake the Agent so it can perform the final gate and close out the watch. Use+`--only-on-failure` only when a green result intentionally needs no follow-up;+that mode exits `64` with the no-event marker and records the summary in the+Avibe watch log instead of creating an Agent turn.## Practical Advicediff --git a/skills/background-watch-hook/scripts/_github_wait_common.py b/skills/background-watch-hook/scripts/_github_wait_common.pyindex 61000c321..52e0d48ff 100644--- a/skills/background-watch-hook/scripts/_github_wait_common.py+++ b/skills/background-watch-hook/scripts/_github_wait_common.py@@ -9,10 +9,11 @@ import osimport shutilimport subprocessimport sys+import timeimport urllib.errorimport urllib.requestfrom datetime import datetime, timedelta-from typing import Any+from typing import Any, Callable, Generic, TypeVarRETRY_EXIT_CODE = 75@@ -44,6 +45,8 @@ LAST_DELIVERY_ENV = "AVIBE_WATCH_LAST_DELIVERY"# is allowed to block for 30.REQUEST_TIMEOUT_SECONDS = 30RETRYABLE_HTTP_STATUS_CODES = {408, 429, 500, 502, 503, 504}+INITIAL_REQUEST_MAX_ATTEMPTS = 3+INITIAL_REQUEST_BACKOFF_SECONDS = 1.0NOT_MODIFIED_STATUS = 304# GitHub compares timestamps at one-second resolution, and a bot that posts a# review as a batch stamps several comments within the same second. Rewinding the@@ -52,6 +55,126 @@ NOT_MODIFIED_STATUS = 304SINCE_REWIND_SECONDS = 2_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 response that violates the expected GitHub contract."""+++class InitialRequestRetriesExhausted(GitHubTerminalError):+ """A bounded initial GitHub request exhausted its transient retries."""+++class GitHubRequestResult(Generic[_T]):+ """One classified request outcome; callers never catch request exceptions."""++ __slots__ = ("error", "value")++ def __init__(+ self,+ *,+ value: _T | None = None,+ error: GitHubRequestError | None = None,+ ) -> None:+ self.value = value+ self.error = error++ @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],+ *,+ unauthenticated: bool = False,+) -> GitHubRequestResult[_T]:+ """Run one GitHub operation through the 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, unauthenticated=unauthenticated)+ )+++def retry_initial_request(+ operation: Callable[[], _T],+ *,+ description: str,+ unauthenticated: bool = False,+) -> GitHubRequestResult[_T]:+ """Retry initial network and retryable HTTP failures with bounded backoff."""++ for attempt in range(1, INITIAL_REQUEST_MAX_ATTEMPTS + 1):+ result = github_request(operation, unauthenticated=unauthenticated)+ 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:@@ -68,7 +191,7 @@ def no_event(summary: str = "") -> int:def get_token() -> str | None:- for env_name in ("GITHUB_TOKEN", "GH_TOKEN"):+ for env_name in ("GH_TOKEN", "GITHUB_TOKEN"):value = os.environ.get(env_name)if value:return value@@ -170,6 +293,28 @@ def github_get(url: str, token: str | None, *, cache: ResponseCache | None = Nonraise+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}")+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:+ payload = json.loads(response.read().decode("utf-8"))+ if not isinstance(payload, dict):+ raise RuntimeError("GitHub GraphQL returned an unexpected payload")+ if payload.get("errors"):+ raise RuntimeError(f"GitHub GraphQL error: {payload['errors']}")+ data = payload.get("data")+ if not isinstance(data, dict):+ raise RuntimeError("GitHub GraphQL response has no data object")+ return data++def latest_timestamp(items: list[dict[str, Any]]) -> str | None:"""Newest ``updated_at``/``created_at`` across items.@@ -219,19 +364,31 @@ def is_retryable_http_error(err: urllib.error.HTTPError) -> bool:return code in RETRYABLE_HTTP_STATUS_CODES-def get_authenticated_login(token: str | None) -> str | None:+def get_authenticated_login(+ token: str | None,+ *,+ raise_on_error: bool = False,+) -> str | None:if not token:return Nonetry:payload = github_get("https://api.github.com/user", token)except Exception:+ if raise_on_error:+ raisereturn Noneif not isinstance(payload, dict):+ if raise_on_error:+ raise GitHubProtocolError("GitHub viewer response is not an object")return Nonelogin = payload.get("login")- return str(login) if isinstance(login, str) and login else None+ if isinstance(login, str) and login:+ return login+ if raise_on_error:+ raise GitHubProtocolError("GitHub viewer response has no login")+ return Nonedef list_paginated(diff --git a/skills/background-watch-hook/scripts/wait_action.py b/skills/background-watch-hook/scripts/wait_action.pyindex 8571b1549..a8f798586 100755--- a/skills/background-watch-hook/scripts/wait_action.py+++ b/skills/background-watch-hook/scripts/wait_action.py@@ -7,7 +7,6 @@ import argparseimport jsonimport sysimport time-import urllib.errorimport urllib.parsefrom pathlib import Pathfrom typing import Any@@ -19,12 +18,12 @@ if str(SCRIPT_DIR) not in sys.path:from _github_wait_common import ( # noqa: E402NO_EVENT_EXIT_CODE,NO_EVENT_MARKER,- RETRY_EXIT_CODE,get_token,github_get,- is_retryable_http_error,+ github_request,min_interval_for_unauthenticated,no_event,+ retry_initial_request,)DEFAULT_SUCCESS_CONCLUSIONS = {"success", "skipped", "neutral"}@@ -80,9 +79,16 @@ def _select_latest_runs_by_workflow(workflows: list[str],branch: str | None,head_sha: str,-) -> dict[str, dict[str, Any] | None]:+) -> dict[str, list[dict[str, Any]]]:+ """Return every distinct matching run, not just the newest rerun.++ A rerun does not replace the earlier run for merge-gate purposes: an older+ failure or pending run at the same SHA remains a real result to inspect.+ """+workflow_set = set(workflows)- result: dict[str, dict[str, Any] | None] = {workflow: None for workflow in workflows}+ result: dict[str, list[dict[str, Any]]] = {workflow: [] for workflow in workflows}+ seen_ids: dict[str, set[int]] = {workflow: set() for workflow in workflows}normalized_sha = head_sha.casefold()for run in sorted(runs, key=_run_sort_key):@@ -93,7 +99,12 @@ def _select_latest_runs_by_workflow(continueif branch and str(run.get("head_branch") or "") != branch:continue- result[name] = run+ run_id = run.get("id")+ if isinstance(run_id, int) and run_id in seen_ids[name]:+ continue+ if isinstance(run_id, int):+ seen_ids[name].add(run_id)+ result[name].append(run)return result@@ -113,49 +124,50 @@ def _render_actions_result(repo: str,branch: str | None,head_sha: str,- selected: dict[str, dict[str, Any] | None],+ selected: dict[str, list[dict[str, Any]]],success_conclusions: set[str],) -> tuple[str | None, bool]:- missing = [workflow for workflow, run in selected.items() if run is None]+ missing = [workflow for workflow, runs in selected.items() if not runs]running = [workflow- for workflow, run in selected.items()- if run is not None and str(run.get("status") or "") != TERMINAL_STATUS+ 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, Falsefailed = [workflow- for workflow, run in selected.items()- if run is not None and str(run.get("conclusion") or "") not in success_conclusions+ 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:- run = selected[workflow]- if run is not None:+ 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, dict[str, Any] | None]) -> None:+def _write_cursor_output(path: str | None, *, selected: dict[str, list[dict[str, Any]]]) -> None:if not path:returnpayload = {- workflow: {- "id": run.get("id"),- "status": run.get("status"),- "conclusion": run.get("conclusion"),- "html_url": run.get("html_url"),- }- for workflow, run in selected.items()- if run is not None+ workflow: [+ {+ "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()}with open(path, "w", encoding="utf-8") as handle:json.dump(payload, handle)@@ -225,7 +237,7 @@ def main() -> int:effective_interval = base_intervalsuccess_conclusions = _parse_success_conclusions(args.success_conclusion)start = time.monotonic()- selected: dict[str, dict[str, Any] | None] = {workflow: None for workflow in args.workflow}+ selected: dict[str, list[dict[str, Any]]] = {workflow: [] for workflow in args.workflow}first_successful_fetch = Trueprint(@@ -240,40 +252,40 @@ def main() -> int:while True:first_poll = poll_attempt == 0poll_attempt += 1- try:- runs, request_count = _fetch_workflow_runs(++ def _fetch_runs() -> tuple[list[dict[str, Any]], int]:+ return _fetch_workflow_runs(args.repo,token,branch=args.branch,head_sha=args.sha,max_pages=args.max_pages,)- except urllib.error.HTTPError as err:- if first_poll:- print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)- return RETRY_EXIT_CODE if is_retryable_http_error(err) else 1- if token is None and err.code in {403, 429}:- print(- (- "GitHub unauthenticated polling hit a rate limit. "- "Authenticate with 'gh auth login' or GITHUB_TOKEN/GH_TOKEN."- ),- file=sys.stderr,- )- return 1- print(f"GitHub API error during polling: {err.code} {err.reason}", file=sys.stderr)- runs = []- except urllib.error.URLError as err:- print(f"GitHub network error: {err.reason}", file=sys.stderr)- if first_poll:- return RETRY_EXIT_CODE- runs = []- except Exception as err: # noqa: BLE001- print(f"Polling failed: {err}", file=sys.stderr)- if first_poll:++ request_result = (+ retry_initial_request(+ _fetch_runs,+ description="initial GitHub Actions request",+ unauthenticated=token is None,+ )+ if first_poll+ else github_request(_fetch_runs, unauthenticated=token is None)+ )+ 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.valueif token is None and request_count > 0:bootstrap_requests = request_count if first_successful_fetch else 0@@ -329,11 +341,11 @@ def main() -> int:print(output)return 0- missing = [workflow for workflow, run in selected.items() if run is None]+ missing = [workflow for workflow, runs in selected.items() if not runs]running = [workflow- for workflow, run in selected.items()- if run is not None and str(run.get("status") or "") != TERMINAL_STATUS+ 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)diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.pyindex 05e79ee42..fa018a808 100755--- a/skills/background-watch-hook/scripts/wait_pr.py+++ b/skills/background-watch-hook/scripts/wait_pr.py@@ -11,7 +11,6 @@ import reimport sysimport tempfileimport time-import urllib.errorimport urllib.parsefrom contextlib import contextmanagerfrom functools import partial@@ -32,7 +31,8 @@ from _github_wait_common import ( # noqa: E402get_authenticated_login,get_token,github_get,- is_retryable_http_error,+ github_graphql,+ github_request,LAST_DELIVERY_ENV,later_since,list_paginated,@@ -40,14 +40,17 @@ from _github_wait_common import ( # noqa: E402max_id,min_interval_for_unauthenticated,REQUEST_TIMEOUT_SECONDS,- RETRY_EXIT_CODE,+ retry_initial_request,requests_per_poll,ResponseCache,squash,WATCH_ID_ENV,)-CODEX_REVIEW_PASS_REACTION_USER = "chatgpt-codex-connector[bot]"+CODEX_REVIEW_PASS_REACTION_USERS = {+ "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@@ -77,10 +80,32 @@ STATE_CURSOR_KEYS = ("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):@@ -196,10 +221,30 @@ def _keep_item(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 == CODEX_REVIEW_PASS_REACTION_USER and content == CODEX_REVIEW_PASS_REACTION_CONTENT+ return author in CODEX_REVIEW_PASS_REACTION_USERS and content == CODEX_REVIEW_PASS_REACTION_CONTENTdef _format_reaction(reaction: dict[str, Any]) -> str:@@ -252,6 +297,46 @@ def _format_pr_status_event(pr: dict[str, Any], previous_status: str, current_st)+def _current_pr_head_sha(pr: dict[str, Any] | None) -> str:+ if not isinstance(pr, dict):+ return ""+ head = pr.get("head")+ if not isinstance(head, dict):+ return ""+ value = head.get("sha")+ return value if isinstance(value, str) else ""+++def _format_pr_head_event(pr: dict[str, Any], previous_sha: str, current_sha: str) -> str:+ pr_number = pr.get("number")+ url = pr.get("html_url") or ""+ return (+ f"- pr_head #{pr_number} {previous_sha[:12]} -> {current_sha[:12]}\n"+ " Pull request head changed; start a fresh exact-head review cycle.\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"++ return (+ f"- review_thread {thread_id} {_label(previous_resolved)} -> {_label(current_resolved)}\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"@@ -261,11 +346,202 @@ def _format_pull_request(pr: dict[str, Any]) -> str:return f"- pull_request #{pr_number} by {author} ({state})\n {title}\n {url}"-def _with_since(url: str, since: str | None) -> str:- if not since:- return url- separator = "&" if "?" in url else "?"- return f"{url}{separator}since={urllib.parse.quote(since)}"+def _item_fingerprint(item: dict[str, Any]) -> str:+ mutable = {+ key: item.get(key)+ for key in (+ "id",+ "body",+ "state",+ "submitted_at",+ "commit_id",+ "path",+ "line",+ "original_line",+ "side",+ "start_line",+ "start_side",+ "user",+ "updated_at",+ )+ }+ encoded = json.dumps(mutable, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(encoded.encode()).hexdigest()+++def _changed_items(+ items: list[dict[str, Any]],+ since_id: int,+ fingerprints: dict[str, str],+) -> list[dict[str, Any]]:+ """Return new or edited items while advancing fingerprints for this fetch."""++ changed: dict[int, dict[str, Any]] = {}+ for item in items:+ item_id = item.get("id")+ if not isinstance(item_id, int):+ continue+ key = str(item_id)+ fingerprint = _item_fingerprint(item)+ # A legacy cursor has no content baseline. Seed it silently; otherwise every+ # pre-existing item would look edited on the first run after the migration.+ previous = fingerprints.get(key)+ if item_id > since_id or (previous is not None and previous != fingerprint):+ changed[item_id] = item+ fingerprints[key] = fingerprint+ return sorted(+ changed.values(),+ key=lambda item: (str(item.get("updated_at") or item.get("created_at") or ""), int(item["id"])),+ )+++def _fingerprint_map(items: list[dict[str, Any]]) -> dict[str, str]:+ return {+ str(item["id"]): _item_fingerprint(item)+ for item in items+ if isinstance(item.get("id"), int) and not isinstance(item.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 complete gate-relevant state without volatile timestamps."""++ 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:+ raw_threads = state.get("review_threads")+ review_threads = _review_thread_state_map(raw_threads if isinstance(raw_threads, list) else [])+ 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 _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 RuntimeError("GitHub GraphQL response has no reviewThreads connection")+ nodes = connection.get("nodes")+ if not isinstance(nodes, list):+ raise RuntimeError("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 RuntimeError("GitHub GraphQL reviewThreads page has no endCursor")+ end_cursor = next_cursor+ return threads, request_countdef _fetch_state(@@ -289,13 +565,16 @@ def _fetch_state(token,cache=cache,)+ # PR state is a mutable snapshot: complete collections are required to detect+ # edits and removals. The legacy since arguments remain accepted so existing+ # callers do not break, but they intentionally do not narrow these requests.review_comments, review_comment_requests = list_paginated_with_count(- _with_since(f"{base_url}/pulls/{pr_number}/comments", review_comment_since),+ f"{base_url}/pulls/{pr_number}/comments",token,cache=cache,)issue_comments, issue_comment_requests = list_paginated_with_count(- _with_since(f"{base_url}/issues/{pr_number}/comments", issue_comment_since),+ f"{base_url}/issues/{pr_number}/comments",token,cache=cache,)@@ -307,6 +586,7 @@ def _fetch_state(token,cache=cache,)+ review_threads, review_thread_requests = _fetch_review_threads(repo, pr_number, token)return ({"pull_request": pull_request,@@ -314,8 +594,16 @@ def _fetch_state("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,+ (+ 1+ + review_requests+ + review_comment_requests+ + issue_comment_requests+ + reaction_requests+ + review_thread_requests+ ),)@@ -349,6 +637,13 @@ def _render_activity(reaction_cursor: int,pr_status: str,event_limit: int,+ previous_head_sha: str | None = None,+ snapshot: dict[str, Any] | 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,viewer_login: str | None = None,ignore_self_comments: bool = True,actionable_only: bool = False,@@ -357,22 +652,41 @@ def _render_activity() -> tuple[str | None, int, int, int, int, str]:ignored_authors = ignored_authors or set()ignore_patterns = ignore_patterns or []+ review_fingerprints = {} if review_fingerprints is None else review_fingerprints+ review_comment_fingerprints = (+ {} if review_comment_fingerprints is None else review_comment_fingerprints+ )+ issue_comment_fingerprints = (+ {} if issue_comment_fingerprints is None else issue_comment_fingerprints+ )+ 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"))- new_reviews = filter_new(state["reviews"], review_cursor)- new_review_comments = filter_new(state["review_comments"], review_comment_cursor)- new_issue_comments = filter_new(state["issue_comments"], issue_comment_cursor)+ current_head_sha = _current_pr_head_sha(state.get("pull_request"))+ new_reviews = _changed_items(state["reviews"], review_cursor, review_fingerprints)+ new_review_comments = _changed_items(+ state["review_comments"], review_comment_cursor, review_comment_fingerprints+ )+ new_issue_comments = _changed_items(+ state["issue_comments"], issue_comment_cursor, issue_comment_fingerprints+ )def _visible(items: list[dict[str, Any]]) -> list[dict[str, Any]]:- # Cursors advance over everything new; only the rendering is filtered, so a- # dropped item is dropped once and never re-examined on the next poll.- 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)- ]+ 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:@@ -385,29 +699,66 @@ def _render_activity(if _is_codex_pass_reaction(reaction)]has_pr_status_event = current_pr_status != pr_status-- if not (new_reviews or new_review_comments or new_issue_comments or new_reactions or has_pr_status_event):- return None, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status-- next_review_cursor = max(review_cursor, max_id(new_reviews))- next_review_comment_cursor = max(review_comment_cursor, max_id(new_review_comments))- next_issue_comment_cursor = max(issue_comment_cursor, max_id(new_issue_comments))+ has_head_event = bool(previous_head_sha and current_head_sha and previous_head_sha != current_head_sha)+ raw_threads = state.get("review_threads")+ current_thread_states = (+ _review_thread_state_map(raw_threads if isinstance(raw_threads, list) else [])+ if review_threads_available+ else dict(review_thread_states or {})+ )+ thread_changes = _review_thread_state_changes(current_thread_states, review_thread_states or {})+ 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+ snapshot_changed = snapshot is not None and current_snapshot != snapshot+ if snapshot is not None and not snapshot_changed:+ return (+ None,+ next_review_cursor,+ next_review_comment_cursor,+ next_issue_comment_cursor,+ next_reaction_cursor,+ next_pr_status,+ )+ if snapshot is None and not (+ new_reviews+ or new_review_comments+ or new_issue_comments+ or new_reactions+ or has_pr_status_event+ or has_head_event+ or thread_changes+ ):+ return None, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status+render_pr_status_event = has_pr_status_event and (not actionable_only or current_pr_status in ACTIONABLE_PR_STATUSES)- rendered_events: list[str] = []+ 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"], previous_head_sha, current_head_sha))if render_pr_status_event and isinstance(state.get("pull_request"), dict):- rendered_events.append(_format_pr_status_event(state["pull_request"], pr_status, current_pr_status))- rendered_events.extend(_format_review(review) for review in visible_reviews)- rendered_events.extend(_format_review_comment(comment) for comment in visible_review_comments)- rendered_events.extend(_format_issue_comment(comment) for comment in visible_issue_comments)- rendered_events.extend(_format_reaction(reaction) for reaction in new_reactions)-- if not rendered_events:+ required_events.append(_format_pr_status_event(state["pull_request"], pr_status, current_pr_status))+ if isinstance(state.get("pull_request"), dict):+ required_events.extend(+ _format_review_thread_event(state["pull_request"], *change)+ for change in 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 and not optional_events and snapshot_changed:+ required_events.append(+ "- pr_snapshot changed\n"+ " Gate-relevant PR state changed; re-evaluate the exact head, review verdict, "+ "and all unresolved threads."+ )+ if not required_events and not optional_events and not new_reactions:return (None,next_review_cursor,@@ -419,13 +770,18 @@ def _render_activity(lines = [f"GitHub PR activity detected for {repo}#{pr_number}"]- visible_limit = max(event_limit, 1)- for entry in rendered_events[:visible_limit]:+ 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(rendered_events)- if total_events > visible_limit:- lines.append(f"- {total_events - visible_limit} additional event(s) omitted")+ 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")+ # A Codex +1 is durable pass evidence, not ordinary overflow. Always append it+ # after the bounded optional batch so a busy review cannot hide the gate signal.+ lines.extend(_format_reaction(reaction) for reaction in new_reactions)return ("\n".join(lines),@@ -979,6 +1335,24 @@ def _write_state_file(pass+def _check_state_file_path(path: str | None) -> None:+ """Reject an unusable path without claiming it before remote validation."""++ if not path:+ return+ target = Path(path)+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ if target.exists() and not target.is_file():+ raise StatePersistenceError(f"Cannot write state file {path}: target is not a regular file")+ if target.parent.stat().st_mode & 0o222 == 0:+ raise StatePersistenceError(f"Cannot write state file {path}: parent directory is read-only")+ except StatePersistenceError:+ raise+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err++def _token_fingerprint(token: str | None) -> str | None:"""Which credentials a cached ``viewer_login`` was resolved under.@@ -1004,6 +1378,45 @@ def _saved_str(saved: dict[str, Any], key: str) -> str | None: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_id): fingerprint+ for item_id, fingerprint in value.items()+ if isinstance(fingerprint, str) and fingerprint+ }+++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_id): state for item_id, state in value.items() if isinstance(state, 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: list[str] = []+ 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.@@ -1014,6 +1427,18 @@ def _last_delivery() -> str | None: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],@@ -1023,8 +1448,9 @@ def _resolve_staged_state(pr_number: int | None,watch_identity: str | None,watch_id: str | None,-) -> dict[str, Any]:- """Promote or drop the cursors staged for an earlier cycle's report.+ return_replay: bool = False,+) -> dict[str, Any] | tuple[dict[str, Any], str | None]:+ """Promote acknowledged state or replay its persisted event payload.Promoted when the supervisor's last-delivery stamp has moved since the report wasstaged: the report was queued, so polling may start after it. Dropped when the@@ -1037,12 +1463,16 @@ def _resolve_staged_state(staged = saved.get(STAGED_KEY)if not isinstance(staged, dict):- return saved+ return (saved, None) if return_replay else savedcursors = staged.get("cursors")- # A staged block this waiter cannot read is dropped, not guessed at: replaying- # the report it covered costs a turn, promoting cursors of unknown reach loses- # whatever they skip.- delivered = isinstance(cursors, dict) and staged.get("delivered_after") != delivery+ 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) if return_replay else savedresolved = {key: value for key, value in saved.items() if key != STAGED_KEY}if delivered:@@ -1051,7 +1481,7 @@ def _resolve_staged_state(("An earlier report was delivered; advancing past it."if delivered- else "An earlier report was never delivered; reporting it again."+ else "Legacy pending state has no report payload; reconstructing from committed cursors."),file=sys.stderr,)@@ -1068,7 +1498,7 @@ def _resolve_staged_state(watch_id=watch_id,**fields,)- return resolved+ return (resolved, None) if return_replay else resolveddef _deliver(output: str) -> None:@@ -1142,18 +1572,29 @@ def _build_parser() -> argparse.ArgumentParser:parser.add_argument("--ignore-author",action="append",- help="GitHub login whose reviews and comments never trigger a follow-up; repeatable",+ help=(+ "GitHub login whose review/comment payloads never trigger a follow-up; repeatable. "+ "Independent review-thread status transitions remain visible"+ ),)parser.add_argument("--ignore-comment-pattern",action="append",- help="Case-insensitive regex; matching review/comment bodies never trigger a follow-up. Repeatable",+ help=(+ "Case-insensitive regex; matching review/comment payloads never trigger a follow-up. "+ "Independent review-thread status transitions remain visible. 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(+ "--seed-state",+ action="store_true",+ help="Write a complete current baseline to --state-file and exit without waiting",+ )parser.add_argument("--allow-unauthenticated",action="store_true",@@ -1165,7 +1606,6 @@ def _build_parser() -> argparse.ArgumentParser: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@@ -1180,6 +1620,40 @@ def main() -> int:except re.error as err:print(f"Invalid --ignore-comment-pattern: {err}", file=sys.stderr)return 2+ if args.seed_state and (not args.state_file or args.catch_up):+ print("--seed-state requires --state-file and cannot be combined with --catch-up", file=sys.stderr)+ return 2++ watch_identity = _watch_identity(args)+ watch_id = _managed_watch_id()+ delivery_stamp = _last_delivery()+ two_phase = watch_id is not None+ if args.seed_state and two_phase:+ print("--seed-state is a pre-watch command and cannot run as a managed watch", file=sys.stderr)+ return 2+ if two_phase and not args.state_file:+ print(+ "Managed PR watchers require an owner-specific --state-file; refusing to poll without durable state.",+ file=sys.stderr,+ )+ return 2+ _check_state_file_path(args.state_file)+ 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 preflight.",+ file=sys.stderr,+ )+ _deliver(replay_output)+ return 0+ token = get_token()if token is None and not args.allow_unauthenticated:print((@@ -1191,13 +1665,91 @@ def main() -> int:)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+ token_fingerprint = _token_fingerprint(token)+ 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: get_authenticated_login(token, raise_on_error=True),+ description="GitHub viewer lookup",+ unauthenticated=token is None,+ )+ 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 token is not None and not viewer_login:+ print(+ "Could not resolve the authenticated GitHub login; refusing to poll while self-comment filtering is enabled.",+ file=sys.stderr,+ )+ return 1++ base_interval = max(args.interval, 1.0)+ effective_interval = base_interval+ settle_seconds = max(args.settle, 0.0)++ start = time.monotonic()++ 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+ initial_resume = all(_saved_int(saved, key) is not None for key in STATE_CURSOR_KEYS)+ initial_review_comment_since = (+ _saved_str(saved, "review_comment_since")+ if initial_resume and args.since_review_comment_id is None+ else None+ )+ initial_issue_comment_since = (+ _saved_str(saved, "issue_comment_since")+ if initial_resume and args.since_issue_comment_id is None+ else None+ )++ def _fetch_initial_state() -> tuple[dict[str, Any], int]:+ if args.pr is not None:+ return _fetch_state(+ args.repo,+ args.pr,+ token,+ cache=cache,+ review_comment_since=initial_review_comment_since,+ issue_comment_since=initial_issue_comment_since,+ )+ 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+ return _fetch_new_pr_state(+ args.repo,+ token,+ stop_after_id=initial_pr_stop_after_id,+ max_pages=initial_pr_max_pages,+ cache=cache,+ )++ initial_request = retry_initial_request(+ _fetch_initial_state,+ description="initial GitHub PR state request",+ unauthenticated=token is None,+ )+ 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 PR state request completed without a result", file=sys.stderr)+ return 1+ state, requests_per_poll_count = initial_request.value++ # The remote target is now proven valid. Only now may this run create or adopt+ # its state path; a typo or inaccessible PR must leave no ownership claim._verify_state_file_writable(args.state_file,repo=args.repo,@@ -1212,7 +1764,7 @@ def main() -> int:watch_identity=watch_identity,watch_id=watch_id,)- saved = _resolve_staged_state(+ saved, replay_output = _resolve_staged_state(args.state_file,saved,delivery=delivery_stamp,@@ -1220,33 +1772,54 @@ def main() -> int:pr_number=args.pr,watch_identity=watch_identity,watch_id=watch_id,+ return_replay=True,)- token_fingerprint = _token_fingerprint(token)- viewer_login = None- if 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")- viewer_login = viewer_login or get_authenticated_login(token)-- base_interval = max(args.interval, 1.0)- effective_interval = base_interval- settle_seconds = max(args.settle, 0.0)-- start = time.monotonic()+ if replay_output is not None:+ _deliver(replay_output)+ return 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())- # An explicit --since-*-comment-id asks for a replay from that id. The saved- # `since` timestamp is only ever a shortcut for the saved cursor, so keeping it- # would narrow the fetch to comments newer than the last poll and hide exactly- # the history the flag asked to see.+ explicit_replay = args.pr is not None and 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,+ )+ )+ missing_baselines = _missing_pr_baselines(saved) if resumed and args.pr is not None else []+ if missing_baselines and not explicit_replay:+ print(+ "Saved PR state lacks required baseline(s): %s; use --catch-up, or remove "+ "and reseed this legacy state file 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 a state file seeded before the watched action.",+ file=sys.stderr,+ )+ return 2++ 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+ tracked_head_sha = _saved_str(saved, "head_sha")+ 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)+ # Normal monitoring always compares one complete normalized snapshot. Numeric+ # cursors, fingerprints, and thread maps only explain that change in the report;+ # they never decide independently whether to wake. Explicit replay/catch-up is+ # the deliberate exception: there the requested cursor streams are the contract.+ snapshot = None if args.catch_up or explicit_replay else (_saved_snapshot(saved) if resumed else None)review_comment_since = (_saved_str(saved, "review_comment_since")if resumed and args.since_review_comment_id is None@@ -1257,47 +1830,28 @@ def main() -> int:if resumed and args.since_issue_comment_id is Noneelse None)- # --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- try:- if args.pr is not None:- state, requests_per_poll_count = _fetch_state(- args.repo,- args.pr,- token,- cache=cache,- review_comment_since=review_comment_since,- issue_comment_since=issue_comment_since,- )- 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- state, requests_per_poll_count = _fetch_new_pr_state(- args.repo,- token,- stop_after_id=initial_pr_stop_after_id,- max_pages=initial_pr_max_pages,- cache=cache,+ observed_head_sha = _current_pr_head_sha(state.get("pull_request"))++ if args.pr is not None and not resumed and not args.catch_up and not explicit_replay:+ tracked_head_sha = observed_head_sha+ review_fingerprints = _fingerprint_map(state["reviews"])+ review_comment_fingerprints = _fingerprint_map(state["review_comments"])+ issue_comment_fingerprints = _fingerprint_map(state["issue_comments"])+ if token is not None:+ raw_threads = state.get("review_threads")+ review_thread_states = _review_thread_state_map(+ raw_threads if isinstance(raw_threads, list) else [])- except urllib.error.HTTPError as err:- print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)- return RETRY_EXIT_CODE if is_retryable_http_error(err) else 1- except urllib.error.URLError as err:- print(f"GitHub network error: {err.reason}", file=sys.stderr)- return RETRY_EXIT_CODE- except Exception as err: # noqa: BLE001- print(f"Failed to fetch initial PR state: {err}", file=sys.stderr)- return 1+ 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,+ )if token is None:bootstrap_requests = requests_per_poll_count@@ -1372,6 +1926,13 @@ def main() -> int:reaction_cursor=cursors[3],pr_status=cursors[4],event_limit=args.event_limit,+ previous_head_sha=tracked_head_sha,+ snapshot=snapshot,+ review_fingerprints=dict(review_fingerprints),+ review_comment_fingerprints=dict(review_comment_fingerprints),+ issue_comment_fingerprints=dict(issue_comment_fingerprints),+ review_thread_states=review_thread_states,+ review_threads_available=token is not None,viewer_login=viewer_login,ignore_self_comments=not args.include_self_comments,actionable_only=args.actionable_only,@@ -1395,9 +1956,19 @@ def main() -> int:"issue_comment_since": issue_comment_since,"viewer_login": viewer_login,"token_fingerprint": token_fingerprint,+ "head_sha": observed_head_sha,+ REVIEW_FINGERPRINTS_KEY: dict(review_fingerprints),+ REVIEW_COMMENT_FINGERPRINTS_KEY: dict(review_comment_fingerprints),+ ISSUE_COMMENT_FINGERPRINTS_KEY: dict(issue_comment_fingerprints),+ REVIEW_THREAD_STATES_KEY: dict(review_thread_states),+ PR_SNAPSHOT_KEY: snapshot or {},}- def _persist_pr_state(*, previous: dict[str, Any] | None = None) -> None:+ 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@@ -1405,7 +1976,11 @@ def main() -> int:# waiter started from so a later cycle can tell whether it has moved.fields = {**previous,- STAGED_KEY: {"delivered_after": delivery_stamp, "cursors": fields},+ STAGED_KEY: {+ "delivered_after": delivery_stamp,+ "output": output,+ "cursors": fields,+ },}_write_state_file(args.state_file,@@ -1426,7 +2001,7 @@ def main() -> int:"""if two_phase:- _persist_pr_state(previous=previous)+ _persist_pr_state(previous=previous, output=output)_deliver(output)return_deliver(output)@@ -1461,21 +2036,31 @@ def main() -> int:)return besttime.sleep(settle_seconds)- try:- state, _count = _fetch_state(+ settle_request = github_request(+ lambda: _fetch_state(args.repo,args.pr,token,cache=cache,- review_comment_since=review_comment_since,- issue_comment_since=issue_comment_since,+ ),+ unauthenticated=token is None,+ )+ if settle_request.error is not None:+ # Settling only coalesces a batch. Once an event is known, no+ # enrichment failure may suppress it; the follow-up re-fetches+ # live state and can handle a terminal API problem explicitly.+ print(+ f"Settle re-poll failed: {settle_request.error}; reporting the batch seen so far.",+ file=sys.stderr,)- except Exception as err: # noqa: BLE001+ return best+ if settle_request.value is None:print(- f"Settle re-poll failed; reporting the batch as first seen: {err}",+ "Settle re-poll returned no state; reporting the batch seen so far.",file=sys.stderr,)return best+ 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)@@ -1494,7 +2079,11 @@ def main() -> int:pr_status,)pre_event_fields = _pr_state_fields()- initial_result = _render(pending_cursors)+ initial_result = (+ (None, *pending_cursors)+ if args.seed_state+ else _render(pending_cursors)+ )if initial_result[0] is not None and not args.catch_up:initial_result = _settle(initial_result, pending_cursors)(@@ -1505,11 +2094,34 @@ def main() -> int:reaction_cursor,pr_status,) = initial_result+ observed_head_sha = _current_pr_head_sha(state.get("pull_request"))_advance_since()+ review_fingerprints = _fingerprint_map(state["reviews"])+ review_comment_fingerprints = _fingerprint_map(state["review_comments"])+ issue_comment_fingerprints = _fingerprint_map(state["issue_comments"])+ if token is not None:+ raw_threads = state.get("review_threads")+ review_thread_states = _review_thread_state_map(+ raw_threads if isinstance(raw_threads, list) 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,+ committed_snapshot=snapshot,+ review_threads_available=token is not None,+ )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()+ tracked_head_sha = observed_head_sha+ if args.seed_state:+ print(f"Seeded GitHub PR baseline in {args.state_file}", file=sys.stderr)+ return 0else:_write_cursor_output(args.cursor_output,@@ -1534,13 +2146,18 @@ def main() -> int:pr_cursor=pr_cursor,event_limit=args.event_limit,)- def _persist_new_pr_state(*, previous: int | None = None) -> None:+ 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},},}@@ -1557,7 +2174,7 @@ def main() -> int:"""Same staging contract as ``_report_pr``, over the single new-PR cursor."""if two_phase:- _persist_new_pr_state(previous=previous)+ _persist_new_pr_state(previous=previous, output=output)_deliver(output)return_deliver(output)@@ -1565,6 +2182,9 @@ def main() -> int:if initial_output is None:_persist_new_pr_state()+ if args.seed_state:+ print(f"Seeded GitHub repository PR baseline in {args.state_file}", file=sys.stderr)+ return 0else:_write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)_report_new_pr(initial_output, pre_event_pr_cursor)@@ -1582,38 +2202,39 @@ def main() -> int:time.sleep(sleep_seconds)- try:- if args.pr is not None:- state, requests_per_poll_count = _fetch_state(+ if args.pr is not None:+ poll_request = github_request(+ lambda: _fetch_state(args.repo,args.pr,token,cache=cache,- review_comment_since=review_comment_since,- issue_comment_since=issue_comment_since,- )- else:- state, requests_per_poll_count = _fetch_new_pr_state(+ ),+ unauthenticated=token is None,+ )+ 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,- )- except urllib.error.HTTPError as err:- if token is None and err.code in {403, 429}:+ ),+ unauthenticated=token is None,+ )+ if poll_request.error is not None:+ print(f"GitHub polling failed: {poll_request.error}", file=sys.stderr)+ if poll_request.error.retryable:print(- (- "GitHub unauthenticated polling hit a rate limit. "- "Authenticate with 'gh auth login' or GITHUB_TOKEN/GH_TOKEN."- ),+ "Retryable GitHub request failure; continuing in this watch",file=sys.stderr,)- return 1- print(f"GitHub API error during polling: {err.code} {err.reason}", file=sys.stderr)- continue- except Exception as err: # noqa: BLE001- print(f"Polling failed: {err}", file=sys.stderr)- continue+ 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.valueif token is None:unauthenticated_min = min_interval_for_unauthenticated(requests_per_poll_count)@@ -1640,6 +2261,7 @@ def main() -> int:effective_interval = target_intervalif args.pr is not None:+ observed_head_sha = _current_pr_head_sha(state.get("pull_request"))pending_cursors = (review_cursor,review_comment_cursor,@@ -1659,12 +2281,32 @@ def main() -> int:reaction_cursor,pr_status,) = result+ observed_head_sha = _current_pr_head_sha(state.get("pull_request"))_advance_since()+ review_fingerprints = _fingerprint_map(state["reviews"])+ review_comment_fingerprints = _fingerprint_map(state["review_comments"])+ issue_comment_fingerprints = _fingerprint_map(state["issue_comments"])+ if token is not None:+ raw_threads = state.get("review_threads")+ review_thread_states = _review_thread_state_map(+ raw_threads if isinstance(raw_threads, list) 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,+ committed_snapshot=snapshot,+ review_threads_available=token is not None,+ )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()+ tracked_head_sha = observed_head_shacontinue_write_cursor_output(diff --git a/tests/test_github_wait_common.py b/tests/test_github_wait_common.pyindex a35e3756c..eb6ab5d69 100644--- a/tests/test_github_wait_common.py+++ b/tests/test_github_wait_common.py@@ -47,6 +47,78 @@ def _not_modified() -> urllib.error.HTTPError:)+def test_retry_initial_request_recovers_with_bounded_backoff() -> None:+ module = _load_module()+ attempts = 0++ def _operation() -> str:+ nonlocal attempts+ attempts += 1+ if attempts < 3:+ raise urllib.error.URLError("temporary network failure")+ return "ok"++ with patch.object(module.time, "sleep", return_value=None) as sleep:+ result = module.retry_initial_request(+ _operation,+ description="test request",+ )++ assert result.value == "ok"+ assert result.error is None+ assert attempts == 3+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 2.0]+++def test_retry_initial_request_does_not_retry_terminal_failure() -> None:+ module = _load_module()+ attempts = 0+ error = urllib.error.HTTPError(+ "https://api.github.com/example",+ 404,+ "Not Found",+ hdrs=None,+ fp=None,+ )++ def _operation() -> None:+ nonlocal attempts+ attempts += 1+ raise error++ with patch.object(module.time, "sleep", return_value=None) as sleep:+ result = module.retry_initial_request(+ _operation,+ description="test request",+ )++ assert result.value is None+ assert result.error is not None+ assert result.error.retryable is False+ assert attempts == 1+ sleep.assert_not_called()+++def test_unauthenticated_rate_limit_is_terminal() -> None:+ module = _load_module()+ error = urllib.error.HTTPError(+ "https://api.github.com/example",+ 429,+ "Too Many Requests",+ hdrs=None,+ fp=None,+ )++ result = module.github_request(+ lambda: (_ for _ in ()).throw(error),+ unauthenticated=True,+ )++ assert result.error is not None+ assert result.error.retryable is False+ assert result.error.status_code == 429++def test_github_get_without_cache_sends_no_conditional_header() -> None:module = _load_module()requests: list[object] = []@@ -62,6 +134,15 @@ def test_github_get_without_cache_sends_no_conditional_header() -> None:assert requests[0].get_header("If-none-match") is None+def test_get_token_prefers_gh_token_like_github_cli(monkeypatch) -> None:+ module = _load_module()+ monkeypatch.setenv("GH_TOKEN", "preferred")+ monkeypatch.setenv("GITHUB_TOKEN", "stale")+ monkeypatch.setattr(module.shutil, "which", lambda _name: None)++ assert module.get_token() == "preferred"++def test_github_get_revalidates_with_etag_and_reuses_the_cached_body() -> None:module = _load_module()cache = module.ResponseCache()@@ -210,3 +291,28 @@ def test_get_authenticated_login_still_works_uncached() -> None:with patch.object(module, "github_get", return_value={"login": "qiqi"}):assert module.get_authenticated_login("token") == "qiqi"+++def test_get_authenticated_login_strict_mode_preserves_request_failures() -> None:+ module = _load_module()+ error = TimeoutError("viewer lookup timed out")++ with patch.object(module, "github_get", side_effect=error):+ try:+ module.get_authenticated_login("token", raise_on_error=True)+ except TimeoutError as raised:+ assert raised is error+ else: # pragma: no cover - strict mode must preserve the failure taxonomy+ raise AssertionError("expected viewer failure to propagate")+++def test_get_authenticated_login_strict_mode_rejects_missing_login() -> None:+ module = _load_module()++ with patch.object(module, "github_get", return_value={}):+ try:+ module.get_authenticated_login("token", raise_on_error=True)+ except module.GitHubProtocolError as error:+ assert "no login" in str(error)+ else: # pragma: no cover - unusable identity must fail closed+ raise AssertionError("expected missing login to fail")diff --git a/tests/test_harness_skill_guidance.py b/tests/test_harness_skill_guidance.pyindex 2fd31833c..252dcf3cf 100644--- a/tests/test_harness_skill_guidance.py+++ b/tests/test_harness_skill_guidance.py@@ -144,3 +144,35 @@ def test_background_watch_skill_defaults_to_current_session() -> None:assert "each follow-up should run in a visible sibling Session" not in bodyassert ' --session-id "sesk8m4q2p7x"' not in bodyassert "`--prefix`" not in body+++def test_background_watch_skill_resolves_local_waiters_and_persists_managed_pr_state() -> None:+ body = _read("skills/background-watch-hook/SKILL.md")++ assert 'REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"' in body+ assert '"$REPO_ROOT/skills/background-watch-hook/SKILL.md"' in body+ assert '"$REPO_ROOT/.agents/skills/background-watch-hook/SKILL.md"' in body+ assert body.count('--state-file "$STATE_FILE"') >= 7+ assert body.count("--seed-state") >= 3+ assert "The one-shot PR and Actions waiters retry" in body+ assert "review-thread status" in body+ assert "independent wake signal" in body+ assert "single wake/no-wake" in body+ assert "caught up or reseeded" in body+++def test_pr_delivery_loop_delegates_waiters_to_background_watch_skill() -> None:+ body = _read(".agents/skills/pr-delivery-loop/SKILL.md")+ agents = _read("AGENTS.md")++ assert "## Dependency boundary" in body+ assert "Use the `background-watch-hook` skill for every managed wait." in body+ assert "Do not copy watcher implementations" in body+ assert ".agents/skills/pr-delivery-loop/scripts/" not in body+ assert not (ROOT / ".agents/skills/pr-delivery-loop/scripts").exists()+ assert not (ROOT / ".agents/skills/pr-delivery-loop/tests").exists()++ assert "the `pr-delivery-loop` skill for every implementation task" in agents+ assert "use the `background-watch-hook` skill" in agents+ assert (ROOT / "skills/background-watch-hook/scripts/wait_pr.py").is_file()+ assert (ROOT / "skills/background-watch-hook/scripts/wait_action.py").is_file()diff --git a/tests/test_wait_for_github_action_runs.py b/tests/test_wait_for_github_action_runs.pyindex 6482132b5..fccc83f99 100644--- a/tests/test_wait_for_github_action_runs.py+++ b/tests/test_wait_for_github_action_runs.py@@ -23,7 +23,7 @@ def _load_module():return module-def test_select_latest_runs_by_workflow_matches_sha_branch_and_workflow() -> None:+def test_select_runs_by_workflow_keeps_every_matching_rerun() -> None:module = _load_module()runs = [{@@ -62,8 +62,8 @@ def test_select_latest_runs_by_workflow_matches_sha_branch_and_workflow() -> Nonhead_sha="abc123",)- assert selected["CI"]["id"] == 2- assert selected["Security Scan"] is None+ assert [run["id"] for run in selected["CI"]] == [1, 2]+ assert selected["Security Scan"] == []def test_render_actions_result_waits_for_missing_or_running_runs() -> None:@@ -73,13 +73,15 @@ def test_render_actions_result_waits_for_missing_or_running_runs() -> None:branch="main",head_sha="abc123",selected={- "CI": {- "id": 1,- "name": "CI",- "status": "in_progress",- "conclusion": None,- },- "Security Scan": None,+ "CI": [+ {+ "id": 1,+ "name": "CI",+ "status": "in_progress",+ "conclusion": None,+ }+ ],+ "Security Scan": [],},success_conclusions={"success"},)@@ -95,20 +97,24 @@ def test_render_actions_result_reports_success() -> None:branch="main",head_sha="abc123",selected={- "CI": {- "id": 1,- "name": "CI",- "status": "completed",- "conclusion": "success",- "html_url": "https://github.com/example/actions/runs/1",- },- "Security Scan": {- "id": 2,- "name": "Security Scan",- "status": "completed",- "conclusion": "skipped",- "html_url": "https://github.com/example/actions/runs/2",- },+ "CI": [+ {+ "id": 1,+ "name": "CI",+ "status": "completed",+ "conclusion": "success",+ "html_url": "https://github.com/example/actions/runs/1",+ }+ ],+ "Security Scan": [+ {+ "id": 2,+ "name": "Security Scan",+ "status": "completed",+ "conclusion": "skipped",+ "html_url": "https://github.com/example/actions/runs/2",+ }+ ],},success_conclusions={"success", "skipped"},)@@ -120,6 +126,40 @@ def test_render_actions_result_reports_success() -> None:assert failed is False+def test_render_actions_result_keeps_an_older_failed_rerun_visible() -> None:+ module = _load_module()+ output, failed = module._render_actions_result(+ repo="cyhhao/sub2api",+ branch="main",+ head_sha="abc123",+ selected={+ "CI": [+ {+ "id": 1,+ "name": "CI",+ "status": "completed",+ "conclusion": "failure",+ "html_url": "https://github.com/example/actions/runs/1",+ },+ {+ "id": 2,+ "name": "CI",+ "status": "completed",+ "conclusion": "success",+ "html_url": "https://github.com/example/actions/runs/2",+ },+ ]+ },+ success_conclusions={"success"},+ )++ assert output is not None+ assert "GitHub Actions failure" in output+ assert "actions/runs/1" in output+ assert "actions/runs/2" in output+ assert failed is True++def test_render_actions_result_reports_failure_but_is_an_event() -> None:module = _load_module()output, failed = module._render_actions_result(@@ -127,13 +167,15 @@ def test_render_actions_result_reports_failure_but_is_an_event() -> None:branch="main",head_sha="abc123",selected={- "CI": {- "id": 1,- "name": "CI",- "status": "completed",- "conclusion": "failure",- "html_url": "https://github.com/example/actions/runs/1",- }+ "CI": [+ {+ "id": 1,+ "name": "CI",+ "status": "completed",+ "conclusion": "failure",+ "html_url": "https://github.com/example/actions/runs/1",+ }+ ]},success_conclusions={"success"},)@@ -315,7 +357,7 @@ def test_main_uses_real_request_count_for_unauthenticated_interval() -> None:assert "GitHub Actions success" in stdout.getvalue()-def test_main_retryable_startup_http_error_returns_retry_code() -> None:+def test_main_retries_retryable_startup_http_error_inside_one_shot() -> None:module = _load_module()err = urllib.error.HTTPError(url="https://api.github.com/repos/example/repo/actions/runs",@@ -324,15 +366,31 @@ def test_main_retryable_startup_http_error_returns_retry_code() -> None:hdrs=None,fp=None,)+ completed = [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "status": "completed",+ "conclusion": "success",+ }+ ]with (patch.object(module, "get_token", return_value="token"),- patch.object(module, "_fetch_workflow_runs", side_effect=err),+ patch.object(+ module,+ "_fetch_workflow_runs",+ side_effect=[err, err, (completed, 1)],+ ) as fetch,+ patch.object(module.time, "sleep", return_value=None) as sleep,patch("sys.argv", ["wait_action.py", "--repo", "cyhhao/sub2api", "--sha", "abc123", "--workflow", "CI"]),):rc = module.main()- assert rc == module.RETRY_EXIT_CODE+ assert rc == 0+ assert fetch.call_count == 3+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 2.0]def test_main_unexpected_startup_error_fails_fast() -> None:@@ -348,6 +406,104 @@ def test_main_unexpected_startup_error_fails_fast() -> None:assert rc == 1+def test_main_stops_on_a_terminal_polling_http_error() -> None:+ module = _load_module()+ error = urllib.error.HTTPError(+ url="https://api.github.com/repos/example/repo/actions/runs",+ code=404,+ msg="Not Found",+ hdrs=None,+ fp=None,+ )++ runs = [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "head_branch": "main",+ "status": "in_progress",+ "conclusion": None,+ }+ ]+ with (+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "_fetch_workflow_runs", side_effect=[(runs, 1), error]),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_action.py",+ "--repo",+ "cyhhao/sub2api",+ "--branch",+ "main",+ "--sha",+ "abc123",+ "--workflow",+ "CI",+ "--interval",+ "1",+ ],+ ),+ ):+ rc = module.main()++ assert rc == 1+++def test_main_recovers_from_retryable_actions_polling_failure() -> None:+ module = _load_module()+ running = [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "status": "in_progress",+ "conclusion": None,+ }+ ]+ completed = [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "status": "completed",+ "conclusion": "success",+ }+ ]+ error = urllib.error.URLError("temporary network failure")++ with (+ patch.object(module, "get_token", return_value="token"),+ patch.object(+ module,+ "_fetch_workflow_runs",+ side_effect=[(running, 1), error, (completed, 1)],+ ) as fetch,+ patch.object(module.time, "sleep", return_value=None) as sleep,+ patch(+ "sys.argv",+ [+ "wait_action.py",+ "--repo",+ "cyhhao/sub2api",+ "--sha",+ "abc123",+ "--workflow",+ "CI",+ "--interval",+ "1",+ ],+ ),+ ):+ rc = module.main()++ assert rc == 0+ assert fetch.call_count == 3+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 1.0]++def test_main_only_on_failure_skips_agent_turn_for_green_run() -> None:module = _load_module()diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.pyindex a7dd818f6..0e6faa502 100644--- a/tests/test_wait_for_github_pr_activity.py+++ b/tests/test_wait_for_github_pr_activity.py@@ -23,6 +23,16 @@ def _load_module():module = importlib.util.module_from_spec(spec)assert spec is not None and spec.loader is not Nonespec.loader.exec_module(module)+ module.github_graphql = lambda *_args, **_kwargs: {+ "repository": {+ "pullRequest": {+ "reviewThreads": {+ "nodes": [],+ "pageInfo": {"hasNextPage": False, "endCursor": None},+ }+ }+ }+ }return module@@ -65,6 +75,141 @@ def test_render_activity_includes_codex_pr_body_reaction() -> None:assert pr_status == "open"+def test_render_activity_accepts_api_codex_login_and_keeps_reaction_outside_limit() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [+ {+ "id": 501,+ "body": "Fix this",+ "path": "core/watches.py",+ "html_url": "https://github.com/example/repo/pull/153#discussion_r501",+ "user": {"login": "reviewer"},+ }+ ],+ "issue_comments": [],+ "reactions": [+ {+ "id": 601,+ "content": "+1",+ "created_at": "2026-04-02T13:05:42Z",+ "user": {"login": "chatgpt-codex-connector"},+ }+ ],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=1,+ )++ assert output is not None+ assert "review_comment #501" in output+ assert "pr_reaction #601" in output+ assert "additional event(s) omitted" not in output+++def test_render_activity_reports_a_changed_pr_head() -> None:+ module = _load_module()+ state = {+ "pull_request": {+ "number": 153,+ "state": "open",+ "draft": False,+ "head": {"sha": "new-head"},+ "html_url": "https://github.com/example/repo/pull/153",+ },+ "reviews": [],+ "review_comments": [],+ "issue_comments": [],+ "reactions": [],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ previous_head_sha="old-head",+ )++ assert output is not None+ assert "pr_head #153 old-head -> new-head" in output+++def test_render_activity_reports_an_edited_existing_comment() -> None:+ module = _load_module()+ comment = {+ "id": 501,+ "body": "Initial text",+ "path": "core/watches.py",+ "created_at": "2026-04-02T13:05:42Z",+ "updated_at": "2026-04-02T13:05:42Z",+ "html_url": "https://github.com/example/repo/pull/153#discussion_r501",+ "user": {"login": "reviewer"},+ }+ state = _pr_state(review_comments=[comment])+ fingerprints: dict[str, str] = {}++ first = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ review_comment_fingerprints=fingerprints,+ )+ assert first[0] is not None++ unchanged = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=first[1],+ review_comment_cursor=first[2],+ issue_comment_cursor=first[3],+ reaction_cursor=first[4],+ pr_status=first[5],+ event_limit=8,+ review_comment_fingerprints=fingerprints,+ )+ assert unchanged[0] is None++ edited = dict(comment, body="Corrected text", updated_at="2026-04-02T13:10:42Z")+ changed = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=_pr_state(review_comments=[edited]),+ review_cursor=unchanged[1],+ review_comment_cursor=unchanged[2],+ issue_comment_cursor=unchanged[3],+ reaction_cursor=unchanged[4],+ pr_status=unchanged[5],+ event_limit=8,+ review_comment_fingerprints=fingerprints,+ )+ assert changed[0] is not None+ assert "Corrected text" in changed[0]++def test_render_activity_ignores_non_codex_or_non_plus_one_reactions() -> None:module = _load_module()state = {@@ -535,7 +680,7 @@ def test_main_uses_since_pr_cursor_for_initial_new_pr_fetch() -> None:with (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",[@@ -584,7 +729,7 @@ def test_main_bootstraps_new_pr_watch_from_first_page_only() -> None:with (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--new-prs", "--interval", "1"]),redirect_stdout(stdout),@@ -640,7 +785,7 @@ def test_main_detects_pr_status_change_during_polling() -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1"]),redirect_stdout(stdout),@@ -688,7 +833,7 @@ def test_main_reduces_unauthenticated_new_pr_interval_after_bootstrap() -> None:with (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value=None),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module, "min_interval_for_unauthenticated", side_effect=_fake_min_interval),patch.object(module.time, "sleep", side_effect=lambda seconds: sleep_calls.append(seconds)),patch(@@ -713,22 +858,37 @@ def test_main_reduces_unauthenticated_new_pr_interval_after_bootstrap() -> None:assert "pull_request #158" in stdout.getvalue()-def test_main_returns_retry_exit_code_for_retryable_initial_pr_http_error() -> None:+def test_main_retries_retryable_initial_pr_http_error_inside_one_shot() -> None:module = _load_module()+ state = _pr_state()+ state["issue_comments"] = [+ {+ "id": 501,+ "body": "Review result",+ "html_url": "https://github.com/example/repo/pull/153#issuecomment-501",+ "user": {"login": "reviewer"},+ }+ ]stderr = io.StringIO()err = urllib.error.HTTPError("https://api.github.com/example", 503, "Service Unavailable", hdrs=None, fp=None)with (- patch.object(module, "_fetch_state", side_effect=err),+ patch.object(module, "_fetch_state", side_effect=[err, err, (state, 1)]) as fetch,patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),- patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", return_value=None) as sleep,+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--catch-up"],+ ),patch("sys.stderr", stderr),):rc = module.main()- assert rc == 75- assert "GitHub API error: 503 Service Unavailable" in stderr.getvalue()+ assert rc == 0+ assert fetch.call_count == 3+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 2.0]+ assert "Transient initial GitHub PR state request failure" in stderr.getvalue()def test_main_returns_terminal_exit_code_for_non_retryable_initial_pr_http_error() -> None:@@ -739,32 +899,176 @@ def test_main_returns_terminal_exit_code_for_non_retryable_initial_pr_http_errorwith (patch.object(module, "_fetch_state", side_effect=err),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),patch("sys.stderr", stderr),):rc = module.main()assert rc == 1- assert "GitHub API error: 404 Not Found" in stderr.getvalue()+ assert "Failed to fetch initial PR state: GitHub HTTP 404 Not Found" in stderr.getvalue()-def test_main_returns_retry_exit_code_for_initial_pr_network_error() -> None:+def test_main_stops_after_bounded_initial_pr_network_retries() -> None:module = _load_module()stderr = io.StringIO()err = urllib.error.URLError("temporary network failure")with (- patch.object(module, "_fetch_state", side_effect=err),+ patch.object(module, "_fetch_state", side_effect=err) as fetch,+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", return_value=None),+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 1+ assert fetch.call_count == 3+ assert "failed after 3 attempts" in stderr.getvalue()+++def test_main_recovers_from_retryable_pr_polling_failure() -> None:+ module = _load_module()+ updated = _pr_state()+ updated["issue_comments"] = [+ {+ "id": 501,+ "body": "New review result",+ "html_url": "https://github.com/example/repo/pull/153#issuecomment-501",+ "user": {"login": "reviewer"},+ }+ ]+ error = urllib.error.URLError("temporary network failure")+ stdout = io.StringIO()++ with (+ patch.object(module, "_fetch_state", side_effect=[(_pr_state(), 1), error, (updated, 1)]) as fetch,+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1"],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 0+ assert fetch.call_count == 3+ assert "issue_comment #501" in stdout.getvalue()+++def test_main_stops_on_a_terminal_polling_http_error() -> None:+ module = _load_module()+ error = urllib.error.HTTPError(+ url="https://api.github.com/repos/example/repo/pulls/153",+ code=404,+ msg="Not Found",+ hdrs=None,+ fp=None,+ )+ stderr = io.StringIO()++ with (+ patch.object(module, "_fetch_state", side_effect=[(_pr_state(), 1), error]),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1"],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 1+ assert "GitHub polling failed: GitHub HTTP 404 Not Found" in stderr.getvalue()+++def test_new_pr_seed_does_not_resolve_viewer_login(tmp_path: Path) -> None:+ module = _load_module()+ state_file = tmp_path / "new-prs.json"++ with (+ patch.object(module, "_fetch_new_pr_state", return_value=({"pull_requests": []}, 1)),+ patch.object(module, "get_token", return_value="app-token"),+ patch.object(+ module,+ "get_authenticated_login",+ side_effect=AssertionError("new-PR mode must not call /user"),+ ),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--new-prs",+ "--state-file",+ str(state_file),+ "--seed-state",+ ],+ ),+ ):+ rc = module.main()++ assert rc == 0+ assert state_file.is_file()+++def test_main_fails_closed_when_authenticated_login_cannot_be_resolved() -> None:+ module = _load_module()+ stderr = io.StringIO()++ with (patch.object(module, "get_token", return_value="token"),patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),patch("sys.stderr", stderr),):rc = module.main()- assert rc == 75- assert "GitHub network error: temporary network failure" in stderr.getvalue()+ assert rc == 1+ assert "refusing to poll" in stderr.getvalue()+++def test_main_retries_transient_authenticated_login_failure() -> None:+ module = _load_module()+ state = _pr_state(+ issue_comments=[+ {+ "id": 501,+ "body": "Review result",+ "html_url": "https://github.com/example/repo/pull/153#issuecomment-501",+ "user": {"login": "reviewer"},+ }+ ]+ )++ with (+ patch.object(module, "get_token", return_value="token"),+ patch.object(+ module,+ "get_authenticated_login",+ side_effect=[TimeoutError("temporary viewer timeout"), "tester"],+ ) as lookup,+ patch.object(module, "_fetch_state", return_value=(state, 1)),+ patch.object(module.time, "sleep", return_value=None) as sleep,+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--catch-up"],+ ),+ ):+ rc = module.main()++ assert rc == 0+ assert lookup.call_count == 2+ assert [call.args[0] for call in sleep.call_args_list] == [1.0]def test_render_activity_actionable_only_drops_bot_trigger_comment_but_advances_cursor() -> None:@@ -1160,6 +1464,7 @@ def _pr_state(review_comments=None,issue_comments=None,reactions=None,+ review_threads=None,pr_state="open",):return {@@ -1173,6 +1478,7 @@ def _pr_state("review_comments": review_comments or [],"issue_comments": issue_comments or [],"reactions": reactions or [],+ "review_threads": review_threads or [],}@@ -1188,6 +1494,24 @@ def _review_comment(comment_id: int, *, body="Fix this", created_at="2026-08-04T}+def _complete_pr_baseline_fields(module, state=None) -> dict[str, object]:+ baseline = state or _pr_state()+ raw_threads = baseline.get("review_threads")+ return {+ "head_sha": module._current_pr_head_sha(baseline.get("pull_request")) or "unknown",+ "review_fingerprints": module._fingerprint_map(baseline["reviews"]),+ "review_comment_fingerprints": module._fingerprint_map(baseline["review_comments"]),+ "issue_comment_fingerprints": module._fingerprint_map(baseline["issue_comments"]),+ "review_thread_states": module._review_thread_state_map(+ raw_threads if isinstance(raw_threads, list) else []+ ),+ "snapshot": module._normalized_pr_snapshot(+ baseline,+ ignore_self_comments=False,+ ),+ }++def test_fetch_state_narrows_comments_and_filters_reactions_server_side() -> None:module = _load_module()urls: list[str] = []@@ -1216,8 +1540,8 @@ def test_fetch_state_narrows_comments_and_filters_reactions_server_side() -> Non# The reviews endpoint supports neither `since` nor a newest-first order, so it# must stay unfiltered and lean on revalidation instead.assert "since=" not in reviews_url- assert "since=2026-08-04T06%3A47%3A10Z" in review_comments_url- assert "since=2026-08-04T06%3A47%3A10Z" in issue_comments_url+ assert "since=" not in review_comments_url+ assert "since=" not in issue_comments_url# Only the Codex pass reaction is ever reported, so the rest never travel.assert "content=%2B1" in reactions_url@@ -1258,6 +1582,267 @@ def test_fetch_state_shares_one_cache_across_every_request() -> None:assert fake_get.call_args.kwargs["cache"] is sentinel+def test_fetch_state_paginates_review_threads_as_part_of_the_pr_snapshot() -> None:+ module = _load_module()+ graphql_pages = iter(+ [+ {+ "repository": {+ "pullRequest": {+ "reviewThreads": {+ "nodes": [{"id": "thread-1", "isResolved": False}],+ "pageInfo": {"hasNextPage": True, "endCursor": "cursor-1"},+ }+ }+ }+ },+ {+ "repository": {+ "pullRequest": {+ "reviewThreads": {+ "nodes": [{"id": "thread-2", "isResolved": True}],+ "pageInfo": {"hasNextPage": False, "endCursor": None},+ }+ }+ }+ },+ ]+ )+ with (+ patch.object(module, "github_get", return_value={"number": 153, "state": "open"}),+ patch.object(module, "list_paginated_with_count", return_value=([], 1)),+ patch.object(module, "github_graphql", side_effect=lambda *_args, **_kwargs: next(graphql_pages)),+ ):+ state, request_count = module._fetch_state("avibe-bot/avibe", 153, "token")++ assert state["review_threads"] == [+ {"id": "thread-1", "isResolved": False},+ {"id": "thread-2", "isResolved": True},+ ]+ assert request_count == 7+++def test_fresh_pr_watch_baselines_existing_review_threads() -> None:+ module = _load_module()+ state = _pr_state(review_threads=[{"id": "thread-1", "isResolved": False}])+ stdout = io.StringIO()++ with (+ patch.object(module, "_fetch_state", return_value=(state, 1)) as fetch,+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "monotonic", side_effect=[0.0, 1.0]),+ patch.object(module.time, "sleep", side_effect=AssertionError("must not wait")),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.5",+ ],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 124+ assert fetch.call_count == 1+ assert stdout.getvalue() == ""+++def test_render_activity_reports_review_edit_and_thread_transition() -> None:+ module = _load_module()+ old_review = {+ "id": 7,+ "state": "COMMENTED",+ "body": "old",+ "commit_id": "old-head",+ "user": {"login": "reviewer"},+ }+ baseline = _pr_state(reviews=[old_review], review_threads=[{"id": "thread-1", "isResolved": False}])+ current = _pr_state(+ reviews=[{**old_review, "body": "edited", "commit_id": "new-head"}],+ review_threads=[{"id": "thread-1", "isResolved": True}],+ )+ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=current,+ review_cursor=7,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ snapshot=module._normalized_pr_snapshot(baseline, ignore_self_comments=False),+ review_fingerprints={"7": module._item_fingerprint(old_review)},+ review_thread_states={"thread-1": False},+ ignore_self_comments=False,+ )++ assert output is not None+ assert "review #7" in output+ assert "edited" in output+ assert "review_thread thread-1 unresolved -> resolved" in output+++def test_snapshot_gate_advances_past_filtered_activity_without_waking() -> None:+ module = _load_module()+ baseline = _pr_state()+ current = _pr_state(+ issue_comments=[+ {+ "id": 9,+ "body": "@codex review",+ "user": {"login": "maintainer"},+ }+ ]+ )++ result = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=current,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ snapshot=module._normalized_pr_snapshot(+ baseline,+ viewer_login="maintainer",+ ignore_self_comments=True,+ ),+ viewer_login="maintainer",+ ignore_self_comments=True,+ )++ assert result[0] is None+ assert result[3] == 9+++def test_review_thread_status_remains_visible_when_its_comment_author_is_filtered() -> None:+ module = _load_module()+ baseline = _pr_state()+ current = _pr_state(+ review_comments=[+ {+ **_review_comment(501),+ "user": {"login": "dependabot[bot]"},+ }+ ],+ review_threads=[{"id": "thread-1", "isResolved": False}],+ )++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=current,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ snapshot=module._normalized_pr_snapshot(+ baseline,+ ignore_self_comments=False,+ ignored_authors={"dependabot[bot]"},+ ),+ review_thread_states={},+ ignore_self_comments=False,+ ignored_authors={"dependabot[bot]"},+ )++ assert output is not None+ assert "review_thread thread-1 absent -> unresolved" in output+ assert "review_comment #501" not in output+++def test_pending_report_payload_is_replayable_without_remote_state(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "state.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": "filters",+ "owner": "watch-1",+ "pending": {+ "delivered_after": "delivery-1",+ "output": "persisted report",+ "cursors": {"review_cursor": 2},+ },+ }+ )+ )+ saved = module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="filters",+ watch_id="watch-1",+ )++ resolved = module._resolve_staged_state(+ str(state_file),+ saved,+ delivery="delivery-1",+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="filters",+ watch_id="watch-1",+ )++ assert resolved == saved+ assert module._staged_replay_output(saved, "delivery-1") == "persisted report"+++def test_main_replays_pending_output_before_auth_or_remote_preflight(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _managed_state(+ module,+ state_file,+ "wat_9",+ **{+ module.STAGED_KEY: {+ "delivered_after": "delivery-1",+ "output": "persisted report",+ "cursors": {"review_cursor": 2},+ }+ },+ )++ stdout = io.StringIO()+ with (+ patch.dict(+ "os.environ",+ {module.WATCH_ID_ENV: "wat_9", module.LAST_DELIVERY_ENV: "delivery-1"},+ clear=False,+ ),+ patch.object(module, "get_token", side_effect=AssertionError("must not authenticate")),+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 0+ assert stdout.getvalue() == "persisted report\n"++def test_main_settle_window_reports_a_batched_review_as_one_event() -> None:module = _load_module()fetches = 0@@ -1280,7 +1865,7 @@ def test_main_settle_window_reports_a_batched_review_as_one_event() -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1324,7 +1909,7 @@ def test_main_settle_window_stops_once_the_batch_is_stable() -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1358,7 +1943,7 @@ def test_main_settle_window_survives_a_failed_re_poll() -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1373,6 +1958,55 @@ def test_main_settle_window_survives_a_failed_re_poll() -> None:assert "review_comment #501" in stdout.getvalue()+ "error",+ [+ TimeoutError("settle timed out"),+ ConnectionError("connection reset"),+ OSError("socket unavailable"),+ ],+)+def test_main_settle_preserves_detected_event_for_every_transient_error(error) -> None:+ module = _load_module()+ fetches = 0++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ nonlocal fetches+ fetches += 1+ if fetches == 1:+ return _pr_state(), 1+ if fetches == 2:+ return _pr_state(review_comments=[_review_comment(501)]), 1+ raise error++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--interval",+ "1",+ "--settle",+ "5",+ ],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 0+ assert "review_comment #501" in stdout.getvalue()++def test_main_writes_the_state_file_even_with_nothing_to_report(tmp_path) -> None:module = _load_module()state_file = tmp_path / "cursors" / "pr-153.json"@@ -1416,6 +2050,127 @@ def test_main_writes_the_state_file_even_with_nothing_to_report(tmp_path) -> Nonassert saved["review_comment_since"] == "2026-08-04T09:59:58Z"+def test_seed_state_persists_a_complete_pr_baseline_and_exits(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state = _pr_state(+ reviews=[+ {+ "id": 7,+ "body": "reviewed",+ "state": "COMMENTED",+ "submitted_at": "2026-08-04T10:00:00Z",+ "commit_id": "head-1",+ "user": {"login": "reviewer"},+ }+ ],+ review_comments=[_review_comment(501)],+ review_threads=[{"id": "thread-1", "isResolved": False}],+ )+ state["pull_request"]["head"] = {"sha": "head-1"}++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", return_value=(state, 7)),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module.time, "sleep", side_effect=AssertionError("must not wait")),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--state-file",+ str(state_file),+ "--seed-state",+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 0+ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["review_cursor"] == 7+ assert saved["review_comment_cursor"] == 501+ assert saved["head_sha"] == "head-1"+ assert saved["review_fingerprints"]["7"]+ assert saved["review_comment_fingerprints"]["501"]+ assert saved["review_thread_states"] == {"thread-1": False}+ assert saved["snapshot"]+ assert "Seeded GitHub PR baseline" in stderr.getvalue()+++def test_manual_resume_rejects_complete_cursors_without_snapshot_baselines(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "legacy-pr-153.json"+ raw = json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 400,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "viewer_login": "qiqi",+ "token_fingerprint": module._token_fingerprint("token"),+ }+ )+ state_file.write_text(raw, encoding="utf-8")+ stderr = io.StringIO()++ with (+ patch.object(module, "_fetch_state", return_value=(_pr_state(), 1)) as fetch,+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login") as lookup,+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 2+ assert fetch.call_count == 1+ lookup.assert_not_called()+ assert "lacks required baseline" in stderr.getvalue()+ assert state_file.read_text(encoding="utf-8") == raw+++def test_invalid_remote_target_does_not_claim_the_state_file(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-999.json"++ with (+ patch.object(module, "_fetch_state", side_effect=RuntimeError("pull request not found")),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="tester"),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "999", "--state-file", str(state_file)],+ ),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 1+ assert not state_file.exists()++def test_main_resumes_from_the_state_file_instead_of_re_baselining(tmp_path) -> None:module = _load_module()state_file = tmp_path / "pr-153.json"@@ -1434,6 +2189,7 @@ def test_main_resumes_from_the_state_file_instead_of_re_baselining(tmp_path) ->"issue_comment_since": "2026-08-04T09:00:00Z","viewer_login": "qiqi","token_fingerprint": module._token_fingerprint("token"),+ **_complete_pr_baseline_fields(module),}),encoding="utf-8",@@ -1480,6 +2236,7 @@ def test_main_re_resolves_the_login_when_the_token_changed(tmp_path) -> None:"pr_status": "open","viewer_login": "someone-else","token_fingerprint": module._token_fingerprint("old-token"),+ **_complete_pr_baseline_fields(module),}),encoding="utf-8",@@ -1520,7 +2277,7 @@ def test_main_re_resolves_the_login_when_the_token_changed(tmp_path) -> None:# The cached login belonged to the previous credential. Reusing it would let the# new account's own comments wake the Agent, so the login is resolved again and# it is the fresh login that filters this cycle.- fake_login.assert_called_once_with("new-token")+ fake_login.assert_called_once_with("new-token", raise_on_error=True)assert rc == 124assert stdout.getvalue() == ""saved = json.loads(state_file.read_text(encoding="utf-8"))@@ -1596,7 +2353,7 @@ def test_main_replays_from_an_explicit_cursor_without_a_saved_since(tmp_path) ->with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",[@@ -1645,7 +2402,7 @@ def test_main_refuses_a_state_file_belonging_to_another_pr(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1702,7 +2459,7 @@ def test_main_ignores_a_partial_state_file(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1751,7 +2508,7 @@ def test_main_refuses_to_poll_past_an_unreadable_state_file(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1794,7 +2551,7 @@ def test_main_refuses_a_state_file_it_does_not_recognise(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],@@ -1826,7 +2583,7 @@ def test_main_starts_over_from_an_empty_state_file(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1872,7 +2629,7 @@ def test_main_refuses_to_poll_when_the_state_file_cannot_be_written(tmp_path) ->with (patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -1906,7 +2663,7 @@ def test_main_refuses_to_poll_when_the_state_file_cannot_be_replaced(tmp_path) -with (patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -2152,7 +2909,7 @@ def _run_new_pr_catch_up(module, state_file, *extra: str) -> str:with (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -2233,7 +2990,7 @@ def test_main_stops_when_persisting_advanced_cursors_fails(tmp_path) -> None:with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.os, "replace", side_effect=_replace_then_break),patch.object(module.time, "sleep", return_value=None),patch(@@ -2285,7 +3042,7 @@ def test_main_state_file_round_trips_new_pr_cursor(tmp_path) -> None:with (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep", return_value=None),patch("sys.argv",@@ -2441,6 +3198,7 @@ def test_main_skips_the_settle_window_that_would_outlast_the_timeout(tmp_path) -"pr_status": "open","viewer_login": "qiqi","token_fingerprint": module._token_fingerprint("token"),+ **_complete_pr_baseline_fields(module),}),encoding="utf-8",@@ -2456,7 +3214,7 @@ def test_main_skips_the_settle_window_that_would_outlast_the_timeout(tmp_path) -with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep") as fake_sleep,patch("sys.argv",@@ -2508,6 +3266,7 @@ def test_main_skips_the_settle_window_when_only_its_sleep_would_fit(tmp_path) ->"pr_status": "open","viewer_login": "qiqi","token_fingerprint": module._token_fingerprint("token"),+ **_complete_pr_baseline_fields(module),}),encoding="utf-8",@@ -2525,7 +3284,7 @@ def test_main_skips_the_settle_window_when_only_its_sleep_would_fit(tmp_path) ->with (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch.object(module.time, "sleep") as fake_sleep,patch("sys.argv",@@ -2591,6 +3350,7 @@ def test_main_commits_cursors_only_after_the_event_is_reported(tmp_path) -> None"pr_status": "open","viewer_login": "qiqi","token_fingerprint": module._token_fingerprint("token"),+ **_complete_pr_baseline_fields(module),}),encoding="utf-8",@@ -2604,7 +3364,7 @@ def test_main_commits_cursors_only_after_the_event_is_reported(tmp_path) -> Nonewith (patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],@@ -2646,7 +3406,7 @@ def test_main_new_prs_commits_the_cursor_only_after_the_event_is_reported(tmp_pawith (patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",["wait_pr.py", "--repo", "avibe-bot/avibe", "--new-prs", "--state-file", str(state_file)],@@ -2666,6 +3426,7 @@ def test_main_new_prs_commits_the_cursor_only_after_the_event_is_reported(tmp_padef _managed_state(module, path, watch_id: str | None, **fields) -> None:"""A state file already owned by ``watch_id``, so a managed run resumes from it."""+ baseline = _pr_state()path.write_text(json.dumps({@@ -2679,6 +3440,15 @@ def _managed_state(module, path, watch_id: str | None, **fields) -> None:"issue_comment_cursor": 0,"reaction_cursor": 0,"pr_status": "open",+ "head_sha": "unknown",+ "review_fingerprints": {},+ "review_comment_fingerprints": {},+ "issue_comment_fingerprints": {},+ "review_thread_states": {},+ "snapshot": module._normalized_pr_snapshot(+ baseline,+ ignore_self_comments=False,+ ),**fields,}),@@ -2695,7 +3465,7 @@ def _run_managed(module, state_file, fetch, *, delivery: str = ""):patch.dict("os.environ", env, clear=False),patch.object(module, "_fetch_state", side_effect=fetch),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],@@ -2731,6 +3501,7 @@ def test_a_managed_run_stages_the_cursors_that_cover_its_report(tmp_path) -> Non# Still pointing before the event that was just reported.assert payload["review_comment_cursor"] == 500assert payload[module.STAGED_KEY]["cursors"]["review_comment_cursor"] == 501+ assert payload[module.STAGED_KEY]["output"] == stdout.strip()# Stamped with the delivery this cycle started from, which is what a later cycle# compares against to learn whether this report was queued.assert payload[module.STAGED_KEY]["delivered_after"] == "2026-08-04T10:00:00+00:00"@@ -2829,7 +3600,7 @@ def test_a_manual_run_stages_nothing_because_printing_is_its_delivery(tmp_path)patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_ENV: ""}, clear=False),patch.object(module, "_fetch_state", side_effect=_fetch),patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module, "get_authenticated_login", return_value="tester"),patch("sys.argv",["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],