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(watch): add GitHub Actions waiter

cyh268d7d6c34b8
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index fd03b1ad6..4b3cb7471 100644
--- a/skills/background-watch-hook/SKILL.md
+++ b/skills/background-watch-hook/SKILL.md
@@ -159,6 +159,8 @@ This skill ships bundled GitHub waiters:
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.
- `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.
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.
@@ -243,6 +245,23 @@ uv run --no-project scripts/wait_issue.py --repo cyhhao/vibe-remote --new-issues
uv run --no-project scripts/wait_issue.py --repo cyhhao/vibe-remote --issue 157 --interval 60
```
+GitHub Actions for a pushed commit:
+
+```bash
+vibe watch add \
+ --session-key "slack::channel::C123::thread::171717.123" \
+ --name "Watch CI" \
+ --prefix "GitHub Actions finished. Inspect the result below and continue with the deployment or fix failures." \
+ -- \
+ uv run --no-project scripts/wait_action.py \
+ --repo cyhhao/sub2api \
+ --branch main \
+ --sha "$HEAD_SHA" \
+ --workflow CI \
+ --workflow "Security Scan" \
+ --interval 60
+```
+
## Practical Advice
- Keep prefixes action-oriented. Tell the next turn what to do with the waiter result.
diff --git a/skills/background-watch-hook/scripts/wait_action.py b/skills/background-watch-hook/scripts/wait_action.py
new file mode 100755
index 000000000..1d7ae166c
--- /dev/null
+++ b/skills/background-watch-hook/scripts/wait_action.py
@@ -0,0 +1,314 @@
+#!/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.error
+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
+ RETRY_EXIT_CODE,
+ get_token,
+ github_get,
+ is_retryable_http_error,
+ min_interval_for_unauthenticated,
+)
+
+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, dict[str, Any] | None]:
+ workflow_set = set(workflows)
+ result: dict[str, dict[str, Any] | None] = {workflow: None 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
+ result[name] = 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, dict[str, Any] | None],
+ success_conclusions: set[str],
+) -> tuple[str | None, bool]:
+ missing = [workflow for workflow, run in selected.items() if run is None]
+ running = [
+ workflow
+ for workflow, run in selected.items()
+ if run is not None and str(run.get("status") or "") != TERMINAL_STATUS
+ ]
+ if missing or running:
+ return None, False
+
+ failed = [
+ workflow
+ for workflow, run in selected.items()
+ if run is not None and str(run.get("conclusion") or "") not in success_conclusions
+ ]
+ 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:
+ 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:
+ if not path:
+ return
+
+ payload = {
+ 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
+ }
+ 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("--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, dict[str, Any] | None] = {workflow: None for workflow in args.workflow}
+
+ if token is None:
+ unauthenticated_min = min_interval_for_unauthenticated(1, bootstrap_requests=1)
+ if effective_interval < unauthenticated_min:
+ print(
+ (
+ "No GitHub token detected; clamping polling interval from %.1fs to %.1fs "
+ "to avoid unauthenticated rate-limit lockout."
+ )
+ % (effective_interval, unauthenticated_min),
+ file=sys.stderr,
+ )
+ effective_interval = unauthenticated_min
+
+ 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
+ try:
+ runs, _request_count = _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)
+ runs = []
+
+ 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)
+ print(output)
+ return 0
+
+ missing = [workflow for workflow, run in selected.items() if run is None]
+ running = [
+ workflow
+ for workflow, run in selected.items()
+ if run is not None and str(run.get("status") or "") != TERMINAL_STATUS
+ ]
+ 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/tests/test_wait_for_github_action_runs.py b/tests/test_wait_for_github_action_runs.py
new file mode 100644
index 000000000..60ce687fd
--- /dev/null
+++ b/tests/test_wait_for_github_action_runs.py
@@ -0,0 +1,262 @@
+from __future__ import annotations
+
+import io
+import importlib.util
+import urllib.error
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+
+
+def _load_module():
+ script_path = (
+ Path(__file__).resolve().parents[1]
+ / "skills"
+ / "background-watch-hook"
+ / "scripts"
+ / "wait_action.py"
+ )
+ spec = importlib.util.spec_from_file_location("wait_action", script_path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec is not None and spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_select_latest_runs_by_workflow_matches_sha_branch_and_workflow() -> None:
+ module = _load_module()
+ runs = [
+ {
+ "id": 1,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "status": "completed",
+ "conclusion": "failure",
+ "created_at": "2026-04-24T00:00:00Z",
+ },
+ {
+ "id": 2,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "status": "completed",
+ "conclusion": "success",
+ "created_at": "2026-04-24T00:01:00Z",
+ },
+ {
+ "id": 3,
+ "name": "Security Scan",
+ "head_sha": "other",
+ "head_branch": "main",
+ "status": "completed",
+ "conclusion": "success",
+ "created_at": "2026-04-24T00:02:00Z",
+ },
+ ]
+
+ selected = module._select_latest_runs_by_workflow(
+ runs,
+ workflows=["CI", "Security Scan"],
+ branch="main",
+ head_sha="abc123",
+ )
+
+ assert selected["CI"]["id"] == 2
+ assert selected["Security Scan"] is None
+
+
+def test_render_actions_result_waits_for_missing_or_running_runs() -> 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": "in_progress",
+ "conclusion": None,
+ },
+ "Security Scan": None,
+ },
+ success_conclusions={"success"},
+ )
+
+ assert output is None
+ assert failed is False
+
+
+def test_render_actions_result_reports_success() -> 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": "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"},
+ )
+
+ assert output is not None
+ assert "GitHub Actions success" in output
+ assert "CI: status=completed conclusion=success" in output
+ assert "Security Scan: status=completed conclusion=skipped" in output
+ assert failed is False
+
+
+def test_render_actions_result_reports_failure_but_is_an_event() -> 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",
+ }
+ },
+ success_conclusions={"success"},
+ )
+
+ assert output is not None
+ assert "GitHub Actions failure" in output
+ assert "Failed workflow(s): CI" in output
+ assert failed is True
+
+
+def test_main_waits_until_target_runs_complete() -> None:
+ module = _load_module()
+ calls = 0
+
+ def _fake_fetch_workflow_runs(repo, token, *, branch=None, head_sha=None, max_pages=3):
+ nonlocal calls
+ calls += 1
+ assert repo == "cyhhao/sub2api"
+ assert branch == "main"
+ assert head_sha == "abc123"
+ if calls == 1:
+ return (
+ [
+ {
+ "id": 1,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "status": "in_progress",
+ "conclusion": None,
+ }
+ ],
+ 1,
+ )
+ return (
+ [
+ {
+ "id": 1,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "status": "completed",
+ "conclusion": "success",
+ "html_url": "https://github.com/example/actions/runs/1",
+ }
+ ],
+ 1,
+ )
+
+ stdout = io.StringIO()
+ with (
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "_fetch_workflow_runs", side_effect=_fake_fetch_workflow_runs),
+ 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"]),
+ redirect_stdout(stdout),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert calls == 2
+ assert "GitHub Actions success" in stdout.getvalue()
+
+
+def test_main_returns_zero_for_completed_failed_workflow() -> None:
+ module = _load_module()
+
+ def _fake_fetch_workflow_runs(repo, token, *, branch=None, head_sha=None, max_pages=3):
+ return (
+ [
+ {
+ "id": 1,
+ "name": "CI",
+ "head_sha": "abc123",
+ "head_branch": "main",
+ "status": "completed",
+ "conclusion": "failure",
+ "html_url": "https://github.com/example/actions/runs/1",
+ }
+ ],
+ 1,
+ )
+
+ stdout = io.StringIO()
+ with (
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "_fetch_workflow_runs", side_effect=_fake_fetch_workflow_runs),
+ patch("sys.argv", ["wait_action.py", "--repo", "cyhhao/sub2api", "--branch", "main", "--sha", "abc123", "--workflow", "CI"]),
+ redirect_stdout(stdout),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert "GitHub Actions failure" in stdout.getvalue()
+
+
+def test_main_requires_authentication_by_default() -> None:
+ module = _load_module()
+
+ with (
+ patch.object(module, "get_token", return_value=None),
+ patch("sys.argv", ["wait_action.py", "--repo", "cyhhao/sub2api", "--sha", "abc123", "--workflow", "CI"]),
+ ):
+ rc = module.main()
+
+ assert rc == 2
+
+
+def test_main_retryable_startup_http_error_returns_retry_code() -> None:
+ module = _load_module()
+ err = urllib.error.HTTPError(
+ url="https://api.github.com/repos/example/repo/actions/runs",
+ code=503,
+ msg="Service Unavailable",
+ hdrs=None,
+ fp=None,
+ )
+
+ with (
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "_fetch_workflow_runs", side_effect=err),
+ patch("sys.argv", ["wait_action.py", "--repo", "cyhhao/sub2api", "--sha", "abc123", "--workflow", "CI"]),
+ ):
+ rc = module.main()
+
+ assert rc == module.RETRY_EXIT_CODE