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.

fix(watch): preserve CI notification baselines across incomplete polls (#2031)

Call Whitef70caa379f5b
diff --git a/docs/plans/watch-actions-dedup.md b/docs/plans/watch-actions-dedup.md
new file mode 100644
index 000000000..9f8c43ae3
--- /dev/null
+++ b/docs/plans/watch-actions-dedup.md
@@ -0,0 +1,150 @@
+# Preserve the GitHub Watch notification baseline
+
+## Change contract
+
+A combined PR/Actions Watch must not announce an already acknowledged CI result
+again because a later query omitted runs, returned a nonterminal state, reordered
+runs, or returned an older rerun attempt. A new PR head, run ID, rerun attempt, or
+terminal conclusion remains reportable. PR review, comment, thread, and lifecycle
+events remain independent of CI.
+
+The existing `actions` cursor is the notification baseline, not a cache of the
+latest poll. Preserve it until a complete, current-head terminal result is
+reported. Reset it on a head transition. Keep its existing JSON shape and use
+the existing staged-output/delivery-acknowledgement transaction; do not introduce
+a second delivery owner, change reporting filters, or reseed existing Watches.
+
+Retain the current head's known run inventory under an optional
+`actions_observed` field, defaulting to the existing `actions` baseline for
+version-1 files. Observation does not advance the notification baseline.
+This is required by a consuming regression: a new failed run appears during
+settle, disappears before delivery, and remains absent in later polls or across
+a PR-only delivery/restart. Without that inventory, the very next poll can still
+announce a success that omitted the known failed run. Reuse the existing
+normalization, per-head lifetime, persistence, and pending transaction.
+
+Incomplete observations are not new CI verdicts. In particular, a terminal subset
+that omits a previously known run cannot turn an earlier failure into success.
+Lower rerun attempts cannot supersede a delivered newer attempt. A settle
+candidate that returns to the acknowledged baseline must not be reported.
+
+### Report/snapshot atomicity
+
+A settled report owns both its PR observation and its optional Actions verdict.
+If a quiet re-poll omits previously detected PR activity, retain the PR
+observation with that fallback output; derive its fingerprints, head, and
+normalized snapshot from the same observation. Revalidate Actions separately
+against the latest successful poll. Both still use the existing pending
+transaction and delivery acknowledgement, not a second cursor or delivery owner.
+The startup and loop paths must consume the same report/baseline contract.
+
+Validate persisted Actions records before normalization or run-ID indexing.
+Malformed records are not an empty inventory: fail closed with the existing
+state-file diagnostic and preserve the file rather than discarding notification
+history or silently disabling requested CI monitoring. An absent optional
+observed inventory remains compatible with version-1 cursors.
+
+Actions monitoring is optional to request, but its persisted notification history
+is not disposable optional-feature configuration. Once `--workflow` is requested,
+silently disabling CI would change the Watch's contract. This integrity failure
+stops only the affected waiter and is surfaced by the supervisor's existing
+terminal-failure notification; it does not prevent Avibe service startup.
+
+The same protection precedes explicit replay, catch-up, seed, fresh manual
+initialization, and pending replay/acknowledgement. Those modes may reset valid
+history, not bypass corruption. Cursor writes replace the whole file: skipping
+validation would overwrite unreadable Actions history with a fresh baseline, or
+remove it in PR-only mode. Deferring validation until acknowledgement would also
+allow an unacknowledged corrupt pending report to replay first. Safe degradation
+would need an explicit evidence-preservation and recovery contract, which this
+repair does not add. Missing legacy baselines and present-but-malformed sections
+remain different cases; a valid released-state fixture rejected by these checks
+would warrant a compatibility fix rather than general sanitization.
+
+### Explicit replay and initialization boundaries
+
+The notification baseline and observed inventory must share the caller's
+initialization policy. Ordinary monitoring retains saved current-head run IDs
+and attempt high-water marks. Explicit seed, catch-up, PR cursor replay, and
+permitted fresh initialization of a partial manual cursor file instead
+initialize the inventory from the first current observation; inheriting
+a missing run or higher attempt from the old inventory can otherwise prevent
+all future CI verdicts after a deliberate reset.
+
+Keep the existing mode-specific notification behavior: seed adopts current CI
+silently, catch-up reports current completed CI, and explicit PR replay silently
+baselines unrelated CI while replaying the selected PR stream. Reset inventory
+only at initialization, not during polling or settle. Observations made after
+that boundary still constrain every complete gate and survive acknowledgement
+and ordinary restart.
+
+The smallest complete repair is this initialization-policy alignment, not a
+change to the delivery owner or missing-run policy. Only a valid ordinary
+resume inherits saved inventory; partial manual cursors already establish a
+fresh baseline, while managed unseeded starts remain rejected.
+Pending replay/acknowledgement
+and malformed-state validation still precede initialization; an explicit replay
+must neither discard an undelivered report nor bypass corrupt-state diagnostics.
+Validate saved optional inventory and legacy baseline fallback, missing rows and
+older attempts, immediate and later CI completion, PR-only replay, and an
+acknowledged restart that again enforces newly observed inventory.
+
+## Boundaries
+
+- Production changes are limited to the bundled GitHub PR waiter and stable
+ Actions normalization, with a patch-version skill update.
+- The Watch supervisor, GitHub authentication, retry budgets, polling intervals,
+ PR review filters, and public CLI arguments are unchanged.
+- Existing version-1 cursor files remain readable without manual migration.
+- Histories already erased by older quiet-poll writes cannot be reconstructed;
+ compatibility does not invent evidence of a past notification.
+- The existing at-least-once contract remains: an unacknowledged staged report
+ is replayed; an acknowledged report advances the same cursor.
+- No service restart, merge, deployment, or production application change.
+
+## Validation
+
+Use hermetic synthetic GitHub responses, a virtual clock, and test-owned cursor
+files. Reproduce the following before production edits, then verify the fix:
+
+- complete -> missing/nonterminal/older attempt/partial -> same complete result;
+- PR-only delivery while CI is absent, then acknowledgement and restart;
+- a transient settle candidate that returns to the prior baseline.
+
+Positive controls cover new heads, run IDs, rerun attempts, changed conclusions,
+multi-workflow gates, and undelivered replay. Run the complete PR/Actions waiter
+tests, related Watch supervisor tests, skill guidance tests, and changed-file lint.
+Obtain independent read-only review and exact-head GitHub review/CI before
+delivery close-out. Existing live Watches retain their IDs, cursors, and filters.
+
+Settle tests must continue through unacknowledged replay and acknowledged
+restart, including restoration of the unchanged PR item and a subsequent real
+edit/deletion. Cover PR-only and combined reports, startup and loop detection,
+and malformed committed/observed Actions records without overwriting evidence.
+
+Explicit PR replay baselines unrelated CI at the currently fetched head without
+altering the requested PR history. SHA comparisons use the same case-insensitive
+contract as preflight and run selection. An explicit ownerless seed writes the
+current CI baseline and inventory; this supported CLI operation is distinct from
+ordinary Watch re-arming, which must never reseed.
+
+## Known by design
+
+- Missing or regressed Actions observations do not establish a fresh terminal
+ gate. A deleted known run can require investigation; absence is not success.
+- Corrupt notification history intentionally stops the affected waiter with the
+ original file intact. This is stricter than the base's incomplete nested-row
+ validation, not a claim of unchanged behavior. Schema compatibility covers
+ valid released files; it does not authorize erasing unreadable history.
+- Existing PR settle limitation, not fixed here: a later nonempty PR snapshot
+ containing event B but omitting previously detected event A can replace the
+ earlier candidate and report only B. The unchanged base has the same behavior;
+ six hermetic comparisons (startup/loop, each with PR-only, stable CI, or
+ withdrawn CI) produced the same output and staged PR snapshot before and
+ after this change. Quiet-poll fallback and report/snapshot binding do not turn
+ bounded snapshot coalescing into an append-only activity log. Extending that
+ contract is separate from fixing introduced CI notification regressions.
+- This fixes a reproduced notification defect. Historical raw polling responses
+ were not retained, so it does not claim to prove every earlier duplicate's
+ remote API cause.
+- Source delivery does not automatically install a new Avibe release.
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index 4ac388947..71beebd96 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.17.3
+version: 0.17.4
---
# Background Watch Hook
@@ -254,6 +254,23 @@ rerun remains visible to the follow-up turn. Set the forever Watch's `--timeout
the default 21600-second per-cycle timeout treats six quiet hours as a terminal
failure, which is not a meaningful end condition for a PR delivery loop.
+The durable Actions snapshot is the notification baseline, not the latest poll.
+Missing runs, nonterminal responses, and older rerun attempts do not erase a
+previously reported result. A new head starts a new baseline; complete terminal
+results for new run IDs, rerun attempts, or conclusions still wake the Agent.
+An inventory missing a previously known run cannot establish a new CI verdict.
+Review/comment/thread activity remains reportable while CI is incomplete.
+The current head's known run inventory is retained separately from notification
+progress, including through a PR-only report or a restart. Existing cursor files
+are accepted without reseeding; notification history already overwritten by an
+older waiter cannot be reconstructed.
+Explicit `--catch-up` and PR cursor replay reset the observed run inventory to
+the initial current response, just as `--seed-state` does. Catch-up reports
+current completed CI; explicit PR replay baselines unrelated CI silently.
+Permitted fresh manual initialization also adopts the current inventory.
+Subsequent polls retain newly observed runs normally. Do not use these reset
+modes when re-arming an existing Watch.
+
```bash
STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"
BRANCH="$(gh pr view 151 --repo avibe-bot/avibe --json headRefName --jq .headRefName)"
diff --git a/skills/background-watch-hook/scripts/_github_actions_wait.py b/skills/background-watch-hook/scripts/_github_actions_wait.py
index bd6817b80..549bc5974 100644
--- a/skills/background-watch-hook/scripts/_github_actions_wait.py
+++ b/skills/background-watch-hook/scripts/_github_actions_wait.py
@@ -100,7 +100,9 @@ def normalize_selected_runs(selected: dict[str, list[dict[str, Any]]]) -> dict[s
"head_branch": run.get("head_branch"),
"run_attempt": run.get("run_attempt"),
}
- for run in runs
+ # run_started_at can move during a rerun. Run ordering is not a
+ # verdict change and must not affect durable snapshot equality.
+ for run in sorted(runs, key=lambda item: str(item.get("id") or ""))
]
for workflow, runs in selected.items()
}
diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.py
index 89556b4ac..cf8ccd62f 100755
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@ -15,7 +15,7 @@ import urllib.parse
from contextlib import contextmanager
from functools import partial
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any, Iterator, NamedTuple
try: # POSIX only, which is every platform `vibe` runs the waiter on.
import fcntl
@@ -95,6 +95,18 @@ ISSUE_COMMENT_FINGERPRINTS_KEY = "issue_comment_fingerprints"
REVIEW_THREAD_STATES_KEY = "review_thread_states"
PR_SNAPSHOT_KEY = "snapshot"
ACTIONS_SNAPSHOT_KEY = "actions"
+ACTIONS_OBSERVED_KEY = "actions_observed"
+
+
+class PRReport(NamedTuple):
+ """One delivery and the observations its pending transaction will commit."""
+
+ output: str | None
+ cursors: tuple[int, int, int, int, str]
+ pr_state: dict[str, Any]
+ actions: dict[str, Any] | None = None
+
+
PR_FINGERPRINT_KEYS = (
REVIEW_FINGERPRINTS_KEY,
REVIEW_COMMENT_FINGERPRINTS_KEY,
@@ -1124,6 +1136,12 @@ def _load_state_file(
)
if conflict is not None:
raise StateFileOwnershipError(f"State file {path} {conflict}")
+ _validate_saved_actions(payload)
+ pending = payload.get(STAGED_KEY)
+ if isinstance(pending, dict) and isinstance(pending.get("cursors"), dict):
+ # Legacy pending transactions may contain only some cursor fields.
+ # Validate their effective state before acknowledgement can write it.
+ _validate_saved_actions({**payload, **pending["cursors"]})
return payload
@@ -1545,9 +1563,86 @@ 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 _saved_actions_snapshot(saved: dict[str, Any], key: str = ACTIONS_SNAPSHOT_KEY) -> dict[str, Any]:
+ return saved.get(key, {})
+
+
+def _validate_saved_actions(saved: dict[str, Any]) -> None:
+ """Reject corrupt history, never filter it into an apparently empty gate."""
+
+ for key in (ACTIONS_SNAPSHOT_KEY, ACTIONS_OBSERVED_KEY):
+ if key not in saved:
+ continue
+ value = saved[key]
+ if not isinstance(value, dict):
+ raise StateFileUnusableError(f"Saved {key} is malformed: expected a workflow mapping")
+ for workflow, runs in value.items():
+ if not isinstance(workflow, str) or not isinstance(runs, list):
+ raise StateFileUnusableError(f"Saved {key} is malformed: expected workflow run lists")
+ for run in runs:
+ if not isinstance(run, dict):
+ raise StateFileUnusableError(f"Saved {key} is malformed: expected run objects")
+ run_id = run.get("id")
+ attempt = run.get("run_attempt")
+ if (
+ not isinstance(run_id, (int, str))
+ or isinstance(run_id, bool)
+ or (isinstance(run_id, str) and not run_id)
+ or any(
+ run.get(field) is not None and not isinstance(run[field], str)
+ for field in ("status", "conclusion", "head_sha", "head_branch")
+ )
+ or (
+ attempt is not None
+ and (not isinstance(attempt, int) or isinstance(attempt, bool) or attempt < 1)
+ )
+ ):
+ raise StateFileUnusableError(f"Saved {key} is malformed: invalid run comparison fields")
+ if ACTIONS_SNAPSHOT_KEY in saved and ACTIONS_OBSERVED_KEY in saved:
+ if set(saved[ACTIONS_SNAPSHOT_KEY]) != set(saved[ACTIONS_OBSERVED_KEY]):
+ raise StateFileUnusableError("Saved actions_observed is malformed: workflow inventory differs from actions")
+
+
+def _actions_snapshot_regressed(current: dict[str, Any], previous: dict[str, Any]) -> bool:
+ """An incomplete inventory or older attempt cannot establish a new verdict."""
+
+ for workflow, previous_runs in previous.items():
+ current_runs = {run.get("id"): run for run in current.get(workflow, [])}
+ for previous_run in previous_runs:
+ current_run = current_runs.get(previous_run.get("id"))
+ if current_run is None:
+ return True
+ previous_attempt = previous_run.get("run_attempt")
+ current_attempt = current_run.get("run_attempt")
+ if isinstance(previous_attempt, int) and (
+ not isinstance(current_attempt, int) or current_attempt < previous_attempt
+ ):
+ return True
+ return False
+
+
+def _observe_actions(
+ previous: dict[str, Any], current: dict[str, Any], head_sha: str
+) -> dict[str, Any]:
+ """Remember known run IDs/attempts without treating observation as delivery."""
+
+ observed = {}
+ for workflow, runs in current.items():
+ known = {
+ run.get("id"): run
+ for run in previous.get(workflow, [])
+ if str(run.get("head_sha") or "").casefold() == head_sha.casefold()
+ }
+ for run in runs:
+ old_attempt = known.get(run.get("id"), {}).get("run_attempt")
+ new_attempt = run.get("run_attempt")
+ if isinstance(old_attempt, int) and (
+ not isinstance(new_attempt, int) or new_attempt < old_attempt
+ ):
+ continue
+ known[run.get("id")] = run
+ observed[workflow] = list(known.values())
+ return normalize_selected_runs(observed)
def _ci_enabled(args: argparse.Namespace) -> bool:
@@ -1664,6 +1759,7 @@ def _resolve_staged_state(
resolved = {key: value for key, value in saved.items() if key != STAGED_KEY}
if delivered:
resolved.update(cursors)
+ _validate_saved_actions(resolved)
print(
(
"An earlier report was delivered; advancing past it."
@@ -2087,7 +2183,7 @@ def main() -> int:
# replay an already observed terminal Actions result.
actions_snapshot = normalize_selected_runs(selected_actions)
elif resumed:
- actions_snapshot = _saved_actions_snapshot(saved)
+ actions_snapshot = normalize_selected_runs(_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
@@ -2127,6 +2223,25 @@ def main() -> int:
)
actions_snapshot = normalize_selected_runs(selected_actions) if ci_enabled else None
+ # Explicit PR replay baselines CI at the current head, independently of the
+ # historical PR cursor. Explicit seed likewise adopts the current snapshot.
+ if ci_enabled and args.seed_state:
+ actions_snapshot = normalize_selected_runs(selected_actions)
+ actions_head_sha = observed_head_sha if explicit_replay or args.seed_state else tracked_head_sha
+ actions_observed = (
+ _observe_actions(
+ # Only a normal resume inherits old inventory. Replaying or
+ # establishing a fresh baseline must not retain omitted old runs.
+ {} if not resumed or args.seed_state or explicit_replay else (
+ _saved_actions_snapshot(saved, ACTIONS_OBSERVED_KEY)
+ if ACTIONS_OBSERVED_KEY in saved else _saved_actions_snapshot(saved)
+ ),
+ normalize_selected_runs(selected_actions),
+ args.sha or observed_head_sha,
+ )
+ if ci_enabled else {}
+ )
+
if token is None:
bootstrap_requests = requests_per_poll_count
unauthenticated_min = min_interval_for_unauthenticated(
@@ -2153,6 +2268,9 @@ def main() -> int:
def _active_ci_head_sha() -> str:
return args.sha or _current_pr_head_sha(state.get("pull_request"))
+ def _same_actions_head() -> bool:
+ return actions_head_sha is not None and actions_head_sha.casefold() == _active_ci_head_sha().casefold()
+
def _initial_cursor(flag_value: int | None, saved_key: str, items_key: str) -> int:
if flag_value is not None:
return flag_value
@@ -2192,8 +2310,8 @@ def main() -> int:
file=sys.stderr,
)
- def _render(cursors: tuple[int, int, int, int, str]) -> tuple[str | None, int, int, int, int, str]:
- return _render_activity(
+ def _render(cursors: tuple[int, int, int, int, str]) -> PRReport:
+ activity = _render_activity(
repo=args.repo,
pr_number=args.pr,
state=state,
@@ -2216,32 +2334,66 @@ def main() -> int:
ignored_authors=ignored_authors,
ignore_patterns=ignore_patterns,
)
+ return PRReport(activity[0], activity[1:], state)
def _render_combined(
cursors: tuple[int, int, int, int, str],
- ) -> tuple[str | None, int, int, int, int, str]:
+ *,
+ fallback_pr: PRReport | None = None,
+ ) -> PRReport:
pr_result = _render(cursors)
+ if pr_result.output is None and fallback_pr is not None and fallback_pr.output is not None:
+ pr_result = fallback_pr
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=_active_ci_head_sha(),
- selected=selected_actions,
- success_conclusions=success_conclusions,
- )
+ # A transient PR head can itself be retained as evidence. Never
+ # attach another head's CI verdict to that observation's baseline.
+ if _current_pr_head_sha(pr_result.pr_state.get("pull_request")).casefold() != (
+ _current_pr_head_sha(state.get("pull_request")).casefold()
+ ):
+ return pr_result
+
+ actions_output = _render_new_actions()
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:])
+ reported_actions = normalize_selected_runs(selected_actions)
+ output = actions_output if pr_result.output is None else f"{pr_result.output}\n{actions_output}"
+ return pr_result._replace(output=output, actions=reported_actions)
+
+ def _render_new_actions() -> str | None:
+ current_actions = normalize_selected_runs(selected_actions)
+ if _actions_snapshot_regressed(current_actions, actions_observed):
+ return None
+ # A push starts a new CI epoch even if it returns to an earlier SHA.
+ previous = actions_snapshot if _same_actions_head() else None
+ if previous is not None and current_actions == previous:
+ return None
+ output, _failed = render_actions_result(
+ repo=args.repo,
+ branch=args.branch,
+ head_sha=_active_ci_head_sha(),
+ selected=selected_actions,
+ success_conclusions=success_conclusions,
+ )
+ return output
+
+ def _advance_actions_baseline(report: PRReport) -> None:
+ nonlocal actions_snapshot, actions_head_sha
+ if not ci_enabled:
+ return
+ # Only a reported terminal result advances the notification baseline.
+ # Quiet polls and PR-only reports must not erase an acknowledged CI
+ # result. The existing pending transaction covers this state too.
+ report_head = args.sha or _current_pr_head_sha(report.pr_state.get("pull_request"))
+ if report.actions is not None:
+ actions_snapshot = report.actions
+ elif actions_head_sha is None or actions_head_sha.casefold() != report_head.casefold():
+ actions_snapshot = {workflow: [] for workflow in args.workflow}
+ actions_head_sha = report_head
def _refresh_actions() -> None:
- nonlocal selected_actions
+ nonlocal selected_actions, actions_observed
if ci_enabled:
selected_actions = select_matching_runs(
state.get("actions", []),
@@ -2249,12 +2401,18 @@ def main() -> int:
branch=args.branch,
head_sha=_active_ci_head_sha(),
)
+ actions_observed = _observe_actions(
+ actions_observed, normalize_selected_runs(selected_actions), _active_ci_head_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:
+ previous = actions_snapshot if _same_actions_head() else None
+ if _actions_snapshot_regressed(current_actions, actions_observed):
+ return True
+ if previous is not None and current_actions == previous:
return False
actions_output, _failed = render_actions_result(
repo=args.repo,
@@ -2265,10 +2423,35 @@ def main() -> int:
)
return actions_output is None
- def _advance_since() -> None:
+ def _adopt_report(report: PRReport) -> None:
+ nonlocal review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status
+ nonlocal observed_head_sha, snapshot
+ nonlocal review_fingerprints, review_comment_fingerprints, issue_comment_fingerprints, review_thread_states
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"])
+ review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status = report.cursors
+ pr_state = report.pr_state
+ observed_head_sha = _current_pr_head_sha(pr_state.get("pull_request"))
+ review_comment_since = later_since(review_comment_since, pr_state["review_comments"])
+ issue_comment_since = later_since(issue_comment_since, pr_state["issue_comments"])
+ review_fingerprints = _fingerprint_map(pr_state["reviews"])
+ review_comment_fingerprints = _fingerprint_map(pr_state["review_comments"])
+ issue_comment_fingerprints = _fingerprint_map(pr_state["issue_comments"])
+ if token is not None:
+ raw_threads = pr_state.get("review_threads")
+ review_thread_states = _review_thread_state_map(
+ raw_threads if isinstance(raw_threads, list) else []
+ )
+ snapshot = _normalized_pr_snapshot(
+ pr_state,
+ viewer_login=viewer_login,
+ ignore_self_comments=not args.include_self_comments,
+ actionable_only=args.actionable_only,
+ ignored_authors=ignored_authors,
+ ignore_patterns=ignore_patterns,
+ committed_snapshot=snapshot,
+ review_threads_available=token is not None,
+ )
+ _advance_actions_baseline(report)
def _pr_state_fields() -> dict[str, Any]:
fields = {
@@ -2289,7 +2472,8 @@ def main() -> int:
PR_SNAPSHOT_KEY: snapshot or {},
}
if ci_enabled:
- fields[ACTIONS_SNAPSHOT_KEY] = normalize_selected_runs(selected_actions)
+ fields[ACTIONS_SNAPSHOT_KEY] = actions_snapshot or {workflow: [] for workflow in args.workflow}
+ fields[ACTIONS_OBSERVED_KEY] = actions_observed
return fields
def _persist_pr_state(
@@ -2337,9 +2521,9 @@ def main() -> int:
_persist_pr_state()
def _settle(
- first: tuple[str | None, int, int, int, int, str],
+ first: PRReport,
pending: tuple[int, int, int, int, str],
- ) -> tuple[str | None, int, int, int, int, str]:
+ ) -> PRReport:
"""Re-poll while a batch is still landing so it costs one Agent turn."""
nonlocal state
@@ -2347,12 +2531,14 @@ def main() -> int:
return first
best = first
- best_pr_only = _render(pending) if ci_enabled else None
+ best_pr = _render(pending)
- 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
+ def _fallback() -> PRReport:
+ # Revalidate against the latest successful poll, not a transient
+ # earlier candidate that may now equal the delivered baseline.
+ # PR evidence remains at-least-once even if a later collection
+ # omits it; only the provisional CI verdict can be withdrawn.
+ return _render_combined(pending, fallback_pr=best_pr)
for _round in range(SETTLE_MAX_ROUNDS):
# The batch is already worth a turn, so waiting for the rest of it must
@@ -2403,16 +2589,16 @@ def main() -> int:
state, _count = settle_request.value
_refresh_actions()
pr_candidate = _render(pending)
+ if pr_candidate.output is not None:
+ best_pr = pr_candidate
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_combined(pending)
- if candidate[0] is None:
- return best
- if candidate[1:] == best[1:]:
+ candidate = _fallback()
+ if candidate.output is None:
+ return candidate
+ if candidate.cursors == best.cursors:
return candidate
best = candidate
return _fallback()
@@ -2424,42 +2610,19 @@ def main() -> int:
reaction_cursor,
pr_status,
)
+ # Until a report is adopted, the committed PR head must stay paired
+ # with the saved snapshot, even if the first fetch already saw a push.
+ observed_head_sha = tracked_head_sha or observed_head_sha
pre_event_fields = _pr_state_fields()
initial_result = (
- (None, *pending_cursors)
+ PRReport(None, pending_cursors, state)
if args.seed_state
else _render_combined(pending_cursors)
)
- if initial_result[0] is not None and not args.catch_up:
+ if initial_result.output is not None and not args.catch_up:
initial_result = _settle(initial_result, pending_cursors)
- (
- initial_output,
- review_cursor,
- review_comment_cursor,
- issue_comment_cursor,
- reaction_cursor,
- pr_status,
- ) = initial_result
- observed_head_sha = _current_pr_head_sha(state.get("pull_request"))
- _advance_since()
- review_fingerprints = _fingerprint_map(state["reviews"])
- review_comment_fingerprints = _fingerprint_map(state["review_comments"])
- issue_comment_fingerprints = _fingerprint_map(state["issue_comments"])
- if token is not None:
- raw_threads = state.get("review_threads")
- review_thread_states = _review_thread_state_map(
- raw_threads if isinstance(raw_threads, list) else []
- )
- snapshot = _normalized_pr_snapshot(
- state,
- viewer_login=viewer_login,
- ignore_self_comments=not args.include_self_comments,
- actionable_only=args.actionable_only,
- ignored_authors=ignored_authors,
- ignore_patterns=ignore_patterns,
- committed_snapshot=snapshot,
- review_threads_available=token is not None,
- )
+ initial_output = initial_result.output
+ _adopt_report(initial_result)
if initial_output is None:
# Persisted even with nothing to report: the baseline this cycle
# established is exactly what the next cycle must resume from.
@@ -2612,7 +2775,6 @@ def main() -> int:
if args.pr is not None:
_refresh_actions()
- observed_head_sha = _current_pr_head_sha(state.get("pull_request"))
pending_cursors = (
review_cursor,
review_comment_cursor,
@@ -2622,38 +2784,10 @@ def main() -> int:
)
pre_event_fields = _pr_state_fields()
result = _render_combined(pending_cursors)
- if result[0] is not None:
+ if result.output is not None:
result = _settle(result, pending_cursors)
- (
- output,
- review_cursor,
- review_comment_cursor,
- issue_comment_cursor,
- reaction_cursor,
- pr_status,
- ) = result
- observed_head_sha = _current_pr_head_sha(state.get("pull_request"))
- _advance_since()
- review_fingerprints = _fingerprint_map(state["reviews"])
- review_comment_fingerprints = _fingerprint_map(state["review_comments"])
- issue_comment_fingerprints = _fingerprint_map(state["issue_comments"])
- if token is not None:
- raw_threads = state.get("review_threads")
- review_thread_states = _review_thread_state_map(
- raw_threads if isinstance(raw_threads, list) else []
- )
- snapshot = _normalized_pr_snapshot(
- state,
- viewer_login=viewer_login,
- ignore_self_comments=not args.include_self_comments,
- actionable_only=args.actionable_only,
- ignored_authors=ignored_authors,
- ignore_patterns=ignore_patterns,
- committed_snapshot=snapshot,
- review_threads_available=token is not None,
- )
- if ci_enabled:
- actions_snapshot = normalize_selected_runs(selected_actions)
+ output = result.output
+ _adopt_report(result)
if output is None:
# Cursors also move when everything new was filtered out, and that
# progress has to survive the cycle or the next one re-examines it.
diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.py
index 2c40720f5..784997444 100644
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@ -4273,6 +4273,781 @@ def test_dynamic_combined_cycles_report_activity_that_lands_during_the_follow_up
assert second_payload[module.STAGED_KEY]["cursors"]["issue_comment_cursor"] == 601
+def _ci_run(run_id=7, *, attempt=1, workflow="CI", head="head-1", status="completed", conclusion="success"):
+ return {
+ "id": run_id,
+ "name": workflow,
+ "head_sha": head,
+ "head_branch": "feature",
+ "status": status,
+ "conclusion": conclusion,
+ "run_attempt": attempt,
+ "html_url": f"https://github.com/example/actions/runs/{run_id}",
+ }
+
+
+def _ci_state(*runs, head="head-1", comment=False):
+ state = _pr_state(review_comments=[_review_comment(501)] if comment else [])
+ state["pull_request"]["head"] = {"sha": head}
+ state["actions"] = list(runs)
+ return state
+
+
+def _seed_ci_state(module, path, *runs, workflows=("CI",), head="head-1", owner="wat_9"):
+ state = _ci_state(*runs, head=head)
+ _managed_state(
+ module,
+ path,
+ owner,
+ **_complete_pr_baseline_fields(module, state),
+ actions=module.normalize_selected_runs(
+ module.select_matching_runs(list(runs), workflows=list(workflows), branch="feature", head_sha=head)
+ ),
+ )
+
+
+def _ci_cycle(module, path, states, *, delivery="1", workflows=("CI",), settle=0, sha=None, extra_args=()):
+ """Use real cursor IO in tmp_path, fake GitHub, and a bounded virtual clock."""
+ clock = 0.0
+ polls = iter(states)
+ latest = states[-1]
+
+ def sleep(seconds):
+ nonlocal clock
+ clock += seconds
+
+ def fetch(*args, **kwargs):
+ nonlocal latest
+ latest = next(polls, latest)
+ return latest, 2
+
+ workflow_args = tuple(arg for workflow in workflows for arg in ("--workflow", workflow))
+ ci_args = ("--branch", "feature", *workflow_args) if workflows else ()
+ sha_args = ("--sha", sha) if sha is not None else ()
+ with (
+ patch.object(module.time, "monotonic", side_effect=lambda: clock),
+ patch.object(module.time, "sleep", side_effect=sleep),
+ ):
+ return _run_managed(
+ module,
+ path,
+ fetch,
+ delivery=delivery,
+ extra_args=(
+ *ci_args, *sha_args, "--interval", "1", "--timeout", "100",
+ "--settle", str(settle), *extra_args,
+ ),
+ )
+
+
[email protected]("intermediate", ["missing", "nonterminal", "older-attempt", "partial"])
+def test_combined_ci_does_not_reannounce_observed_results_after_snapshot_regression(tmp_path, intermediate):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ first = _ci_run(attempt=2, conclusion="failure")
+ second = _ci_run(8)
+ _seed_ci_state(module, path, first, second)
+ regressed = {
+ "missing": _ci_state(),
+ "nonterminal": _ci_state(_ci_run(attempt=2, status="in_progress", conclusion=None), second),
+ "older-attempt": _ci_state(_ci_run(attempt=1, conclusion="failure"), second),
+ "partial": _ci_state(first),
+ }[intermediate]
+
+ rc, output, _ = _ci_cycle(
+ module, path, [_ci_state(first, second), regressed, _ci_state(first, second)]
+ )
+
+ assert rc == 124
+ assert output == ""
+
+
+def test_combined_ci_remembers_a_result_across_pr_only_delivery_and_restart(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ run = _ci_run()
+ _seed_ci_state(module, path, run)
+
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(comment=True)])
+ assert rc == 0
+ assert "review_comment #501" in output
+ assert "GitHub Actions" not in output
+
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(run, comment=True)], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("new_result", ["rerun", "new-run", "new-head", "conclusion"])
+def test_combined_ci_still_reports_new_terminal_results_and_acknowledges_once(tmp_path, new_result):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ old = _ci_run()
+ _seed_ci_state(module, path, old)
+ new = {
+ "rerun": _ci_run(attempt=2),
+ "new-run": _ci_run(8),
+ "new-head": _ci_run(9, head="head-2"),
+ "conclusion": _ci_run(conclusion="failure"),
+ }[new_result]
+ state = _ci_state(old, new) if new_result == "new-run" else _ci_state(new, head=new["head_sha"])
+
+ rc, first_output, payload = _ci_cycle(module, path, [state])
+ assert rc == 0
+ assert "GitHub Actions" in first_output
+ assert payload[module.STAGED_KEY]["output"] == first_output.strip()
+ assert payload["actions"] == module.normalize_selected_runs({"CI": [old]})
+
+ # Losing the acknowledgement must replay even when the API is unavailable.
+ def unavailable(*args, **kwargs):
+ raise AssertionError("replay must not reach GitHub")
+
+ rc, replay, _ = _run_managed(
+ module, path, unavailable, delivery="1", extra_args=("--branch", "feature", "--workflow", "CI")
+ )
+ assert rc == 0
+ assert replay == first_output
+
+ rc, output, _ = _ci_cycle(module, path, [state], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+
+def test_combined_ci_settle_drops_a_candidate_that_returns_to_the_reported_baseline(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ old = _ci_run()
+ _seed_ci_state(module, path, old)
+
+ rc, output, _ = _ci_cycle(
+ module, path, [_ci_state(old), _ci_state(_ci_run(attempt=2)), _ci_state(old)], settle=1
+ )
+
+ assert rc == 124
+ assert output == ""
+
+
+def test_combined_ci_waits_for_all_workflows_without_reannouncing_a_restored_one(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ ci = _ci_run()
+ security = _ci_run(8, workflow="Security Scan")
+ workflows = ("CI", "Security Scan")
+ _seed_ci_state(module, path, ci, security, workflows=workflows)
+
+ rc, output, _ = _ci_cycle(
+ module, path, [_ci_state(ci), _ci_state(ci, security)], workflows=workflows
+ )
+ assert rc == 124
+ assert output == ""
+
+ pending = _ci_run(attempt=2, status="in_progress", conclusion=None)
+ completed = _ci_run(attempt=2)
+ rc, output, _ = _ci_cycle(
+ module, path,
+ [_ci_state(pending, security), _ci_state(completed), _ci_state(completed, security)],
+ workflows=workflows,
+ )
+ assert rc == 0
+ assert "CI: status=completed" in output
+ assert "Security Scan: status=completed" in output
+
+
[email protected]("with_comment", [False, True])
+def test_combined_ci_settle_does_not_commit_a_terminal_subset_of_its_candidate(tmp_path, with_comment):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ old = _ci_run()
+ failed = _ci_run(8, conclusion="failure")
+ succeeded = _ci_run(9)
+ _seed_ci_state(module, path, old)
+ candidate = _ci_state(old, failed, succeeded, comment=with_comment)
+ partial = _ci_state(old, succeeded, comment=with_comment)
+
+ rc, output, payload = _ci_cycle(
+ module, path, [_ci_state(old), candidate, partial], settle=1
+ )
+ assert rc == (0 if with_comment else 124)
+ assert "GitHub Actions" not in output
+ fields = payload[module.STAGED_KEY]["cursors"] if with_comment else payload
+ assert fields["actions"] == module.normalize_selected_runs({"CI": [old]})
+
+ # Remember the missing failed run across a restart, including a PR-only ack.
+ rc, output, _ = _ci_cycle(module, path, [partial], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+ # The candidate was withdrawn, so the full result must still be delivered.
+ rc, output, payload = _ci_cycle(module, path, [candidate], delivery="2")
+ assert rc == 0
+ assert "GitHub Actions failure" in output
+ assert "actions/runs/8" in output
+ assert payload[module.STAGED_KEY]["cursors"]["actions"] == module.normalize_selected_runs(
+ {"CI": [old, failed, succeeded]}
+ )
+
+
+def test_combined_ci_run_order_and_timestamp_changes_are_not_events(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ first = _ci_run()
+ second = _ci_run(8)
+ _seed_ci_state(module, path, first, second)
+ first["run_started_at"] = "2026-01-02T00:00:00Z"
+ second["run_started_at"] = "2026-01-01T00:00:00Z"
+
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(second, first)])
+ assert rc == 124
+ assert output == ""
+
+
+def test_combined_ci_new_head_does_not_inherit_old_known_runs_or_lose_completion(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ _seed_ci_state(module, path, _ci_run(conclusion="failure"))
+ pending = _ci_run(9, head="head-2", status="in_progress", conclusion=None)
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(pending, head="head-2")])
+ assert rc == 0
+ assert "pr_head" in output
+ assert "GitHub Actions" not in output
+
+ completed = _ci_run(9, head="head-2")
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(completed, head="head-2")], delivery="2")
+ assert rc == 0
+ assert "GitHub Actions success" in output
+ assert "actions/runs/7" not in output
+
+
+def test_combined_ci_settle_fetch_failure_retains_the_report_and_its_snapshot(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ old, new = _ci_run(), _ci_run(attempt=2)
+ _seed_ci_state(module, path, old)
+ error = urllib.error.HTTPError("https://api.github.com/example", 503, "Unavailable", hdrs=None, fp=None)
+ polls = iter([(_ci_state(new), 2), error])
+
+ def fetch(*args, **kwargs):
+ value = next(polls)
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+ with patch.object(module.time, "sleep", return_value=None):
+ rc, output, payload = _run_managed(
+ module, path, fetch, delivery="1",
+ extra_args=("--branch", "feature", "--workflow", "CI", "--settle", "1", "--timeout", "0"),
+ )
+ assert rc == 0
+ assert "GitHub Actions success" in output
+ assert payload["actions"] == module.normalize_selected_runs({"CI": [old]})
+ assert payload[module.STAGED_KEY]["cursors"]["actions"] == module.normalize_selected_runs({"CI": [new]})
+
+
+def test_combined_ci_pinned_sha_case_does_not_start_a_new_epoch(tmp_path):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ run = _ci_run(head="abc123")
+ _seed_ci_state(module, path, run, head="abc123")
+
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(run, head="abc123")], sha="ABC123")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("with_comment", [False, True])
+def test_explicit_pr_replay_does_not_replay_unrelated_completed_ci(with_comment):
+ module = _load_module()
+ state = _ci_state(_ci_run(), comment=with_comment)
+ stdout = io.StringIO()
+ with (
+ patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_ENV: ""}, clear=False),
+ patch.object(module, "_fetch_state", return_value=(state, 2)),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value="tester"),
+ patch.object(module.time, "monotonic", side_effect=[0, 2]),
+ patch(
+ "sys.argv",
+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--workflow", "CI",
+ "--since-review-comment-id", "0", "--timeout", "1"],
+ ),
+ redirect_stdout(stdout),
+ patch("sys.stderr", io.StringIO()),
+ ):
+ rc = module.main()
+ assert rc == (0 if with_comment else 124)
+ assert "GitHub Actions" not in stdout.getvalue()
+ assert ("review_comment #501" in stdout.getvalue()) == with_comment
+
+
[email protected]("mode", ["catch-up", "pr-replay", "catch-up-pr-replay", "monitor"])
[email protected]("inventory_present", [False, True])
[email protected]("stale_kind", ["missing-run", "higher-attempt"])
[email protected]("initial_terminal", [False, True])
+def test_explicit_replay_resets_ci_inventory_but_ordinary_resume_retains_it(
+ tmp_path, mode, inventory_present, stale_kind, initial_terminal,
+):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ old = _ci_run()
+ stale = (
+ [old, _ci_run(8, conclusion="failure")]
+ if stale_kind == "missing-run" else [_ci_run(attempt=9, conclusion="failure")]
+ )
+ _seed_ci_state(module, path, *([old] if inventory_present else stale))
+ if inventory_present:
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ saved[module.ACTIONS_OBSERVED_KEY] = module.normalize_selected_runs({"CI": stale})
+ path.write_text(json.dumps(saved), encoding="utf-8")
+
+ current = old if initial_terminal else _ci_run(status="in_progress", conclusion=None)
+ state = _ci_state(current, comment=True)
+ flags = {
+ "catch-up": ("--catch-up",),
+ "pr-replay": ("--since-review-comment-id", "0"),
+ "catch-up-pr-replay": ("--catch-up", "--since-review-comment-id", "0"),
+ "monitor": (),
+ }[mode]
+ rc, first_output, payload = _ci_cycle(module, path, [state], extra_args=flags)
+ assert rc == 0
+ assert "review_comment #501" in first_output
+ assert ("GitHub Actions success" in first_output) == ("--catch-up" in flags and initial_terminal)
+ expected_inventory = module._observe_actions(
+ module.normalize_selected_runs({"CI": stale}) if mode == "monitor" else {},
+ module.normalize_selected_runs({"CI": [current]}),
+ "head-1",
+ )
+ assert payload[module.STAGED_KEY]["cursors"][module.ACTIONS_OBSERVED_KEY] == expected_inventory
+
+ # Explicit reset flags must not supersede an undelivered transaction.
+ def unavailable(*args, **kwargs):
+ raise AssertionError("pending replay must not reach GitHub")
+
+ rc, replay, _ = _run_managed(
+ module, path, unavailable, delivery="1",
+ extra_args=("--branch", "feature", "--workflow", "CI", *flags),
+ )
+ assert rc == 0
+ assert replay == first_output
+
+ # A normal restart adopts the reset inventory and remains quiet on the
+ # initial state. A genuinely new CI result then reports exactly once.
+ rc, output, _ = _ci_cycle(module, path, [state], delivery="2")
+ assert rc == 124
+ assert output == ""
+ complete = _ci_state(old, _ci_run(9), comment=True)
+ rc, output, _ = _ci_cycle(module, path, [complete], delivery="2")
+ assert rc == (124 if mode == "monitor" else 0)
+ assert ("GitHub Actions success" in output) == (mode != "monitor")
+ assert "review_comment #501" not in output
+ rc, output, _ = _ci_cycle(module, path, [complete], delivery="3")
+ assert rc == 124
+ assert output == ""
+
+
+ "flags",
+ [
+ ("--since-review-id", "0"),
+ ("--since-review-comment-id", "0"),
+ ("--since-issue-comment-id", "0"),
+ ("--since-reaction-id", "0"),
+ ("--since-pr-status", "open"),
+ ("--catch-up",),
+ ],
+)
+def test_explicit_replay_with_empty_ci_baselines_quietly_then_tracks_new_observations(tmp_path, flags):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ _seed_ci_state(module, path, _ci_run(conclusion="failure"))
+ rc, output, payload = _ci_cycle(module, path, [_ci_state()], extra_args=flags)
+ assert rc == 124
+ assert output == ""
+ assert payload["actions"] == {"CI": []}
+ assert payload[module.ACTIONS_OBSERVED_KEY] == {"CI": []}
+
+ succeeded, pending = _ci_run(9), _ci_run(10, status="in_progress", conclusion=None)
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(succeeded, pending), _ci_state(succeeded)])
+ assert rc == 124
+ assert output == ""
+ # Reset is an initialization boundary, not permission to forget runs
+ # observed afterwards, including across a normal restart.
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(succeeded)])
+ assert rc == 124
+ assert output == ""
+ complete = _ci_state(succeeded, _ci_run(10))
+ rc, output, _ = _ci_cycle(module, path, [complete])
+ assert rc == 0
+ assert "GitHub Actions success" in output
+ rc, output, _ = _ci_cycle(module, path, [complete], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("inventory_present", [False, True])
[email protected]("stale_kind", ["missing-run", "higher-attempt"])
+def test_partial_manual_initialization_resets_observation_with_its_ci_baseline(
+ tmp_path, inventory_present, stale_kind,
+):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ current = _ci_run()
+ stale = _ci_run(8, conclusion="failure") if stale_kind == "missing-run" else _ci_run(attempt=9)
+ _seed_ci_state(module, path, stale, owner=None)
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ del saved["review_cursor"]
+ if inventory_present:
+ saved[module.ACTIONS_OBSERVED_KEY] = saved["actions"]
+ path.write_text(json.dumps(saved), encoding="utf-8")
+ state = _ci_state(current, comment=True)
+ stdout = io.StringIO()
+ with (
+ patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_ENV: ""}, clear=False),
+ patch.object(module, "_fetch_state", return_value=(state, 2)),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value="tester"),
+ patch.object(module.time, "monotonic", side_effect=[0, 2]),
+ patch(
+ "sys.argv",
+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--branch", "feature",
+ "--workflow", "CI", "--state-file", str(path), "--timeout", "1"],
+ ),
+ redirect_stdout(stdout),
+ patch("sys.stderr", io.StringIO()),
+ ):
+ assert module.main() == 124
+ assert stdout.getvalue() == ""
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ expected = module.normalize_selected_runs({"CI": [current]})
+ assert saved["actions"] == expected
+ assert saved[module.ACTIONS_OBSERVED_KEY] == expected
+ rc, output, _ = _ci_cycle(module, path, [state])
+ assert rc == 124
+ assert output == ""
+ complete = _ci_state(_ci_run(attempt=2), comment=True)
+ rc, output, _ = _ci_cycle(module, path, [complete])
+ assert rc == 0
+ assert "GitHub Actions success" in output
+ assert "review_comment #501" not in output
+ rc, output, _ = _ci_cycle(module, path, [complete], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("head", ["head-1", "head-2"])
+def test_explicit_seed_replaces_an_ownerless_actions_baseline_with_current_state(tmp_path, head):
+ module = _load_module()
+ path = tmp_path / "ci.json"
+ _seed_ci_state(module, path, _ci_run(conclusion="failure"), owner=None)
+ current = _ci_run(8, head=head)
+ state = _ci_state(current, head=head)
+ with (
+ patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_ENV: ""}, clear=False),
+ patch.object(module, "_fetch_state", return_value=(state, 2)),
+ 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", "--branch", "feature",
+ "--workflow", "CI", "--state-file", str(path), "--seed-state"],
+ ),
+ patch("sys.stdout", io.StringIO()),
+ patch("sys.stderr", io.StringIO()),
+ ):
+ assert module.main() == 0
+
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ expected = module.normalize_selected_runs({"CI": [current]})
+ assert saved["actions"] == expected
+ assert saved[module.ACTIONS_OBSERVED_KEY] == expected
+ rc, output, _ = _ci_cycle(module, path, [state])
+ assert rc == 124
+ assert output == ""
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(current, _ci_run(9, head=head), head=head)])
+ assert rc == 0
+ assert "GitHub Actions success" in output
+
+
[email protected]("with_ci", [False, True])
+def test_settle_preserves_detected_pr_activity_when_later_polls_omit_it(tmp_path, with_ci):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ old = _ci_run()
+ _seed_ci_state(module, path, old)
+ first = _ci_state(_ci_run(attempt=2), comment=True)
+ quiet = _ci_state(old)
+ calls = 0
+ clock = 0.0
+
+ def sleep(seconds):
+ nonlocal clock
+ clock += seconds
+
+ def fetch(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ return (first if calls == 1 else quiet), 2
+
+ ci_args = ("--branch", "feature", "--workflow", "CI") if with_ci else ()
+ with (
+ patch.object(module.time, "sleep", side_effect=sleep),
+ patch.object(module.time, "monotonic", side_effect=lambda: clock),
+ ):
+ rc, output, payload = _run_managed(
+ module, path, fetch, delivery="1",
+ extra_args=(*ci_args, "--settle", "1", "--timeout", "100"),
+ )
+ assert rc == 0
+ assert "review_comment #501" in output
+ assert "GitHub Actions" not in output
+ assert payload[module.STAGED_KEY]["output"] == output.strip()
+ if with_ci:
+ assert payload[module.STAGED_KEY]["cursors"]["actions"] == module.normalize_selected_runs({"CI": [old]})
+
+
[email protected]("during_loop", [False, True])
[email protected]("ci_mode", ["off", "stable", "complete", "withdraw"])
+def test_settled_pr_report_keeps_its_snapshot_through_ack_and_restart(tmp_path, during_loop, ci_mode):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ old = _ci_run()
+ _seed_ci_state(module, path, old)
+ first_run = {
+ "off": old,
+ "stable": old,
+ "complete": _ci_run(attempt=2, status="in_progress", conclusion=None),
+ "withdraw": _ci_run(attempt=2),
+ }[ci_mode]
+ final_run = _ci_run(attempt=2) if ci_mode == "complete" else old
+ first = _ci_state(first_run, comment=True)
+ quiet = _ci_state(final_run)
+ workflows = () if ci_mode == "off" else ("CI",)
+ states = [_ci_state(old), first, quiet] if during_loop else [first, quiet]
+
+ rc, output, payload = _ci_cycle(module, path, states, workflows=workflows, settle=1)
+ assert rc == 0
+ assert "review_comment #501" in output
+ assert ("GitHub Actions" in output) == (ci_mode == "complete")
+ staged = payload[module.STAGED_KEY]["cursors"]
+ assert staged["snapshot"]["review_comments"] == module._normalized_pr_snapshot(first)["review_comments"]
+ assert staged["review_comment_fingerprints"] == module._fingerprint_map(first["review_comments"])
+
+ def unavailable(*args, **kwargs):
+ raise AssertionError("unacknowledged output must replay without polling")
+
+ ci_args = ("--branch", "feature", "--workflow", "CI") if workflows else ()
+ rc, replay, _ = _run_managed(module, path, unavailable, delivery="1", extra_args=ci_args)
+ assert rc == 0
+ assert replay == output
+
+ restored = _ci_state(final_run, comment=True)
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", workflows=workflows)
+ assert rc == 124
+ assert output == ""
+
+ if ci_mode == "withdraw":
+ restored["actions"] = [_ci_run(attempt=2)]
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", workflows=workflows)
+ assert rc == 0
+ assert "GitHub Actions success" in output
+ assert "GitHub PR activity" not in output
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="ci-ack", workflows=workflows)
+ assert rc == 124
+ assert output == ""
+
+ restored["review_comments"][0]["body"] = "A genuine edit after acknowledgement"
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", workflows=workflows)
+ assert rc == 0
+ assert "review_comment #501" in output
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", workflows=workflows)
+ assert rc == 124
+ assert output == ""
+
+ restored["review_comments"] = []
+ restored["review_threads"] = [{"id": "thread-1", "isResolved": False}]
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", workflows=workflows)
+ assert rc == 0
+ assert "review_thread thread-1" in output
+ assert "501" not in json.loads(path.read_text())[module.STAGED_KEY]["cursors"]["snapshot"]["review_comments"]
+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="4", workflows=workflows)
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("during_loop", [False, True])
+def test_settled_pr_fallback_does_not_attribute_current_ci_to_a_transient_head(tmp_path, during_loop):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ old = _ci_run()
+ _seed_ci_state(module, path, old)
+ transient = _ci_state(_ci_run(9, head="head-2"), head="head-2", comment=True)
+ quiet = _ci_state(old)
+ states = [_ci_state(old), transient, quiet] if during_loop else [transient, quiet]
+ rc, output, payload = _ci_cycle(module, path, states, settle=1)
+ assert rc == 0
+ assert "head-2" in output
+ assert "GitHub Actions" not in output
+ staged = payload[module.STAGED_KEY]["cursors"]
+ assert payload["head_sha"] == "head-1"
+ assert staged["head_sha"] == staged["snapshot"]["pull_request"]["head_sha"] == "head-2"
+ assert staged["actions"] == {"CI": []}
+ assert staged["actions_observed"]["CI"][0]["head_sha"] == "head-1"
+ rc, output, _ = _ci_cycle(module, path, [quiet], delivery="2")
+ assert rc == 0
+ assert "head-2 -> head-1" in output
+ assert "GitHub Actions success" in output
+ rc, output, _ = _ci_cycle(module, path, [quiet], delivery="3")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("during_loop", [False, True])
+def test_settled_pr_snapshot_survives_a_failed_repoll_and_ack(tmp_path, during_loop):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ run = _ci_run()
+ _seed_ci_state(module, path, run)
+ first = _ci_state(run, comment=True)
+ failure = urllib.error.URLError("synthetic settle failure")
+ states = [_ci_state(run), first, failure] if during_loop else [first, failure]
+ clock = 0.0
+
+ def sleep(seconds):
+ nonlocal clock
+ clock += seconds
+
+ def fetch(*args, **kwargs):
+ item = states.pop(0)
+ if isinstance(item, Exception):
+ raise item
+ return item, 2
+
+ with (
+ patch.object(module.time, "monotonic", side_effect=lambda: clock),
+ patch.object(module.time, "sleep", side_effect=sleep),
+ ):
+ rc, output, payload = _run_managed(
+ module, path, fetch, delivery="1",
+ extra_args=("--workflow", "CI", "--branch", "feature", "--settle", "1", "--timeout", "100"),
+ )
+ assert rc == 0
+ assert "review_comment #501" in output
+ assert "501" in payload[module.STAGED_KEY]["cursors"]["snapshot"]["review_comments"]
+ rc, output, _ = _ci_cycle(module, path, [first], delivery="2")
+ assert rc == 124
+ assert output == ""
+
+
[email protected]("location", ["committed", "pending"])
[email protected]("key", ["actions", "actions_observed"])
[email protected]("bad_value", [
+ {"CI": [None]}, {"CI": ["invalid"]}, {"CI": [{"id": []}]},
+ {"CI": "not-a-list"}, None, [], {"CI": [{"id": 7, "run_attempt": []}]},
+])
+def test_malformed_saved_actions_fail_closed_without_overwriting_history(tmp_path, key, bad_value, location):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ _seed_ci_state(module, path, _ci_run())
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ if location == "pending":
+ saved[module.STAGED_KEY] = {
+ "delivered_after": "0",
+ "output": "an earlier report",
+ "cursors": {key: bad_value},
+ }
+ else:
+ saved[key] = bad_value
+ path.write_text(json.dumps(saved), encoding="utf-8")
+ original = path.read_bytes()
+ stderr = io.StringIO()
+ with (
+ patch.dict("os.environ", {module.WATCH_ID_ENV: "wat_9", module.LAST_DELIVERY_ENV: "1"}),
+ patch.object(module, "_fetch_state", return_value=(_ci_state(_ci_run()), 2)),
+ 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", "--workflow", "CI",
+ "--branch", "feature", "--state-file", str(path), "--timeout", "0.001",
+ ]),
+ patch("sys.stderr", stderr),
+ ):
+ assert module.run_cli() == 1
+ assert key in stderr.getvalue()
+ assert "malformed" in stderr.getvalue()
+ assert path.read_bytes() == original
+
+
[email protected]("mode", ["resume", "catch-up", "pr-replay", "seed", "fresh-manual", "pr-only"])
[email protected]("key", ["actions", "actions_observed"])
[email protected]("location", ["committed", "pending-delivered", "pending-undelivered"])
+def test_corrupt_actions_cannot_be_bypassed_by_initialization_or_pending_replay(tmp_path, mode, key, location):
+ """Resetting valid history never authorizes overwriting unreadable evidence."""
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ _seed_ci_state(module, path, _ci_run(), owner=None)
+ saved = json.loads(path.read_text(encoding="utf-8"))
+ if mode in {"seed", "fresh-manual"}:
+ saved.pop("review_cursor")
+ malformed = {"CI": [None]}
+ if location == "committed":
+ saved[key] = malformed
+ else:
+ saved[module.STAGED_KEY] = {
+ "delivered_after": "1" if location == "pending-undelivered" else "0",
+ "output": "an earlier combined report",
+ "cursors": {key: malformed},
+ }
+ path.write_text(json.dumps(saved), encoding="utf-8")
+ original = path.read_bytes()
+ flags = [] if mode == "pr-only" else ["--workflow", "CI", "--branch", "feature"]
+ flags += {
+ "resume": [],
+ "catch-up": ["--catch-up"],
+ "pr-replay": ["--since-review-comment-id", "0"],
+ "seed": ["--seed-state"],
+ "fresh-manual": [],
+ "pr-only": [],
+ }[mode]
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with (
+ patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_ENV: "1"}),
+ patch.object(module, "get_token", side_effect=AssertionError("must reject before authentication")),
+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),
+ patch("sys.argv", [
+ "wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153",
+ "--state-file", str(path), *flags,
+ ]),
+ redirect_stdout(stdout),
+ patch("sys.stderr", stderr),
+ ):
+ assert module.run_cli() == 1
+ assert "malformed" in stderr.getvalue()
+ assert key in stderr.getvalue()
+ assert stdout.getvalue() == ""
+ assert path.read_bytes() == original
+
+
[email protected]("attempt", ["missing", None])
+def test_valid_legacy_actions_and_partial_pending_remain_compatible(tmp_path, attempt):
+ module = _load_module()
+ path = tmp_path / "pr.json"
+ run = _ci_run(attempt=attempt)
+ if attempt == "missing":
+ run.pop("run_attempt")
+ _seed_ci_state(module, path, run)
+ saved = json.loads(path.read_text())
+ if attempt == "missing":
+ saved["actions"]["CI"][0].pop("run_attempt")
+ saved[module.STAGED_KEY] = {
+ "delivered_after": "0",
+ "output": "legacy partial transaction",
+ "cursors": {"review_comment_cursor": 500},
+ }
+ path.write_text(json.dumps(saved))
+ rc, output, _ = _ci_cycle(module, path, [_ci_state(run)], delivery="1")
+ assert rc == 124
+ assert output == ""
+
+
def test_a_managed_run_reports_the_event_again_when_it_was_never_delivered(tmp_path) -> None:
"""An unchanged delivery stamp means the report was never queued: replay it.