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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(watch): coalesce PR review and CI success notifications (#2663)
Call Whiteb4eb5cca1409
diff --git a/.agents/skills/pr-delivery-loop/SKILL.md b/.agents/skills/pr-delivery-loop/SKILL.mdindex 37ea7c215..d8f7d1f57 100644--- a/.agents/skills/pr-delivery-loop/SKILL.md+++ b/.agents/skills/pr-delivery-loop/SKILL.md@@ -1,6 +1,6 @@---name: pr-delivery-loop-description: Deliver implementation PRs across Avibe, avibe-backend, avibe-docs, avault, and vault-sandbox. Required for branch and scope discipline, Codex review, CI, circuit breaking, and user-facing close-out, regardless of agent backend.+description: Deliver Avibe, backend, docs, avault and vault-sandbox PRs through worktrees, Codex review, CI, circuit breaking and gated close-out. Required on every Agent backend.---# PR Delivery Loop@@ -74,8 +74,8 @@ do not load them routinely. They introduce no additional delivery gates.manual/E2E checks, dependencies, and a **Known-by-design ledger** for intentionalnon-changes. Reply to repeated intentional findings with that ledger entry.- Use one durable combined PR + CI Watch per owner/concern through- `background-watch-hook`: `wait_pr.py`, `--forever`, required `--workflow`- names, optional `--branch`, and no fixed `--sha` during a normal delivery loop.+ `background-watch-hook`'s preferred mode: `wait_pr.py`, `--forever`, required+ `--workflow` names; no fixed `--sha` during a normal delivery loop.Set `--timeout 0` on both supervisor and waiter; do not impose a lifetime cap.- Seed one complete owner-specific baseline and arm the Watch before the firstwatched push or review trigger. For a new PR, create it first, then immediately@@ -141,8 +141,8 @@ do not load them routinely. They introduce no additional delivery gates.person's pending review prevents a reply, never delete/dismiss it: preservetheir drafts, report the blocker, keep observation live, and continue safework. Retry the reply after they submit/discard it; do not hide the open thread.-- Internal round reports identify PR/head, findings addressed, and remaining- gates in one or two lines. Do not add redundant round-summary PR comments.+- Notify findings/errors promptly; keep half-success silent until CI/review+ both pass. Fix reports include PR/head; no round-summary PR comments.## 4. Complete deliverydiff --git a/docs/plans/pr-watch-coalesce-success.md b/docs/plans/pr-watch-coalesce-success.mdnew file mode 100644index 000000000..9a2ae066d--- /dev/null+++ b/docs/plans/pr-watch-coalesce-success.md@@ -0,0 +1,71 @@+# Coalesce successful PR review and CI notifications++## Change contract++The bundled combined PR/CI waiter gains an opt-in `--coalesce-success` reporting policy. The preferred PR delivery example enables it. PR-only and standalone Actions monitoring keep their existing behavior.++Observable invariants:++- A current-head CI success alone or a recognized current-head Codex clean-pass alone does not emit a report or create an Agent turn.+- Once both are present for the same head, emit one combined success candidate. Bind the candidate and notification signature to that head, the selected semantic review evidence, and the CI verdict inventory; stronger review evidence must wake the Agent even when CI is unchanged. The follow-up Agent still verifies all delivery/merge gates; the waiter does not authorize a merge.+- New CI failures report even if another requested workflow is missing or running. Review findings, Codex infrastructure errors, lifecycle/head changes, and unfamiliar review payloads remain reportable.+- Preserve successful review evidence while CI is pending, including across a restart and a problem-only report. Invalidate it on a new head, changed/deleted evidence, or new bot findings/errors.+- Never combine an old-head pass with new-head CI. A PR-body reaction is only a completion candidate when this durable observer first sees it after the unchanged head's baseline. Existing or head-transition reactions are not manufactured into head-bound passes.+- Keep the original owner-specific state file, pending transaction, at-least-once replay, and delivery acknowledgement. Reporting policy participates in cursor ownership. Existing activity-mode Watches remain unchanged; enabling a different policy requires a separately established pre-action baseline, not reseeding an armed Watch.+- Recognized SHA-bearing clean comments/reviews and newly observed Codex PR-body `+1` reactions are the supported success shapes. Unknown/ambiguous evidence is surfaced for judgment, not silently accepted as a merge gate.++## Observation and delivery invariants++Success batching must track monotonic observations, not replaceable response snapshots. The current head retains the latest ordered bot outcome, including an invalidating error/finding; a later clean verdict in the same batch supersedes an earlier error, but restoring an older row cannot supersede a newer outcome. Retain a per-resource semantic fingerprint map across omitted rows so metadata-only restoration cannot become a new verdict. Different resources with equal timestamps are unordered even within one collection: an invalidation wins a conflict, and IDs only choose deterministically among equivalent outcomes. An observed semantic edit of the exact retained resource can replace it within one timestamp tick. Keep a reaction-ID high-water mark across head changes, initialized from the durable reaction cursor. Explicit cursors and catch-up preserve their requested activity streams; success coalescing defers routine monitoring, not deliberate replay.++Advance those observations on every successful poll and settle fetch. Rendering a candidate must not commit delivery progress; the existing pending transaction still owns acknowledgement. The latest head and last authenticated thread map persist independently across process boundaries; notification adoption cannot overwrite them. Bind new reactions to that observed head, not an older notification snapshot. Actual observed head transitions reset epoch evidence, but retaining a B event must not erase a fresh A verdict observed after returning to a stable A. The existing CI/report guard still prevents attaching A's CI verdict to B's event.++Fail-fast CI may tolerate missing inventory, never an older run attempt. Preserve a known terminal observation against same-attempt nonterminal regression and merge acknowledged partial failure inventories instead of replacing previously notified run IDs. Render observed unacknowledged failures even when a later raw page omits them; an emitted failure bypasses settle. These observation changes are scoped to coalescing; activity mode retains its released behavior. Preserve the existing complete-inventory requirement for a success candidate.++Malformed batching state fails only the affected waiter, with the original evidence intact and the supervisor's existing error notification. It is deferred delivery/notification history, not disposable optional-feature configuration. Clearing it can lose the only review evidence or notification watermark. This does not affect Avibe service startup; see the same distinction for Actions history in `docs/plans/watch-actions-dedup.md`.++## Circuit-breaker scope decision++The second reviewed head exposed the same observation-retention class at additional boundaries, so further blind patches were stopped. The orchestrator fetched the full GitHub inventory and obtained the independent reviewer's complete bounded inventory before authorizing one shared classifier repair: the narrow problem-text regex was not a safe negative test for either progress summaries or clean verdicts. Progress now requires the complete known summary envelope, including the exact standard footer and every expected review row, and clean verdicts require their complete two-line shape with agreeing reviewed SHAs; arbitrary trailing text, malformed rows, cross-stream ties within and across polls, and contradictory evidence remain reportable. No service, API, persistence migration, merge-policy, or external-operations scope was added. The latest-head observation and older delivered PR snapshot are intentionally separate owners; forcing their heads equal was a local workaround that erased valid new evidence.++The `832b09593` recurrence was inventoried across all nine findings-bearing reviewed heads and all 15 threads before changing the outcome producer. The remaining replay defect conflated scanning existing rows with observing a new semantic verdict: `initialize=True` bypassed retained per-resource fingerprints, so a metadata-only timestamp refresh could restore an old pass over a newer invalidation. Initialization may adopt unseen rows, but a same-head replay must use the same semantic-change rule as ordinary polling. Scope is the shared initializer and the existing replay regression matrix (comment/review, catch-up/cursor, unchanged/refreshed metadata), including genuine new-verdict recovery; no new state, classifier heuristic, prompt text, or live-Watch mutation is needed.++The `b44e519d7` inventory covers ten findings-bearing heads and all 16 threads; only the new same-stream edit-tie finding remains open. Creation IDs cannot order mutable updates, so limiting conservative ties to different collections was the wrong boundary. Apply the same timestamp/conflict rule in same-poll selection and persisted-outcome adoption, regardless of collection or resource ID. Preserve same-resource semantic replacement and fresh clean-to-clean evidence at an equal timestamp; do not make every tie permanently invalidating. The existing tie tests are consolidated into one same/cross-stream arrival-order matrix, with recovery controls, plus an equal-timestamp stronger-evidence case. No schema, new owner, regex, or prompt expansion is required.++The independent review also verified the real summary from comment `6186377372`: its inline `Reviews are triggered when you` preamble differs from the older split `Codex reviews are triggered when you` footer. Accept both complete known footer forms, keeping arbitrary footer content reportable and leaving trigger policy unchanged. The existing progress/error matrix now covers both forms; the two live-form progress cases failed before this compatibility fix, while the 12 controls passed.++## Validation evidence++- With only the new parser flag present, both arrival-order regressions failed because the unchanged waiter emitted a single success (`rc=0` instead of the expected quiet wait).+- The focused PR waiter, Actions waiter, repository guidance, and Harness Skill guidance suite passes after the complete observation-history repair: **386 tests**. The latest regressions cover both deliberate replay modes retaining a newer invalidating outcome, unmarked finding text in progress summaries, the live Codex state-summary footer, unknown footer content and rows, unmarked finding text appended to a SHA-bearing clean pass, cross-stream timestamp ties within and across polls, contradictory reviewed SHAs, and metadata-only restoration during both explicit replay modes. Four new replay cases failed on `832b09593` because they emitted a false success candidate; their unchanged-metadata controls passed. Four ordering cases also failed on `b44e519d7`: three same-stream arrival orders emitted false success, and an equal-timestamp SHA verdict failed to refresh reaction-only evidence. The related CLI Watch tests also passed in the earlier combined run; that run's only failure was the newly added documentation-command extractor, corrected and revalidated by the focused suite.+- Changed-file Ruff, `git diff --check`, and `askill validate skills/background-watch-hook/SKILL.md` pass.+- The normal Codex summary table shape was checked against a live read-only PR response. Its normal Running/Completed updates, including the standard About Codex details footer, are quiet; finding text outside that known shape and failure/unrecognized statuses remain visible.+- First-head independent review found ordered-outcome, reaction-epoch, settle, replay, and partial-CI-history regressions. Fourteen focused cases were run against the original `3c88ae3d1` waiter and failed for those intended behavioral reasons, including metadata-only invalidation. They now exercise the monotonic-observation contract rather than a collection of special-case retries.+- GitHub first-head findings on exact summary statuses and seeded stale passes are covered by suffix-status and initialization ordering regressions. The malformed-history suggestion is intentionally not adopted for the delivery-state reason above.+- The second-head full inventory was reproduced before the bounded repair: missing/terminal-regressed CI failures, fresh late-head reaction retention, mixed summary findings, semantic restoration with newer metadata, and three unauthenticated startup/replay variants. All repaired paths retain the existing at-least-once delivery owner and have positive recovery controls.+- Independent read-only re-review, current-head GitHub Codex review, and required CI remain delivery gates, not waived by these local results.++## Prompt surface++The routine Watch Skill entry is 100 lines, down from 602 in the initial proposal and 560 on the base branch. Detailed examples and cursor mechanics live in an optional reference that is not rendered with the entry. The PR delivery Skill replaces existing observation/report clauses rather than adding a section and is shorter than its base. This task's recurring Watch message was reduced from 727 to 160 characters without changing its command, routing, lifecycle, or cursor.++## Known by design++- Activity mode is the compatibility default; the preferred delivery example explicitly enables coalescing on both the seed and waiter. This is not an in-place migration of an already armed Watch's reporting identity.+- The combined success is a candidate, not merge permission. The Agent still checks exact-head review qualification (especially reaction epochs), all required CI, and all unresolved threads.+- Head, lifecycle, thread, human-request, and unknown-result activity can still wake the Agent; the notification reduction is deliberately limited to recognized green/progress payloads.+- Error payloads use the existing bounded rendering and link back to the full GitHub object, which the follow-up fetches.+- No existing Watch was replaced, no service was restarted, and no installed built-in Skill snapshot was upgraded.+- Fail-closed notification-history corruption is intentional; it stops the affected waiter and sends the existing terminal failure notice, not Avibe startup. Do not silently discard deferred evidence or an undelivered transaction.++## Owning boundaries and scope++Implementation belongs in `skills/background-watch-hook/scripts/wait_pr.py` and its existing shared Actions renderer. Document the option and bump the Skill minor version. Do not change the Watch supervisor, service configuration, polling/retry budgets, merge policy, or unrelated live Watches. No service restart, deployment, automatic merge, or registry publication is part of this change.++## Validation contract++The existing managed-cycle harness provides synthetic GitHub snapshots, a virtual clock, and test-owned files. Extend it rather than introducing a second framework. Existing tests intentionally report each success independently and do not cover this new policy.++Add owner-boundary regressions for both arrival orders; quiet half-success across restart; paired notification plus undelivered replay and acknowledged deduplication; SHA/comment/review/reaction shapes; stale or ambiguous evidence; immediate partial-CI failure; bot findings/infrastructure failure before the other gate; evidence revocation; and head changes. A pre-implementation run with only the parser flag present must fail because it reports a single success, not because the option is missing.++Run focused PR/Actions waiter tests, related repository guidance and Watch tests, changed-file Ruff, and Skill validation. Obtain exact-head GitHub Codex review, complete required CI, and zero unresolved threads before close-out. A source PR does not upgrade the user's installed Skill snapshot; existing live monitoring remains on its configured package until an authorized rollout.diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdindex 71beebd96..e159b9bc0 100644--- a/skills/background-watch-hook/SKILL.md+++ b/skills/background-watch-hook/SKILL.md@@ -1,560 +1,100 @@---name: background-watch-hookslug: 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.4+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.0---# Background Watch Hook-Use this skill when the job is "wait now, continue later in the same conversation".+Use `vibe watch` for a durable wait that resumes an Agent when an external event+arrives. The waiter detects events; the follow-up Agent verifies live state and+acts. A success candidate is not merge authorization.-What it gives the agent:+## Contract and lifecycle-- a managed background task instead of manual polling-- a clean way to come back to the same channel or thread later-- a reusable pattern that works for reviews, CI, files, logs, and process completion+| Waiter exit | Meaning |+| --- | --- |+| `0` | One **new** reportable event; summary on stdout |+| `75` (or configured retry code) | Still waiting; no Agent turn |+| `64` plus `avibe-watch: no-event` on stderr | Quiet completed cycle: retire once, re-arm forever |+| `124` or other terminal failure | Notify the Agent and stop |-Good trigger scenarios:+A bare `64` is an error. Keep diagnostics on stderr. A once Watch waiting for its+first event uses a retry code, not `64`. Forever waiters need durable cursors or+edge detection; a persistent true condition is not a new event. Avibe serializes+follow-ups, re-arms after they settle, and pauses rapid repeated events for repair.-- PR reviews or comments may arrive later-- CI, deployments, or exports need time to finish-- a file, log line, or process exit should wake the agent up later+- Read `vibe watch add --help` before first use; inspect/update with+ `vibe watch <list|show|update|pause|resume|remove>`.+- `--timeout` bounds each cycle (default six hours); `--lifetime-timeout` bounds+ the whole Watch. Use `0` for an intentionally unbounded PR delivery loop.+- Remove the Watch at close-out. Do not use detached shells for durable waits.-Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or removable later.--## Main Tools--- `vibe watch add`- Main entrypoint. Starts a managed background watch and creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure.-- `vibe watch list`, `vibe watch show`, `vibe watch update`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`- Use these to inspect and manage the watch after creation.-- `scripts/wait_pr.py`- Bundled GitHub waiter for PR activity, with optional exact-head Actions monitoring.--## Use `vibe watch` First--Use `vibe watch add` first. Most tasks only need:--1. a short action-oriented message-2. a blocking waiter command--Generic shape:--```bash-vibe watch add \- --message "<what the next Agent Run should do>" \- --name "<optional label>" \- -- \- <waiter command ...>-```--Default behavior:--- returns immediately-- keeps the waiter managed by Avibe-- lets the agent inspect or stop the watch later-- creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure--Use `--forever` when the same waiter should re-arm after each detected event instead of exiting after one follow-up.--## `vibe watch` Parameters To Remember--- `--message`: the instruction template for the follow-up Agent Run created from waiter output-- `--name`: optional label for later management-- `--session-id`: only when the follow-up should continue a different explicit Agent Session-- `--create-session --same-scope`: create a visible sibling Session for the follow-up instead of continuing this conversation-- `--create-session --scope-id <scopes.id>`: create the follow-up Session in a specific existing scope-- `--forever`: re-arm after each detected event-- `--timeout`: per-cycle timeout-- `--lifetime-timeout`: whole-watch lifetime cap, mainly for forever watches--Management commands:--- `vibe watch list`-- `vibe watch show <watch-id>`-- `vibe watch update <watch-id> --name '...'`-- `vibe watch pause <watch-id>`-- `vibe watch resume <watch-id>`-- `vibe watch remove <watch-id>` hides the watch while keeping prior run history--## Waiter Contract--Write waiters to follow this contract:--- `exit 0`: event detected; final summary printed to `stdout`-- `exit 64` **plus the line `avibe-watch: no-event` on `stderr`**: cycle completed with nothing worth reporting; **no follow-up Agent Run**, the watch ends (`once`) or re-arms (`--forever`)-- `exit 124`: timeout; still send a timeout follow-up-- other non-zero: failure; the watch stops and sends a failure follow-up--Exit 64 is the token-saving path. Every other terminal exit costs one Agent turn,-so a waiter whose normal outcome is uninteresting — green CI, review chatter that-was filtered out — should end on 64 rather than reporting "nothing to do". It is a-clean ending, so a `once` watch that retires on 64 reads as completed rather than-failed, and whatever the waiter wrote to `stderr` is logged beside the watch id.--The marker is not optional. 64 is also BSD `sysexits` EX_USAGE, so a watched command-that rejects its own arguments exits with it — and it must keep failing loudly rather-than being read as a quiet cycle and, in `--forever`, rerun indefinitely. A bare 64-is therefore treated as a failure; only 64 with the marker is a no-event cycle. In-the bundled waiters, `_github_wait_common.no_event("<summary>")` prints the summary-and the marker to `stderr` and returns the code, so `return no_event(...)` is the-only place the contract has to be spelled out.--Keep the output split clean:--- `stdout`: final summary for the next turn-- `stderr`: polling logs and diagnostics--## Generic Examples--Delay:--```bash-vibe watch add \- --name "Delay follow-up" \- --message "The delayed check completed. Continue from the result below." \- -- \- bash -lc 'sleep 120; echo "Timer finished after 120 seconds."'-```--File appears:--```bash-vibe watch add \- --name "Wait for export file" \- --message "The export file is ready. Inspect it and continue." \- -- \- bash -lc 'while [ ! -f /tmp/export.json ]; do sleep 10; done; echo "Detected /tmp/export.json"'-```--Log match:--```bash-vibe watch add \- --name "Watch app log" \- --message "The expected log pattern appeared. Inspect the event and continue." \- --forever \- -- \- bash -lc 'tail -Fn0 /tmp/app.log | while read -r line; do case "$line" in *READY*) echo "$line"; break;; esac; done'-```--## Session Targeting--Use the current Avibe context:+## Session targeting- Inside an Avibe-injected Agent shell, omitting the target continues this conversation.-- Use `--session-id <id>` only when the follow-up should continue a different existing Agent Session.-- Use `--create-session --same-scope` when follow-ups should run in one visible sibling Session under the same Workbench project or IM scope.-- For `--forever` watches that need a separate visible Session for each event, use `--create-session-per-run --same-scope`.-- Use `--create-session --scope-id <scopes.id>` when follow-ups should run in one Session under a specific existing scope.-- For separate visible Sessions in a specific existing scope, use `--create-session-per-run --scope-id <scopes.id>`.-- If `--cwd` is omitted while creating a Session, Avibe uses the command's current working directory.--## Timeout And Lifecycle--For `vibe watch add`:--- `--timeout` is the waiter timeout for one cycle-- default is `21600` seconds-- `0` means no per-cycle timeout-- `--forever` means re-arm after each detected event-- an allowed `--retry-exit-code` keeps either mode waiting; a once Watch stops after its first event-- `--lifetime-timeout` limits the whole long-running watch; default is `0` meaning run until killed--This separation matters: a once Watch may now have several retry cycles, and a forever-Watch can still use a bounded timeout for each cycle.--Exit `0` means one new reportable event, never merely that a condition remains true.-For a persistent level, return an allowed retry code (default `75`) until a new edge is-observed. Exit `64` plus `avibe-watch: no-event` on stderr is a completed cycle with-nothing worth reporting. A forever waiter must keep a durable cursor, state transition,-or domain cooldown so it cannot emit the same level repeatedly.--Avibe admits only one queued/running follow-up per Watch. A forever Watch re-arms after-that Agent Run settles and a five-second safety delay. If the waiter still produces six-successful events within 60 seconds, Avibe pauses the Watch and sends the target Agent-one repair message containing the bounded latest waiter output. The Agent should inspect-and fix the waiter, and resume only after verifying an unambiguous, reversible fix.--## Bundled Waiter Example--This skill ships bundled GitHub waiters:--- `scripts/wait_pr.py`- Waits for GitHub PR review activity, including reviews, inline review comments, PR conversation comments, PR status transitions such as `draft -> open`, `open -> merged`, or `open -> closed`, and the special Codex `+1` reaction on the PR body. It can also wait for newly opened PRs in a repository.- When one or more `--workflow` values are provided for a specific PR, the same- waiter also watches every matching Actions run at the PR's current head and- optional branch. Add `--sha` only to pin a one-shot wait to one exact head.-- `scripts/wait_issue.py`- Waits for GitHub issue activity, either newly opened issues in a repository or new comments on a single issue.-- `scripts/wait_action.py`- Waits for selected GitHub Actions workflow runs on a specific commit SHA to finish- when there is no PR activity stream to combine with them. Workflow failures are- reported as an event so the follow-up turn can inspect and handle them.--Use bundled waiters as examples or as ready-to-run building blocks. The main skill is still `vibe watch`; the waiter is only the thing that blocks until the condition is met.-When running a bundled script through `uv`, prefer `uv run --no-project ...` so the script does not accidentally attach itself to an unrelated parent project.-Bundled GitHub waiters classify temporary network failures and GitHub-`408/429/5xx` responses as retryable. The one-shot PR and Actions waiters retry-those failures inside the same process so the managed watch stays alive. A-cycle-oriented waiter may use exit code `75` only when its supervisor explicitly-opts into retrying that code. Exit code `64` with the-`avibe-watch: no-event` marker means a cycle finished with nothing worth an Agent-turn.--**A waiter detects change; the follow-up Agent Run makes the decision.** Keep that-split when writing your own. A waiter that fires only once a composite gate is-satisfied — CI green *and* a verdict bound to the exact head *and* zero unresolved-threads — must match the shape of every signal in that gate, and it can only match-the shapes its author has already seen. A wrong predicate then produces silence,-which is indistinguishable from "nothing has happened yet", so it can sit on a retry-exit code for hours after the state it was armed for arrived. The bundled waiters-avoid that by reporting the change and leaving the judgment to the turn that has the-whole picture. One caveat on the CI half: `render_actions_result` reports nothing-while a requested workflow is missing, so a `--workflow` value that never matches —-renamed, misspelled, or never triggered on this branch — never yields a CI event. PR-activity still comes through, so the watch keeps firing; it is the CI verdict that-silently never arrives. Check the name against a head that actually ran it.--A predicate never seen to fire has not been tested. Verify it the way the delivery-loop below is armed — seed the baseline, produce one event, confirm exit `0` — not by-starting it on an event that already exists: an edge-triggered waiter is supposed to-adopt that as its baseline, and one that fires there is level-triggered and will-re-report forever. `--catch-up` is the bundled waiters' explicit replay mode for-deliberately processing history.--Run bundled waiters relative to the directory containing this loaded `SKILL.md`.-The examples below use `BACKGROUND_WATCH_HOOK_DIR` for that directory:+- Use `--session-id <id>` only when resuming a different existing Agent Session.+- Use `--create-session --same-scope` for one visible sibling Session; use+ `--create-session-per-run --same-scope` for a separate visible Session per event.+- Use `--scope-id <scopes.id>` instead of `--same-scope` for an explicit scope.+- If `--cwd` is omitted, Avibe uses the command's current working directory.++## Preferred PR + CI watch++Use `--forever` and one owner-specific state file for the whole loop. Seed and+arm before the watched push/review trigger; for a new PR, create it first, then+immediately seed/arm. Keep the same Watch and cursor across all later rounds.++- `wait_pr.py --workflow <actual-name>` combines PR activity with exact-head CI;+ repeat `--workflow` for every required workflow. Omit `--sha` to follow pushes.+- `--coalesce-success`: keep half-success quiet; report one same-head CI/review+ success candidate. Findings, errors and unfamiliar results remain reportable.+- `--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.+- 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+ part of cursor ownership; enable them on the initial seed and armed command.+- Cursor corruption, ownership conflicts or write failures require repair with+ evidence preserved, not a fresh baseline. Retryable GitHub failures keep waiting.++Run scripts from the loaded Skill directory, not a guessed installation path:```bashBACKGROUND_WATCH_HOOK_DIR="<directory containing the loaded SKILL.md>"-```--## GitHub Example Waiter--For a PR delivery loop, prefer one durable combined `wait_pr.py` watch. It observes-PR review, comment, reaction, thread, lifecycle, and head-change events together-with selected Actions workflows for the PR's current head. Use `--forever` and one-state file for the whole loop: when a push changes the head, the next cycle fetches-Actions for the new exact SHA without replacing the Watch or rebuilding its PR-baseline. Use `wait_pr.py` without CI arguments for PR-only monitoring. Use-`wait_action.py` only for an Actions wait that is not attached to a PR.--### Preferred PR + CI watch--At least one repeatable `--workflow` enables combined CI monitoring. Omit `--sha`-for the normal delivery loop: each cycle resolves the PR's current head and queries-Actions for that exact SHA. `--branch`, `--max-pages`, and `--success-conclusion`-remain optional. Add `--sha` only when the caller intentionally wants a fixed-head-one-shot wait. The waiter stays quiet while a requested run is missing or still-running, then reports the complete exact-head result when every requested workflow-has terminal runs. Every distinct matching run ID is included, so an earlier failed-rerun remains visible to the follow-up turn. Set the forever Watch's `--timeout 0`:-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.--```bashSTATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"BRANCH="$(gh pr view 151 --repo avibe-bot/avibe --json headRefName --jq .headRefName)"uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe --pr 151 \- --branch "$BRANCH" \- --workflow lint \- --actionable-only \+ --repo avibe-bot/avibe --pr 151 --branch "$BRANCH" \+ --workflow lint --coalesce-success --actionable-only \--state-file "$STATE_FILE" --seed-statevibe watch add \- --name "Watch PR 151 review and CI" \- --forever \- --timeout 0 \- --message "PR #151 has new review activity, a head change, or current-head CI activity. Fetch the latest PR and Actions state, resolve actionable findings, and leave this durable combined Watch armed until close-out. Summarise the round here in one or two lines; do not post that summary as a PR comment." \+ --name "Watch PR 151 review and CI" --forever --timeout 0 \+ --message "PR #151 has an event. Follow pr-delivery-loop; verify live gates, handle findings/errors, and keep half-success silent." \-- \uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe --pr 151 \- --branch "$BRANCH" \- --workflow lint \- --actionable-only --settle 20 --state-file "$STATE_FILE" --interval 60 \- --timeout 0--# After the seeded Watch is confirmed live, push or post the review trigger.-# Keep this same state file and Watch for every later head and review round.+ --repo avibe-bot/avibe --pr 151 --branch "$BRANCH" \+ --workflow lint --coalesce-success --actionable-only \+ --settle 20 --state-file "$STATE_FILE" --interval 60 --timeout 0```-Do not combine `--new-prs` with CI arguments. A new PR has no stable exact-head-gate until the follow-up turn resolves its head and workflow set.--One-shot watch:--```bash-STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"-uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state--# Push or post the review trigger only after the baseline is durable.-vibe watch add \- --name "Watch PR 151 reviews" \- --message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \- -- \- uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe \- --pr 151 \- --actionable-only \- --settle 20 \- --state-file "$STATE_FILE" \- --interval 60-```--Before the first watched push or review trigger in the delivery loop, seed an-owner-specific state file from the current complete PR snapshot. Arm the forever-Watch with that exact file and confirm it is live before taking the watched action.-Set `--timeout 0` on both sides of the `--` command separator: the first disables-the Watch supervisor's per-cycle deadline, while the second disables the bundled-waiter's own default six-hour deadline. GitHub request timeouts remain bounded inside-the waiter. A nonzero timeout at either layer is for a Watch whose lack of an event-by that deadline is itself reportable.-After the Watch starts, never reseed or replace its state between rounds: a later-event may already exist, and turning it into the new baseline silently drops it.-The forever Watch promotes each delivered batch and compares the next cycle against-that durable pre-event snapshot, including activity that landed while the Agent-follow-up was running.--Use `--catch-up` only when deliberately processing historical activity. It is-not a substitute for the pre-action baseline in a review loop.--Prefer `--actionable-only` for review loops. Without it the waiter wakes the Agent-for every comment on the PR, including the `@codex review` triggers the loop itself-posts and the bodyless `COMMENTED` review envelope GitHub wraps around inline-comments. With it the waiter still reports inline review comments, reviews carrying-a verdict or a body, the Codex pass reaction, and merged/closed transitions — which-is everything the review loop needs to make progress or close out.--Narrow it further with `--ignore-author <login>` and `--ignore-comment-pattern <regex>`-(both repeatable). Filtered items still advance the cursors, so they are examined-once and never re-reported. These filters suppress review/comment payloads, not-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.--`--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-event. With `--settle` the waiter re-polls until the set stops growing (at most three-extra polls) and reports the whole batch as one event, which is one Agent turn-instead of several. 20 seconds is a reasonable starting point. The window never runs-past `--timeout`: settling is skipped unless both the wait and a full re-poll fit in-what is left of the deadline, so a batch already worth a turn is reported rather than-lost to the timeout kill. Keep `--settle` well under `--timeout`.--Catch up on existing activity first:--```bash-STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-catch-up.json"-vibe watch add \- --name "Catch up PR 151 reviews" \- --message "PR #151 already has review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \- -- \- uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe \- --pr 151 \- --state-file "$STATE_FILE" \- --catch-up-```--Stay armed for future activity:--```bash-STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-forever.json"-uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state--vibe watch add \- --name "Monitor PR 151 reviews" \- --forever \- --timeout 0 \- --lifetime-timeout 0 \- --message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \- -- \- uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe \- --pr 151 \- --actionable-only \- --settle 20 \- --state-file "$STATE_FILE" \- --interval 60 \- --timeout 0-```--Always pass `--state-file` to a `--forever` watch. Each cycle is a fresh waiter-process, so without it the next cycle re-snapshots the PR as its baseline and-anything that arrived between the previous cycle's exit and that snapshot is lost.-The file carries the resolved GitHub login and the complete mutable PR baseline-forward. PR cycles reread complete review/comment/thread collections because-edits, deletions, and thread-resolution changes are wake-worthy state.-For an ordinary wait, that normalized complete snapshot is the single wake/no-wake-decision. Numeric cursors, fingerprints, and the thread map only describe a detected-change; they cannot wake independently. `--catch-up` and explicit `--since-*-id`-flags are the deliberate replay modes and therefore remain cursor-driven. A legacy-state file with cursors but no complete snapshot is rejected until it is deliberately-caught up or reseeded, rather than silently absorbing mutable changes.-The login is reused only while the token still fingerprints to the account it was-resolved for. Explicit cursor flags still request a replay from that cursor, while-the complete PR collections remain the source of truth for edits and removals. The-state also records the last observed PR head, review/comment fingerprints, and every-review-thread resolution state, so a pushed head, edited object, deletion, or thread-transition is activity even when no new numeric ID exists. Cursors that cover a reported event are not committed by the-cycle that reports it. A waiter cannot observe its own delivery — `vibe watch` reads-its stdout only after the process exits — so those cursors are staged under `pending`-while the committed ones stay before the event, together with the rendered report-and the value of-`AVIBE_WATCH_LAST_DELIVERY` the cycle started from. That variable is when this watch-last had a report durably queued, stamped in the same transaction as the follow-up, so-any later cycle that reads a *different* value knows the report was delivered and-promotes the staged cursors. An unchanged value means it may never have been queued,-so they are dropped and the event is reported again: at-least-once, costing one-repeated Agent turn instead of losing the activity for good. Comparing a durable stamp-rather than consuming a one-shot acknowledgement is what makes this correct across a-service restart, and for a `once` watch, whose one report is followed by no cycle at-all until the user resumes it. A manual run has no supervisor, and there printing *is*-the delivery, so it commits straight after reporting. Progress made by filtering — new-activity that was deliberately not reported — commits immediately either way, since-there is no delivery to wait for. Three failures are terminal rather than a warning —-a path that cannot be written to (checked before the first poll), a path already owned-by another watch, and an existing file whose cursors cannot be read — and each stops-the watch with exit `1` rather than polling on without the cursors it was asked to-keep, or clobbering another watch's. A corrupt or unrecognised state file is left-exactly as found: re-baselining from the current PR would skip everything that-arrived after the cursor it did hold and then overwrite the only evidence of how far-the watch had got. An empty file is the one exception, since it is a claim caught-between its exclusive create and its first write and never held a cursor at all.--Ownership is claimed, not assumed. A missing state file is created before the first-poll holding nothing but the identity it belongs to, so two watches started together-cannot both see an unowned path; the one that loses that exclusive create reads the-winner's claim and stops. Ownership is re-checked before every replacement as well,-because the loser of a microsecond-wide race has already passed the startup check.-Identity is the repo, the PR, and the options that decide what the watch reports-(`--actionable-only`, `--ignore-author`, `--ignore-comment-pattern`,-`--include-self-comments`, `--new-prs`) — two watches on the same PR that report-different things cannot share cursors either, because the filtered one advances past-events the other never reported. Pacing options such as `--interval` and `--settle`-are not part of it. When `vibe watch` runs the cycle it also names the watch in-`AVIBE_WATCH_ID`, and the waiter records it as the owner, so even two watches-configured identically down to the last filter are kept apart; a manual run has no-id and adopts whatever it finds -- and a managed watch that starts on a file with no-owner, from a manual run or an older version, stamps itself on it before polling,-because an owner that is absent fits every watch and two of them would share the-path. That decision is read-then-write, so it is taken under a `<state-file>.lock`-sidecar; the lock lives beside the state file rather than on it, since the state file-is replaced rather than rewritten. Give each watch its own state file.--Arguments are validated before any of this: a rejected `--ignore-comment-pattern` or-a missing token exits `2` without claiming the path, so the corrected re-run is not-refused as a different watch's state.--GitHub-specific notes:--- `--catch-up` reports activity that already exists at startup, and overrides saved- cursors when a state file is present; an explicit `--since-*-id` still wins-- without `--catch-up` or a `--state-file`, the waiter snapshots current PR activity as the baseline-- polling is cheap by design: mutable review/comment collections are fetched in full- so edits and deletions remain observable, reactions are filtered server-side with- `content=+1`, and unchanged pages revalidate to `304`, which GitHub does not charge- against the rate limit — an idle watch can poll for hours for free-- a Codex verdict arrives in more than one shape and the waiter reports all of them:- findings as a review with inline comments, and a pass as either a `+1` reaction on- the PR body or a PR conversation comment. Pass reactions remain visible even when- `--event-limit` is reached. A predicate keyed to reviews alone never sees a pass.- Whether a reported pass *counts* — bot author, pass phrase, reviewed SHA against the- current head, and the different qualification a bodyless reaction carries — is a- judgment the follow-up turn makes against this repo's review rules, and is not- something a waiter should encode-- PR activity also includes lifecycle changes on the PR itself, for example draft/ready, closed, reopened, or merged transitions-- a changed PR head is reported as activity so a new push cannot leave the review- loop asleep-- 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-STATE_FILE="$HOME/.avibe/state/watch-cursors/new-prs-avibe.json"-uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe --new-prs --state-file "$STATE_FILE" --seed-state--vibe watch add \- --name "Watch new PRs" \- --message "The repository has new pull requests. Review the new PRs and continue as needed." \- -- \- uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \- --repo avibe-bot/avibe \- --new-prs \- --state-file "$STATE_FILE" \- --interval 60-```--New issues or issue comments:--```bash-uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --new-issues --interval 60-uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --issue 157 --interval 60-```--Standalone GitHub Actions for a pushed commit that is not being monitored through a PR:--```bash-vibe watch add \- --name "Watch CI" \- --message "GitHub Actions failed. Inspect the result below and fix the failures. Then summarise the round here in one or two lines -- what failed and what you changed. Save a longer message for the build going green, the loop being blocked, or a decision that needs the user." \- -- \- uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_action.py" \- --repo cyhhao/sub2api \- --branch main \- --sha "$HEAD_SHA" \- --workflow CI \- --workflow "Security Scan" \- --interval 60-```+After confirming the seeded Watch is live, push or trigger review. Check exactly+one live Watch per owner/PR/concern at each round's end. The state file stages+reports until delivery acknowledgement, so an undelivered report may replay;+never discard it merely to avoid a duplicate.-For a merge gate, omit `--only-on-failure`: a successful exact-head build must-wake the Agent so it can perform the final gate and close out the watch. Use-`--only-on-failure` only when a green result intentionally needs no follow-up;-that mode exits `64` with the no-event marker and records the summary in the-Avibe watch log instead of creating an Agent turn.+## Other waits and troubleshooting-## Practical Advice+Use `wait_pr.py` without CI arguments for PR-only activity; use `wait_action.py`+for standalone Actions and `wait_issue.py` for issues. Do not combine `--new-prs`+with CI options. `--catch-up` and explicit cursors deliberately replay history,+not routine re-arming. Keep Watch messages short and action-oriented; reference+loaded policy rather than restating it on every fire.-- Keep messages action-oriented. Tell the next turn what to do with the waiter result.-- In a fix loop, have every round report itself in one or two lines. The user is- watching a loop they cannot see inside: with no per-round summary all they get is a- stream of tool activity, and no way to tell a converging PR from one that is- thrashing on the same finding. Name the findings resolved and what changed, not a- diff walkthrough — the detail is already in the commit and on the PR. Keep it in the- conversation only; re-posting the same summary as a PR comment adds noise to the- review the bot is reading. Save a longer, user-facing message for the outcomes a- human has to act on: the review passed, the loop is blocked, or a decision has to be- made. A reply containing only a `<silent>...</silent>` block sends nothing at all, so- keep that for cycles that genuinely produced nothing worth reading — a re-poll that- found no new findings — not for the rounds that did the work.-- If this is the first time using `vibe watch add`, read `vibe watch add --help` first; the help text explains both argument syntax and runtime behavior such as how `--message` and waiter stdout become the follow-up Agent Run input.-- Prefer `vibe watch` over ad-hoc detached shells when the wait should survive the current turn cleanly.-- Treat GitHub as just one example waiter, not the main point of the skill.-- If a watch is no longer useful, remove it instead of leaving stale background work behind.+[Detailed waiter reference](references/waiters.md) covers alternative commands,+filters, replay, authentication, and cursor/settle internals. Read it only for+those tasks or a concrete failure, not for routine PR monitoring.diff --git a/skills/background-watch-hook/references/waiters.md b/skills/background-watch-hook/references/waiters.mdnew file mode 100644index 000000000..054e2d218--- /dev/null+++ b/skills/background-watch-hook/references/waiters.md@@ -0,0 +1,602 @@+# Watch Operations and GitHub Waiter Reference++Optional command variants and implementation details for `background-watch-hook`.+Do not load this reference for routine PR monitoring; the Skill entry contains the+normal workflow. Script paths below are relative to the Skill root.++Use this skill when the job is "wait now, continue later in the same conversation".++What it gives the agent:++- a managed background task instead of manual polling+- a clean way to come back to the same channel or thread later+- a reusable pattern that works for reviews, CI, files, logs, and process completion++Good trigger scenarios:++- PR reviews or comments may arrive later+- CI, deployments, or exports need time to finish+- a file, log line, or process exit should wake the agent up later++Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or removable later.++## Main Tools++- `vibe watch add`+ Main entrypoint. Starts a managed background watch and creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure.+- `vibe watch list`, `vibe watch show`, `vibe watch update`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`+ Use these to inspect and manage the watch after creation.+- `scripts/wait_pr.py`+ Bundled GitHub waiter for PR activity, with optional exact-head Actions monitoring.++## Use `vibe watch` First++Use `vibe watch add` first. Most tasks only need:++1. a short action-oriented message+2. a blocking waiter command++Generic shape:++```bash+vibe watch add \+ --message "<what the next Agent Run should do>" \+ --name "<optional label>" \+ -- \+ <waiter command ...>+```++Default behavior:++- returns immediately+- keeps the waiter managed by Avibe+- lets the agent inspect or stop the watch later+- creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure++Use `--forever` when the same waiter should re-arm after each detected event instead of exiting after one follow-up.++## `vibe watch` Parameters To Remember++- `--message`: the instruction template for the follow-up Agent Run created from waiter output+- `--name`: optional label for later management+- `--session-id`: only when the follow-up should continue a different explicit Agent Session+- `--create-session --same-scope`: create a visible sibling Session for the follow-up instead of continuing this conversation+- `--create-session --scope-id <scopes.id>`: create the follow-up Session in a specific existing scope+- `--forever`: re-arm after each detected event+- `--timeout`: per-cycle timeout+- `--lifetime-timeout`: whole-watch lifetime cap, mainly for forever watches++Management commands:++- `vibe watch list`+- `vibe watch show <watch-id>`+- `vibe watch update <watch-id> --name '...'`+- `vibe watch pause <watch-id>`+- `vibe watch resume <watch-id>`+- `vibe watch remove <watch-id>` hides the watch while keeping prior run history++## Waiter Contract++Write waiters to follow this contract:++- `exit 0`: event detected; final summary printed to `stdout`+- `exit 64` **plus the line `avibe-watch: no-event` on `stderr`**: cycle completed with nothing worth reporting; **no follow-up Agent Run**, the watch ends (`once`) or re-arms (`--forever`)+- `exit 124`: timeout; still send a timeout follow-up+- other non-zero: failure; the watch stops and sends a failure follow-up++Exit 64 is the token-saving path. Every other terminal exit costs one Agent turn,+so a waiter whose normal outcome is uninteresting — green CI, review chatter that+was filtered out — should end on 64 rather than reporting "nothing to do". It is a+clean ending, so a `once` watch that retires on 64 reads as completed rather than+failed, and whatever the waiter wrote to `stderr` is logged beside the watch id.++The marker is not optional. 64 is also BSD `sysexits` EX_USAGE, so a watched command+that rejects its own arguments exits with it — and it must keep failing loudly rather+than being read as a quiet cycle and, in `--forever`, rerun indefinitely. A bare 64+is therefore treated as a failure; only 64 with the marker is a no-event cycle. In+the bundled waiters, `_github_wait_common.no_event("<summary>")` prints the summary+and the marker to `stderr` and returns the code, so `return no_event(...)` is the+only place the contract has to be spelled out.++Keep the output split clean:++- `stdout`: final summary for the next turn+- `stderr`: polling logs and diagnostics++## Generic Examples++Delay:++```bash+vibe watch add \+ --name "Delay follow-up" \+ --message "The delayed check completed. Continue from the result below." \+ -- \+ bash -lc 'sleep 120; echo "Timer finished after 120 seconds."'+```++File appears:++```bash+vibe watch add \+ --name "Wait for export file" \+ --message "The export file is ready. Inspect it and continue." \+ -- \+ bash -lc 'while [ ! -f /tmp/export.json ]; do sleep 10; done; echo "Detected /tmp/export.json"'+```++Log match:++```bash+vibe watch add \+ --name "Watch app log" \+ --message "The expected log pattern appeared. Inspect the event and continue." \+ --forever \+ -- \+ bash -lc 'tail -Fn0 /tmp/app.log | while read -r line; do case "$line" in *READY*) echo "$line"; break;; esac; done'+```++## Session Targeting++Use the current Avibe context:++- Inside an Avibe-injected Agent shell, omitting the target continues this conversation.+- Use `--session-id <id>` only when the follow-up should continue a different existing Agent Session.+- Use `--create-session --same-scope` when follow-ups should run in one visible sibling Session under the same Workbench project or IM scope.+- For `--forever` watches that need a separate visible Session for each event, use `--create-session-per-run --same-scope`.+- Use `--create-session --scope-id <scopes.id>` when follow-ups should run in one Session under a specific existing scope.+- For separate visible Sessions in a specific existing scope, use `--create-session-per-run --scope-id <scopes.id>`.+- If `--cwd` is omitted while creating a Session, Avibe uses the command's current working directory.++## Timeout And Lifecycle++For `vibe watch add`:++- `--timeout` is the waiter timeout for one cycle+- default is `21600` seconds+- `0` means no per-cycle timeout+- `--forever` means re-arm after each detected event+- an allowed `--retry-exit-code` keeps either mode waiting; a once Watch stops after its first event+- `--lifetime-timeout` limits the whole long-running watch; default is `0` meaning run until killed++This separation matters: a once Watch may now have several retry cycles, and a forever+Watch can still use a bounded timeout for each cycle.++Exit `0` means one new reportable event, never merely that a condition remains true.+For a persistent level, return an allowed retry code (default `75`) until a new edge is+observed. Exit `64` plus `avibe-watch: no-event` on stderr is a completed cycle with+nothing worth reporting. A forever waiter must keep a durable cursor, state transition,+or domain cooldown so it cannot emit the same level repeatedly.++Avibe admits only one queued/running follow-up per Watch. A forever Watch re-arms after+that Agent Run settles and a five-second safety delay. If the waiter still produces six+successful events within 60 seconds, Avibe pauses the Watch and sends the target Agent+one repair message containing the bounded latest waiter output. The Agent should inspect+and fix the waiter, and resume only after verifying an unambiguous, reversible fix.++## Bundled Waiter Example++This skill ships bundled GitHub waiters:++- `scripts/wait_pr.py`+ Waits for GitHub PR review activity, including reviews, inline review comments, PR conversation comments, PR status transitions such as `draft -> open`, `open -> merged`, or `open -> closed`, and the special Codex `+1` reaction on the PR body. It can also wait for newly opened PRs in a repository.+ When one or more `--workflow` values are provided for a specific PR, the same+ waiter also watches every matching Actions run at the PR's current head and+ optional branch. Add `--sha` only to pin a one-shot wait to one exact head.+- `scripts/wait_issue.py`+ Waits for GitHub issue activity, either newly opened issues in a repository or new comments on a single issue.+- `scripts/wait_action.py`+ Waits for selected GitHub Actions workflow runs on a specific commit SHA to finish+ when there is no PR activity stream to combine with them. Workflow failures are+ reported as an event so the follow-up turn can inspect and handle them.++Use bundled waiters as examples or as ready-to-run building blocks. The main skill is still `vibe watch`; the waiter is only the thing that blocks until the condition is met.+When running a bundled script through `uv`, prefer `uv run --no-project ...` so the script does not accidentally attach itself to an unrelated parent project.+Bundled GitHub waiters classify temporary network failures and GitHub+`408/429/5xx` responses as retryable. The one-shot PR and Actions waiters retry+those failures inside the same process so the managed watch stays alive. A+cycle-oriented waiter may use exit code `75` only when its supervisor explicitly+opts into retrying that code. Exit code `64` with the+`avibe-watch: no-event` marker means a cycle finished with nothing worth an Agent+turn.++**A waiter detects reportable change; the follow-up Agent Run makes the decision.**+Do not turn the waiter into a merge authorizer. `--coalesce-success` is a narrow+notification policy for recognized success shapes, not a generic readiness gate:+known half-successes stay quiet, but findings, errors, unfamiliar review payloads,+and head/lifecycle/thread changes still reach the Agent. The Agent must fetch live+state and apply the repository's exact-head review, complete CI, and thread gates.+A completed Codex summary or a `Reviewed commit` line alone is not a clean pass.++One caveat on CI: a requested workflow that never matches — renamed, misspelled,+or never triggered on this branch — cannot establish success. Verify each+`--workflow` name against actual runs. Coalescing still reports failures from+other matching workflows and actionable PR activity; it never treats missing CI+as green.++A predicate never seen to fire has not been tested. Verify it the way the delivery+loop below is armed — seed the baseline, produce one event, confirm exit `0` — not by+starting it on an event that already exists: an edge-triggered waiter is supposed to+adopt that as its baseline, and one that fires there is level-triggered and will+re-report forever. `--catch-up` is the bundled waiters' explicit replay mode for+deliberately processing history.++Run bundled waiters relative to the directory containing this loaded `SKILL.md`.+The examples below use `BACKGROUND_WATCH_HOOK_DIR` for that directory:++```bash+BACKGROUND_WATCH_HOOK_DIR="<directory containing the loaded SKILL.md>"+```++## GitHub Example Waiter++For a PR delivery loop, prefer one durable combined `wait_pr.py` watch. It observes+PR review, comment, reaction, thread, lifecycle, and head-change events together+with selected Actions workflows for the PR's current head. Use `--forever` and one+state file for the whole loop: when a push changes the head, the next cycle fetches+Actions for the new exact SHA without replacing the Watch or rebuilding its PR+baseline. Use `wait_pr.py` without CI arguments for PR-only monitoring. Use+`wait_action.py` only for an Actions wait that is not attached to a PR.++### Preferred PR + CI watch++At least one repeatable `--workflow` enables combined CI monitoring. Omit `--sha`+for the normal delivery loop: each cycle resolves the PR's current head and queries+Actions for that exact SHA. `--branch`, `--max-pages`, and `--success-conclusion`+remain optional. Add `--sha` only when the caller intentionally wants a fixed-head+one-shot wait. Prefer `--coalesce-success` for delivery loops:++| Observation | Report |+| --- | --- |+| Only CI is green, or only a recognized Codex pass arrived | None; persist it and keep waiting |+| Both successes at the same head, with no unresolved threads | One combined success **candidate** for Agent verification |+| A requested CI run fails/cancels/times out | Report immediately, even if another workflow is missing/running |+| Review findings, Codex errors, or unfamiliar review payloads | Report without waiting for CI |++Recognized review successes are Codex-authored clean-pass comments/reviews naming+the current SHA, and a new Codex `+1` on the PR body observed after an unchanged+head's baseline. A reaction present at seeding or first seen with a head change+cannot be bound this way; head-transition reactions remain visible as ordinary+activity. A reaction candidate still needs the repository's stricter epoch and+prior-review checks in the follow-up; the waiter does not certify that gate.+Codex's mutable summary comment is progress, not a verdict: routine updates stay+quiet in this mode, while its error/failure text remains reportable. Unknown+verdict formats are surfaced rather than silently interpreted as success.++Deferred evidence lives in the same owner-specific state file and pending delivery+transaction. Retain the latest ordered bot outcome, per-resource semantic history,+and reaction-ID high-water mark through every poll and settle fetch, including+temporary missing rows. The latest observation is independently head-tagged; an+older retained PR event cannot erase a valid verdict on the subsequently observed+head. A later clean verdict may supersede an earlier error, but restoring old+evidence or changing its metadata cannot erase a newer failure.+A head change, changed/deleted verdict, or newer bot finding/error invalidates the+deferred review; CI from another SHA cannot complete its pair. Preserve known+unresolved threads when GraphQL is unavailable, rather than treating absence as+resolution. Fail-fast CI rejects older attempts, preserves terminal observations+and prior partial failures, and reports an observed failure without settling it away.+A combined success is deduplicated across ordinary polls and restarts using both+CI verdicts and semantic review evidence. A new CI run/attempt, stronger review+proof, or recovery after a reported problem can produce a fresh pair.++Without `--coalesce-success`, combined mode retains the activity stream: each PR+change is reportable and CI reports once all requested workflows have terminal+runs. Every distinct matching run ID is included in either mode, so an earlier+failed rerun remains visible. Set the forever Watch's `--timeout 0`: 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 reporting mode is part of cursor ownership. Enable it on a new, pre-action+seed and Watch with the same arguments; do not append it to an armed activity-mode+Watch, replace its cursor, or reseed between rounds. Existing Watches and installed+Skill snapshots retain their configured behavior until deliberately rolled out.+Malformed deferred notification history is a waiter failure, not permission to+silently discard evidence or reseed. The supervisor reports that failure; Avibe+service startup is unaffected.++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; in+`--coalesce-success` mode only recognized success/progress payloads are deferred.+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)"++uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 \+ --branch "$BRANCH" \+ --workflow lint \+ --coalesce-success --actionable-only \+ --state-file "$STATE_FILE" --seed-state++vibe watch add \+ --name "Watch PR 151 review and CI" \+ --forever \+ --timeout 0 \+ --message "PR #151 has a combined review/CI success candidate or new actionable activity. Fetch live PR, review threads, and exact-head Actions state. Handle findings/errors promptly and summarize actual fixes or blockers briefly; do not announce a half-success. For a success candidate, verify all delivery gates and send one combined final report. Keep this durable combined Watch armed until close-out. Do not post round summaries as PR comments." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 \+ --branch "$BRANCH" \+ --workflow lint \+ --coalesce-success --actionable-only --settle 20 --state-file "$STATE_FILE" --interval 60 \+ --timeout 0++# After the seeded Watch is confirmed live, push or post the review trigger.+# Keep this same state file and Watch for every later head and review round.+```++Do not combine `--new-prs` with CI arguments. A new PR has no stable exact-head+gate until the follow-up turn resolves its head and workflow set.++One-shot watch:++```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-review.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state++# Push or post the review trigger only after the baseline is durable.+vibe watch add \+ --name "Watch PR 151 reviews" \+ --message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe \+ --pr 151 \+ --actionable-only \+ --settle 20 \+ --state-file "$STATE_FILE" \+ --interval 60+```++Before the first watched push or review trigger in the delivery loop, seed an+owner-specific state file from the current complete PR snapshot. Arm the forever+Watch with that exact file and confirm it is live before taking the watched action.+Set `--timeout 0` on both sides of the `--` command separator: the first disables+the Watch supervisor's per-cycle deadline, while the second disables the bundled+waiter's own default six-hour deadline. GitHub request timeouts remain bounded inside+the waiter. A nonzero timeout at either layer is for a Watch whose lack of an event+by that deadline is itself reportable.+After the Watch starts, never reseed or replace its state between rounds: a later+event may already exist, and turning it into the new baseline silently drops it.+The forever Watch promotes each delivered batch and compares the next cycle against+that durable pre-event snapshot, including activity that landed while the Agent+follow-up was running.++Use `--catch-up` only when deliberately processing historical activity. It is+not a substitute for the pre-action baseline in a review loop. Catch-up and+explicit `--since-*-id` cursors replay requested verdicts as ordinary activity,+even with `--coalesce-success`; normal monitoring still defers half-success.++Prefer `--actionable-only` for review loops. Without it the waiter wakes the Agent+for every comment on the PR, including the `@codex review` triggers the loop itself+posts and the bodyless `COMMENTED` review envelope GitHub wraps around inline+comments. With it the waiter still reports inline review comments, reviews carrying+a verdict or a body, the Codex pass reaction, and merged/closed transitions — which+is everything the review loop needs to make progress or close out.++Narrow it further with `--ignore-author <login>` and `--ignore-comment-pattern <regex>`+(both repeatable). Filtered items still advance the cursors, so they are examined+once and never re-reported. These filters suppress review/comment payloads, not+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.++`--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+event. With `--settle` the waiter re-polls until the set stops growing (at most three+extra polls) and reports the whole batch as one event, which is one Agent turn+instead of several. 20 seconds is a reasonable starting point. The window never runs+past `--timeout`: settling is skipped unless both the wait and a full re-poll fit in+what is left of the deadline, so a batch already worth a turn is reported rather than+lost to the timeout kill. Keep `--settle` well under `--timeout`.++Catch up on existing activity first:++```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-catch-up.json"+vibe watch add \+ --name "Catch up PR 151 reviews" \+ --message "PR #151 already has review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe \+ --pr 151 \+ --state-file "$STATE_FILE" \+ --catch-up+```++Stay armed for future activity:++```bash+STATE_FILE="$HOME/.avibe/state/watch-cursors/pr-151-forever.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --pr 151 --state-file "$STATE_FILE" --seed-state++vibe watch add \+ --name "Monitor PR 151 reviews" \+ --forever \+ --timeout 0 \+ --lifetime-timeout 0 \+ --message "PR #151 has new review activity. Fetch the latest review state and resolve the actionable findings on the PR. Then summarise the round here in one or two lines -- which findings you resolved and what changed -- and do not post that summary as a PR comment. Save a longer message for the review passing, the loop being blocked, or a decision that needs the user." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe \+ --pr 151 \+ --actionable-only \+ --settle 20 \+ --state-file "$STATE_FILE" \+ --interval 60 \+ --timeout 0+```++Always pass `--state-file` to a `--forever` watch. Each cycle is a fresh waiter+process, so without it the next cycle re-snapshots the PR as its baseline and+anything that arrived between the previous cycle's exit and that snapshot is lost.+The file carries the resolved GitHub login and the complete mutable PR baseline+forward. PR cycles reread complete review/comment/thread collections because+edits, deletions, and thread-resolution changes are wake-worthy state.+For an ordinary wait, that normalized complete snapshot is the single wake/no-wake+decision. Numeric cursors, fingerprints, and the thread map only describe a detected+change; they cannot wake independently. `--catch-up` and explicit `--since-*-id`+flags are the deliberate replay modes and therefore remain cursor-driven. A legacy+state file with cursors but no complete snapshot is rejected until it is deliberately+caught up or reseeded, rather than silently absorbing mutable changes.+The login is reused only while the token still fingerprints to the account it was+resolved for. Explicit cursor flags still request a replay from that cursor, while+the complete PR collections remain the source of truth for edits and removals. The+state also records the last observed PR head, review/comment fingerprints, and every+review-thread resolution state, so a pushed head, edited object, deletion, or thread+transition is activity even when no new numeric ID exists. Cursors that cover a reported event are not committed by the+cycle that reports it. A waiter cannot observe its own delivery — `vibe watch` reads+its stdout only after the process exits — so those cursors are staged under `pending`+while the committed ones stay before the event, together with the rendered report+and the value of+`AVIBE_WATCH_LAST_DELIVERY` the cycle started from. That variable is when this watch+last had a report durably queued, stamped in the same transaction as the follow-up, so+any later cycle that reads a *different* value knows the report was delivered and+promotes the staged cursors. An unchanged value means it may never have been queued,+so they are dropped and the event is reported again: at-least-once, costing one+repeated Agent turn instead of losing the activity for good. Comparing a durable stamp+rather than consuming a one-shot acknowledgement is what makes this correct across a+service restart, and for a `once` watch, whose one report is followed by no cycle at+all until the user resumes it. A manual run has no supervisor, and there printing *is*+the delivery, so it commits straight after reporting. Progress made by filtering — new+activity that was deliberately not reported — commits immediately either way, since+there is no delivery to wait for. Three failures are terminal rather than a warning —+a path that cannot be written to (checked before the first poll), a path already owned+by another watch, and an existing file whose cursors cannot be read — and each stops+the watch with exit `1` rather than polling on without the cursors it was asked to+keep, or clobbering another watch's. A corrupt or unrecognised state file is left+exactly as found: re-baselining from the current PR would skip everything that+arrived after the cursor it did hold and then overwrite the only evidence of how far+the watch had got. An empty file is the one exception, since it is a claim caught+between its exclusive create and its first write and never held a cursor at all.++Ownership is claimed, not assumed. A missing state file is created before the first+poll holding nothing but the identity it belongs to, so two watches started together+cannot both see an unowned path; the one that loses that exclusive create reads the+winner's claim and stops. Ownership is re-checked before every replacement as well,+because the loser of a microsecond-wide race has already passed the startup check.+Identity is the repo, the PR, and the options that decide what the watch reports+(`--actionable-only`, `--coalesce-success`, `--ignore-author`, `--ignore-comment-pattern`,+`--include-self-comments`, `--new-prs`) — two watches on the same PR that report+different things cannot share cursors either, because the filtered one advances past+events the other never reported. Pacing options such as `--interval` and `--settle`+are not part of it. When `vibe watch` runs the cycle it also names the watch in+`AVIBE_WATCH_ID`, and the waiter records it as the owner, so even two watches+configured identically down to the last filter are kept apart; a manual run has no+id and adopts whatever it finds -- and a managed watch that starts on a file with no+owner, from a manual run or an older version, stamps itself on it before polling,+because an owner that is absent fits every watch and two of them would share the+path. That decision is read-then-write, so it is taken under a `<state-file>.lock`+sidecar; the lock lives beside the state file rather than on it, since the state file+is replaced rather than rewritten. Give each watch its own state file.++Arguments are validated before any of this: a rejected `--ignore-comment-pattern` or+a missing token exits `2` without claiming the path, so the corrected re-run is not+refused as a different watch's state.++GitHub-specific notes:++- `--catch-up` reports activity that already exists at startup, and overrides saved+ cursors when a state file is present; an explicit `--since-*-id` still wins+- without `--catch-up` or a `--state-file`, the waiter snapshots current PR activity as the baseline+- polling is cheap by design: mutable review/comment collections are fetched in full+ so edits and deletions remain observable, reactions are filtered server-side with+ `content=+1`, and unchanged pages revalidate to `304`, which GitHub does not charge+ against the rate limit — an idle watch can poll for hours for free+- a Codex verdict arrives in more than one shape: findings as a review with inline+ comments, and a pass as a PR-body `+1` reaction or PR conversation comment. Pass reactions remain visible+ even when `--event-limit` is reached (or are retained for the paired candidate+ in `--coalesce-success` mode). A predicate keyed to reviews alone never sees+ a pass. Whether evidence *counts* — bot author, clean-pass phrase, reviewed SHA,+ and a reaction's stricter epoch qualification — remains the follow-up Agent's+ responsibility, not a merge decision encoded in the waiter+- PR activity also includes lifecycle changes on the PR itself, for example draft/ready, closed, reopened, or merged transitions+- a changed PR head is reported as activity so a new push cannot leave the review+ loop asleep+- 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+STATE_FILE="$HOME/.avibe/state/watch-cursors/new-prs-avibe.json"+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe --new-prs --state-file "$STATE_FILE" --seed-state++vibe watch add \+ --name "Watch new PRs" \+ --message "The repository has new pull requests. Review the new PRs and continue as needed." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py" \+ --repo avibe-bot/avibe \+ --new-prs \+ --state-file "$STATE_FILE" \+ --interval 60+```++New issues or issue comments:++```bash+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --new-issues --interval 60+uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_issue.py" --repo avibe-bot/avibe --issue 157 --interval 60+```++Standalone GitHub Actions for a pushed commit that is not being monitored through a PR:++```bash+vibe watch add \+ --name "Watch CI" \+ --message "GitHub Actions failed. Inspect the result below and fix the failures. Then summarise the round here in one or two lines -- what failed and what you changed. Save a longer message for the build going green, the loop being blocked, or a decision that needs the user." \+ -- \+ uv run --no-project "$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_action.py" \+ --repo cyhhao/sub2api \+ --branch main \+ --sha "$HEAD_SHA" \+ --workflow CI \+ --workflow "Security Scan" \+ --interval 60+```++For a merge gate, omit `--only-on-failure`: a successful exact-head build must+wake the Agent so it can perform the final gate and close out the watch. Use+`--only-on-failure` only when a green result intentionally needs no follow-up;+that mode exits `64` with the no-event marker and records the summary in the+Avibe watch log instead of creating an Agent turn.++## Practical Advice++- Keep messages action-oriented. Tell the next turn what to do with the waiter result.+- In a fix loop, have every round report itself in one or two lines. The user is+ watching a loop they cannot see inside: with no per-round summary all they get is a+ stream of tool activity, and no way to tell a converging PR from one that is+ thrashing on the same finding. Name the findings resolved and what changed, not a+ diff walkthrough — the detail is already in the commit and on the PR. Keep it in the+ conversation only; re-posting the same summary as a PR comment adds noise to the+ review the bot is reading. Save a longer, user-facing message for the outcomes a+ human has to act on: the review passed, the loop is blocked, or a decision has to be+ made. A reply containing only a `<silent>...</silent>` block sends nothing at all, so+ keep that for cycles that genuinely produced nothing worth reading — a re-poll that+ found no new findings — not for the rounds that did the work.+- If this is the first time using `vibe watch add`, read `vibe watch add --help` first; the help text explains both argument syntax and runtime behavior such as how `--message` and waiter stdout become the follow-up Agent Run input.+- Prefer `vibe watch` over ad-hoc detached shells when the wait should survive the current turn cleanly.+- Treat GitHub as just one example waiter, not the main point of the skill.+- If a watch is no longer useful, remove it instead of leaving stale background work behind.diff --git a/skills/background-watch-hook/scripts/_github_actions_wait.py b/skills/background-watch-hook/scripts/_github_actions_wait.pyindex 549bc5974..47dd6dc86 100644--- a/skills/background-watch-hook/scripts/_github_actions_wait.py+++ b/skills/background-watch-hook/scripts/_github_actions_wait.py@@ -125,21 +125,26 @@ def render_actions_result(head_sha: str,selected: dict[str, list[dict[str, Any]]],success_conclusions: set[str],+ fail_fast: bool = False,) -> tuple[str | None, bool]:+ failed = [+ workflow+ for workflow, runs in selected.items()+ if any(+ str(run.get("status") or "") == TERMINAL_STATUS+ and str(run.get("conclusion") or "") not in success_conclusions+ for run in runs+ )+ ]missing = [workflow for workflow, runs in selected.items() if not runs]running = [workflowfor workflow, runs in selected.items()if any(str(run.get("status") or "") != TERMINAL_STATUS for run in runs)]- if missing or running:+ if (missing or running) and not (fail_fast and failed):return None, False- failed = [- workflow- for workflow, runs in selected.items()- if any(str(run.get("conclusion") or "") not in success_conclusions for run in runs)- ]result = "failure" if failed else "success"short_sha = head_sha[:12]branch_label = f" on {branch}" if branch else ""@@ -149,4 +154,6 @@ def render_actions_result(lines.append(format_run(run))if failed:lines.append(f"Failed workflow(s): {', '.join(failed)}")+ if missing or running:+ lines.append(f"Still waiting for workflow(s): {', '.join(dict.fromkeys([*missing, *running]))}")return "\n".join(lines), bool(failed)diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.pyindex cf8ccd62f..1746632cd 100755--- a/skills/background-watch-hook/scripts/wait_pr.py+++ b/skills/background-watch-hook/scripts/wait_pr.py@@ -61,6 +61,17 @@ CODEX_REVIEW_PASS_REACTION_USERS = {"chatgpt-codex-connector[bot]",}CODEX_REVIEW_PASS_REACTION_CONTENT = "+1"+CODEX_STANDARD_SUMMARY_FOOTER = (+ "<details> <summary>ℹ️ About Codex in GitHub</summary>",+ "<br/>",+ "[Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general).",+ "Codex reviews are triggered when you",+ "- Open a pull request for review",+ "- Mark a draft as ready",+ "- Comment \"@codex review\" or \"@codex security review\".",+ "Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.",+ "</details>",+)# Comments that only drive the review loop rather than report its result. On a# busy PR these outnumber the real findings, and each one costs a full Agent turn.@@ -96,6 +107,7 @@ REVIEW_THREAD_STATES_KEY = "review_thread_states"PR_SNAPSHOT_KEY = "snapshot"ACTIONS_SNAPSHOT_KEY = "actions"ACTIONS_OBSERVED_KEY = "actions_observed"+SUCCESS_BATCH_KEY = "success_batch"class PRReport(NamedTuple):@@ -105,6 +117,8 @@ class PRReport(NamedTuple):cursors: tuple[int, int, int, int, str]pr_state: dict[str, Any]actions: dict[str, Any] | None = None+ success_batch: dict[str, Any] | None = None+ failed_actions: bool = FalsePR_FINGERPRINT_KEYS = (@@ -269,6 +283,187 @@ def _is_codex_pass_reaction(reaction: dict[str, Any]) -> bool:return author in CODEX_REVIEW_PASS_REACTION_USERS and content == CODEX_REVIEW_PASS_REACTION_CONTENT+def _is_codex_item(item: dict[str, Any]) -> bool:+ author = item.get("author") or ((item.get("user") or {}).get("login"))+ return author in CODEX_REVIEW_PASS_REACTION_USERS+++def _has_codex_problem_text(body: str) -> bool:+ return bool(re.search(+ r"\b(errors?|failed|failures?|something went wrong|changes requested|found issues|needs? changes|P[0-3])\b",+ body, re.IGNORECASE,+ ))+++def _codex_summary_cells(line: str) -> list[str] | None:+ stripped = line.strip()+ if not stripped.startswith("|") or not stripped.endswith("|"):+ return None+ cells = stripped.split("|")+ return cells if len(cells) == 6 else None+++def _is_codex_summary_table_line(line: str) -> bool:+ return _codex_summary_cells(line) is not None+++def _is_codex_summary_separator(line: str) -> bool:+ cells = _codex_summary_cells(line)+ return bool(cells) and all(re.fullmatch(r":?-{3,}:?", cell.strip()) for cell in cells[1:-1])+++def _is_codex_summary_review_row(line: str) -> bool:+ cells = _codex_summary_cells(line)+ if cells is None:+ return False+ label = re.sub(r"^[^\w]+", "", cells[1].strip()).replace("*", "").strip()+ return (+ label in {"Code Review", "Security Review"}+ and bool(cells[2].strip())+ and re.fullmatch(r"`[0-9a-f]{7,40}`", cells[3].strip(), re.IGNORECASE) is not None+ and bool(cells[4].strip())+ )+++def _is_codex_summary_state_line(line: str) -> bool:+ match = re.fullmatch(r"<!-- codex-review-state:v1 (.+) -->", line.strip())+ if not match:+ return False+ try:+ state = json.loads(match.group(1))+ except json.JSONDecodeError:+ return False+ return isinstance(state, dict)+++def _is_codex_summary_shape(body: str) -> bool:+ """Require the recognized progress table to be the whole known summary shape."""++ lines = body.splitlines()+ table_start = next(+ (+ index for index, line in enumerate(lines)+ if _is_codex_summary_table_line(line)+ and (cells := line.strip().split("|"))[1].strip() == "Review"+ and cells[2].strip() == "Status"+ ),+ None,+ )+ if table_start is None:+ return False++ allowed_prefix = {+ "<!-- codex-pull-request-review-summary -->",+ "## Codex Review Summary",+ "This comment shows the latest Codex review activity on this pull request.",+ }+ if any(+ line.strip()+ and line.strip() not in allowed_prefix+ and not _is_codex_summary_state_line(line)+ for line in lines[:table_start]+ ):+ return False++ table_end = table_start+ while table_end + 1 < len(lines) and _is_codex_summary_table_line(lines[table_end + 1]):+ table_end += 1+ table_lines = lines[table_start:table_end + 1]+ if (+ len(table_lines) < 3+ or not _is_codex_summary_separator(table_lines[1])+ or not all(_is_codex_summary_review_row(line) for line in table_lines[2:])+ ):+ return False+ suffix = [line.strip() for line in lines[table_end + 1:] if line.strip()]+ if not suffix:+ return True+ standard_footer = "\n".join(CODEX_STANDARD_SUMMARY_FOOTER)+ return "\n".join(suffix) in {+ standard_footer,+ standard_footer.replace(+ "\nCodex reviews are triggered when you", " Reviews are triggered when you", 1,+ ),+ }+++def _codex_clean_pass_body_sha(body: str) -> str | None:+ lines = [line.strip() for line in body.splitlines() if line.strip()]+ if not lines or not re.fullmatch(+ r"Codex Review:\s*Didn['’]t find any major issues\.?", lines[0], re.IGNORECASE,+ ):+ return None+ if len(lines) == 1:+ return ""+ if len(lines) != 2:+ return None+ match = re.fullmatch(+ r"\*{0,2}Reviewed commit\*{0,2}:\*{0,2}\s*`([0-9a-f]{7,40})`",+ lines[1], re.IGNORECASE,+ )+ return match.group(1) if match else None+++def _is_codex_clean_pass(item: dict[str, Any], head_sha: str) -> bool:+ """Recognize a success shape, not a substitute for the Agent's review gate."""++ if not head_sha or not _is_codex_item(item):+ return False+ if str(item.get("state") or "").lower() in {"changes_requested", "dismissed"}:+ return False+ body_sha = _codex_clean_pass_body_sha(str(item.get("body") or ""))+ if body_sha is None:+ return False+ item_sha = item.get("commit_id")+ item_sha = item_sha if isinstance(item_sha, str) else ""+ if item_sha and body_sha and not (+ item_sha.casefold().startswith(body_sha.casefold())+ or body_sha.casefold().startswith(item_sha.casefold())+ ):+ return False+ reviewed = item_sha or body_sha+ return len(reviewed) >= 7 and head_sha.casefold().startswith(reviewed.casefold())+++def _is_codex_progress(item: dict[str, Any]) -> bool:+ body = str(item.get("body") or "")+ if (+ not _is_codex_item(item)+ or "<!-- codex-pull-request-review-summary -->" not in body+ or _has_codex_problem_text(body)+ or not _is_codex_summary_shape(body)+ ):+ return False+ statuses = [+ cells[2].strip() for line in body.splitlines()+ if len(cells := line.strip().split("|")) >= 5 and cells[0] == ""+ and cells[2].strip() != "Status" and cells[2].strip(": -")+ ]+ return bool(statuses) and all(+ re.fullmatch(+ r"[\W_]*(queued|pending|running|in progress|completed)[\W_]*"+ r"(?:since\s+)?(?:<relative-time\b[^>]*>[^<]*</relative-time>\s*)?",+ status, re.IGNORECASE,+ )+ for status in statuses+ )+++def _quiet_success_snapshot(value: dict[str, Any], *, defer_reactions: bool) -> dict[str, Any]:+ """Remove only recognized success/progress payloads from the wake comparison."""++ result = dict(value)+ head = str((value.get("pull_request") or {}).get("head_sha") or "")+ for kind in ("reviews", "issue_comments"):+ result[kind] = {+ key: item for key, item in value.get(kind, {}).items()+ if not (_is_codex_clean_pass(item, head) or _is_codex_progress(item))+ }+ if defer_reactions:+ result["reactions"] = {}+ return result++def _format_reaction(reaction: dict[str, Any]) -> str:reaction_id = reaction.get("id")author = ((reaction.get("user") or {}).get("login")) or "unknown"@@ -509,6 +704,129 @@ def _normalized_pr_snapshot(}+def _review_observation(kind: str, item: dict[str, Any]) -> dict[str, Any]:+ fields = {+ "reviews": ("state", "body", "commit_id"),+ "issue_comments": ("body",),+ "review_comments": ("body", "path"),+ "reactions": ("content",),+ }[kind]+ normalized = _normalized_item_map([item], fields=fields)+ if _is_codex_item(item):+ for value in normalized.values():+ value["author"] = "chatgpt-codex-connector"+ encoded = json.dumps(normalized, sort_keys=True, separators=(",", ":"))+ return {+ "kind": kind, "id": item["id"],+ "fingerprint": hashlib.sha256(encoded.encode()).hexdigest(),+ "order": [str(item.get("updated_at") or item.get("submitted_at") or item.get("created_at") or ""),+ int(item["id"])],+ }+++def _select_review_outcome(+ outcomes: list[tuple[dict[str, Any], bool]],+) -> tuple[dict[str, Any], bool]:+ # IDs break equivalent ties, never conflicting updates within one clock tick.+ return max(+ outcomes,+ key=lambda pair: (pair[0]["order"][0], not pair[1], pair[0]["id"]),+ )+++def _should_adopt_review_outcome(+ outcome: dict[str, Any],+ clean: bool,+ last_outcome: dict[str, Any] | None,+ batch: dict[str, Any],+) -> bool:+ if last_outcome is None:+ return True+ timestamp, last_timestamp = outcome["order"][0], last_outcome["order"][0]+ if timestamp != last_timestamp:+ return timestamp > last_timestamp+ if outcome["kind"] == last_outcome["kind"] and outcome["id"] == last_outcome["id"]:+ return outcome["fingerprint"] != last_outcome["fingerprint"]+ return not clean or batch.get("review") is not None+++def _coalesced_review_state(+ state: dict[str, Any],+ previous: dict[str, Any] | None,+ baseline: dict[str, Any] | None,+ *,+ reaction_cursor: int = 0,+ initialize: bool = False,+) -> tuple[dict[str, Any], bool]:+ """Advance monotonic observations, independently of notification progress.++ Retain the latest bot outcome even when its response row disappears. Retain+ reaction IDs across head epochs so an old reaction cannot become a new pass.+ """++ head = _current_pr_head_sha(state.get("pull_request"))+ previous = previous or {}+ same_head = str(previous.get("head_sha") or "").casefold() == head.casefold()+ reaction_floor = max(+ reaction_cursor, previous.get("reaction_seen", 0),+ max((int(key) for key in (baseline or {}).get("reactions", {})), default=0),+ )+ batch = dict(previous) if same_head else {+ "head_sha": head, "review": None, "outcome": None, "notified": None,+ }+ batch["reaction_seen"] = max(reaction_floor, max_id(state["reactions"]))+ seen = dict(batch.get("review_seen") or {})+ batch["review_seen"] = seen+ evidence = batch.get("review")+ revoked = False+ if evidence:+ item = next((item for item in state[evidence["kind"]] if item.get("id") == evidence["id"]), None)+ if item is None or _review_observation(evidence["kind"], item)["fingerprint"] != evidence["fingerprint"]:+ batch.update(review=None, notified=None)+ revoked = True++ outcomes: list[tuple[dict[str, Any], bool]] = []+ for kind, fields in (+ ("reviews", ("state", "body", "commit_id")),+ ("issue_comments", ("body",)),+ ("review_comments", ("body", "path")),+ ):+ old_items = (baseline or {}).get(kind, {})+ for item in state[kind]:+ if not _is_codex_item(item) or _is_codex_progress(item):+ continue+ if kind == "reviews" and not _is_actionable_review(item):+ continue+ normalized = _normalized_item_map([item], fields=fields)+ observation = _review_observation(kind, item)+ key = f"{kind}/{item['id']}"+ previous_fingerprint = seen.get(key)+ changed = (+ previous_fingerprint != observation["fingerprint"] if previous_fingerprint is not None+ else old_items.get(str(item.get("id"))) != normalized.get(str(item.get("id")))+ )+ seen[key] = observation["fingerprint"]+ # A replay scans old rows without renewing already-seen verdicts.+ if changed or (initialize and previous_fingerprint is None):+ clean = kind != "review_comments" and _is_codex_clean_pass(item, head)+ outcomes.append((observation, clean))++ if not initialize and same_head:+ outcomes.extend(+ (_review_observation("reactions", item), True) for item in state["reactions"]+ if _is_codex_pass_reaction(item) and int(item["id"]) > reaction_floor+ )+ if outcomes:+ outcome, clean = _select_review_outcome(outcomes)+ last_outcome = batch.get("outcome")+ if _should_adopt_review_outcome(outcome, clean, last_outcome, batch):+ batch["outcome"] = outcome+ batch["review"] = outcome if clean else None+ if not clean:+ batch["notified"] = None+ return batch, revoked and batch.get("review") is None++def _review_thread_state_changes(current: dict[str, bool],baseline: dict[str, bool],@@ -709,6 +1027,7 @@ def _render_activity(actionable_only: bool = False,ignored_authors: set[str] | None = None,ignore_patterns: list[re.Pattern[str]] | None = None,+ coalesce_success: bool = False,) -> tuple[str | None, int, int, int, int, str]:ignored_authors = ignored_authors or set()ignore_patterns = ignore_patterns or []@@ -773,6 +1092,18 @@ def _render_activity(next_reaction_cursor = max(reaction_cursor, max_id(state["reactions"]))next_pr_status = current_pr_status+ if coalesce_success:+ def quiet(item: dict[str, Any]) -> bool:+ return _is_codex_clean_pass(item, current_head_sha) or _is_codex_progress(item)++ visible_reviews = [item for item in visible_reviews if not quiet(item)]+ visible_issue_comments = [item for item in visible_issue_comments if not quiet(item)]+ defer_reactions = not has_head_event and snapshot is not None+ if defer_reactions:+ new_reactions = []+ current_snapshot = _quiet_success_snapshot(current_snapshot, defer_reactions=defer_reactions)+ if snapshot is not None:+ snapshot = _quiet_success_snapshot(snapshot, defer_reactions=defer_reactions)snapshot_changed = snapshot is not None and current_snapshot != snapshotif snapshot is not None and not snapshot_changed:return (@@ -968,6 +1299,8 @@ def _watch_identity(material_fields["ci_max_pages"] = args.max_pagesif legacy_ci_sha is not None:material_fields["ci_sha"] = legacy_ci_sha+ if args.coalesce_success:+ material_fields["coalesce_success"] = Truematerial = json.dumps(material_fields, sort_keys=True)return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{material}".encode()).hexdigest()[:16]@@ -1137,11 +1470,13 @@ def _load_state_file(if conflict is not None:raise StateFileOwnershipError(f"State file {path} {conflict}")_validate_saved_actions(payload)+ _validate_saved_success_batch(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"]})+ _validate_saved_success_batch({**payload, **pending["cursors"]})return payload@@ -1603,6 +1938,53 @@ def _validate_saved_actions(saved: dict[str, Any]) -> None:raise StateFileUnusableError("Saved actions_observed is malformed: workflow inventory differs from actions")+def _validate_saved_success_batch(saved: dict[str, Any]) -> None:+ if SUCCESS_BATCH_KEY not in saved:+ return+ value = saved[SUCCESS_BATCH_KEY]+ if not isinstance(value, dict) or not isinstance(value.get("head_sha"), str):+ raise StateFileUnusableError("Saved success_batch is malformed: expected head-bound state")+ notified = value.get("notified")+ if notified is not None and not isinstance(notified, str):+ raise StateFileUnusableError("Saved success_batch is malformed: invalid notification signature")+ reaction_seen = value.get("reaction_seen", 0)+ if not isinstance(reaction_seen, int) or isinstance(reaction_seen, bool) or reaction_seen < 0:+ raise StateFileUnusableError("Saved success_batch is malformed: invalid reaction watermark")+ threads = value.get("thread_states", {})+ if not isinstance(threads, dict) or any(not isinstance(key, str) or not isinstance(flag, bool) for key, flag in threads.items()):+ raise StateFileUnusableError("Saved success_batch is malformed: invalid observed thread states")+ seen = value.get("review_seen", {})+ if not isinstance(seen, dict) or any(not isinstance(key, str) or not isinstance(fp, str) for key, fp in seen.items()):+ raise StateFileUnusableError("Saved success_batch is malformed: invalid semantic observation history")+ for key in ("review", "outcome"):+ review = value.get(key)+ if review is None:+ continue+ if (+ not isinstance(review, dict)+ or review.get("kind") not in {"reviews", "issue_comments", "review_comments", "reactions"}+ or not isinstance(review.get("id"), (int, str))+ or isinstance(review.get("id"), bool)+ or not isinstance(review.get("fingerprint"), str)+ or not isinstance(review.get("order"), list)+ or len(review["order"]) != 2+ or not isinstance(review["order"][0], str)+ or not isinstance(review["order"][1], int)+ ):+ raise StateFileUnusableError("Saved success_batch is malformed: invalid review evidence")+++def _combined_success_signature(selected: dict[str, Any], batch: dict[str, Any]) -> str:+ review = batch["review"]+ material = {+ "head": str(batch["head_sha"]).casefold(),+ "review": {key: review[key] for key in ("kind", "id", "fingerprint")},+ "actions": normalize_selected_runs(selected),+ }+ encoded = json.dumps(material, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(encoded.encode()).hexdigest()++def _actions_snapshot_regressed(current: dict[str, Any], previous: dict[str, Any]) -> bool:"""An incomplete inventory or older attempt cannot establish a new verdict."""@@ -1622,7 +2004,7 @@ def _actions_snapshot_regressed(current: dict[str, Any], previous: dict[str, Anydef _observe_actions(- previous: dict[str, Any], current: dict[str, Any], head_sha: str+ previous: dict[str, Any], current: dict[str, Any], head_sha: str, *, preserve_terminal: bool = False,) -> dict[str, Any]:"""Remember known run IDs/attempts without treating observation as delivery."""@@ -1640,17 +2022,41 @@ def _observe_actions(not isinstance(new_attempt, int) or new_attempt < old_attempt):continue+ if (+ preserve_terminal and old_attempt == new_attempt+ and known.get(run.get("id"), {}).get("status") == "completed"+ and run.get("status") != "completed"+ ):+ continueknown[run.get("id")] = runobserved[workflow] = list(known.values())return normalize_selected_runs(observed)+def _without_older_attempts(+ selected: dict[str, list[dict[str, Any]]], observed: dict[str, Any],+) -> dict[str, list[dict[str, Any]]]:+ """Missing inventory does not hide a new failure; an older attempt does."""++ result = {}+ for workflow, runs in selected.items():+ known = {run["id"]: run for run in observed.get(workflow, [])}+ result[workflow] = [+ run for run in runs+ if not isinstance(attempt := known.get(run.get("id"), {}).get("run_attempt"), int)+ or (isinstance(run.get("run_attempt"), int) and run["run_attempt"] >= attempt)+ ]+ return result++def _ci_enabled(args: argparse.Namespace) -> bool:return bool(args.sha or args.branch or args.workflow or args.success_conclusion)def _validate_ci_args(args: argparse.Namespace) -> str | None:provided = _ci_enabled(args)+ if args.coalesce_success and not args.workflow:+ return "--coalesce-success requires --pr and at least one --workflow"if not provided:return Noneif args.pr is None:@@ -1760,6 +2166,7 @@ def _resolve_staged_state(if delivered:resolved.update(cursors)_validate_saved_actions(resolved)+ _validate_saved_success_batch(resolved)print(("An earlier report was delivered; advancing past it."@@ -1898,6 +2305,14 @@ def _build_parser() -> argparse.ArgumentParser:"omitted; repeatable and enables combined CI mode"),)+ parser.add_argument(+ "--coalesce-success",+ action="store_true",+ help=(+ "In combined PR/CI mode, defer recognized Codex and CI successes until both are "+ "present at the same head; findings, errors, and unfamiliar activity still report"+ ),+ )parser.add_argument("--max-pages",type=int,@@ -2169,6 +2584,7 @@ def main() -> int:review_comment_fingerprints = _saved_fingerprints(saved, REVIEW_COMMENT_FINGERPRINTS_KEY)issue_comment_fingerprints = _saved_fingerprints(saved, ISSUE_COMMENT_FINGERPRINTS_KEY)review_thread_states = _saved_review_thread_states(saved)+ latest_review_thread_states = dict((saved.get(SUCCESS_BATCH_KEY) or {}).get("thread_states", review_thread_states))# Normal monitoring always compares one complete normalized snapshot. Numeric# cursors, fingerprints, and thread maps only explain that change in the report;# they never decide independently whether to wake. Explicit replay/catch-up is@@ -2200,6 +2616,18 @@ def main() -> int:else None)+ def _pr_observation_snapshot(pr_state: dict[str, Any]) -> dict[str, Any]:+ return _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={"review_threads": dict(+ latest_review_thread_states if args.coalesce_success else review_thread_states+ )},+ review_threads_available=token is not None,+ )+observed_head_sha = _current_pr_head_sha(state.get("pull_request"))if args.pr is not None and not resumed and not args.catch_up and not explicit_replay:@@ -2212,15 +2640,7 @@ def main() -> int: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,- review_threads_available=token is not None,- )+ snapshot = _pr_observation_snapshot(state)actions_snapshot = normalize_selected_runs(selected_actions) if ci_enabled else None# Explicit PR replay baselines CI at the current head, independently of the@@ -2238,10 +2658,54 @@ def main() -> int:),normalize_selected_runs(selected_actions),args.sha or observed_head_sha,+ preserve_terminal=args.coalesce_success,)if ci_enabled else {})+ def _visible_success_state() -> dict[str, Any]:+ visible = dict(state)+ for kind in ("reviews", "review_comments", "issue_comments"):+ visible[kind] = _visible_activity_items(+ state[kind], viewer_login=viewer_login,+ ignore_self_comments=not args.include_self_comments,+ ignored_authors=ignored_authors, ignore_patterns=ignore_patterns,+ )+ return visible++ success_batch = (+ saved.get(SUCCESS_BATCH_KEY) or {+ "head_sha": tracked_head_sha or observed_head_sha, "review": None,+ "outcome": None, "notified": None, "reaction_seen": _saved_int(saved, "reaction_cursor") or 0,+ }+ ) if args.coalesce_success else None+ if args.coalesce_success and token is not None:+ latest_review_thread_states = _review_thread_state_map(state.get("review_threads") or [])+ if args.coalesce_success and (args.seed_state or not resumed or explicit_replay):+ # Deliberate replay must not rebuild monotonic review history from the+ # current response: omitted rows can otherwise resurrect an older pass+ # over a newer invalidating outcome. A seed is an explicit new baseline.+ prior_success_batch = success_batch if (args.catch_up or explicit_replay) else None+ success_batch, _ = _coalesced_review_state(+ _visible_success_state(), prior_success_batch, snapshot, initialize=True,+ reaction_cursor=_saved_int(saved, "reaction_cursor") or 0,+ )+ _baseline_output, baseline_failed = render_actions_result(+ repo=args.repo, branch=args.branch, head_sha=args.sha or observed_head_sha,+ selected=selected_actions, success_conclusions=success_conclusions,+ )+ if (+ not args.catch_up and success_batch["review"] and _baseline_output and not baseline_failed+ and all(_pr_observation_snapshot(state)["review_threads"].values())+ ):+ success_batch["notified"] = _combined_success_signature(selected_actions, success_batch)+ if args.coalesce_success:+ success_batch = {**success_batch, "thread_states": dict(latest_review_thread_states)}+ success_observed = success_batch+ success_observation_snapshot = snapshot+ success_observation_state = None+ success_revoked = False+if token is None:bootstrap_requests = requests_per_poll_countunauthenticated_min = min_interval_for_unauthenticated(@@ -2310,6 +2774,38 @@ def main() -> int:file=sys.stderr,)+ def _observe_success_state() -> None:+ nonlocal success_observed, success_observation_snapshot, success_observation_state, success_revoked+ nonlocal latest_review_thread_states+ if not args.coalesce_success or state is success_observation_state:+ return+ visible = _visible_success_state()+ if token is not None:+ latest_review_thread_states = _review_thread_state_map(visible.get("review_threads") or [])+ success_observed, revoked = _coalesced_review_state(+ visible, success_observed, success_observation_snapshot, reaction_cursor=reaction_cursor,+ )+ success_observed["thread_states"] = dict(latest_review_thread_states)+ success_revoked = success_revoked or revoked+ success_observation_snapshot = _pr_observation_snapshot(visible)+ success_observation_state = state++ def _active_actions() -> dict[str, list[dict[str, Any]]]:+ if not args.coalesce_success:+ return selected_actions+ active = _without_older_attempts(selected_actions, actions_observed)+ for workflow, observed_runs in actions_observed.items():+ by_id = {run["id"]: run for run in active.get(workflow, [])}+ for run in observed_runs:+ if run.get("status") == "completed" and run.get("conclusion") not in success_conclusions:+ payload = by_id.get(run["id"], {})+ by_id[run["id"]] = {+ **payload, **run, "name": workflow,+ "html_url": payload.get("html_url") or f"https://github.com/{args.repo}/actions/runs/{run['id']}",+ }+ active[workflow] = list(by_id.values())+ return active+def _render(cursors: tuple[int, int, int, int, str]) -> PRReport:activity = _render_activity(repo=args.repo,@@ -2333,6 +2829,7 @@ def main() -> int:actionable_only=args.actionable_only,ignored_authors=ignored_authors,ignore_patterns=ignore_patterns,+ coalesce_success=args.coalesce_success and not (args.catch_up or explicit_replay),)return PRReport(activity[0], activity[1:], state)@@ -2347,6 +2844,14 @@ def main() -> int:if not ci_enabled:return pr_result+ _observe_success_state()+ if args.coalesce_success:+ batch = dict(success_observed)+ # Observation history is independently head-tagged. Preserve a+ # fresh latest-head verdict even when the PR report retains an+ # older head event; the CI guard below still forbids mixing them.+ pr_result = pr_result._replace(success_batch=batch)+# 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() != (@@ -2354,28 +2859,86 @@ def main() -> int:):return pr_result+ if args.coalesce_success:+ if success_revoked and batch.get("review") is None and pr_result.output is None:+ pr_result = pr_result._replace(output=(+ f"Codex review evidence changed or was removed for {args.repo}#{args.pr}; "+ "re-evaluate the current head."+ ))+ ci_output, failed = render_actions_result(+ repo=args.repo, branch=args.branch, head_sha=_active_ci_head_sha(),+ selected=_active_actions(), success_conclusions=success_conclusions,+ fail_fast=True,+ )+ unresolved = not all(success_observation_snapshot["review_threads"].values())+ if failed or unresolved:+ batch["notified"] = None+ elif (+ ci_output and batch.get("review")+ and str(batch["head_sha"]).casefold() == _active_ci_head_sha().casefold()+ and not _actions_snapshot_regressed(normalize_selected_runs(selected_actions), actions_observed)+ ):+ signature = _combined_success_signature(selected_actions, batch)+ if batch.get("notified") != signature:+ evidence = batch["review"]+ item = next(item for item in state[evidence["kind"]] if item.get("id") == evidence["id"])+ formatter = {+ "reviews": _format_review, "issue_comments": _format_issue_comment,+ "reactions": _format_reaction,+ }[evidence["kind"]]+ output = (+ f"CI + Codex review success candidate for {args.repo}#{args.pr}"+ f"@{_active_ci_head_sha()[:12]}; verify all delivery gates before close-out.\n"+ f"{formatter(item)}\n{ci_output}"+ )+ if pr_result.output:+ output = f"{pr_result.output}\n{output}"+ batch["notified"] = signature+ return pr_result._replace(+ output=output, actions=normalize_selected_runs(selected_actions),+ )+ # A green CI result alone must not advance its delivery baseline.+ # The review evidence above is still adopted on quiet/problem polls.+ if not failed:+ return pr_result+actions_output = _render_new_actions()if actions_output is None:return pr_result- reported_actions = normalize_selected_runs(selected_actions)+ reported_actions = normalize_selected_runs(_active_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)+ return pr_result._replace(+ output=output, actions=reported_actions, failed_actions=args.coalesce_success and failed,+ )def _render_new_actions() -> str | None:- current_actions = normalize_selected_runs(selected_actions)- if _actions_snapshot_regressed(current_actions, actions_observed):- return None+ active_actions = _active_actions()+ current_actions = normalize_selected_runs(active_actions)# A push starts a new CI epoch even if it returns to an earlier SHA.previous = actions_snapshot if _same_actions_head() else Noneif previous is not None and current_actions == previous:return None- output, _failed = render_actions_result(+ output, failed = render_actions_result(repo=args.repo,branch=args.branch,head_sha=_active_ci_head_sha(),- selected=selected_actions,+ selected=active_actions,success_conclusions=success_conclusions,+ fail_fast=args.coalesce_success,)+ if _actions_snapshot_regressed(current_actions, actions_observed) and not (args.coalesce_success and failed):+ return None+ if args.coalesce_success and failed and previous is not None:+ # Other workflows finishing must not reannounce the same failure.+ known = {+ (workflow, run["id"]): run for workflow, runs in previous.items() for run in runs+ }+ failures = [+ (workflow, run) for workflow, runs in current_actions.items() for run in runs+ if run.get("status") == "completed" and run.get("conclusion") not in success_conclusions+ ]+ if all(known.get((workflow, run["id"])) == run for workflow, run in failures):+ return Nonereturn outputdef _advance_actions_baseline(report: PRReport) -> None:@@ -2387,7 +2950,10 @@ def main() -> int:# 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+ actions_snapshot = (+ _observe_actions(actions_snapshot or {}, report.actions, report_head, preserve_terminal=True)+ if args.coalesce_success else 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@@ -2402,30 +2968,35 @@ def main() -> int:head_sha=_active_ci_head_sha(),)actions_observed = _observe_actions(- actions_observed, normalize_selected_runs(selected_actions), _active_ci_head_sha()+ actions_observed, normalize_selected_runs(selected_actions), _active_ci_head_sha(),+ preserve_terminal=args.coalesce_success,)+ _observe_success_state()def _actions_waiting_for_terminal_result() -> bool:if not ci_enabled:return Falsecurrent_actions = normalize_selected_runs(selected_actions)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(+ actions_output, failed = render_actions_result(repo=args.repo,branch=args.branch,head_sha=_active_ci_head_sha(),- selected=selected_actions,+ selected=_active_actions(),success_conclusions=success_conclusions,+ fail_fast=args.coalesce_success,)+ if args.coalesce_success and failed:+ return False+ if _actions_snapshot_regressed(current_actions, actions_observed):+ return True+ if previous is not None and current_actions == previous:+ return Falsereturn actions_output is Nonedef _adopt_report(report: PRReport) -> None:nonlocal review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status- nonlocal observed_head_sha, snapshot+ nonlocal observed_head_sha, snapshot, success_batchnonlocal review_fingerprints, review_comment_fingerprints, issue_comment_fingerprints, review_thread_statesnonlocal review_comment_since, issue_comment_sincereview_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status = report.cursors@@ -2441,17 +3012,10 @@ def main() -> int: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,- )+ snapshot = _pr_observation_snapshot(pr_state)_advance_actions_baseline(report)+ if report.success_batch is not None:+ success_batch = report.success_batchdef _pr_state_fields() -> dict[str, Any]:fields = {@@ -2474,6 +3038,8 @@ def main() -> int:if ci_enabled:fields[ACTIONS_SNAPSHOT_KEY] = actions_snapshot or {workflow: [] for workflow in args.workflow}fields[ACTIONS_OBSERVED_KEY] = actions_observed+ if args.coalesce_success:+ fields[SUCCESS_BATCH_KEY] = success_batchreturn fieldsdef _persist_pr_state(@@ -2527,7 +3093,7 @@ def main() -> int:"""Re-poll while a batch is still landing so it costs one Agent turn."""nonlocal state- if settle_seconds <= 0:+ if settle_seconds <= 0 or first.failed_actions:return firstbest = first@@ -2596,6 +3162,8 @@ def main() -> int:# Rendered from the same cursors as the first hit, so the result is a# superset rather than a second, partial report.candidate = _fallback()+ if candidate.failed_actions:+ return candidateif candidate.output is None:return candidateif candidate.cursors == best.cursors:diff --git a/tests/test_harness_skill_guidance.py b/tests/test_harness_skill_guidance.pyindex aa8c2d47e..72f33e903 100644--- a/tests/test_harness_skill_guidance.py+++ b/tests/test_harness_skill_guidance.py@@ -176,12 +176,12 @@ def test_use_avibe_harness_owns_the_extracted_harness_protocol() -> None:def test_background_watch_skill_defaults_to_current_session() -> None:body = _read("skills/background-watch-hook/SKILL.md")- assert ' --message "<what the next Agent Run should do>"' in body+ assert '--message "PR #151 has an event.' in bodyassert "Inside an Avibe-injected Agent shell, omitting the target continues this conversation." in bodyassert "Use `--session-id <id>` only when" in body- assert "Use `--create-session --same-scope` when follow-ups should run in one visible sibling Session" in body- assert "use `--create-session-per-run --same-scope`" in body- assert "use `--create-session-per-run --scope-id <scopes.id>`" in body+ assert "Use `--create-session --same-scope` for one visible sibling Session" in body+ assert "`--create-session-per-run --same-scope` for a separate visible Session per event" in body+ assert "Use `--scope-id <scopes.id>` instead of `--same-scope`" in bodyassert "Avibe uses the command's current working directory" in bodyassert "each follow-up should run in a visible sibling Session" not in bodyassert ' --session-id "sesk8m4q2p7x"' not in body@@ -189,7 +189,14 @@ def test_background_watch_skill_defaults_to_current_session() -> None:def test_background_watch_skill_uses_bundled_waiters_and_persists_managed_pr_state() -> None:- body = _read("skills/background-watch-hook/SKILL.md")+ entry = _read("skills/background-watch-hook/SKILL.md")+ reference = _read("skills/background-watch-hook/references/waiters.md")+ body = entry + "\n" + reference+ skill = parse_skill_file(ROOT / "skills/background-watch-hook/SKILL.md", priority=(1, 0, 1))+ assert skill is not None+ rendered = render_skill_content(skill)+ assert reference not in rendered+ assert "Read it only for" in entry and "not for routine PR monitoring" in entryassert ('BACKGROUND_WATCH_HOOK_DIR="<directory containing the loaded SKILL.md>"'@@ -215,7 +222,7 @@ def test_background_watch_skill_uses_bundled_waiters_and_persists_managed_pr_staassert "Omit `--sha`" in bodyassert "Use `--forever` and one" in bodyassert "never reseed or replace its state between rounds" in body- preferred_section = body.split("### Preferred PR + CI watch", 1)[1]+ preferred_section = entry.split("Preferred PR + CI watch", 1)[1]preferred_forever_command = preferred_section.split('vibe watch add \\\n', 1)[1].split("```", 1)[0]diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.pyindex 784997444..c7fbd49f8 100644--- a/tests/test_wait_for_github_pr_activity.py+++ b/tests/test_wait_for_github_pr_activity.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport ioimport importlib.utilimport json+import re+import shleximport urllib.errorfrom contextlib import redirect_stdoutfrom pathlib import Path@@ -4084,7 +4086,7 @@ def _managed_state(module, path, watch_id: str | None, **fields) -> None:)-def _run_managed(module, state_file, fetch, *, delivery: str = "", extra_args=()):+def _run_managed(module, state_file, fetch, *, delivery: str = "", extra_args=(), token="token"):"""One managed cycle over ``state_file``, told when this watch last delivered."""env = {module.WATCH_ID_ENV: "wat_9", module.LAST_DELIVERY_ENV: delivery}@@ -4092,8 +4094,8 @@ def _run_managed(module, state_file, fetch, *, delivery: str = "", extra_args=()with (patch.dict("os.environ", env, clear=False),patch.object(module, "_fetch_state", side_effect=fetch),- patch.object(module, "get_token", return_value="token"),- patch.object(module, "get_authenticated_login", return_value="tester"),+ patch.object(module, "get_token", return_value=token),+ patch.object(module, "get_authenticated_login", return_value="tester" if token else None),patch("sys.argv",[@@ -4306,7 +4308,7 @@ def _seed_ci_state(module, path, *runs, workflows=("CI",), head="head-1", owner=)-def _ci_cycle(module, path, states, *, delivery="1", workflows=("CI",), settle=0, sha=None, extra_args=()):+def _ci_cycle(module, path, states, *, delivery="1", workflows=("CI",), settle=0, sha=None, extra_args=(), token="token"):"""Use real cursor IO in tmp_path, fake GitHub, and a bounded virtual clock."""clock = 0.0polls = iter(states)@@ -4333,6 +4335,7 @@ def _ci_cycle(module, path, states, *, delivery="1", workflows=("CI",), settle=0path,fetch,delivery=delivery,+ token=token,extra_args=(*ci_args, *sha_args, "--interval", "1", "--timeout", "100","--settle", str(settle), *extra_args,@@ -4340,6 +4343,956 @@ def _ci_cycle(module, path, states, *, delivery="1", workflows=("CI",), settle=0)+COALESCED_HEAD = "a" * 40+++def _clean_codex_comment(comment_id=601, *, head=COALESCED_HEAD, author="chatgpt-codex-connector[bot]"):+ return {+ "id": comment_id,+ "body": f"Codex Review: Didn't find any major issues.\n\n**Reviewed commit:** `{head[:7]}`",+ "user": {"login": author},+ "created_at": f"2026-10-15T08:00:{comment_id % 60:02d}Z",+ "html_url": f"https://github.com/example/repo/pull/153#issuecomment-{comment_id}",+ }+++def _success_state(*runs, clean=False, head=COALESCED_HEAD, **items):+ state = _pr_state(+ issue_comments=[_clean_codex_comment(head=head)] if clean else items.pop("issue_comments", []),+ **items,+ )+ state["pull_request"]["head"] = {"sha": head}+ state["actions"] = list(runs)+ return state++[email protected]("first", ["ci", "review"])+def test_coalesced_success_waits_for_both_gates_across_restart_and_delivers_once(tmp_path, first):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ green = _ci_run(head=COALESCED_HEAD)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ half = _success_state(green) if first == "ci" else _success_state(pending, clean=True)+ options = ("--coalesce-success",)++ rc, output, payload = _ci_cycle(module, path, [half], extra_args=options)+ assert rc == 124 # Virtual-clock timeout proves that no Agent event was emitted.+ assert output == ""+ assert module.STAGED_KEY not in payload++ both = _success_state(green, clean=True)+ rc, output, payload = _ci_cycle(module, path, [both], extra_args=options)+ assert rc == 0+ assert "CI + Codex review success candidate" in output+ assert "GitHub Actions success" in output+ assert "Didn't find any major issues" in output+ assert payload[module.STAGED_KEY]["output"] == output.strip()++ # No delivery stamp change: replay exactly, even if the live evidence is gone.+ rc, replay, _ = _ci_cycle(module, path, [_success_state()], extra_args=options)+ assert rc == 0+ assert replay == output++ # Acknowledgement and a process restart may not turn the same level into an edge.+ rc, repeated, _ = _ci_cycle(module, path, [both], delivery="2", extra_args=options)+ assert rc == 124+ assert repeated == ""++[email protected]("shape", ["comment", "review", "reaction", "api-reaction"])+def test_coalesced_success_recognizes_all_supported_codex_shapes(tmp_path, shape):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ items = {"issue_comments": [_clean_codex_comment()]}+ if shape == "review":+ review = {**_clean_codex_comment(), "state": "COMMENTED", "commit_id": COALESCED_HEAD}+ items = {"reviews": [review]}+ elif "reaction" in shape:+ login = "chatgpt-codex-connector" if shape == "api-reaction" else "chatgpt-codex-connector[bot]"+ items = {"reactions": [{"id": 701, "content": "+1", "user": {"login": login}}]}++ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(module, path, [_success_state(pending, **items)], extra_args=options)+ assert (rc, output) == (124, "")+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), **items)], extra_args=options,+ )+ assert rc == 0+ assert "CI + Codex review success candidate" in output++[email protected]("event", ["inline", "changes-requested", "error", "unknown", "wrong-sha", "spoof", "reviewed-only"])+def test_coalescing_never_hides_findings_errors_or_unknown_evidence(tmp_path, event):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ items = {"issue_comments": [{**_clean_codex_comment(), "body": "Something went wrong. Please try again."}]}+ if event == "inline":+ items = {"review_comments": [_review_comment(501)]}+ elif event == "changes-requested":+ items = {"reviews": [{**_clean_codex_comment(), "state": "CHANGES_REQUESTED", "body": "Fix this"}]}+ elif event == "unknown":+ items = {"issue_comments": [{**_clean_codex_comment(), "body": "A new verdict format worth inspecting"}]}+ elif event == "wrong-sha":+ items = {"issue_comments": [_clean_codex_comment(head="b" * 40)]}+ elif event == "spoof":+ items = {"issue_comments": [_clean_codex_comment(author="another-person")]}+ elif event == "reviewed-only":+ items = {"issue_comments": [{**_clean_codex_comment(), "body": f"Reviewed commit: `{COALESCED_HEAD}`"}]}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, **items)], extra_args=("--coalesce-success",),+ )+ assert rc == 0+ assert "success candidate" not in output+ assert "GitHub PR activity" in output++[email protected]("other", ["missing", "running", "missing-known-run"])+def test_coalesced_ci_failure_reports_before_other_workflows_and_is_not_repeated(tmp_path, other):+ module = _load_module()+ path = tmp_path / "ci.json"+ workflows = ("CI", "Security")+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ security = _ci_run(8, head=COALESCED_HEAD, workflow="Security", status="in_progress", conclusion=None)+ initial = (pending, security) if other == "missing-known-run" else (pending,)+ _seed_ci_state(module, path, *initial, workflows=workflows, head=COALESCED_HEAD)+ failure = _ci_run(head=COALESCED_HEAD, conclusion="failure")+ runs = (failure, security) if other == "running" else (failure,)+ options = ("--coalesce-success",)++ rc, output, _ = _ci_cycle(+ module, path, [_success_state(*runs)], workflows=workflows, settle=1, extra_args=options,+ )+ assert rc == 0+ assert "GitHub Actions failure" in output+ assert "Still waiting for workflow(s): Security" in output++ # Another workflow finishing is not a new failure or a combined success.+ complete = _success_state(failure, {**security, "status": "completed", "conclusion": "success"})+ rc, output, _ = _ci_cycle(module, path, [complete], delivery="2", workflows=workflows, extra_args=options)+ assert (rc, output) == (124, "")+ newer = _success_state({**failure, "run_attempt": 2}, {**security, "status": "completed", "conclusion": "success"})+ rc, output, _ = _ci_cycle(module, path, [newer], delivery="2", workflows=workflows, extra_args=options)+ assert rc == 0+ assert "GitHub Actions failure" in output+++def test_deferred_review_survives_an_unrelated_report_and_acknowledgement(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ assert (rc, output) == (124, "")+ comments = [_clean_codex_comment(), {"id": 602, "body": "Please check this too", "user": {"login": "human"}}]+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=comments)], extra_args=options,+ )+ assert rc == 0+ assert "Please check this too" in output+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), issue_comments=comments)],+ delivery="2", extra_args=options,+ )+ assert rc == 0+ assert "CI + Codex review success candidate" in output++[email protected]("invalidation", ["delete", "edit-to-error", "finding"])+def test_deferred_review_is_invalidated_until_a_new_clean_verdict(tmp_path, invalidation):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ assert (rc, output) == (124, "")+ items = {}+ if invalidation == "edit-to-error":+ items = {"issue_comments": [{+ **_clean_codex_comment(), "body": "Something went wrong", "updated_at": "2026-10-15T08:00:02Z",+ }]}+ elif invalidation == "finding":+ items = {+ "issue_comments": [_clean_codex_comment()],+ "review_comments": [_review_comment(501, created_at="2026-10-15T08:00:02Z")],+ }+ broken = _success_state(_ci_run(head=COALESCED_HEAD), **items)+ rc, output, _ = _ci_cycle(module, path, [broken], extra_args=options)+ assert rc == 0+ assert "success candidate" not in output+ rc, output, _ = _ci_cycle(module, path, [broken], delivery="2", extra_args=options)+ assert (rc, output) == (124, "")+ fixed = {**broken, "issue_comments": [*broken["issue_comments"], _clean_codex_comment(603)]}+ rc, output, _ = _ci_cycle(module, path, [fixed], delivery="2", extra_args=options)+ assert rc == 0+ assert "success candidate" in output+++def test_coalescing_never_binds_an_existing_or_head_transition_reaction(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ baseline = _success_state(pending, reactions=[{+ "id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"},+ }])+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, baseline),+ actions=module.normalize_selected_runs({"CI": [pending]}))+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(+ module, path, [{**baseline, "actions": [_ci_run(head=COALESCED_HEAD)]}], extra_args=options,+ )+ assert (rc, output) == (124, "")+ moved = _success_state(_ci_run(head="b" * 40), head="b" * 40, reactions=[+ *baseline["reactions"], {**baseline["reactions"][0], "id": 702},+ ])+ rc, output, _ = _ci_cycle(module, path, [moved], extra_args=options)+ assert rc == 0+ assert "pr_head" in output and "pr_reaction #702" in output+ assert "success candidate" not in output+ rc, output, _ = _ci_cycle(module, path, [moved], delivery="2", extra_args=options)+ assert (rc, output) == (124, "")+++def test_coalescing_resets_old_head_evidence_without_mixing_ci(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ new_head = "b" * 40+ moved = _success_state(_ci_run(head=new_head), head=new_head, issue_comments=[_clean_codex_comment()])+ rc, output, _ = _ci_cycle(module, path, [moved], extra_args=options)+ assert rc == 0 and "pr_head" in output and "success candidate" not in output+ rc, output, _ = _ci_cycle(module, path, [moved], delivery="2", extra_args=options)+ assert (rc, output) == (124, "")+ moved["issue_comments"].append(_clean_codex_comment(602, head=new_head))+ rc, output, _ = _ci_cycle(module, path, [moved], delivery="2", extra_args=options)+ assert rc == 0+ assert "success candidate" in output+ assert f"@{new_head[:12]}" in output++[email protected]("footer_layout", ["split", "inline"])[email protected]("status", [+ "Running", "Completed", "Something went wrong", "Unavailable",+ "Completed with errors", "Completed / findings", "Running slowly",+])+def test_coalescing_ignores_codex_summary_progress_but_not_errors(tmp_path, status, footer_layout):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ footer_intro = {+ "split": (+ "[Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general).\n"+ "Codex reviews are triggered when you"+ ),+ "inline": "[Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you",+ }[footer_layout]+ summary = {**_clean_codex_comment(), "body": (+ "<!-- codex-pull-request-review-summary -->\n"+ "<!-- codex-review-state:v1 {\"code_review\":{\"status\":\"running\"}} -->\n"+ "## Codex Review Summary\n\n"+ "This comment shows the latest Codex review activity on this pull request.\n\n"+ "| Review | Status | Commit | Review trigger |\n"+ "| --- | --- | --- | --- |\n"+ f"| 📝 **Code Review** | ✅ **{status}** | `{COALESCED_HEAD[:7]}` | New commits |\n\n"+ "<details> <summary>ℹ️ About Codex in GitHub</summary>\n"+ "<br/>\n"+ f"{footer_intro}\n"+ "- Open a pull request for review\n"+ "- Mark a draft as ready\n"+ "- Comment \"@codex review\" or \"@codex security review\".\n"+ "Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.\n"+ "</details>"+ )}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[summary])], extra_args=("--coalesce-success",),+ )+ if status not in {"Running", "Completed"}:+ assert rc == 0 and "issue_comment #601" in output+ else:+ assert (rc, output) == (124, "")+++def test_coalescing_surfaces_an_unknown_codex_summary_footer(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ summary = {**_clean_codex_comment(), "body": (+ "<!-- codex-pull-request-review-summary -->\n"+ "<!-- codex-review-state:v1 {\"code_review\":{\"status\":\"running\"}} -->\n"+ "## Codex Review Summary\n\n"+ "This comment shows the latest Codex review activity on this pull request.\n\n"+ "| Review | Status | Commit | Review trigger |\n"+ "| --- | --- | --- | --- |\n"+ f"| 📝 **Code Review** | 🔄 **Running** | `{COALESCED_HEAD[:7]}` | New commits |\n\n"+ "<details><summary>About Codex in GitHub</summary>\n"+ "The reviewer noted an authentication bypass in the generated report.\n"+ "</details>"+ )}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[summary])], extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "issue_comment #601" in output+ assert "success candidate" not in output+++def test_coalescing_surfaces_an_unrecognized_summary_row(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ footer = "\n".join(module.CODEX_STANDARD_SUMMARY_FOOTER)+ summary = {**_clean_codex_comment(), "body": (+ "<!-- codex-pull-request-review-summary -->\n"+ "<!-- codex-review-state:v1 {\"code_review\":{\"status\":\"running\"}} -->\n"+ "## Codex Review Summary\n\n"+ "This comment shows the latest Codex review activity on this pull request.\n\n"+ "| Review | Status | Commit | Review trigger |\n"+ "| --- | --- | --- | --- |\n"+ f"| Review findings: race allows duplicates | Completed | `{COALESCED_HEAD[:7]}` | New commits |\n\n"+ f"{footer}"+ )}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[summary])], extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "issue_comment #601" in output+ assert "success candidate" not in output+++def test_coalescing_policy_requires_ci_and_has_independent_cursor_ownership():+ module = _load_module()+ parser = module._build_parser()+ base = ["--repo", "avibe-bot/avibe", "--pr", "153"]+ assert module._validate_ci_args(parser.parse_args([*base, "--coalesce-success"])) is not None+ ordinary = parser.parse_args([*base, "--workflow", "CI"])+ coalesced = parser.parse_args([*base, "--workflow", "CI", "--coalesce-success"])+ assert module._watch_identity(ordinary) != module._watch_identity(coalesced)+ assert module._watch_identity(ordinary) not in module._legacy_watch_identity_aliases(coalesced, None)++[email protected]("metadata", ["timestamp", "profile", "bot-alias"])+def test_deferred_review_ignores_nonsemantic_metadata_changes(tmp_path, metadata):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ assert (rc, output) == (124, "")+ verdict = _clean_codex_comment()+ if metadata == "timestamp":+ verdict["updated_at"] = "2026-10-15T08:00:00Z"+ elif metadata == "profile":+ verdict["user"] = {**verdict["user"], "avatar_url": "https://example.com/new-avatar.png"}+ else:+ verdict["user"] = {"login": "chatgpt-codex-connector"}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[verdict])], extra_args=options,+ )+ assert (rc, output) == (124, "")+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), issue_comments=[verdict])], extra_args=options,+ )+ assert rc == 0 and "success candidate" in output++[email protected]("new_ci", ["rerun", "new-run"])+def test_coalesced_success_reports_a_new_ci_pair_without_repeating_the_old_pair(tmp_path, new_ci):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ green = _ci_run(head=COALESCED_HEAD)+ rc, output, _ = _ci_cycle(module, path, [_success_state(green, clean=True)], extra_args=options)+ assert rc == 0 and "success candidate" in output+ next_runs = [{**green, "run_attempt": 2}] if new_ci == "rerun" else [green, {**green, "id": 8}]+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(*next_runs, clean=True)], delivery="2", extra_args=options,+ )+ assert rc == 0 and "success candidate" in output+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(*next_runs, clean=True)], delivery="3", extra_args=options,+ )+ assert (rc, output) == (124, "")++[email protected]("location", ["committed", "pending"])+def test_malformed_deferred_success_evidence_does_not_overwrite_history(tmp_path, location):+ module = _load_module()+ path = tmp_path / "ci.json"+ _seed_ci_state(module, path, _ci_run(head=COALESCED_HEAD), head=COALESCED_HEAD)+ payload = json.loads(path.read_text())+ invalid = {"head_sha": COALESCED_HEAD, "review": {"kind": "not-a-collection", "id": 601}}+ if location == "pending":+ payload[module.STAGED_KEY] = {"delivered_after": "1", "output": "old report", "cursors": {+ module.SUCCESS_BATCH_KEY: invalid,+ }}+ else:+ payload[module.SUCCESS_BATCH_KEY] = invalid+ path.write_text(json.dumps(payload))+ before = path.read_bytes()+ with pytest.raises(module.StateFileUnusableError, match="success_batch"):+ _ci_cycle(module, path, [_success_state()], extra_args=("--coalesce-success",))+ assert path.read_bytes() == before+++def test_preferred_combined_watch_examples_parse_with_the_same_success_policy():+ module = _load_module()+ body = (Path(__file__).resolve().parents[1] / "skills/background-watch-hook/SKILL.md").read_text()+ preferred = body.split("Preferred PR + CI watch", 1)[1].split("One-shot watch:", 1)[0]+ commands = re.findall(+ r'uv run --no-project "\$BACKGROUND_WATCH_HOOK_DIR/scripts/wait_pr.py"[^\n]*',+ preferred.replace("\\\n", " "),+ )+ assert len(commands) == 2 # The seed and the armed waiter must share ownership.+ args = [module._build_parser().parse_args(shlex.split(command)[4:]) for command in commands]+ assert all(arg.coalesce_success and arg.actionable_only for arg in args)+ assert all(module._validate_ci_args(arg) is None for arg in args)+ assert module._watch_identity(args[0]) == module._watch_identity(args[1])+++def _codex_error(comment_id=602):+ return {**_clean_codex_comment(comment_id), "body": "Something went wrong. Please try again."}+++def test_coalescing_retains_a_later_clean_verdict_in_the_same_error_batch(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ comments = [_codex_error(601), _clean_codex_comment(602)]+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=comments)], extra_args=options,+ )+ assert rc == 0 and "Something went wrong" in output+ assert payload[module.STAGED_KEY]["cursors"][module.SUCCESS_BATCH_KEY]["review"]["id"] == 602+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), issue_comments=comments)],+ delivery="2", extra_args=options,+ )+ assert rc == 0 and "success candidate" in output+++def test_coalescing_initialization_respects_the_latest_existing_bot_outcome():+ module = _load_module()+ state = _success_state(issue_comments=[_clean_codex_comment(), _codex_error(602)])+ batch, _ = module._coalesced_review_state(state, None, None, initialize=True)+ assert batch["review"] is None+ assert batch["outcome"]["id"] == 602+++def test_coalescing_does_not_rebind_a_restored_old_reaction_after_a_push(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ reaction = {"id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"}}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, reactions=[reaction])], extra_args=options,+ )+ assert (rc, output) == (124, "")+ new_head = "b" * 40+ moved = _success_state(_ci_run(head=new_head), head=new_head)+ rc, output, _ = _ci_cycle(module, path, [moved], extra_args=options)+ assert rc == 0 and "pr_head" in output+ rc, output, _ = _ci_cycle(+ module, path, [{**moved, "reactions": [reaction]}], delivery="2", extra_args=options,+ )+ assert (rc, output) == (124, "")+++def test_coalescing_retains_settle_invalidation_after_the_error_row_disappears(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ first = _success_state(pending, issue_comments=[_clean_codex_comment(), _codex_error()])+ restored = _success_state(_ci_run(head=COALESCED_HEAD), clean=True)+ rc, output, payload = _ci_cycle(module, path, [first, restored, restored], settle=1, extra_args=options)+ assert rc == 0 and "Something went wrong" in output+ assert "success candidate" not in output+ assert payload[module.STAGED_KEY]["cursors"][module.SUCCESS_BATCH_KEY]["review"] is None+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", extra_args=options)+ # The fallback report retained the error's PR snapshot; its later deletion+ # remains ordinary PR activity, but cannot resurrect the old clean verdict.+ assert "success candidate" not in output+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", extra_args=options)+ assert (rc, output) == (124, "")+++def test_coalescing_does_not_restore_old_reactions_when_report_head_differs(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ reaction = {"id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"}}+ original = _success_state(pending, reactions=[reaction])+ _ci_cycle(module, path, [original], extra_args=options)+ transient = _success_state(head="b" * 40)+ restored = {**original, "actions": [_ci_run(head=COALESCED_HEAD)]}+ rc, output, payload = _ci_cycle(module, path, [transient, restored, restored], settle=1, extra_args=options)+ assert rc == 0 and "success candidate" not in output+ staged = payload[module.STAGED_KEY]["cursors"]+ assert staged[module.SUCCESS_BATCH_KEY]["head_sha"] == COALESCED_HEAD+ assert staged["head_sha"] == "b" * 40+ assert staged[module.SUCCESS_BATCH_KEY]["review"] is None+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", extra_args=options)+ assert "success candidate" not in output++[email protected]("suffix", [+ "Something went wrong. Please try again.",+ "P1: fix the race",+ "Changes requested",+ "## Review findings\nRace allows duplicate notifications",+])+def test_coalescing_surfaces_mixed_clean_and_error_text(tmp_path, suffix):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ mixed = _clean_codex_comment()+ mixed["body"] += "\n\n" + suffix+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[mixed])], extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "issue_comment #601" in output+ assert "success candidate" not in output++[email protected]("finding_kind", ["review_comments", "issue_comments"])[email protected]("arrival", ["same-poll", "finding-first", "clean-first"])+def test_coalescing_preserves_invalidations_between_distinct_resources_at_one_timestamp(tmp_path, finding_kind, arrival):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ timestamp = "2026-10-15T08:00:01Z"+ clean = {**_clean_codex_comment(602), "created_at": timestamp}+ older = {**_clean_codex_comment(501), "created_at": "2026-10-15T08:00:00Z"}+ finding = (+ _review_comment(501, body="Race allows duplicate notifications", created_at=timestamp)+ if finding_kind == "review_comments" else {+ **older, "body": "Something went wrong", "updated_at": timestamp,+ }+ )++ def snapshot(run, finding_item=None, clean_item=clean):+ items = {"issue_comments": [clean_item] if clean_item else []}+ if finding_item is not None:+ items.setdefault(finding_kind, []).append(finding_item)+ return _success_state(run, **items)++ first_finding = finding if arrival != "clean-first" else (+ older if finding_kind == "issue_comments" else None+ )+ first = snapshot(pending, first_finding, None if arrival == "finding-first" else clean)+ event = "review_comment #501" if finding_kind == "review_comments" else "issue_comment #501"+ rc, output, _ = _ci_cycle(module, path, [first], extra_args=options)+ if arrival == "clean-first":+ assert (rc, output) == (124, "")+ else:+ assert rc == 0 and event in output+ assert "success candidate" not in output++ both = snapshot(pending, finding)+ rc, output, _ = _ci_cycle(module, path, [both], delivery="2", extra_args=options)+ if arrival == "clean-first":+ assert rc == 0 and event in output+ assert "success candidate" not in output+ green = _ci_run(head=COALESCED_HEAD)+ rc, output, payload = _ci_cycle(+ module, path, [snapshot(green, finding)], delivery="3", extra_args=options,+ )+ assert (rc, output) == (124, "")+ assert payload[module.SUCCESS_BATCH_KEY]["review"] is None+ assert payload[module.SUCCESS_BATCH_KEY]["outcome"]["id"] == 501++ # An observed edit of that exact resource is ordered; unrelated IDs are not.+ recovered = snapshot(green, finding, _clean_codex_comment(603))+ if finding_kind == "issue_comments":+ recovered = snapshot(green, {**finding, "body": older["body"]})+ rc, output, _ = _ci_cycle(module, path, [recovered], delivery="3", extra_args=options)+ assert rc == 0 and "success candidate" in output+++def test_coalescing_rejects_contradictory_reviewed_shas(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ review = {+ **_clean_codex_comment(),+ "state": "COMMENTED",+ "commit_id": COALESCED_HEAD,+ "body": "Codex Review: Didn't find any major issues.\n\n**Reviewed commit:** `bbbbbbb`",+ }+ state = _success_state(_ci_run(head=COALESCED_HEAD), reviews=[review])+ rc, output, _ = _ci_cycle(module, path, [state], extra_args=("--coalesce-success",))+ assert rc == 0 and "review #601" in output+ assert "success candidate" not in output+++def test_coalesced_failure_never_reports_or_commits_an_older_attempt(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ current = _ci_run(head=COALESCED_HEAD, attempt=2)+ _seed_ci_state(module, path, current, head=COALESCED_HEAD)+ old_failure = _ci_run(head=COALESCED_HEAD, attempt=1, conclusion="failure")+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(old_failure)], extra_args=("--coalesce-success",),+ )+ assert (rc, output) == (124, "")+ assert payload["actions"]["CI"][0]["run_attempt"] == 2++[email protected]("regression", ["missing", "nonterminal"])+def test_coalesced_partial_failure_reports_preserve_all_acknowledged_failures(tmp_path, regression):+ module = _load_module()+ path = tmp_path / "ci.json"+ first = _ci_run(head=COALESCED_HEAD, conclusion="failure")+ pending = _ci_run(8, head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(module, path, [_success_state(first, pending)], extra_args=options)+ assert rc == 0 and "failure" in output+ second = {**pending, "status": "completed", "conclusion": "failure"}+ partial = _success_state(second) if regression == "missing" else _success_state(+ {**first, "status": "in_progress", "conclusion": None}, second,+ )+ rc, output, _ = _ci_cycle(module, path, [partial], delivery="2", extra_args=options)+ assert rc == 0 and "failure" in output+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(first, second)], delivery="3", extra_args=options,+ )+ assert (rc, output) == (124, "")+ assert {run["id"] for run in payload["actions"]["CI"]} == {7, 8}++[email protected]("replay", [("--catch-up",), ("--since-reaction-id", "0")])+def test_coalescing_replays_unbound_reactions_as_activity(tmp_path, replay):+ module = _load_module()+ path = tmp_path / "ci.json"+ green = _ci_run(head=COALESCED_HEAD)+ reaction = {"id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"}}+ state = _success_state(green, reactions=[reaction])+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, state),+ actions=module.normalize_selected_runs({"CI": [green]}))+ rc, output, _ = _ci_cycle(+ module, path, [state], extra_args=("--coalesce-success", *replay),+ )+ assert rc == 0 and "pr_reaction #701" in output+ assert "success candidate" not in output++[email protected]("replay", [(), ("--catch-up",), ("--since-reaction-id", "0")])+def test_coalescing_preserves_known_threads_when_graphql_is_unavailable(tmp_path, replay):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ unresolved = [{"id": "thread-1", "isResolved": False}]+ baseline = _success_state(pending, review_threads=unresolved)+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, baseline),+ actions=module.normalize_selected_runs({"CI": [pending]}))+ options = ("--coalesce-success",)+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, clean=True, review_threads=unresolved)], extra_args=options,+ )+ assert (rc, output) == (124, "")+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), clean=True)], token=None,+ extra_args=(*options, "--allow-unauthenticated", *replay),+ )+ if replay == ("--catch-up",):+ assert rc == 0 and "issue_comment #601" in output+ else:+ assert (rc, output) == (124, "")+ assert "success candidate" not in output+ assert payload["review_thread_states"] == {"thread-1": False}+ effective = payload.get(module.STAGED_KEY, {}).get("cursors", payload)+ assert effective["snapshot"]["review_threads"] == {"thread-1": False}++ # Only an authenticated resolved observation can unblock the paired result.+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), clean=True,+ review_threads=[{"id": "thread-1", "isResolved": True}])],+ delivery="2", extra_args=options,+ )+ assert rc == 0 and "success candidate" in output++[email protected]("phase", ["startup", "settle"])+def test_coalescing_never_settles_away_an_observed_ci_failure(tmp_path, phase):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ failed = _success_state(_ci_run(head=COALESCED_HEAD, conclusion="failure"))+ states = [failed, _success_state()]+ if phase == "settle":+ states.insert(0, _success_state(pending, issue_comments=[{+ "id": 601, "body": "Please inspect this", "user": {"login": "human"},+ }]))+ rc, output, payload = _ci_cycle(+ module, path, states, settle=1, extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "GitHub Actions failure" in output+ assert payload[module.STAGED_KEY]["cursors"]["actions"]["CI"][0]["conclusion"] == "failure"+++def test_coalescing_preserves_a_fresh_reaction_for_the_latest_observed_head(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ reaction = {"id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"}}+ returned = _success_state({**pending, "run_attempt": 2})+ fresh = {**returned, "reactions": [reaction]}+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(head="b" * 40), returned, fresh], settle=1, extra_args=options,+ )+ assert rc == 0 and "success candidate" not in output+ observed = payload[module.STAGED_KEY]["cursors"][module.SUCCESS_BATCH_KEY]+ assert observed["head_sha"] == COALESCED_HEAD and observed["review"]["id"] == 701+ rc, output, _ = _ci_cycle(module, path, [fresh], delivery="2", extra_args=options)+ assert "success candidate" not in output+ green = {**fresh, "actions": [_ci_run(head=COALESCED_HEAD, attempt=2)]}+ rc, output, _ = _ci_cycle(module, path, [green], delivery="3", extra_args=options)+ assert rc == 0 and "success candidate" in output+++def test_coalescing_never_silences_a_finding_appended_to_a_progress_summary(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ summary = {**_clean_codex_comment(), "body": (+ "<!-- codex-pull-request-review-summary -->\n"+ "| Review | Status | Commit | Review trigger |\n| --- | --- | --- | --- |\n"+ f"| Code Review | **Completed** | `{COALESCED_HEAD[:7]}` | New commits |\n"+ "## Review findings\n"+ "Race allows duplicate notifications"+ )}+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[summary])], extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "issue_comment #601" in output+ assert "success candidate" not in output+++def test_coalescing_remembers_semantics_across_missing_rows_and_timestamp_changes(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ _ci_cycle(module, path, [_success_state(pending, clean=True)], extra_args=options)+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[_codex_error()])], extra_args=options,+ )+ assert rc == 0 and "success candidate" not in output+ old_clean = {**_clean_codex_comment(), "updated_at": "2026-10-15T08:01:00Z"}+ restored = _success_state(_ci_run(head=COALESCED_HEAD), issue_comments=[old_clean])+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="2", extra_args=options)+ assert "success candidate" not in output+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", extra_args=options)+ assert (rc, output) == (124, "")+ restored["issue_comments"].append(_clean_codex_comment(603))+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", extra_args=options)+ assert rc == 0 and "success candidate" in output+++def test_coalescing_preserves_latest_threads_when_settle_reports_an_older_transition(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ unresolved = [{"id": "thread-1", "isResolved": False}]+ baseline = _success_state(pending, review_threads=unresolved)+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, baseline),+ actions=module.normalize_selected_runs({"CI": [pending]}))+ options = ("--coalesce-success",)+ current = _success_state(pending, clean=True, review_threads=unresolved)+ assert _ci_cycle(module, path, [current], extra_args=options)[:2] == (124, "")+ resolved = {**current, "review_threads": [{"id": "thread-1", "isResolved": True}]}+ rc, output, _ = _ci_cycle(module, path, [resolved, current], settle=1, extra_args=options)+ assert rc == 0 and "success candidate" not in output+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(_ci_run(head=COALESCED_HEAD), clean=True)], delivery="2", token=None,+ extra_args=(*options, "--allow-unauthenticated"),+ )+ assert (rc, output) == (124, "")+ assert payload[module.SUCCESS_BATCH_KEY]["thread_states"] == {"thread-1": False}+++def test_coalescing_binds_a_new_reaction_after_restart_to_the_latest_observed_head(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ returned = _success_state({**pending, "run_attempt": 2})+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(head="b" * 40), returned], settle=1, extra_args=options,+ )+ assert rc == 0 and "success candidate" not in output+ reaction = {"id": 701, "content": "+1", "user": {"login": "chatgpt-codex-connector[bot]"}}+ fresh = {**returned, "reactions": [reaction]}+ rc, output, payload = _ci_cycle(module, path, [fresh], delivery="2", extra_args=options)+ assert rc == 0 and "success candidate" not in output+ assert payload[module.STAGED_KEY]["cursors"][module.SUCCESS_BATCH_KEY]["review"]["id"] == 701+ green = {**fresh, "actions": [_ci_run(head=COALESCED_HEAD, attempt=2)]}+ rc, output, _ = _ci_cycle(module, path, [green], delivery="3", extra_args=options)+ assert rc == 0 and "success candidate" in output++[email protected]("same_timestamp", [False, True])+def test_coalescing_reawakens_for_stronger_review_evidence_with_unchanged_ci(tmp_path, same_timestamp):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ reaction = {+ "id": 701, "content": "+1", "created_at": "2026-10-15T08:00:00Z",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+ state = _success_state(_ci_run(head=COALESCED_HEAD), reactions=[reaction])+ rc, output, _ = _ci_cycle(module, path, [state], extra_args=options)+ assert rc == 0 and "success candidate" in output and "pr_reaction #701" in output+ # The Agent rejected the reaction's epoch proof and requested a SHA verdict.+ clean = _clean_codex_comment()+ if same_timestamp:+ clean = {**clean, "created_at": reaction["created_at"]}+ state = {**state, "issue_comments": [clean]}+ rc, output, _ = _ci_cycle(module, path, [state], delivery="2", extra_args=options)+ assert rc == 0 and "success candidate" in output and "issue_comment #601" in output+ rc, output, _ = _ci_cycle(module, path, [state], delivery="3", extra_args=options)+ assert (rc, output) == (124, "")+++def test_coalesced_candidate_explicitly_rejects_a_pinned_ci_head_mismatch(tmp_path):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ # The fetcher already drops this mismatch; also protect the composite+ # consumer if fixed-SHA polling is later allowed to retain that CI inventory.+ moved = _success_state(_ci_run(head=COALESCED_HEAD), head="b" * 40, clean=True)+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending), moved], sha=COALESCED_HEAD,+ extra_args=("--coalesce-success",),+ )+ assert rc == 0 and "pr_head" in output+ assert "success candidate" not in output++[email protected]("kind", ["issue_comments", "reviews"])[email protected]("ci_complete", [False, True])[email protected]("catch_up", [False, True])+def test_coalescing_preserves_requested_clean_verdict_replay(tmp_path, kind, ci_complete, catch_up):+ module = _load_module()+ path = tmp_path / "ci.json"+ run = _ci_run(head=COALESCED_HEAD) if ci_complete else _ci_run(+ head=COALESCED_HEAD, status="in_progress", conclusion=None,+ )+ verdict = _clean_codex_comment()+ if kind == "reviews":+ verdict = {**verdict, "state": "COMMENTED", "commit_id": COALESCED_HEAD}+ state = _success_state(run, **{kind: [verdict]})+ cursor = "issue_comment_cursor" if kind == "issue_comments" else "review_cursor"+ _managed_state(module, path, "wat_9", **_complete_pr_baseline_fields(module, state),+ **{cursor: 601}, actions=module.normalize_selected_runs({"CI": [run]}))+ flags = ("--catch-up",) if catch_up else (("--since-issue-comment-id", "0") if kind == "issue_comments" else ("--since-review-id", "0"))+ rc, output, payload = _ci_cycle(+ module, path, [state], extra_args=("--coalesce-success", *flags),+ )+ event = "issue_comment #601" if kind == "issue_comments" else "review #601"+ assert rc == 0 and event in output+ if not catch_up:+ assert "GitHub Actions" not in output # Explicit PR replay baselines unrelated CI.+ assert payload[module.STAGED_KEY]["cursors"][cursor] == 601++[email protected]("catch_up", [False, True])[email protected]("kind", ["issue_comments", "reviews"])[email protected]("metadata_only_update", [False, True])+def test_deliberate_replay_preserves_a_newer_invalidating_outcome(tmp_path, catch_up, kind, metadata_only_update):+ module = _load_module()+ path = tmp_path / "ci.json"+ pending = _ci_run(head=COALESCED_HEAD, status="in_progress", conclusion=None)+ _seed_ci_state(module, path, pending, head=COALESCED_HEAD)+ options = ("--coalesce-success",)+ old_clean = _clean_codex_comment(601)+ if kind == "reviews":+ old_clean = {**old_clean, "state": "COMMENTED", "commit_id": COALESCED_HEAD}++ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, **{kind: [old_clean]})], extra_args=options,+ )+ assert (rc, output) == (124, "")+ error = _codex_error(602)+ rc, output, _ = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[error])], extra_args=options,+ )+ assert rc == 0 and "Something went wrong" in output+ rc, output, payload = _ci_cycle(+ module, path, [_success_state(pending, issue_comments=[error])],+ delivery="2", extra_args=options,+ )+ assert (rc, output) == (124, "")+ assert payload[module.SUCCESS_BATCH_KEY]["outcome"]["id"] == 602+ assert payload[module.SUCCESS_BATCH_KEY]["review"] is None++ # Replay may restore a row, but metadata alone is not a new verdict.+ if metadata_only_update:+ old_clean = {**old_clean, "updated_at": "2026-10-15T08:01:00Z"}+ replay = ("--catch-up",) if catch_up else (+ ("--since-review-id", "0") if kind == "reviews" else ("--since-issue-comment-id", "0")+ )+ replay_state = _success_state(pending, **{kind: [old_clean]})+ rc, output, _ = _ci_cycle(+ module, path, [replay_state], delivery="2",+ extra_args=(*options, *replay),+ )+ event = "review #601" if kind == "reviews" else "issue_comment #601"+ assert rc == 0 and event in output+ assert "success candidate" not in output++ green = _ci_run(head=COALESCED_HEAD)+ restored = _success_state(green, **{kind: [old_clean]})+ rc, output, payload = _ci_cycle(+ module, path, [restored], delivery="3", extra_args=options,+ )+ assert (rc, output) == (124, "")+ assert payload[module.SUCCESS_BATCH_KEY]["outcome"]["id"] == 602+ assert payload[module.SUCCESS_BATCH_KEY]["review"] is None++ fresh = _clean_codex_comment(603)+ if kind == "reviews":+ fresh = {**fresh, "state": "COMMENTED", "commit_id": COALESCED_HEAD}+ restored[kind].append(fresh)+ rc, output, _ = _ci_cycle(module, path, [restored], delivery="3", extra_args=options)+ assert rc == 0 and "success candidate" in output++@pytest.mark.parametrize("intermediate", ["missing", "nonterminal", "older-attempt", "partial"])def test_combined_ci_does_not_reannounce_observed_results_after_snapshot_regression(tmp_path, intermediate):module = _load_module()