Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(skills): combine PR and CI waiting (#1390)

Call Whiteb6c4393f0162
diff --git a/.agents/skills/pr-delivery-loop/SKILL.md b/.agents/skills/pr-delivery-loop/SKILL.md
index fd0971354..613cfa4d6 100644
--- a/.agents/skills/pr-delivery-loop/SKILL.md
+++ b/.agents/skills/pr-delivery-loop/SKILL.md
@@ -186,16 +186,21 @@ 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 of
the current head, or one you just triggered. Never wait on nothing.
-- 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.
+- Use `background-watch-hook` to create one one-shot combined PR watch for each
+ review phase; never use `--forever` for a delivery loop. Prefer the bundled
+ `wait_pr.py` with the current `--sha` and each required `--workflow`, plus the
+ optional `--branch`, so one waiter observes PR activity and exact-head Actions
+ transitions with one state file and one follow-up Agent Run. Re-arm after every
+ round and update `--sha` when the PR head changes. Use `wait_pr.py` without CI
+ arguments for a PR-only loop, and reserve `wait_action.py` for Actions targets
+ that are not attached to a PR.
- The one-watch invariant is scoped by owner and concern: one live lane/fix
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 the
- lane watch.
+ delegated. Review activity and the PR's exact-head CI are one lane concern
+ and should use the combined `wait_pr.py` watch rather than two sibling
+ waiters. Each genuinely independent concern needs its own state; never share
+ cursor state between concurrent watches or count unrelated global monitors as
+ the lane watch.
- Follow `background-watch-hook` for waiter commands, state, baseline seeding,
catch-up,
filtering, settling, retries, and delivery acknowledgement. Those mechanics
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index 9c2325ff7..0084e0797 100644
--- a/skills/background-watch-hook/SKILL.md
+++ b/skills/background-watch-hook/SKILL.md
@@ -2,7 +2,7 @@
name: background-watch-hook
slug: background-watch-hook
description: 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.14.0
+version: 0.15.0
---
# Background Watch Hook
@@ -30,7 +30,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or
- `vibe watch list`, `vibe watch show`, `vibe watch update`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`
Use these to inspect and manage the watch after creation.
- `scripts/wait_pr.py`
- Bundled waiter example for one common case: GitHub PR review activity.
+ Bundled GitHub waiter for PR activity, with optional exact-head Actions monitoring.
## Use `vibe watch` First
@@ -183,10 +183,15 @@ This skill ships bundled GitHub waiters:
- `scripts/wait_pr.py`
Waits for GitHub PR review activity, including reviews, inline review comments, PR conversation comments, PR status transitions such as `draft -> open`, `open -> merged`, or `open -> closed`, and the special Codex `+1` reaction on the PR body. It can also wait for newly opened PRs in a repository.
+ When `--sha` and one or more `--workflow` values are provided for a specific PR,
+ the same waiter also waits for every matching Actions run at that exact SHA and
+ optional branch.
- `scripts/wait_issue.py`
Waits for GitHub issue activity, either newly opened issues in a repository or new comments on a single issue.
- `scripts/wait_action.py`
- Waits for selected GitHub Actions workflow runs on a specific commit SHA to finish. Workflow failures are reported as an event so the follow-up turn can inspect and handle them.
+ Waits for selected GitHub Actions workflow runs on a specific commit SHA to finish
+ when there is no PR activity stream to combine with them. Workflow failures are
+ reported as an event so the follow-up turn can inspect and handle them.
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.
@@ -227,7 +232,54 @@ BACKGROUND_WATCH_HOOK_DIR="$(dirname "$BACKGROUND_WATCH_HOOK_SKILL_FILE")"
## GitHub Example Waiter
-Use the bundled GitHub waiter only when the watched thing is PR review activity.
+For a PR delivery loop, prefer one combined `wait_pr.py` watch. It observes PR review,
+comment, reaction, thread, lifecycle, and head-change events together with selected
+Actions workflows for one exact commit. This keeps one cursor/state file and one
+follow-up Agent Run for the whole PR concern. Use `wait_pr.py` without CI arguments
+for PR-only monitoring. Use `wait_action.py` only for an Actions wait that is not
+attached to a PR.
+
+### Preferred PR + CI watch
+
+The CI arguments are one group: `--sha` and at least one repeatable `--workflow` are
+required, while `--branch`, `--max-pages`, and `--success-conclusion` are optional.
+The waiter stays quiet while a requested run is missing or still running, then reports
+the complete exact-head result when every requested workflow has terminal runs. Every
+distinct matching run ID is included, so an earlier failed rerun remains visible to
+the follow-up turn. If the PR head changes, the waiter reports that event; fetch the
+new head and re-arm with a new `--sha` rather than continuing to gate the old commit.
+
+```bash
+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"
+HEAD_SHA="$(gh pr view 151 --repo avibe-bot/avibe --json headRefOid --jq .headRefOid)"
+BRANCH="$(gh pr view 151 --repo avibe-bot/avibe --json headRefName --jq .headRefName)"
+
+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \
+ --repo avibe-bot/avibe --pr 151 \
+ --sha "$HEAD_SHA" --branch "$BRANCH" \
+ --workflow lint \
+ --actionable-only \
+ --state-file "$STATE_FILE" --seed-state
+
+# Push or post the review trigger only after the combined baseline is durable.
+# If the push changed the PR head after seeding, refresh both values before arming.
+# This is required even when the old SHA was used to create the baseline.
+HEAD_SHA="$(gh pr view 151 --repo avibe-bot/avibe --json headRefOid --jq .headRefOid)"
+BRANCH="$(gh pr view 151 --repo avibe-bot/avibe --json headRefName --jq .headRefName)"
+
+vibe watch add \
+ --name "Watch PR 151 review and CI" \
+ --message "PR #151 has new review activity, a head change, or exact-head CI activity. Fetch the latest PR and Actions state, resolve actionable findings, and re-arm the combined waiter for any new head. Summarise the round here in one or two lines; do not post that summary as a PR comment." \
+ -- \
+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \
+ --repo avibe-bot/avibe --pr 151 \
+ --sha "$HEAD_SHA" --branch "$BRANCH" \
+ --workflow lint \
+ --actionable-only --settle 20 --state-file "$STATE_FILE" --interval 60
+```
+
+Do not combine `--new-prs` with CI arguments. A new PR has no stable exact-head
+gate until the follow-up turn resolves its head and workflow set.
One-shot watch:
@@ -430,7 +482,7 @@ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo av
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:
+Standalone GitHub Actions for a pushed commit that is not being monitored through a PR:
```bash
vibe watch add \
diff --git a/skills/background-watch-hook/scripts/_github_actions_wait.py b/skills/background-watch-hook/scripts/_github_actions_wait.py
new file mode 100644
index 000000000..bd6817b80
--- /dev/null
+++ b/skills/background-watch-hook/scripts/_github_actions_wait.py
@@ -0,0 +1,150 @@
+"""Shared GitHub Actions polling helpers for the bundled waiters."""
+
+from __future__ import annotations
+
+import urllib.parse
+from typing import Any
+
+from _github_wait_common import github_get
+
+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,
+ cache: Any = None,
+) -> 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, cache=cache)
+ request_count += 1
+ if not isinstance(payload, dict):
+ raise RuntimeError(f"Expected a JSON object from {url}")
+ page_runs = payload.get("workflow_runs")
+ if not isinstance(page_runs, list):
+ raise RuntimeError(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_matching_runs(
+ runs: list[dict[str, Any]],
+ *,
+ workflows: list[str],
+ branch: str | None,
+ head_sha: str,
+) -> dict[str, list[dict[str, Any]]]:
+ """Return every distinct matching run, including older reruns."""
+
+ workflow_set = set(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):
+ 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 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
+
+
+def normalize_selected_runs(selected: dict[str, list[dict[str, Any]]]) -> dict[str, list[dict[str, Any]]]:
+ """Keep only stable gate state so timestamps do not create false events."""
+
+ return {
+ workflow: [
+ {
+ "id": run.get("id"),
+ "status": run.get("status"),
+ "conclusion": run.get("conclusion"),
+ "head_sha": run.get("head_sha"),
+ "head_branch": run.get("head_branch"),
+ "run_attempt": run.get("run_attempt"),
+ }
+ for run in runs
+ ]
+ for workflow, runs in selected.items()
+ }
+
+
+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)
diff --git a/skills/background-watch-hook/scripts/wait_action.py b/skills/background-watch-hook/scripts/wait_action.py
index a8f798586..e8777d520 100755
--- a/skills/background-watch-hook/scripts/wait_action.py
+++ b/skills/background-watch-hook/scripts/wait_action.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Wait until selected GitHub Actions workflow runs finish for a commit."""
+"""Wait until standalone GitHub Actions workflow runs finish for a commit."""
from __future__ import annotations
@@ -7,7 +7,6 @@ import argparse
import json
import sys
import time
-import urllib.parse
from pathlib import Path
from typing import Any
@@ -19,138 +18,20 @@ from _github_wait_common import ( # noqa: E402
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 RuntimeError(f"Expected a JSON object from {url}")
- page_runs = payload.get("workflow_runs")
- if not isinstance(page_runs, list):
- raise RuntimeError(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]]]:
- """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, 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):
- 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 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
-
-
-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)
+from _github_actions_wait import ( # noqa: E402
+ DEFAULT_SUCCESS_CONCLUSIONS,
+ TERMINAL_STATUS,
+ fetch_workflow_runs as _fetch_workflow_runs,
+ normalize_selected_runs as _normalize_selected_runs,
+ render_actions_result as _render_actions_result,
+ select_matching_runs as _select_latest_runs_by_workflow,
+)
def _write_cursor_output(path: str | None, *, selected: dict[str, list[dict[str, Any]]]) -> None:
@@ -163,6 +44,7 @@ def _write_cursor_output(path: str | None, *, selected: dict[str, list[dict[str,
"id": run.get("id"),
"status": run.get("status"),
"conclusion": run.get("conclusion"),
+ "run_attempt": run.get("run_attempt"),
"html_url": run.get("html_url"),
}
for run in runs
diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.py
index 1e4f54564..91ba0bb19 100755
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@ -48,6 +48,13 @@ from _github_wait_common import ( # noqa: E402
squash,
WATCH_ID_ENV,
)
+from _github_actions_wait import ( # noqa: E402
+ DEFAULT_SUCCESS_CONCLUSIONS,
+ fetch_workflow_runs,
+ normalize_selected_runs,
+ render_actions_result,
+ select_matching_runs,
+)
CODEX_REVIEW_PASS_REACTION_USERS = {
"chatgpt-codex-connector",
@@ -87,6 +94,7 @@ 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"
+ACTIONS_SNAPSHOT_KEY = "actions"
PR_FINGERPRINT_KEYS = (
REVIEW_FINGERPRINTS_KEY,
REVIEW_COMMENT_FINGERPRINTS_KEY,
@@ -554,6 +562,10 @@ def _fetch_state(
cache: ResponseCache | None = None,
review_comment_since: str | None = None,
issue_comment_since: str | None = None,
+ ci_sha: str | None = None,
+ ci_branch: str | None = None,
+ ci_workflows: list[str] | None = None,
+ ci_max_pages: int = 3,
) -> tuple[dict[str, list[dict[str, Any]]], int]:
encoded_repo = urllib.parse.quote(repo, safe="/")
base_url = f"https://api.github.com/repos/{encoded_repo}"
@@ -589,6 +601,28 @@ def _fetch_state(
cache=cache,
)
review_threads, review_thread_requests = _fetch_review_threads(repo, pr_number, token)
+ actions: list[dict[str, Any]] = []
+ action_requests = 0
+ if ci_sha and ci_workflows:
+ actions, action_requests = fetch_workflow_runs(
+ repo,
+ token,
+ branch=ci_branch,
+ head_sha=ci_sha,
+ max_pages=ci_max_pages,
+ cache=cache,
+ )
+ # Actions are fetched after several independent PR requests. Re-read the
+ # mutable PR object after that window so a push cannot pair an old head with
+ # a terminal result from the exact SHA supplied by the caller.
+ pull_request = github_get(f"{base_url}/pulls/{pr_number}", token, cache=cache)
+ requests_after_actions = 1
+ else:
+ requests_after_actions = 0
+ if ci_sha and ci_workflows and _current_pr_head_sha(pull_request).casefold() != ci_sha.casefold():
+ # The PR moved while this snapshot was assembled. The caller will report the
+ # head transition and re-arm with a new SHA; never render old-SHA Actions.
+ actions = []
return (
{
"pull_request": pull_request,
@@ -597,6 +631,7 @@ def _fetch_state(
"issue_comments": issue_comments,
"reactions": reactions,
"review_threads": review_threads,
+ "actions": actions,
},
(
1
@@ -605,6 +640,8 @@ def _fetch_state(
+ issue_comment_requests
+ reaction_requests
+ review_thread_requests
+ + action_requests
+ + requests_after_actions
),
)
@@ -867,7 +904,12 @@ def _startup_failure_exit_code(error: Any) -> int:
return RETRY_EXIT_CODE if isinstance(error, InitialRequestRetriesExhausted) else 1
-def _watch_identity(args: argparse.Namespace) -> str:
+def _watch_identity(
+ args: argparse.Namespace,
+ *,
+ legacy_ci_sha: str | None = None,
+ include_ci_max_pages: bool = True,
+) -> 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 --
@@ -881,19 +923,83 @@ def _watch_identity(args: argparse.Namespace) -> str:
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,
- )
+ material_fields = {
+ "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 [])),
+ }
+ # Keep the v0.14 PR-only identity stable. Adding CI fields to that hash would
+ # make every existing PR-only state file look owned by a different watch after
+ # upgrading, even though its report contract has not changed.
+ if _ci_enabled(args):
+ material_fields.update(
+ {
+ "ci_branch": args.branch,
+ "ci_workflows": list(args.workflow or []),
+ "ci_success_conclusions": sorted(
+ _parse_success_conclusions(args.success_conclusion)
+ ),
+ }
+ )
+ if include_ci_max_pages:
+ material_fields["ci_max_pages"] = args.max_pages
+ if legacy_ci_sha is not None:
+ material_fields["ci_sha"] = legacy_ci_sha
+ material = json.dumps(material_fields, sort_keys=True)
return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{material}".encode()).hexdigest()[:16]
+def _legacy_watch_identity_aliases(
+ args: argparse.Namespace,
+ path: str | None,
+) -> set[str]:
+ """Return released combined identities that can be migrated at this path.
+
+ Before combined waiting was stabilized, the CI target SHA was part of the watch
+ identity. A head change therefore made an otherwise identical watch look foreign.
+ Only hashes derived from this path's own recorded PR/Actions head are accepted;
+ this is a narrow migration, not a general identity bypass.
+ """
+
+ if not path or not _ci_enabled(args):
+ return set()
+ try:
+ payload = json.loads(Path(path).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return set()
+ if not isinstance(payload, dict):
+ return set()
+ if payload.get("version") != STATE_FILE_VERSION:
+ return set()
+ if payload.get("repo") != args.repo or payload.get("pr") != args.pr:
+ return set()
+
+ candidate_shas: set[str] = set()
+ for value in (args.sha, payload.get("head_sha")):
+ if isinstance(value, str) and value:
+ candidate_shas.add(value)
+ actions = payload.get(ACTIONS_SNAPSHOT_KEY)
+ if isinstance(actions, dict):
+ for runs in actions.values():
+ if not isinstance(runs, list):
+ continue
+ for run in runs:
+ if isinstance(run, dict):
+ value = run.get("head_sha")
+ if isinstance(value, str) and value:
+ candidate_shas.add(value)
+ aliases = {
+ _watch_identity(args, legacy_ci_sha=sha, include_ci_max_pages=False)
+ for sha in candidate_shas
+ }
+ # The released combined identity omitted both the target SHA and page limit.
+ # Accept that exact old shape once so adding coverage cannot strand cursors.
+ aliases.add(_watch_identity(args, include_ci_max_pages=False))
+ return aliases
+
+
def _managed_watch_id() -> str | None:
"""The id of the ``vibe watch`` this waiter is a cycle of, when there is one.
@@ -915,6 +1021,7 @@ def _owner_conflict(
pr_number: int | None,
watch_identity: str | None,
watch_id: str | None,
+ watch_identity_aliases: set[str] | None = None,
) -> str | None:
"""Why ``owner`` is somebody else's claim on the path, or ``None`` when it is ours.
@@ -935,7 +1042,12 @@ def _owner_conflict(
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 (
+ saved_watch is not None
+ and watch_identity is not None
+ and saved_watch != watch_identity
+ and saved_watch not in (watch_identity_aliases or set())
+ ):
return (
f"belongs to another watch on {saved_repo}#{saved_pr} with different "
"reporting filters"
@@ -957,6 +1069,7 @@ def _load_state_file(
pr_number: int | None,
watch_identity: str | None = None,
watch_id: str | None = None,
+ watch_identity_aliases: set[str] | None = None,
) -> dict[str, Any]:
"""Read cursors left behind by an earlier run of this same waiter.
@@ -998,6 +1111,7 @@ def _load_state_file(
pr_number=pr_number,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
if conflict is not None:
raise StateFileOwnershipError(f"State file {path} {conflict}")
@@ -1188,6 +1302,7 @@ def _verify_state_file_writable(
pr_number: int | None,
watch_identity: str | None = None,
watch_id: str | None = None,
+ watch_identity_aliases: set[str] | None = None,
) -> None:
"""Claim the requested state file, and fail before the first poll if it is unusable.
@@ -1255,6 +1370,7 @@ def _verify_state_file_writable(
pr_number=pr_number,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
if conflict is not None:
return
@@ -1300,6 +1416,7 @@ def _write_state_file(
pr_number: int | None,
watch_identity: str | None = None,
watch_id: str | None = None,
+ watch_identity_aliases: set[str] | None = None,
**fields: Any,
) -> None:
if not path:
@@ -1325,6 +1442,7 @@ def _write_state_file(
pr_number=pr_number,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
if conflict is not None:
raise StateFileOwnershipError(f"State file {path} now {conflict}")
@@ -1418,6 +1536,41 @@ def _saved_snapshot(saved: dict[str, Any]) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
+def _saved_actions_snapshot(saved: dict[str, Any]) -> dict[str, Any]:
+ value = saved.get(ACTIONS_SNAPSHOT_KEY)
+ return value if isinstance(value, dict) else {}
+
+
+def _ci_enabled(args: argparse.Namespace) -> bool:
+ return bool(args.sha or args.branch or args.workflow or args.success_conclusion)
+
+
+def _validate_ci_args(args: argparse.Namespace) -> str | None:
+ provided = _ci_enabled(args)
+ if not provided:
+ return None
+ if args.pr is None:
+ return "CI monitoring requires --pr; --new-prs cannot be combined with --sha or --workflow"
+ if not args.sha:
+ return "CI monitoring requires --sha"
+ if not args.workflow:
+ return "CI monitoring requires at least one --workflow when --sha is provided"
+ if args.max_pages < 1:
+ return "--max-pages must be at least 1"
+ if len(set(args.workflow)) != len(args.workflow):
+ return "--workflow values must be unique"
+ return None
+
+
+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 _missing_pr_baselines(saved: dict[str, Any]) -> list[str]:
missing: list[str] = []
if _saved_str(saved, "head_sha") is None:
@@ -1434,6 +1587,15 @@ def _missing_pr_baselines(saved: dict[str, Any]) -> list[str]:
return missing
+def _missing_actions_baselines(saved: dict[str, Any], workflows: list[str]) -> list[str]:
+ value = saved.get(ACTIONS_SNAPSHOT_KEY)
+ if not isinstance(value, dict) or set(value) != set(workflows):
+ return [ACTIONS_SNAPSHOT_KEY]
+ if any(not isinstance(runs, list) for runs in value.values()):
+ return [ACTIONS_SNAPSHOT_KEY]
+ return []
+
+
def _last_delivery() -> str | None:
"""When the supervisor last queued a report from this watch, as it sees it.
@@ -1465,6 +1627,7 @@ def _resolve_staged_state(
pr_number: int | None,
watch_identity: str | None,
watch_id: str | None,
+ watch_identity_aliases: set[str] | None = None,
return_replay: bool = False,
) -> dict[str, Any] | tuple[dict[str, Any], str | None]:
"""Promote acknowledged state or replay its persisted event payload.
@@ -1513,6 +1676,7 @@ def _resolve_staged_state(
pr_number=pr_number,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
**fields,
)
return (resolved, None) if return_replay else resolved
@@ -1612,6 +1776,36 @@ def _build_parser() -> argparse.ArgumentParser:
action="store_true",
help="Write a complete current baseline to --state-file and exit without waiting",
)
+ parser.add_argument(
+ "--sha",
+ help=(
+ "Exact PR head SHA whose Actions runs should be monitored together with PR activity; "
+ "requires at least one --workflow"
+ ),
+ )
+ parser.add_argument(
+ "--branch",
+ help="Optional Actions head branch constraint used with --sha and --workflow",
+ )
+ parser.add_argument(
+ "--workflow",
+ action="append",
+ help="Actions workflow name to monitor at --sha; repeatable and enables combined CI mode",
+ )
+ parser.add_argument(
+ "--max-pages",
+ type=int,
+ default=3,
+ help="Maximum Actions run-list pages to inspect per poll in combined CI mode",
+ )
+ parser.add_argument(
+ "--success-conclusion",
+ action="append",
+ help=(
+ "Actions conclusion treated as successful in combined CI mode; repeatable or comma-separated. "
+ "Defaults to success,skipped,neutral."
+ ),
+ )
parser.add_argument(
"--allow-unauthenticated",
action="store_true",
@@ -1623,6 +1817,13 @@ def _build_parser() -> argparse.ArgumentParser:
def main() -> int:
args = _build_parser().parse_args()
+ ci_error = _validate_ci_args(args)
+ if ci_error is not None:
+ print(ci_error, file=sys.stderr)
+ return 2
+ ci_enabled = _ci_enabled(args)
+ success_conclusions = _parse_success_conclusions(args.success_conclusion)
+
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
@@ -1642,6 +1843,7 @@ def main() -> int:
return 2
watch_identity = _watch_identity(args)
+ watch_identity_aliases = _legacy_watch_identity_aliases(args, args.state_file)
watch_id = _managed_watch_id()
delivery_stamp = _last_delivery()
two_phase = watch_id is not None
@@ -1661,6 +1863,7 @@ def main() -> int:
pr_number=args.pr,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
replay_output = _staged_replay_output(saved, delivery_stamp)
if replay_output is not None:
@@ -1737,6 +1940,10 @@ def main() -> int:
cache=cache,
review_comment_since=initial_review_comment_since,
issue_comment_since=initial_issue_comment_since,
+ ci_sha=args.sha if ci_enabled else None,
+ ci_branch=args.branch if ci_enabled else None,
+ ci_workflows=args.workflow if ci_enabled else None,
+ ci_max_pages=args.max_pages,
)
initial_pr_stop_after_id = None
initial_pr_max_pages = None
@@ -1763,7 +1970,25 @@ def main() -> int:
if initial_request.value is None:
print("Initial GitHub PR state request completed without a result", file=sys.stderr)
return 1
+ selected_actions: dict[str, list[dict[str, Any]]] = {}
state, requests_per_poll_count = initial_request.value
+ if args.pr is not None and ci_enabled:
+ observed_head_sha = _current_pr_head_sha(state.get("pull_request"))
+ if observed_head_sha.casefold() != args.sha.casefold():
+ print(
+ "Refusing to start a combined watch: PR head "
+ f"{observed_head_sha} does not match --sha {args.sha}. "
+ "Refresh the SHA and retry.",
+ file=sys.stderr,
+ )
+ return 2
+ if ci_enabled:
+ selected_actions = select_matching_runs(
+ state.get("actions", []),
+ workflows=args.workflow or [],
+ branch=args.branch,
+ head_sha=args.sha,
+ )
# 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.
@@ -1773,6 +1998,7 @@ def main() -> int:
pr_number=args.pr,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
saved = _load_state_file(
args.state_file,
@@ -1780,6 +2006,7 @@ def main() -> int:
pr_number=args.pr,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
)
saved, replay_output = _resolve_staged_state(
args.state_file,
@@ -1789,6 +2016,7 @@ def main() -> int:
pr_number=args.pr,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
return_replay=True,
)
if replay_output is not None:
@@ -1808,6 +2036,8 @@ def main() -> int:
)
)
missing_baselines = _missing_pr_baselines(saved) if resumed and args.pr is not None else []
+ if ci_enabled and resumed and args.pr is not None:
+ missing_baselines.extend(_missing_actions_baselines(saved, args.workflow or []))
if missing_baselines and not explicit_replay:
print(
"Saved PR state lacks required baseline(s): %s; use --catch-up, or remove "
@@ -1837,6 +2067,21 @@ def main() -> int:
# 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)
+ if not ci_enabled:
+ actions_snapshot = None
+ elif args.catch_up:
+ actions_snapshot = None
+ elif explicit_replay:
+ # Explicit cursor replay is a PR activity request, not a request to
+ # replay an already observed terminal Actions result.
+ actions_snapshot = normalize_selected_runs(selected_actions)
+ elif resumed:
+ actions_snapshot = _saved_actions_snapshot(saved)
+ else:
+ # Explicit PR cursor replay does not replay an unrelated already-terminal
+ # Actions result. A fresh normal watch still needs the current CI snapshot
+ # as its baseline to avoid waking on the seed itself.
+ actions_snapshot = normalize_selected_runs(selected_actions)
review_comment_since = (
_saved_str(saved, "review_comment_since")
if resumed and args.since_review_comment_id is None
@@ -1869,6 +2114,7 @@ def main() -> int:
ignore_patterns=ignore_patterns,
review_threads_available=token is not None,
)
+ actions_snapshot = normalize_selected_runs(selected_actions) if ci_enabled else None
if token is None:
bootstrap_requests = requests_per_poll_count
@@ -1957,13 +2203,61 @@ def main() -> int:
ignore_patterns=ignore_patterns,
)
+ def _render_combined(
+ cursors: tuple[int, int, int, int, str],
+ ) -> tuple[str | None, int, int, int, int, str]:
+ pr_result = _render(cursors)
+ if not ci_enabled:
+ return pr_result
+
+ current_actions = normalize_selected_runs(selected_actions)
+ actions_output = None
+ if actions_snapshot is None or current_actions != actions_snapshot:
+ actions_output, _failed = render_actions_result(
+ repo=args.repo,
+ branch=args.branch,
+ head_sha=args.sha,
+ selected=selected_actions,
+ success_conclusions=success_conclusions,
+ )
+ if actions_output is None:
+ return pr_result
+ if pr_result[0] is None:
+ return (actions_output, *pr_result[1:])
+ return (f"{pr_result[0]}\n{actions_output}", *pr_result[1:])
+
+ def _refresh_actions() -> None:
+ nonlocal selected_actions
+ if ci_enabled:
+ selected_actions = select_matching_runs(
+ state.get("actions", []),
+ workflows=args.workflow or [],
+ branch=args.branch,
+ head_sha=args.sha,
+ )
+
+ def _actions_waiting_for_terminal_result() -> bool:
+ if not ci_enabled:
+ return False
+ current_actions = normalize_selected_runs(selected_actions)
+ if actions_snapshot is not None and current_actions == actions_snapshot:
+ return False
+ actions_output, _failed = render_actions_result(
+ repo=args.repo,
+ branch=args.branch,
+ head_sha=args.sha,
+ selected=selected_actions,
+ success_conclusions=success_conclusions,
+ )
+ return actions_output is None
+
def _advance_since() -> None:
nonlocal review_comment_since, issue_comment_since
review_comment_since = later_since(review_comment_since, state["review_comments"])
issue_comment_since = later_since(issue_comment_since, state["issue_comments"])
def _pr_state_fields() -> dict[str, Any]:
- return {
+ fields = {
"review_cursor": review_cursor,
"review_comment_cursor": review_comment_cursor,
"issue_comment_cursor": issue_comment_cursor,
@@ -1980,6 +2274,9 @@ def main() -> int:
REVIEW_THREAD_STATES_KEY: dict(review_thread_states),
PR_SNAPSHOT_KEY: snapshot or {},
}
+ if ci_enabled:
+ fields[ACTIONS_SNAPSHOT_KEY] = normalize_selected_runs(selected_actions)
+ return fields
def _persist_pr_state(
*,
@@ -2005,6 +2302,7 @@ def main() -> int:
pr_number=args.pr,
watch_identity=watch_identity,
watch_id=watch_id,
+ watch_identity_aliases=watch_identity_aliases,
**fields,
)
@@ -2035,6 +2333,13 @@ def main() -> int:
return first
best = first
+ best_pr_only = _render(pending) if ci_enabled else None
+
+ def _fallback() -> tuple[str | None, int, int, int, int, str]:
+ if _actions_waiting_for_terminal_result():
+ return best_pr_only or (None, *best[1:])
+ return best
+
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
@@ -2051,7 +2356,7 @@ def main() -> int:
"reporting the batch seen so far.",
file=sys.stderr,
)
- return best
+ return _fallback()
time.sleep(settle_seconds)
settle_request = github_request(
lambda: _fetch_state(
@@ -2059,6 +2364,10 @@ def main() -> int:
args.pr,
token,
cache=cache,
+ ci_sha=args.sha if ci_enabled else None,
+ ci_branch=args.branch if ci_enabled else None,
+ ci_workflows=args.workflow if ci_enabled else None,
+ ci_max_pages=args.max_pages,
),
unauthenticated=token is None,
)
@@ -2070,23 +2379,29 @@ def main() -> int:
f"Settle re-poll failed: {settle_request.error}; reporting the batch seen so far.",
file=sys.stderr,
)
- return best
+ return _fallback()
if settle_request.value is None:
print(
"Settle re-poll returned no state; reporting the batch seen so far.",
file=sys.stderr,
)
- return best
+ return _fallback()
state, _count = settle_request.value
+ _refresh_actions()
+ pr_candidate = _render(pending)
+ if _actions_waiting_for_terminal_result():
+ if pr_candidate[0] is not None:
+ best_pr_only = pr_candidate
+ continue
# Rendered from the same cursors as the first hit, so the result is a
# superset rather than a second, partial report.
- candidate = _render(pending)
+ candidate = _render_combined(pending)
if candidate[0] is None:
return best
if candidate[1:] == best[1:]:
return candidate
best = candidate
- return best
+ return _fallback()
pending_cursors = (
review_cursor,
@@ -2099,7 +2414,7 @@ def main() -> int:
initial_result = (
(None, *pending_cursors)
if args.seed_state
- else _render(pending_cursors)
+ else _render_combined(pending_cursors)
)
if initial_result[0] is not None and not args.catch_up:
initial_result = _settle(initial_result, pending_cursors)
@@ -2226,6 +2541,10 @@ def main() -> int:
args.pr,
token,
cache=cache,
+ ci_sha=args.sha if ci_enabled else None,
+ ci_branch=args.branch if ci_enabled else None,
+ ci_workflows=args.workflow if ci_enabled else None,
+ ci_max_pages=args.max_pages,
),
unauthenticated=token is None,
)
@@ -2278,6 +2597,7 @@ def main() -> int:
effective_interval = target_interval
if args.pr is not None:
+ _refresh_actions()
observed_head_sha = _current_pr_head_sha(state.get("pull_request"))
pending_cursors = (
review_cursor,
@@ -2287,7 +2607,7 @@ def main() -> int:
pr_status,
)
pre_event_fields = _pr_state_fields()
- result = _render(pending_cursors)
+ result = _render_combined(pending_cursors)
if result[0] is not None:
result = _settle(result, pending_cursors)
(
@@ -2318,6 +2638,8 @@ def main() -> int:
committed_snapshot=snapshot,
review_threads_available=token is not None,
)
+ if ci_enabled:
+ actions_snapshot = normalize_selected_runs(selected_actions)
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.
diff --git a/tests/test_wait_for_github_action_runs.py b/tests/test_wait_for_github_action_runs.py
index fccc83f99..dac474ec9 100644
--- a/tests/test_wait_for_github_action_runs.py
+++ b/tests/test_wait_for_github_action_runs.py
@@ -90,6 +90,41 @@ def test_render_actions_result_waits_for_missing_or_running_runs() -> None:
assert failed is False
+def test_normalize_selected_runs_distinguishes_rerun_attempts() -> None:
+ module = _load_module()
+ first = module._normalize_selected_runs(
+ {
+ "CI": [
+ {
+ "id": 1,
+ "status": "completed",
+ "conclusion": "success",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "run_attempt": 1,
+ }
+ ]
+ }
+ )
+ rerun = module._normalize_selected_runs(
+ {
+ "CI": [
+ {
+ "id": 1,
+ "status": "completed",
+ "conclusion": "success",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "run_attempt": 2,
+ }
+ ]
+ }
+ )
+
+ assert first != rerun
+ assert first["CI"][0]["run_attempt"] == 1
+
+
def test_render_actions_result_reports_success() -> None:
module = _load_module()
output, failed = module._render_actions_result(
diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.py
index 9e3920005..6195eed14 100644
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@ -797,6 +797,419 @@ def test_main_detects_pr_status_change_during_polling() -> None:
assert "pr_status #153 open -> merged" in stdout.getvalue()
+def test_combined_ci_mode_requires_exact_sha_and_workflow() -> None:
+ module = _load_module()
+
+ valid = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "153", "--sha", "abc123", "--workflow", "CI"]
+ )
+ assert module._validate_ci_args(valid) is None
+
+ missing_sha = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "153", "--workflow", "CI"]
+ )
+ assert "--sha" in (module._validate_ci_args(missing_sha) or "")
+
+ new_pr_mode = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--new-prs", "--sha", "abc123", "--workflow", "CI"]
+ )
+ assert "--new-prs" in (module._validate_ci_args(new_pr_mode) or "")
+
+
+def test_pr_only_watch_identity_keeps_the_legacy_material() -> None:
+ module = _load_module()
+ args = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "153", "--actionable-only"]
+ )
+ expected_material = json.dumps(
+ {
+ "mode": "pr",
+ "actionable_only": True,
+ "include_self_comments": False,
+ "ignore_authors": [],
+ "ignore_comment_patterns": [],
+ },
+ sort_keys=True,
+ )
+ expected = module.hashlib.sha256(
+ f"wait_pr/{module.STATE_FILE_VERSION}/{expected_material}".encode()
+ ).hexdigest()[:16]
+
+ assert module._watch_identity(args) == expected
+
+
+def test_combined_watch_identity_includes_ci_contract() -> None:
+ module = _load_module()
+ pr_only = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "153", "--actionable-only"]
+ )
+ combined = module._build_parser().parse_args(
+ [
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "153",
+ "--actionable-only",
+ "--sha",
+ "abc123",
+ "--workflow",
+ "CI",
+ ]
+ )
+
+ assert module._watch_identity(pr_only) != module._watch_identity(combined)
+
+
+def test_combined_watch_identity_includes_actions_page_limit() -> None:
+ module = _load_module()
+
+ def _identity(max_pages: str) -> str:
+ return module._watch_identity(
+ module._build_parser().parse_args(
+ [
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "153",
+ "--sha",
+ "abc123",
+ "--workflow",
+ "CI",
+ "--max-pages",
+ max_pages,
+ ]
+ )
+ )
+
+ assert _identity("1") != _identity("3")
+
+
+def test_combined_watch_migrates_identity_without_actions_page_limit(tmp_path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "pr-153-combined.json"
+ args = module._build_parser().parse_args(
+ ["--repo", "avibe-bot/avibe", "--pr", "153", "--sha", "abc123", "--workflow", "CI"]
+ )
+ legacy_identity = module._watch_identity(args, include_ci_max_pages=False)
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": module.STATE_FILE_VERSION,
+ "repo": "avibe-bot/avibe",
+ "pr": 153,
+ "watch": legacy_identity,
+ "owner": "wat_123",
+ "head_sha": "abc123",
+ "actions": {"CI": []},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ aliases = module._legacy_watch_identity_aliases(args, str(state_file))
+ assert legacy_identity in aliases
+
+
+def test_combined_watch_migrates_the_legacy_sha_identity(tmp_path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "pr-153-combined.json"
+ args = module._build_parser().parse_args(
+ [
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "153",
+ "--sha",
+ "new-sha",
+ "--branch",
+ "feature",
+ "--workflow",
+ "CI",
+ ]
+ )
+ legacy_identity = module._watch_identity(args, legacy_ci_sha="old-sha", include_ci_max_pages=False)
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": module.STATE_FILE_VERSION,
+ "repo": "avibe-bot/avibe",
+ "pr": 153,
+ "watch": legacy_identity,
+ "owner": "wat_123",
+ "head_sha": "old-sha",
+ "actions": {"CI": []},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ identity = module._watch_identity(args)
+ aliases = module._legacy_watch_identity_aliases(args, str(state_file))
+ saved = module._load_state_file(
+ str(state_file),
+ repo="avibe-bot/avibe",
+ pr_number=153,
+ watch_identity=identity,
+ watch_id="wat_123",
+ watch_identity_aliases=aliases,
+ )
+
+ assert saved["watch"] == legacy_identity
+ assert legacy_identity in aliases
+ module._write_state_file(
+ str(state_file),
+ repo="avibe-bot/avibe",
+ pr_number=153,
+ watch_identity=identity,
+ watch_id="wat_123",
+ watch_identity_aliases=aliases,
+ head_sha="new-sha",
+ actions={"CI": []},
+ )
+ assert json.loads(state_file.read_text(encoding="utf-8"))["watch"] == identity
+
+
+def test_fresh_combined_baseline_rejects_a_stale_sha(tmp_path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "pr-153-combined.json"
+ state = _pr_state()
+ state["pull_request"]["head"] = {"sha": "new-sha"}
+
+ stdout = io.StringIO()
+ stderr = io.StringIO()
+ with (
+ patch.object(module, "_fetch_state", return_value=(state, 1)),
+ 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",
+ "153",
+ "--sha",
+ "old-sha",
+ "--workflow",
+ "CI",
+ "--state-file",
+ str(state_file),
+ ],
+ ),
+ redirect_stdout(stdout),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 2
+ assert "does not match --sha old-sha" in stderr.getvalue()
+ assert not state_file.exists()
+
+
+def test_resumed_combined_watch_rejects_a_stale_sha(tmp_path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "pr-153-combined.json"
+ baseline = _pr_state()
+ baseline["pull_request"]["head"] = {"sha": "new-sha"}
+ state_file.write_text(
+ json.dumps(
+ {
+ "version": module.STATE_FILE_VERSION,
+ "repo": "avibe-bot/avibe",
+ "pr": 153,
+ "review_cursor": 0,
+ "review_comment_cursor": 0,
+ "issue_comment_cursor": 0,
+ "reaction_cursor": 0,
+ "pr_status": "open",
+ "review_comment_since": "2026-08-04T09:00:00Z",
+ "issue_comment_since": "2026-08-04T09:00:00Z",
+ "viewer_login": "tester",
+ "token_fingerprint": module._token_fingerprint("token"),
+ **_complete_pr_baseline_fields(module, baseline),
+ "actions": {"CI": []},
+ }
+ ),
+ encoding="utf-8",
+ )
+ original_state = state_file.read_text(encoding="utf-8")
+
+ stdout = io.StringIO()
+ stderr = io.StringIO()
+ with (
+ patch.object(module, "_fetch_state", return_value=(baseline, 1)),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login") as fake_login,
+ patch(
+ "sys.argv",
+ [
+ "wait_pr.py",
+ "--repo",
+ "avibe-bot/avibe",
+ "--pr",
+ "153",
+ "--sha",
+ "old-sha",
+ "--workflow",
+ "CI",
+ "--state-file",
+ str(state_file),
+ ],
+ ),
+ redirect_stdout(stdout),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 2
+ assert "does not match --sha old-sha" in stderr.getvalue()
+ assert stdout.getvalue() == ""
+ assert state_file.read_text(encoding="utf-8") == original_state
+ fake_login.assert_not_called()
+
+
+def test_combined_pr_waiter_reports_ci_completion(tmp_path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "pr-153-combined.json"
+ fetch_calls = 0
+
+ def _fake_fetch_state(repo, pr_number, token, **kwargs):
+ nonlocal fetch_calls
+ fetch_calls += 1
+ assert kwargs["ci_sha"] == "abc123"
+ assert kwargs["ci_workflows"] == ["CI"]
+ action = {
+ "id": 7,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "feature",
+ "status": "in_progress" if fetch_calls == 1 else "completed",
+ "conclusion": None if fetch_calls == 1 else "success",
+ "html_url": "https://github.com/example/actions/runs/7",
+ }
+ state = _pr_state()
+ state["pull_request"]["head"] = {"sha": "abc123"}
+ state["actions"] = [action]
+ return state, 2
+
+ 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",
+ "--sha",
+ "abc123",
+ "--branch",
+ "feature",
+ "--workflow",
+ "CI",
+ "--state-file",
+ str(state_file),
+ "--interval",
+ "1",
+ ],
+ ),
+ redirect_stdout(stdout),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert fetch_calls == 2
+ assert "GitHub Actions success for avibe-bot/avibe@abc123 on feature" in stdout.getvalue()
+ assert "CI: status=completed conclusion=success" in stdout.getvalue()
+
+
+def test_combined_settle_does_not_report_a_stale_ci_success_after_a_rerun_starts() -> None:
+ module = _load_module()
+ fetch_calls = 0
+
+ def _fake_fetch_state(repo, pr_number, token, **kwargs):
+ nonlocal fetch_calls
+ fetch_calls += 1
+ state = _pr_state()
+ state["pull_request"]["head"] = {"sha": "abc123"}
+ if fetch_calls == 1:
+ action = {
+ "id": 7,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "feature",
+ "status": "completed",
+ "conclusion": "success",
+ "run_attempt": 1,
+ }
+ elif fetch_calls == 2:
+ action = {
+ "id": 7,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "feature",
+ "status": "completed",
+ "conclusion": "success",
+ "run_attempt": 2,
+ }
+ state["review_comments"] = [_review_comment(501)]
+ else:
+ action = {
+ "id": 7,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "feature",
+ "status": "in_progress",
+ "conclusion": None,
+ "run_attempt": 2,
+ }
+ state["review_comments"] = [_review_comment(501)]
+ state["actions"] = [action]
+ return state, 2
+
+ 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",
+ "--sha",
+ "abc123",
+ "--branch",
+ "feature",
+ "--workflow",
+ "CI",
+ "--settle",
+ "1",
+ "--timeout",
+ "0",
+ ],
+ ),
+ redirect_stdout(stdout),
+ ):
+ rc = module.main()
+
+ output = stdout.getvalue()
+ assert rc == 0
+ assert fetch_calls == 5
+ assert "review_comment #501" in output
+ assert "GitHub Actions success" not in output
+
+
def test_main_reduces_unauthenticated_new_pr_interval_after_bootstrap() -> None:
module = _load_module()
fetch_calls: list[int | None] = []
@@ -1565,6 +1978,82 @@ def test_fetch_state_narrows_comments_and_filters_reactions_server_side() -> Non
assert "content=%2B1" in reactions_url
+def test_fetch_state_includes_combined_actions_and_request_count() -> None:
+ module = _load_module()
+ with (
+ patch.object(module, "list_paginated_with_count", return_value=([], 1)),
+ patch.object(
+ module,
+ "github_get",
+ side_effect=[
+ {"number": 153, "state": "open", "head": {"sha": "abc123"}},
+ {"number": 153, "state": "open", "head": {"sha": "abc123"}},
+ ],
+ ) as fetch_pr,
+ patch.object(module, "_fetch_review_threads", return_value=([], 1)),
+ patch.object(
+ module,
+ "fetch_workflow_runs",
+ return_value=(
+ [{"id": 7, "name": "CI", "head_sha": "abc123", "status": "in_progress"}],
+ 2,
+ ),
+ ) as fetch_actions,
+ ):
+ state, request_count = module._fetch_state(
+ "avibe-bot/avibe",
+ 153,
+ "token",
+ ci_sha="abc123",
+ ci_branch="feature",
+ ci_workflows=["CI"],
+ ci_max_pages=4,
+ )
+
+ fetch_actions.assert_called_once_with(
+ "avibe-bot/avibe",
+ "token",
+ branch="feature",
+ head_sha="abc123",
+ max_pages=4,
+ cache=fetch_actions.call_args.kwargs["cache"],
+ )
+ assert state["actions"][0]["id"] == 7
+ assert request_count == 2 + 5 + 2
+ assert fetch_pr.call_count == 2
+
+
+def test_fetch_state_discards_actions_when_pr_moves_during_fetch() -> None:
+ module = _load_module()
+ with (
+ patch.object(module, "list_paginated_with_count", return_value=([], 1)),
+ patch.object(module, "_fetch_review_threads", return_value=([], 1)),
+ patch.object(
+ module,
+ "github_get",
+ side_effect=[
+ {"number": 153, "state": "open", "head": {"sha": "abc123"}},
+ {"number": 153, "state": "open", "head": {"sha": "new-sha"}},
+ ],
+ ),
+ patch.object(
+ module,
+ "fetch_workflow_runs",
+ return_value=([{"id": 7, "name": "CI", "head_sha": "abc123", "status": "completed"}], 1),
+ ),
+ ):
+ state, _request_count = module._fetch_state(
+ "avibe-bot/avibe",
+ 153,
+ "token",
+ ci_sha="abc123",
+ ci_workflows=["CI"],
+ )
+
+ assert state["pull_request"]["head"]["sha"] == "new-sha"
+ assert state["actions"] == []
+
+
def test_fetch_state_omits_since_when_no_cursor_is_known() -> None:
module = _load_module()
urls: list[str] = []