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(skill): extend github background waiters

cyh93003330862f
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index b36460627..52cddb266 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 background waiter that returns to the same conversation later. Best for reviews, CI, files, logs, and other wait-now-continue-later workflows.
-version: 0.5.0
+version: 0.6.0
---
# Background Watch Hook
@@ -150,10 +150,12 @@ This separation matters: a forever watch can still use a bounded timeout for eac
## Bundled Waiter Example
-This skill ships one bundled waiter:
+This skill ships bundled GitHub waiters:
- `scripts/wait_pr.py`
- Waits for GitHub PR review activity, including reviews, inline review comments, PR conversation comments, and the special Codex `+1` reaction on the PR body.
+ Waits for GitHub PR review activity, including reviews, inline review comments, PR conversation comments, 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.
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.
@@ -212,8 +214,30 @@ GitHub-specific notes:
- `--catch-up` reports activity that already exists at startup
- without `--catch-up`, the waiter snapshots current PR activity as the baseline
- 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
+- 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 fragile
+New PRs in a repository:
+
+```bash
+vibe watch add \
+ --session-key "slack::channel::C123::thread::171717.123" \
+ --name "Watch new PRs" \
+ --prefix "The repository has new pull requests. Review the new PRs and continue as needed." \
+ -- \
+ uv run --no-project scripts/wait_pr.py \
+ --repo cyhhao/vibe-remote \
+ --new-prs \
+ --interval 60
+```
+
+New issues or issue comments:
+
+```bash
+uv run --no-project scripts/wait_issue.py --repo cyhhao/vibe-remote --new-issues --interval 60
+uv run --no-project scripts/wait_issue.py --repo cyhhao/vibe-remote --issue 157 --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/_github_wait_common.py b/skills/background-watch-hook/scripts/_github_wait_common.py
new file mode 100644
index 000000000..70a4065c9
--- /dev/null
+++ b/skills/background-watch-hook/scripts/_github_wait_common.py
@@ -0,0 +1,115 @@
+#!/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 urllib.request
+from typing import Any
+
+
+def get_token() -> str | None:
+ for env_name in ("GITHUB_TOKEN", "GH_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 Exception:
+ 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)))
+
+
+def github_get(url: str, token: str | 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}")
+
+ with urllib.request.urlopen(request, timeout=30) as response:
+ return json.loads(response.read().decode("utf-8"))
+
+
+def get_authenticated_login(token: str | None) -> str | None:
+ if not token:
+ return None
+
+ try:
+ payload = github_get("https://api.github.com/user", token)
+ except Exception:
+ return None
+
+ if not isinstance(payload, dict):
+ return None
+ login = payload.get("login")
+ return str(login) if isinstance(login, str) and login else None
+
+
+def list_paginated(base_url: str, token: str | None) -> list[dict[str, Any]]:
+ items: list[dict[str, Any]] = []
+ page = 1
+ while True:
+ separator = "&" if "?" in base_url else "?"
+ url = f"{base_url}{separator}per_page=100&page={page}"
+ payload = github_get(url, token)
+ if not isinstance(payload, list):
+ raise RuntimeError(f"Expected a JSON list from {url}")
+ if not payload:
+ break
+ items.extend(item for item in payload if isinstance(item, dict))
+ if len(payload) < 100:
+ break
+ page += 1
+ return items
+
+
+def squash(text: str | None, *, limit: int = 140) -> str:
+ compact = " ".join((text or "").split())
+ if len(compact) <= limit:
+ return compact
+ return compact[: limit - 1].rstrip() + "…"
+
+
+def max_id(items: list[dict[str, Any]]) -> int:
+ values = [int(item["id"]) for item in items if isinstance(item.get("id"), int)]
+ return max(values, default=0)
+
+
+def filter_new(items: list[dict[str, Any]], since_id: int) -> list[dict[str, Any]]:
+ return sorted(
+ [item for item in items if isinstance(item.get("id"), int) and int(item["id"]) > since_id],
+ key=lambda item: (str(item.get("created_at") or ""), int(item["id"])),
+ )
+
+
+def requests_per_poll(*collections: list[dict[str, Any]]) -> int:
+ requests = 0
+ for items in collections:
+ requests += max(1, (len(items) // 100) + 1)
+ return requests
diff --git a/skills/background-watch-hook/scripts/wait_issue.py b/skills/background-watch-hook/scripts/wait_issue.py
new file mode 100644
index 000000000..9b3961ecb
--- /dev/null
+++ b/skills/background-watch-hook/scripts/wait_issue.py
@@ -0,0 +1,351 @@
+#!/usr/bin/env python3
+"""Wait until a GitHub repository or issue receives new issue activity."""
+
+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
+ filter_new,
+ get_authenticated_login,
+ get_token,
+ list_paginated,
+ max_id,
+ min_interval_for_unauthenticated,
+ requests_per_poll,
+ squash,
+)
+
+
+def _is_pull_request_issue(item: dict[str, Any]) -> bool:
+ return isinstance(item.get("pull_request"), dict)
+
+
+def _format_issue(issue: dict[str, Any]) -> str:
+ issue_number = issue.get("number")
+ author = ((issue.get("user") or {}).get("login")) or "unknown"
+ state = str(issue.get("state") or "open").lower()
+ title = squash(issue.get("title") or "")
+ url = issue.get("html_url") or ""
+ return f"- issue #{issue_number} by {author} ({state})\n {title}\n {url}"
+
+
+def _format_issue_comment(issue_number: int, 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} on issue #{issue_number}\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 _fetch_new_issue_state(repo: str, token: str | None) -> dict[str, list[dict[str, Any]]]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ raw_issues = list_paginated(
+ f"https://api.github.com/repos/{encoded_repo}/issues?state=all&sort=created&direction=desc",
+ token,
+ )
+ issues = [item for item in raw_issues if not _is_pull_request_issue(item)]
+ return {"issues": issues}
+
+
+def _fetch_issue_comment_state(repo: str, issue_number: int, token: str | None) -> dict[str, list[dict[str, Any]]]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ comments = list_paginated(
+ f"https://api.github.com/repos/{encoded_repo}/issues/{issue_number}/comments",
+ token,
+ )
+ return {"issue_comments": comments}
+
+
+def _render_new_issues(
+ *,
+ repo: str,
+ state: dict[str, list[dict[str, Any]]],
+ issue_cursor: int,
+ event_limit: int,
+) -> tuple[str | None, int]:
+ new_issues = filter_new(state["issues"], issue_cursor)
+ if not new_issues:
+ return None, issue_cursor
+
+ next_issue_cursor = max(issue_cursor, max_id(new_issues))
+ lines = [f"GitHub new issue activity detected for {repo}"]
+ rendered_events = [_format_issue(issue) for issue in new_issues]
+ visible_limit = max(event_limit, 1)
+ for entry in rendered_events[:visible_limit]:
+ lines.append(entry)
+ if len(rendered_events) > visible_limit:
+ lines.append(f"- {len(rendered_events) - visible_limit} additional event(s) omitted")
+ return "\n".join(lines), next_issue_cursor
+
+
+def _render_issue_comments(
+ *,
+ repo: str,
+ issue_number: int,
+ state: dict[str, list[dict[str, Any]]],
+ issue_comment_cursor: int,
+ event_limit: int,
+ viewer_login: str | None = None,
+ ignore_self_comments: bool = True,
+) -> tuple[str | None, int]:
+ new_comments = filter_new(state["issue_comments"], issue_comment_cursor)
+ if not new_comments:
+ return None, issue_comment_cursor
+
+ visible_comments = (
+ [comment for comment in new_comments if not _is_self_authored_comment(comment, viewer_login)]
+ if ignore_self_comments
+ else new_comments
+ )
+
+ next_issue_comment_cursor = max(issue_comment_cursor, max_id(new_comments))
+ rendered_events = [_format_issue_comment(issue_number, comment) for comment in visible_comments]
+ if not rendered_events:
+ return None, next_issue_comment_cursor
+
+ lines = [f"GitHub issue activity detected for {repo}#{issue_number}"]
+ visible_limit = max(event_limit, 1)
+ for entry in rendered_events[:visible_limit]:
+ lines.append(entry)
+ if len(rendered_events) > visible_limit:
+ lines.append(f"- {len(rendered_events) - visible_limit} additional event(s) omitted")
+ return "\n".join(lines), next_issue_comment_cursor
+
+
+def _write_cursor_output(path: str | None, *, issue_cursor: int | None = None, issue_comment_cursor: int | None = None) -> None:
+ if not path:
+ return
+
+ payload: dict[str, int] = {}
+ if issue_cursor is not None:
+ payload["issue_cursor"] = issue_cursor
+ if issue_comment_cursor is not None:
+ payload["issue_comment_cursor"] = issue_comment_cursor
+ with open(path, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle)
+
+
+def main() -> int:
+ 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("--issue", type=int, help="Issue number")
+ mode.add_argument("--new-issues", action="store_true", help="Watch for new issues 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-issue-id", type=int, default=None, help="Existing repository issue cursor")
+ parser.add_argument("--since-issue-comment-id", type=int, default=None, help="Existing issue comment cursor")
+ parser.add_argument("--cursor-output", help=argparse.SUPPRESS)
+ 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 comments authored by the current authenticated GitHub user",
+ )
+ 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",
+ )
+ args = parser.parse_args()
+
+ token = get_token()
+ viewer_login = None if args.include_self_comments else get_authenticated_login(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
+
+ effective_interval = max(args.interval, 1.0)
+ start = time.monotonic()
+
+ try:
+ if args.issue is not None:
+ state = _fetch_issue_comment_state(args.repo, args.issue, token)
+ else:
+ state = _fetch_new_issue_state(args.repo, token)
+ except urllib.error.HTTPError as err:
+ print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)
+ return 1
+ except Exception as err: # noqa: BLE001
+ print(f"Failed to fetch initial issue state: {err}", file=sys.stderr)
+ return 1
+
+ if token is None:
+ requests_per_poll_count = requests_per_poll(*state.values())
+ bootstrap_requests = requests_per_poll_count
+ unauthenticated_min = min_interval_for_unauthenticated(
+ requests_per_poll_count,
+ bootstrap_requests=bootstrap_requests,
+ )
+ if effective_interval < unauthenticated_min:
+ 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, unauthenticated_min, requests_per_poll_count, bootstrap_requests),
+ file=sys.stderr,
+ )
+ effective_interval = unauthenticated_min
+ else:
+ bootstrap_requests = 0
+
+ if args.issue is not None:
+ issue_comment_cursor = (
+ args.since_issue_comment_id
+ if args.since_issue_comment_id is not None
+ else (0 if args.catch_up else max_id(state["issue_comments"]))
+ )
+ print(
+ (
+ "Watching GitHub issue %s#%s comments from cursor: issue_comment=%s catch_up=%s"
+ % (args.repo, args.issue, issue_comment_cursor, args.catch_up)
+ ),
+ file=sys.stderr,
+ )
+ initial_output, issue_comment_cursor = _render_issue_comments(
+ repo=args.repo,
+ issue_number=args.issue,
+ state=state,
+ issue_comment_cursor=issue_comment_cursor,
+ event_limit=args.event_limit,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ )
+ if initial_output is not None:
+ _write_cursor_output(args.cursor_output, issue_comment_cursor=issue_comment_cursor)
+ print(initial_output)
+ return 0
+ else:
+ issue_cursor = args.since_issue_id if args.since_issue_id is not None else (0 if args.catch_up else max_id(state["issues"]))
+ print(
+ f"Watching GitHub new issues in {args.repo} from cursor: issue={issue_cursor} catch_up={args.catch_up}",
+ file=sys.stderr,
+ )
+ initial_output, issue_cursor = _render_new_issues(
+ repo=args.repo,
+ state=state,
+ issue_cursor=issue_cursor,
+ event_limit=args.event_limit,
+ )
+ if initial_output is not None:
+ _write_cursor_output(args.cursor_output, issue_cursor=issue_cursor)
+ print(initial_output)
+ 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 issue activity", file=sys.stderr)
+ return 124
+ sleep_seconds = min(sleep_seconds, remaining_timeout)
+
+ time.sleep(sleep_seconds)
+
+ try:
+ if args.issue is not None:
+ state = _fetch_issue_comment_state(args.repo, args.issue, token)
+ else:
+ state = _fetch_new_issue_state(args.repo, token)
+ except urllib.error.HTTPError as err:
+ 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)
+ continue
+ except Exception as err: # noqa: BLE001
+ print(f"Polling failed: {err}", file=sys.stderr)
+ continue
+
+ if token is None:
+ requests_per_poll_count = requests_per_poll(*state.values())
+ unauthenticated_min = min_interval_for_unauthenticated(
+ requests_per_poll_count,
+ bootstrap_requests=bootstrap_requests,
+ )
+ if effective_interval < unauthenticated_min:
+ print(
+ (
+ "GitHub unauthenticated polling now needs %.1fs minimum for %s request(s) "
+ "per poll plus %s bootstrap request(s); increasing interval."
+ )
+ % (unauthenticated_min, requests_per_poll_count, bootstrap_requests),
+ file=sys.stderr,
+ )
+ effective_interval = unauthenticated_min
+
+ if args.issue is not None:
+ output, issue_comment_cursor = _render_issue_comments(
+ repo=args.repo,
+ issue_number=args.issue,
+ state=state,
+ issue_comment_cursor=issue_comment_cursor,
+ event_limit=args.event_limit,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ )
+ if output is None:
+ continue
+ _write_cursor_output(args.cursor_output, issue_comment_cursor=issue_comment_cursor)
+ else:
+ output, issue_cursor = _render_new_issues(
+ repo=args.repo,
+ state=state,
+ issue_cursor=issue_cursor,
+ event_limit=args.event_limit,
+ )
+ if output is None:
+ continue
+ _write_cursor_output(args.cursor_output, issue_cursor=issue_cursor)
+
+ print(output)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.py
index ee7805d35..ce5d6a295 100755
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@ -1,113 +1,41 @@
#!/usr/bin/env python3
-"""Wait until a GitHub pull request receives new activity."""
+"""Wait until a GitHub pull request or repository receives new PR activity."""
from __future__ import annotations
import argparse
import json
-import math
-import os
-import shutil
-import subprocess
import sys
import time
import urllib.error
import urllib.parse
-import urllib.request
+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
+ filter_new,
+ get_authenticated_login,
+ get_token,
+ list_paginated,
+ max_id,
+ min_interval_for_unauthenticated,
+ requests_per_poll,
+ squash,
+)
+
CODEX_REVIEW_PASS_REACTION_USER = "chatgpt-codex-connector[bot]"
CODEX_REVIEW_PASS_REACTION_CONTENT = "+1"
-def _get_token() -> str | None:
- for env_name in ("GITHUB_TOKEN", "GH_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 Exception:
- return None
- token = result.stdout.strip()
- return token or None
-
-
-def _min_interval_for_unauthenticated(
- requests_per_poll: int,
- *,
- bootstrap_requests: int = 0,
-) -> float:
- # Keep unauthenticated usage at or below GitHub's 60 requests/hour ceiling,
- # including the initial bootstrap fetch before the polling loop begins.
- 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)))
-
-
-def _github_get(url: str, token: str | 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}")
-
- with urllib.request.urlopen(request, timeout=30) as response:
- return json.loads(response.read().decode("utf-8"))
-
-
-def _list_paginated(base_url: str, token: str | None) -> list[dict[str, Any]]:
- items: list[dict[str, Any]] = []
- page = 1
- while True:
- separator = "&" if "?" in base_url else "?"
- url = f"{base_url}{separator}per_page=100&page={page}"
- payload = _github_get(url, token)
- if not isinstance(payload, list):
- raise RuntimeError(f"Expected a JSON list from {url}")
- if not payload:
- break
- items.extend(item for item in payload if isinstance(item, dict))
- if len(payload) < 100:
- break
- page += 1
- return items
-
-
-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 _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)
+ 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}"
@@ -116,7 +44,7 @@ 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"))
+ 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}"
@@ -124,11 +52,18 @@ def _format_review_comment(comment: dict[str, Any]) -> str:
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"))
+ 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 _is_codex_pass_reaction(reaction: dict[str, Any]) -> bool:
author = ((reaction.get("user") or {}).get("login")) or ""
content = str(reaction.get("content") or "")
@@ -146,18 +81,27 @@ def _format_reaction(reaction: dict[str, Any]) -> str:
)
+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_state(repo: str, pr_number: int, token: str | None) -> dict[str, list[dict[str, Any]]]:
encoded_repo = urllib.parse.quote(repo, safe="/")
- reviews = _list_paginated(f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/reviews", token)
- review_comments = _list_paginated(
+ reviews = list_paginated(f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/reviews", token)
+ review_comments = list_paginated(
f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/comments",
token,
)
- issue_comments = _list_paginated(
+ issue_comments = list_paginated(
f"https://api.github.com/repos/{encoded_repo}/issues/{pr_number}/comments",
token,
)
- reactions = _list_paginated(
+ reactions = list_paginated(
f"https://api.github.com/repos/{encoded_repo}/issues/{pr_number}/reactions",
token,
)
@@ -169,12 +113,13 @@ def _fetch_state(repo: str, pr_number: int, token: str | None) -> dict[str, list
}
-def _requests_per_poll(state: dict[str, list[dict[str, Any]]]) -> int:
- requests = 0
- for key in ("reviews", "review_comments", "issue_comments", "reactions"):
- item_count = len(state[key])
- requests += max(1, (item_count // 100) + 1)
- return requests
+def _fetch_new_pr_state(repo: str, token: str | None) -> dict[str, list[dict[str, Any]]]:
+ encoded_repo = urllib.parse.quote(repo, safe="/")
+ pull_requests = list_paginated(
+ f"https://api.github.com/repos/{encoded_repo}/pulls?state=all&sort=created&direction=desc",
+ token,
+ )
+ return {"pull_requests": pull_requests}
def _render_activity(
@@ -187,31 +132,53 @@ def _render_activity(
issue_comment_cursor: int,
reaction_cursor: int,
event_limit: int,
+ viewer_login: str | None = None,
+ ignore_self_comments: bool = True,
) -> tuple[str | None, int, int, int, int]:
- 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)
+ 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)
+ visible_review_comments = (
+ [comment for comment in new_review_comments if not _is_self_authored_comment(comment, viewer_login)]
+ if ignore_self_comments
+ else new_review_comments
+ )
+ visible_issue_comments = (
+ [comment for comment in new_issue_comments if not _is_self_authored_comment(comment, viewer_login)]
+ if ignore_self_comments
+ else new_issue_comments
+ )
new_reactions = [
reaction
- for reaction in _filter_new(state["reactions"], reaction_cursor)
+ for reaction in filter_new(state["reactions"], reaction_cursor)
if _is_codex_pass_reaction(reaction)
]
if not (new_reviews or new_review_comments or new_issue_comments or new_reactions):
return None, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor
- 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))
- next_reaction_cursor = max(reaction_cursor, _max_id(state["reactions"]))
+ 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))
+ next_reaction_cursor = max(reaction_cursor, max_id(state["reactions"]))
- lines = [f"GitHub PR activity detected for {repo}#{pr_number}"]
rendered_events: list[str] = []
rendered_events.extend(_format_review(review) for review in new_reviews)
- rendered_events.extend(_format_review_comment(comment) for comment in new_review_comments)
- rendered_events.extend(_format_issue_comment(comment) for comment in new_issue_comments)
+ 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:
+ return (
+ None,
+ next_review_cursor,
+ next_review_comment_cursor,
+ next_issue_comment_cursor,
+ next_reaction_cursor,
+ )
+
+ lines = [f"GitHub PR activity detected for {repo}#{pr_number}"]
+
visible_limit = max(event_limit, 1)
for entry in rendered_events[:visible_limit]:
lines.append(entry)
@@ -229,6 +196,32 @@ def _render_activity(
)
+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,
*,
@@ -250,10 +243,20 @@ def _write_cursor_output(
json.dump(payload, handle)
+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 main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", required=True, help="GitHub repo in owner/name form")
- parser.add_argument("--pr", required=True, type=int, help="Pull request number")
+ 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",
@@ -265,8 +268,14 @@ def main() -> int:
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-id", type=int, default=None, help="Existing repository pull request cursor")
parser.add_argument("--cursor-output", help=argparse.SUPPRESS)
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 comments authored by the current authenticated GitHub user",
+ )
parser.add_argument(
"--catch-up",
action="store_true",
@@ -279,7 +288,8 @@ def main() -> int:
)
args = parser.parse_args()
- token = _get_token()
+ token = get_token()
+ viewer_login = None if args.include_self_comments else get_authenticated_login(token)
if token is None and not args.allow_unauthenticated:
print(
(
@@ -296,7 +306,10 @@ def main() -> int:
start = time.monotonic()
try:
- state = _fetch_state(args.repo, args.pr, token)
+ if args.pr is not None:
+ state = _fetch_state(args.repo, args.pr, token)
+ else:
+ state = _fetch_new_pr_state(args.repo, token)
except urllib.error.HTTPError as err:
print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)
return 1
@@ -305,10 +318,10 @@ def main() -> int:
return 1
if token is None:
- requests_per_poll = _requests_per_poll(state)
- bootstrap_requests = requests_per_poll
- unauthenticated_min = _min_interval_for_unauthenticated(
- requests_per_poll,
+ requests_per_poll_count = requests_per_poll(*state.values())
+ bootstrap_requests = requests_per_poll_count
+ unauthenticated_min = min_interval_for_unauthenticated(
+ requests_per_poll_count,
bootstrap_requests=bootstrap_requests,
)
if effective_interval < unauthenticated_min:
@@ -318,70 +331,89 @@ def main() -> int:
"for %s request(s) per poll plus %s bootstrap request(s) to avoid "
"unauthenticated rate-limit lockout."
)
- % (effective_interval, unauthenticated_min, requests_per_poll, bootstrap_requests),
+ % (effective_interval, unauthenticated_min, requests_per_poll_count, bootstrap_requests),
file=sys.stderr,
)
effective_interval = unauthenticated_min
else:
bootstrap_requests = 0
- review_cursor = (
- args.since_review_id
- if args.since_review_id is not None
- else (0 if args.catch_up else _max_id(state["reviews"]))
- )
- review_comment_cursor = (
- args.since_review_comment_id
- if args.since_review_comment_id is not None
- else (0 if args.catch_up else _max_id(state["review_comments"]))
- )
- issue_comment_cursor = (
- args.since_issue_comment_id
- if args.since_issue_comment_id is not None
- else (0 if args.catch_up else _max_id(state["issue_comments"]))
- )
- reaction_cursor = (
- args.since_reaction_id
- if args.since_reaction_id is not None
- else (0 if args.catch_up else _max_id(state["reactions"]))
- )
+ if args.pr is not None:
+ review_cursor = (
+ args.since_review_id
+ if args.since_review_id is not None
+ else (0 if args.catch_up else max_id(state["reviews"]))
+ )
+ review_comment_cursor = (
+ args.since_review_comment_id
+ if args.since_review_comment_id is not None
+ else (0 if args.catch_up else max_id(state["review_comments"]))
+ )
+ issue_comment_cursor = (
+ args.since_issue_comment_id
+ if args.since_issue_comment_id is not None
+ else (0 if args.catch_up else max_id(state["issue_comments"]))
+ )
+ reaction_cursor = (
+ args.since_reaction_id
+ if args.since_reaction_id is not None
+ else (0 if args.catch_up else max_id(state["reactions"]))
+ )
- print(
- (
- "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s reaction=%s catch_up=%s"
- % (
- args.repo,
- args.pr,
- review_cursor,
- review_comment_cursor,
- issue_comment_cursor,
- reaction_cursor,
- args.catch_up,
- )
- ),
- file=sys.stderr,
- )
+ print(
+ (
+ "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s reaction=%s catch_up=%s"
+ % (
+ args.repo,
+ args.pr,
+ review_cursor,
+ review_comment_cursor,
+ issue_comment_cursor,
+ reaction_cursor,
+ args.catch_up,
+ )
+ ),
+ file=sys.stderr,
+ )
- initial_output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor = _render_activity(
- repo=args.repo,
- pr_number=args.pr,
- state=state,
- review_cursor=review_cursor,
- review_comment_cursor=review_comment_cursor,
- issue_comment_cursor=issue_comment_cursor,
- reaction_cursor=reaction_cursor,
- event_limit=args.event_limit,
- )
- if initial_output is not None:
- _write_cursor_output(
- args.cursor_output,
+ initial_output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor = _render_activity(
+ repo=args.repo,
+ pr_number=args.pr,
+ state=state,
review_cursor=review_cursor,
review_comment_cursor=review_comment_cursor,
issue_comment_cursor=issue_comment_cursor,
reaction_cursor=reaction_cursor,
+ event_limit=args.event_limit,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
)
- print(initial_output)
- return 0
+ if initial_output is not None:
+ _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,
+ )
+ print(initial_output)
+ return 0
+ else:
+ pr_cursor = args.since_pr_id if args.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,
+ )
+ initial_output, pr_cursor = _render_new_pull_requests(
+ repo=args.repo,
+ state=state,
+ pr_cursor=pr_cursor,
+ event_limit=args.event_limit,
+ )
+ if initial_output is not None:
+ _write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)
+ print(initial_output)
+ return 0
while True:
sleep_seconds = effective_interval
@@ -395,7 +427,10 @@ def main() -> int:
time.sleep(sleep_seconds)
try:
- state = _fetch_state(args.repo, args.pr, token)
+ if args.pr is not None:
+ state = _fetch_state(args.repo, args.pr, token)
+ else:
+ state = _fetch_new_pr_state(args.repo, token)
except urllib.error.HTTPError as err:
if token is None and err.code in {403, 429}:
print(
@@ -413,9 +448,9 @@ def main() -> int:
continue
if token is None:
- requests_per_poll = _requests_per_poll(state)
- unauthenticated_min = _min_interval_for_unauthenticated(
- requests_per_poll,
+ requests_per_poll_count = requests_per_poll(*state.values())
+ unauthenticated_min = min_interval_for_unauthenticated(
+ requests_per_poll_count,
bootstrap_requests=bootstrap_requests,
)
if effective_interval < unauthenticated_min:
@@ -424,31 +459,45 @@ def main() -> int:
"GitHub unauthenticated polling now needs %.1fs minimum for %s request(s) "
"per poll plus %s bootstrap request(s); increasing interval."
)
- % (unauthenticated_min, requests_per_poll, bootstrap_requests),
+ % (unauthenticated_min, requests_per_poll_count, bootstrap_requests),
file=sys.stderr,
)
effective_interval = unauthenticated_min
- output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor = _render_activity(
- repo=args.repo,
- pr_number=args.pr,
- state=state,
- review_cursor=review_cursor,
- review_comment_cursor=review_comment_cursor,
- issue_comment_cursor=issue_comment_cursor,
- reaction_cursor=reaction_cursor,
- event_limit=args.event_limit,
- )
- if output is None:
- continue
+ if args.pr is not None:
+ output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor = _render_activity(
+ repo=args.repo,
+ pr_number=args.pr,
+ state=state,
+ review_cursor=review_cursor,
+ review_comment_cursor=review_comment_cursor,
+ issue_comment_cursor=issue_comment_cursor,
+ reaction_cursor=reaction_cursor,
+ event_limit=args.event_limit,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ )
+ if output is None:
+ 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,
+ )
+ else:
+ 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:
+ continue
+ _write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)
- _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,
- )
print(output)
return 0
diff --git a/tests/test_wait_for_github_issue_activity.py b/tests/test_wait_for_github_issue_activity.py
new file mode 100644
index 000000000..943c61948
--- /dev/null
+++ b/tests/test_wait_for_github_issue_activity.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+
+def _load_module():
+ script_path = (
+ Path(__file__).resolve().parents[1]
+ / "skills"
+ / "background-watch-hook"
+ / "scripts"
+ / "wait_issue.py"
+ )
+ spec = importlib.util.spec_from_file_location("wait_issue", 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_render_new_issues_ignores_pull_requests() -> None:
+ module = _load_module()
+ state = {
+ "issues": [
+ {
+ "id": 201,
+ "number": 24,
+ "title": "New issue",
+ "state": "open",
+ "html_url": "https://github.com/example/repo/issues/24",
+ "user": {"login": "someone"},
+ }
+ ]
+ }
+
+ output, issue_cursor = module._render_new_issues(
+ repo="cyhhao/vibe-remote",
+ state=state,
+ issue_cursor=0,
+ event_limit=8,
+ )
+
+ assert output is not None
+ assert "issue #24" in output
+ assert issue_cursor == 201
+
+
+def test_render_issue_comments_includes_new_comment() -> None:
+ module = _load_module()
+ state = {
+ "issue_comments": [
+ {
+ "id": 301,
+ "body": "Need more logs",
+ "html_url": "https://github.com/example/repo/issues/24#issuecomment-301",
+ "user": {"login": "reviewer"},
+ }
+ ]
+ }
+
+ output, issue_comment_cursor = module._render_issue_comments(
+ repo="cyhhao/vibe-remote",
+ issue_number=24,
+ state=state,
+ issue_comment_cursor=0,
+ event_limit=8,
+ )
+
+ assert output is not None
+ assert "issue_comment #301" in output
+ assert "issue #24" in output
+ assert issue_comment_cursor == 301
+
+
+def test_render_issue_comments_ignores_self_authored_comment_but_advances_cursor() -> None:
+ module = _load_module()
+ state = {
+ "issue_comments": [
+ {
+ "id": 302,
+ "body": "I will take this",
+ "html_url": "https://github.com/example/repo/issues/24#issuecomment-302",
+ "user": {"login": "cyhhao"},
+ }
+ ]
+ }
+
+ output, issue_comment_cursor = module._render_issue_comments(
+ repo="cyhhao/vibe-remote",
+ issue_number=24,
+ state=state,
+ issue_comment_cursor=0,
+ event_limit=8,
+ viewer_login="cyhhao",
+ )
+
+ assert output is None
+ assert issue_comment_cursor == 302
diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.py
index d5b8ad41c..eec1d4d0f 100644
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@ -89,3 +89,98 @@ def test_render_activity_ignores_non_codex_or_non_plus_one_reactions() -> None:
)
assert output is None
+
+
+def test_render_activity_ignores_self_authored_issue_comment_but_advances_cursor() -> None:
+ module = _load_module()
+ state = {
+ "reviews": [],
+ "review_comments": [],
+ "issue_comments": [
+ {
+ "id": 126,
+ "body": " @CoDeX ReViEw ",
+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-126",
+ "user": {"login": "someone"},
+ }
+ ],
+ "reactions": [],
+ }
+
+ output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor = module._render_activity(
+ repo="cyhhao/vibe-remote",
+ pr_number=153,
+ state=state,
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ event_limit=8,
+ viewer_login="someone",
+ )
+
+ assert output is None
+ assert review_cursor == 0
+ assert review_comment_cursor == 0
+ assert issue_comment_cursor == 126
+ assert reaction_cursor == 0
+
+
+def test_render_activity_includes_self_authored_comment_when_disabled() -> None:
+ module = _load_module()
+ state = {
+ "reviews": [],
+ "review_comments": [],
+ "issue_comments": [
+ {
+ "id": 127,
+ "body": "@codex review",
+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-127",
+ "user": {"login": "someone"},
+ }
+ ],
+ "reactions": [],
+ }
+
+ output, *_rest = module._render_activity(
+ repo="cyhhao/vibe-remote",
+ pr_number=153,
+ state=state,
+ review_cursor=0,
+ review_comment_cursor=0,
+ issue_comment_cursor=0,
+ reaction_cursor=0,
+ event_limit=8,
+ viewer_login="someone",
+ ignore_self_comments=False,
+ )
+
+ assert output is not None
+ assert "issue_comment #127" in output
+
+
+def test_render_new_pull_requests_includes_new_prs() -> None:
+ module = _load_module()
+ state = {
+ "pull_requests": [
+ {
+ "id": 401,
+ "number": 157,
+ "title": "feat: add codex subagent routing",
+ "state": "open",
+ "html_url": "https://github.com/example/repo/pull/157",
+ "user": {"login": "cyhhao"},
+ }
+ ]
+ }
+
+ output, pr_cursor = module._render_new_pull_requests(
+ repo="cyhhao/vibe-remote",
+ state=state,
+ pr_cursor=0,
+ event_limit=8,
+ )
+
+ assert output is not None
+ assert "pull_request #157" in output
+ assert pr_cursor == 401