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): report a stalled Codex review so the PR loop re-requests it (#2941)

Call Whitecfbe830b73e2
diff --git a/.agents/skills/pr-delivery-loop/SKILL.md b/.agents/skills/pr-delivery-loop/SKILL.md
index 04d5d19a0..9dc1f32d7 100644
--- a/.agents/skills/pr-delivery-loop/SKILL.md
+++ b/.agents/skills/pr-delivery-loop/SKILL.md
@@ -34,6 +34,7 @@ The `background-watch-hook` skill owns Watch mechanics: scripts, cursors, filter
Codex signals are easy to misread:
- Review usually starts within a few minutes after a push, shown by Codex `eyes` on the PR. If there is no sign, comment `@codex review`, record the ID of that comment, and check whether that exact comment receives Codex `eyes`. The `eyes` disappear after review; their later absence does not mean Codex never accepted the job.
+- A review can also stall after pickup. When the Watch reports `Codex review stalled` (still running past its window), re-request it the same way: comment `@codex review`, record the comment ID, and verify pickup. After two stalls on the same head, tell the user instead of requesting again.
- Accept conclusions only from `chatgpt-codex-connector` (often displayed as `[bot]`). A pass must name the current head's SHA, in one of two forms: the bot's review summary comment, whose `<!-- codex-review-state:v1 … -->` line shows the current head's full `commit_sha` in `code_review` with `"status":"completed"` and `"has_any_findings":false` (the bot edits this one comment in place, so read its current body); or a comment saying `Codex Review: Didn't find any major issues` and naming the current SHA. A `+1` reaction on the PR body means some review finished with no findings, but it names no commit; treat it as a prompt to read the summary state, never as a pass on its own. If no SHA-bearing conclusion exists for the current head, trigger another review. A finding review also contains `Reviewed commit`; that alone is not a pass.
- Do not push a new head while review is running: that wastes the round and binds the conclusion to the wrong head. Use the time for acceptance checks and close-out preparation.
diff --git a/AGENTS.md b/AGENTS.md
index aeceb81f2..86eb0a75f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -209,7 +209,7 @@ there rather than expanding this index.
### PR Delivery
-- Codex review is triggered automatically by cyhhao after pushes; do not add a trigger while that review is running. When the current head's review fails (Codex reports "Something went wrong") or is never picked up, post `@codex review` yourself and verify pickup; the exact-head review gate is unchanged.
+- Codex review is triggered automatically by cyhhao after pushes; do not add a trigger while that review is running. When the current head's review fails (Codex reports "Something went wrong"), is never picked up, or stalls (its Watch reports `Codex review stalled`), post `@codex review` yourself and verify pickup; the exact-head review gate is unchanged.
- load and follow the `pr-delivery-loop` skill for every implementation task;
it owns the detailed procedure, but cannot weaken the baseline below
- regardless of Skill resolution, use a task branch/worktree, record the change
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index 9fa17b45f..47c352a7e 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: Run durable `vibe watch` waits for PR reviews, CI, files or external signals, then resume the Agent in the right Session.
-version: 0.18.1
+version: 0.19.0
---
# Background Watch Hook
@@ -53,6 +53,10 @@ immediately seed/arm. Keep the same Watch and cursor across all later rounds.
- `--actionable-only` drops review triggers and empty envelopes; `--settle 20`
batches review bursts. New CI failures bypass settle. Final gates belong to
`pr-delivery-loop`, including the stricter qualification of Codex reactions.
+- A Codex review of the current head that stays running for
+ `--review-stall-minutes` (default 30, `0` disables) is reported
+ as `Codex review stalled`, again each further window it lasts; the follow-up
+ re-requests the review as `pr-delivery-loop` says.
- Set `--timeout 0` on both sides of the `--` command separator; six quiet hours
is not a PR failure. Verify workflow names: missing CI is never green.
- Never reseed or replace its state between rounds. Filters/reporting modes are
diff --git a/skills/background-watch-hook/references/waiters.md b/skills/background-watch-hook/references/waiters.md
index 3e66db1d5..b6d836e83 100644
--- a/skills/background-watch-hook/references/waiters.md
+++ b/skills/background-watch-hook/references/waiters.md
@@ -402,6 +402,20 @@ review-thread status. A thread becoming unresolved or resolved remains an
independent wake signal because thread state is a separate mutable resource and
may later be changed by a different actor.
+A review can stall after Codex picks it up: its summary keeps saying "running"
+and GitHub emits nothing more, so a loop waiting for the verdict would stay silent.
+`wait_pr.py --pr` therefore reports `Codex review stalled` when the summary of an
+open, ready PR has shown the current head's review running for
+`--review-stall-minutes` (default 30; `0` disables) with no Codex answer naming
+that head since (a review of its commit, or a verdict comment for it). The clock
+starts at the latest of the summary's last update, a standalone `@codex review`
+request, and when the watch saw the head become reviewable (pushed, reopened, or
+marked ready). A re-request therefore restarts it, and one left unanswered is
+reported a window later. A head Codex never started on stays the post-push pickup
+check of `pr-delivery-loop`. The report rides the
+same staged delivery as any other event. Only a non-default window is part of the
+watch identity, so existing state files keep working.
+
`--settle <seconds>` is worth setting on any review loop. A bot review arrives as a
burst of inline comments plus an envelope, so the poll that happens to catch the
first fragment would otherwise report it alone and the rest would arrive as a second
diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.py
index fe2bbcd4d..e1e8a84a7 100755
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import argparse
import hashlib
import json
+import math
import os
import re
import sys
@@ -13,6 +14,7 @@ import tempfile
import time
import urllib.parse
from contextlib import contextmanager
+from datetime import datetime, timezone
from functools import partial
from pathlib import Path
from typing import Any, Iterator, NamedTuple
@@ -124,6 +126,20 @@ PR_SNAPSHOT_KEY = "snapshot"
ACTIONS_SNAPSHOT_KEY = "actions"
ACTIONS_OBSERVED_KEY = "actions_observed"
SUCCESS_BATCH_KEY = "success_batch"
+# The last Codex review stall this watch reported (``_codex_review_stall``), and when
+# this watch first saw the current head, which no stall of that head may predate.
+REVIEW_STALL_KEY = "review_stall_reported"
+REVIEW_STALL_HEAD_KEY = "review_stall_head"
+CODEX_SUMMARY_MARKER = "<!-- codex-pull-request-review-summary -->"
+# A review request is a comment that is the trigger command and nothing else, the same
+# anchored shape ``DEFAULT_NOISE_COMMENT_PATTERNS`` treats as a trigger; a sentence that
+# merely mentions it is not one.
+CODEX_REVIEW_REQUEST = re.compile(r"\s*@codex\s+review\s*", re.IGNORECASE)
+# Codex reviews almost always conclude within minutes: over 68 reviews on
+# avibe-bot/avibe the median was 3.5 min, p90 15 min and p95 39 min, while a stuck one
+# can sit at "running" for hours. Past this, the review is treated as stalled.
+DEFAULT_REVIEW_STALL_MINUTES = 30.0
+_CODEX_REVIEW_IN_PROGRESS = frozenset({"queued", "pending", "running", "in_progress"})
class PRReport(NamedTuple):
@@ -493,6 +509,112 @@ def _is_codex_progress(item: dict[str, Any]) -> bool:
)
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _github_time(value: Any) -> datetime | None:
+ try:
+ parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
+
+
+def _codex_summary_code_review(body: str) -> dict[str, Any] | None:
+ """The ``code_review`` object of a Codex summary's machine-readable state line."""
+
+ for line in body.splitlines():
+ match = re.fullmatch(r"<!-- codex-review-state:v1 (.+) -->", line.strip())
+ if not match:
+ continue
+ try:
+ state = json.loads(match.group(1))
+ except json.JSONDecodeError:
+ return None
+ code_review = state.get("code_review") if isinstance(state, dict) else None
+ return code_review if isinstance(code_review, dict) else None
+ return None
+
+
+def _codex_review_stall(
+ state: dict[str, Any],
+ *,
+ repo: str,
+ stall_seconds: float,
+ now: datetime,
+ head_seen_at: datetime,
+) -> tuple[str, str] | None:
+ """A Codex review of the current head stuck at "running": (key, report), else ``None``.
+
+ The one shape observed live: Codex's summary names the current head as being
+ reviewed, and no Codex answer naming that head (a review of its commit, or a
+ verdict comment for it) came since. It counts from the latest of the summary's
+ last update, a later standalone ``@codex review`` request (a re-request restarts
+ it, and one left unanswered is caught a window later), and when this watch saw
+ the head become reviewable (``head_seen_at``: pushed, reopened, or marked ready).
+ A head Codex never started on is the pickup check ``pr-delivery-loop`` already
+ owns after each push. ``key`` changes every further ``stall_seconds`` the stall
+ lasts, so a still-stuck review is reported again rather than once and forgotten.
+ """
+
+ pr = state.get("pull_request")
+ head = _current_pr_head_sha(pr)
+ # Only an open, ready PR is expected to be reviewed through; a draft or a closed
+ # PR restarts the clock when it becomes one (``head_seen_at``).
+ if stall_seconds <= 0 or not head or _current_pr_status(pr) != "open":
+ return None
+ summary_at: datetime | None = None
+ code_review: dict[str, Any] = {}
+ request_at: datetime | None = None
+ answered_at: datetime | None = None
+ for comment in state.get("issue_comments") or []:
+ body = str(comment.get("body") or "")
+ stamp = _github_time(comment.get("updated_at") or comment.get("created_at"))
+ if stamp is None:
+ continue
+ if _is_codex_item(comment):
+ parsed = _codex_summary_code_review(body) if CODEX_SUMMARY_MARKER in body else None
+ if parsed is not None:
+ if summary_at is None or stamp > summary_at:
+ summary_at, code_review = stamp, parsed
+ elif _is_codex_clean_pass(comment, head) and (answered_at is None or stamp > answered_at):
+ answered_at = stamp
+ elif CODEX_REVIEW_REQUEST.fullmatch(body):
+ created = _github_time(comment.get("created_at")) or stamp
+ request_at = created if request_at is None or created > request_at else request_at
+ for review in state.get("reviews") or []:
+ stamp = _github_time(review.get("submitted_at"))
+ if (
+ stamp is not None
+ and _is_codex_item(review)
+ and str(review.get("commit_id") or "").casefold() == head.casefold()
+ and (answered_at is None or stamp > answered_at)
+ ):
+ answered_at = stamp
+ if (
+ summary_at is None
+ or str(code_review.get("commit_sha") or "").casefold() != head.casefold()
+ or str(code_review.get("status") or "").casefold() not in _CODEX_REVIEW_IN_PROGRESS
+ or (answered_at is not None and answered_at >= summary_at)
+ ):
+ return None
+ since = max(summary_at, request_at or summary_at, head_seen_at)
+ shape = "has shown the review of this head as running"
+ elapsed = (now - since).total_seconds()
+ if elapsed < stall_seconds:
+ return None
+ rounds = int(elapsed // stall_seconds)
+ number = (pr or {}).get("number")
+ report = (
+ f"Codex review stalled for {repo}#{number}@{head[:12]}\n"
+ f"- Codex {shape} for {int(elapsed // 60)} min (since {since.strftime('%Y-%m-%dT%H:%M:%SZ')}).\n"
+ " Re-request it with `@codex review` and verify that Codex reacts to that comment.\n"
+ f" {(pr or {}).get('html_url') or ''}".rstrip()
+ )
+ return f"{head.casefold()}:{since.isoformat()}:{rounds}", report
+
+
def _quiet_success_snapshot(value: dict[str, Any], *, defer_reactions: bool) -> dict[str, Any]:
"""Remove only recognized success/progress payloads from the wake comparison."""
@@ -1345,6 +1467,10 @@ def _watch_identity(
material_fields["ci_sha"] = legacy_ci_sha
if args.coalesce_success:
material_fields["coalesce_success"] = True
+ # Only a non-default stall window is material, so watches seeded before the stall
+ # report existed keep their identity.
+ if getattr(args, "review_stall_minutes", DEFAULT_REVIEW_STALL_MINUTES) != DEFAULT_REVIEW_STALL_MINUTES:
+ material_fields["review_stall_minutes"] = args.review_stall_minutes
material = json.dumps(material_fields, sort_keys=True)
return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{material}".encode()).hexdigest()[:16]
@@ -2357,6 +2483,17 @@ def _build_parser() -> argparse.ArgumentParser:
"present at the same head; findings, errors, and unfamiliar activity still report"
),
)
+ parser.add_argument(
+ "--review-stall-minutes",
+ type=float,
+ default=DEFAULT_REVIEW_STALL_MINUTES,
+ help=(
+ "PR mode: report when Codex's summary has shown the current head's review running "
+ "this many minutes on an open PR (a re-request restarts the clock), and again each "
+ "further interval while it stays stuck; 0 disables. A head Codex never started on "
+ "is not detected. Default 30."
+ ),
+ )
parser.add_argument(
"--max-pages",
type=int,
@@ -2386,6 +2523,9 @@ def main() -> int:
if ci_error is not None:
print(ci_error, file=sys.stderr)
return 2
+ if not math.isfinite(args.review_stall_minutes) or args.review_stall_minutes < 0:
+ print("--review-stall-minutes must be 0 (off) or a finite positive number", file=sys.stderr)
+ return 2
ci_enabled = _ci_enabled(args)
success_conclusions = _parse_success_conclusions(args.success_conclusion)
@@ -2624,6 +2764,21 @@ def main() -> int:
saved_pr_cursor = None if args.catch_up else _saved_int(saved, "pr_cursor")
since_pr_id = args.since_pr_id if args.since_pr_id is not None else saved_pr_cursor
tracked_head_sha = _saved_str(saved, "head_sha")
+ # A state file from before the stall report has none, which reads as nothing
+ # reported yet: a review already stuck then is reported on the first cycle.
+ reported_stall = (_saved_str(saved, REVIEW_STALL_KEY) or "") if resumed else ""
+ saved_stall_head = saved.get(REVIEW_STALL_HEAD_KEY) if resumed else None
+ stall_head: dict[str, str] = (
+ {
+ "sha": str(saved_stall_head["sha"]),
+ "at": str(saved_stall_head["at"]),
+ "status": str(saved_stall_head.get("status") or ""),
+ }
+ if isinstance(saved_stall_head, dict)
+ and isinstance(saved_stall_head.get("sha"), str)
+ and _github_time(saved_stall_head.get("at")) is not None
+ else {}
+ )
review_fingerprints = _saved_fingerprints(saved, REVIEW_FINGERPRINTS_KEY)
review_comment_fingerprints = _saved_fingerprints(saved, REVIEW_COMMENT_FINGERPRINTS_KEY)
issue_comment_fingerprints = _saved_fingerprints(saved, ISSUE_COMMENT_FINGERPRINTS_KEY)
@@ -3044,6 +3199,39 @@ def main() -> int:
return False
return actions_output is None
+ def _with_review_stall(output: str | None) -> str | None:
+ """Add a Codex review stall not yet reported to this cycle's output.
+
+ Called after the cycle's ``pre_event_fields`` were taken, so a staged report
+ keeps the previous stall key committed until its delivery is confirmed.
+ """
+ nonlocal reported_stall, stall_head
+ now = _utc_now()
+ head = _current_pr_head_sha(state.get("pull_request"))
+ pr_status = _current_pr_status(state.get("pull_request"))
+ # The clock of a head starts when the head appears, and again when the PR
+ # becomes reviewable (draft or closed to open): a review is expected only from then.
+ if head and (
+ stall_head.get("sha", "").casefold() != head.casefold()
+ or (pr_status == "open" and stall_head.get("status") != "open")
+ ):
+ stall_head = {"sha": head, "at": now.isoformat(), "status": pr_status}
+ elif head:
+ stall_head = {**stall_head, "status": pr_status}
+ if args.seed_state or args.catch_up or explicit_replay or not head:
+ return output
+ stall = _codex_review_stall(
+ state,
+ repo=args.repo,
+ stall_seconds=args.review_stall_minutes * 60,
+ now=now,
+ head_seen_at=_github_time(stall_head["at"]) or now,
+ )
+ if stall is None or stall[0] == reported_stall:
+ return output
+ reported_stall = stall[0]
+ return stall[1] if output is None else f"{output}\n\n{stall[1]}"
+
def _adopt_report(report: PRReport) -> None:
nonlocal review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status
nonlocal observed_head_sha, snapshot, success_batch
@@ -3084,6 +3272,8 @@ def main() -> int:
ISSUE_COMMENT_FINGERPRINTS_KEY: dict(issue_comment_fingerprints),
REVIEW_THREAD_STATES_KEY: dict(review_thread_states),
PR_SNAPSHOT_KEY: snapshot or {},
+ REVIEW_STALL_KEY: reported_stall,
+ REVIEW_STALL_HEAD_KEY: dict(stall_head),
}
if ci_enabled:
fields[ACTIONS_SNAPSHOT_KEY] = actions_snapshot or {workflow: [] for workflow in args.workflow}
@@ -3241,6 +3431,7 @@ def main() -> int:
initial_result = _settle(initial_result, pending_cursors)
initial_output = initial_result.output
_adopt_report(initial_result)
+ initial_output = _with_review_stall(initial_output)
if initial_output is None:
# Persisted even with nothing to report: the baseline this cycle
# established is exactly what the next cycle must resume from.
@@ -3406,6 +3597,7 @@ def main() -> int:
result = _settle(result, pending_cursors)
output = result.output
_adopt_report(result)
+ output = _with_review_stall(output)
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_pr_activity.py b/tests/test_wait_for_github_pr_activity.py
index a2090bf9b..b1bea27b0 100644
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@ -6390,3 +6390,216 @@ def test_state_file_lock_serializes_the_ownership_decision(tmp_path) -> None:
# The state file was replaced; the lock's identity survived it.
assert lock_file.stat().st_ino == held
+
+
+def _codex_summary(head, *, status, updated_at, comment_id=640):
+ state = json.dumps({"code_review": {"commit_sha": head, "status": status}})
+ return {
+ "id": comment_id,
+ "body": f"<!-- codex-pull-request-review-summary -->\n<!-- codex-review-state:v1 {state} -->\n## Codex Review Summary",
+ "user": {"login": "chatgpt-codex-connector[bot]"},
+ "created_at": "2026-10-23T01:00:00Z",
+ "updated_at": updated_at,
+ "html_url": f"https://github.com/example/repo/pull/153#issuecomment-{comment_id}",
+ }
+
+
+def _review_request(created_at, comment_id=650):
+ return {
+ "id": comment_id,
+ "body": "@codex review",
+ "user": {"login": "cyhhao"},
+ "created_at": created_at,
+ "updated_at": created_at,
+ "html_url": f"https://github.com/example/repo/pull/153#issuecomment-{comment_id}",
+ }
+
+
+ ("comments", "minutes", "head_seen", "stalled"),
+ [
+ # Running on the current head past the window: stalled.
+ ([_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T03:00:00Z")], 31, -120, True),
+ ([_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T03:00:00Z")], 29, -120, False),
+ # Concluded on the current head, or describing another head.
+ ([_codex_summary(COALESCED_HEAD, status="completed", updated_at="2026-10-23T03:00:00Z")], 300, -120, False),
+ ([_codex_summary("b" * 40, status="running", updated_at="2026-10-23T03:00:00Z")], 300, -120, False),
+ # A re-request restarts the clock; one left unanswered is caught a window later.
+ ([_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T02:00:00Z"),
+ _review_request("2026-10-23T03:00:00Z")], 20, -120, False),
+ ([_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T02:00:00Z"),
+ _review_request("2026-10-23T03:00:00Z")], 31, -120, True),
+ ],
+)
+def test_a_codex_review_that_never_concludes_is_reported_as_stalled(comments, minutes, head_seen, stalled):
+ """A Codex review stuck at "running" produced no GitHub event at all, so a watch
+ waiting for its verdict stayed silent for hours. Past the stall window it is
+ reported, with a key that changes each further window so a review that stays
+ stuck is reported again. ``head_seen`` is minutes from 03:00 when the watch first
+ saw the head."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ state = _success_state(issue_comments=comments)
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+
+ def stall(state, at):
+ return module._codex_review_stall(
+ state, repo="example/repo", stall_seconds=1800, now=base + timedelta(minutes=at),
+ head_seen_at=base + timedelta(minutes=head_seen),
+ )
+
+ found = stall(state, minutes)
+ assert (found is not None) is stalled
+ if stalled:
+ key, report = found
+ assert report.startswith(f"Codex review stalled for example/repo#153@{COALESCED_HEAD[:12]}")
+ assert "@codex review" in report
+ later = stall(state, minutes + 30)
+ assert later is not None and later[0] != key
+ closed = _success_state(issue_comments=comments)
+ closed["pull_request"]["state"] = "closed"
+ assert stall(closed, minutes) is None
+
+
+def test_a_managed_watch_reports_a_stalled_review_once_per_window(tmp_path):
+ """The stall rides the watch's normal staged delivery: reported once, not again while
+ the same window lasts, and again once the review has stayed stuck another window."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)
+ running = _success_state(
+ pending,
+ issue_comments=[_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T03:00:00Z")],
+ )
+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, running),
+ actions=module.normalize_selected_runs({"CI": [pending]}))
+ options = ("--coalesce-success",)
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+
+ def cycle(minutes, delivery):
+ with patch.object(module, "_utc_now", return_value=base + timedelta(minutes=minutes)):
+ return _ci_cycle(module, path, [running], delivery=delivery, extra_args=options)
+
+ # The watch first sees the head at 03:00, when the summary turned running.
+ rc, output, _ = cycle(0, "1")
+ assert (rc, output) == (124, "")
+ rc, output, _ = cycle(10, "1")
+ assert (rc, output) == (124, "")
+ rc, output, payload = cycle(35, "1")
+ assert rc == 0 and "Codex review stalled" in output
+ assert payload[module.STAGED_KEY]["cursors"][module.REVIEW_STALL_KEY]
+ rc, output, _ = cycle(50, "2")
+ assert (rc, output) == (124, "")
+ rc, output, _ = cycle(65, "2")
+ assert rc == 0 and "Codex review stalled" in output
+
+
+def test_only_a_standalone_request_restarts_the_stall_clock():
+ """A comment that merely mentions the trigger is not a request for a review."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ mention = {**_review_request("2026-10-23T03:00:00Z"), "body": "Don't post `@codex review` while one is running."}
+ state = _success_state(issue_comments=[
+ _codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T02:00:00Z"), mention,
+ ])
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+ assert module._codex_review_stall(
+ state, repo="example/repo", stall_seconds=1800, now=base + timedelta(minutes=20),
+ head_seen_at=base - timedelta(hours=2),
+ ) is not None
+
+
[email protected]("value", ["nan", "inf", "-1"])
+def test_a_stall_window_that_is_not_a_finite_duration_is_refused_up_front(tmp_path, value):
+ module = _load_module()
+ with (
+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--review-stall-minutes", value]),
+ patch("sys.stderr", io.StringIO()) as stderr,
+ ):
+ assert module.main() == 2
+ assert "--review-stall-minutes" in stderr.getvalue()
+
+
+def test_a_draft_marked_ready_restarts_the_stall_clock(tmp_path):
+ """A review left running while the PR was a draft counts only from when it was
+ marked ready (same head): Codex gets a full window from then."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)
+ running = [_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T03:00:00Z")]
+ draft = _success_state(pending, issue_comments=running)
+ draft["pull_request"]["draft"] = True
+ ready = _success_state(pending, issue_comments=running)
+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, draft),
+ actions=module.normalize_selected_runs({"CI": [pending]}))
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+
+ def cycle(minutes, state, delivery="1"):
+ with patch.object(module, "_utc_now", return_value=base + timedelta(minutes=minutes)):
+ return _ci_cycle(module, path, [state], delivery=delivery, extra_args=("--coalesce-success",))
+
+ for minutes in (0, 60):
+ rc, output, _ = cycle(minutes, draft)
+ assert "Codex review stalled" not in output
+ rc, output, _ = cycle(61, ready, delivery="2")
+ assert "Codex review stalled" not in output
+ rc, output, _ = cycle(95, ready, delivery="3")
+ assert rc == 0 and "has shown the review of this head as running" in output
+
+
[email protected](("answer", "for_head", "concluded"), [
+ ("verdict_comment", True, True),
+ ("review", True, True),
+ # A delayed answer for an earlier head says nothing about this one.
+ ("verdict_comment", False, False),
+ ("review", False, False),
+])
+def test_a_codex_answer_for_the_head_concludes_its_running_review(answer, for_head, concluded):
+ """Codex may conclude through a verdict comment or a review without touching its
+ summary; only an answer that names the current head concludes its review."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+ reviewed = COALESCED_HEAD if for_head else "b" * 40
+ items = {"issue_comments": [_codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T03:00:00Z")]}
+ if answer == "verdict_comment":
+ items["issue_comments"].append({
+ **_clean_codex_comment(602, head=reviewed),
+ "created_at": "2026-10-23T03:05:00Z", "updated_at": "2026-10-23T03:05:00Z",
+ })
+ else:
+ items["reviews"] = [{
+ "id": 9, "state": "COMMENTED", "body": "findings", "commit_id": reviewed,
+ "submitted_at": "2026-10-23T03:05:00Z", "user": {"login": "chatgpt-codex-connector[bot]"},
+ }]
+ stall = module._codex_review_stall(
+ _success_state(**items), repo="example/repo", stall_seconds=1800,
+ now=base + timedelta(minutes=90), head_seen_at=base - timedelta(minutes=5),
+ )
+ assert (stall is None) is concluded
+
+
+def test_a_running_review_counts_only_from_when_the_pr_became_reviewable():
+ """A summary left running while the PR was closed counts from the reopening."""
+ from datetime import datetime, timedelta, timezone
+
+ module = _load_module()
+ base = datetime(2026, 10, 23, 3, 0, tzinfo=timezone.utc)
+ state = _success_state(issue_comments=[
+ _codex_summary(COALESCED_HEAD, status="running", updated_at="2026-10-23T01:00:00Z"),
+ ])
+
+ def stall(minutes):
+ return module._codex_review_stall(
+ state, repo="example/repo", stall_seconds=1800, now=base + timedelta(minutes=minutes), head_seen_at=base,
+ )
+
+ assert stall(20) is None
+ assert stall(31) is not None