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
perf(harness): quiet, cheap, batch-aware PR watches (#1170)
Qi Qidf01e161eb7d
diff --git a/core/command_runner.py b/core/command_runner.pyindex d67232a35..1a1badb17 100644--- a/core/command_runner.py+++ b/core/command_runner.py@@ -18,7 +18,7 @@ import sysfrom collections import dequefrom dataclasses import dataclassfrom pathlib import Path-from typing import Callable, Optional+from typing import Callable, Mapping, Optionalfrom core import watch_workerfrom core.process_isolation import (@@ -275,16 +275,21 @@ async def run_supervised_command(label: str,on_spawn: Optional[Callable[[int, Optional[PersistedProcessIdentity]], None]] = None,max_output_bytes: Optional[int] = None,+ extra_env: Optional[Mapping[str, str]] = None,) -> SupervisedCommandResult:"""Run one command under the stable supervisor and return its outcome.``timeout_seconds <= 0`` means no timeout. ``max_output_bytes`` of ``None``keeps exact ``communicate()`` semantics; a value caps the retained bytes per- stream while still draining the child to EOF.+ stream while still draining the child to EOF. ``extra_env`` is added to the+ environment the supervisor hands the command, for context the command can only+ learn from its caller."""worker_marker = new_process_identity_marker()spawn_env = process_identity_subprocess_env(worker_marker)+ if extra_env:+ spawn_env.update(extra_env)process = await asyncio.create_subprocess_exec(os.path.abspath(sys.executable),os.fspath(Path(watch_worker.__file__).resolve()),diff --git a/core/watches.py b/core/watches.pyindex 442dd629d..25079e7c5 100644--- a/core/watches.py+++ b/core/watches.py@@ -39,6 +39,7 @@ from core.runtime_work import (from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStorefrom storage.background import (DEFINITION_CYCLE_COLUMNS,+ NO_EVENT_EXIT_CODE,DefinitionWriteConflict,DefinitionWriteExpectation,SQLiteBackgroundTaskStore,@@ -50,6 +51,53 @@ from vibe.i18n import t as i18n_tlogger = logging.getLogger(__name__)DEFAULT_RETRY_EXIT_CODE = 75+# ``NO_EVENT_EXIT_CODE`` (imported above) marks a waiter that ran to completion and+# decided the cycle is not worth waking the Agent for. It is neither an event (exit 0,+# which authorises a hook) nor a failure (any other non-zero, which authorises a+# failure hook): the cycle is recorded, no hook is built, and the watch ends or+# re-arms quietly. Without it every terminal outcome costs an Agent turn, so waiters+# that can only report "nothing happened" -- green CI, filtered-out review chatter --+# had to either fire a useless turn or spin in forever mode.+#+# It lives in ``storage.background`` because the lifecycle projections there have to+# agree that this code is a CLEAN ending. A second literal here is exactly how the+# supervisor and those projections disagreed about it before.+#+# The code alone is NOT the signal. 64 is BSD ``sysexits`` EX_USAGE, so any watched+# command that rejects its own arguments or configuration exits with it -- and reading+# that as "nothing to report" would swallow the failure notice and, in forever mode,+# rerun the broken command indefinitely. A quiet cycle therefore has to say so: the+# waiter prints this marker, which a command that never heard of the protocol cannot+# emit by accident, and everything else keeps failing loudly.+NO_EVENT_MARKER = "avibe-watch: no-event"+# A quiet cycle's own output is logged rather than stored: it is diagnostic detail, not+# state, and the whole point of the code is that it costs nothing to reach. The limit is+# wider than an error squash because a suppressed summary lists every watched workflow.+NO_EVENT_SUMMARY_LOG_LIMIT = 1000+# The watch id, handed to every waiter through its environment. Waiters that keep+# per-watch state on disk use it as the owner of that state, so two identically+# configured watches cannot silently share one file.+WATCH_ID_ENV = "AVIBE_WATCH_ID"+# How many event reports of this watch have been durably queued as a follow-up, or+# empty for none. A waiter cannot see delivery for itself -- its output only reaches+# the service once the process has exited -- so a waiter that stages the cursors+# covering a reported event records this value alongside them, and a later cycle that+# reads a DIFFERENT value knows the report was delivered and the staged cursors are+# safe to promote. The value is opaque to the waiter, which only ever compares it.+LAST_DELIVERY_ENV = "AVIBE_WATCH_LAST_DELIVERY"+#: The count behind that value, on the watch's own ``metadata``, bumped in the same+#: transaction as the follow-up it acknowledges. Entry: a positive ``int``, absent+#: until the first report is queued.+#:+#: Metadata rather than a lifecycle column because a delivery acknowledgement has a+#: DIFFERENT LIFETIME from cycle history: ``definition_resume_clear_columns`` clears+#: ``last_event_at`` when a ``once`` watch is resumed, correctly -- the resumed watch+#: begins a distinct cycle and its row must not claim an event it has not seen yet --+#: and a stamp that resets there tells the resumed waiter that the report it staged+#: cursors for was never delivered, so it reports the same activity again. What the+#: waiter needs is the one fact a resume must NOT rewrite: that the earlier report+#: left. This count only ever moves forward, for the life of the watch.+DELIVERY_ACK_METADATA_KEY = "delivered_reports"WATCH_RECONCILE_INTERVAL_SECONDS = 2.0WATCH_STORE_RECONCILE_FUSE_FAILURES = 3WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS = 2 * DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS@@ -172,6 +220,20 @@ class ManagedWatch:)+def _delivered_reports(watch: ManagedWatch) -> int:+ """How many of this watch's event reports have been queued as a follow-up.++ Anything that is not a positive ``int`` reads as none: a row from before the count+ existed, or metadata some other writer corrupted. That direction is the safe one --+ a waiter comparing against a count that went backwards reports its staged event a+ second time, where one that went forwards would advance past activity it never+ delivered.+ """++ value = watch.metadata.get(DELIVERY_ACK_METADATA_KEY)+ return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0++def _missing_watch_cwd_error(watch: ManagedWatch) -> Optional[str]:if not watch.cwd or Path(watch.cwd).is_dir():return None@@ -697,6 +759,12 @@ class ManagedWatchStore:watch.last_error = errorif event_detected:watch.last_event_at = now+ # A NEW dict: ``expect`` above was derived from the stored one and has to+ # keep describing the row as it was read.+ watch.metadata = {+ **watch.metadata,+ DELIVERY_ACK_METADATA_KEY: _delivered_reports(watch) + 1,+ }if disable:watch.enabled = Falsewatch.updated_at = _utc_now_iso()@@ -790,6 +858,18 @@ class _CycleResult:timed_out: bool+def _cycle_env(watch: ManagedWatch) -> dict[str, str]:+ """What one waiter cycle is told about itself.++ The watch id lets a waiter own its on-disk state, so two identically configured+ watches cannot silently share a state file. The delivery count lets a waiter that+ staged cursors for a reported event tell whether that report was delivered.+ """++ delivered = _delivered_reports(watch)+ return {WATCH_ID_ENV: watch.id, LAST_DELIVERY_ENV: str(delivered) if delivered else ""}++@dataclass(frozen=True)class _StaleWorkerRecovery:recovered: bool@@ -1736,10 +1816,53 @@ class ManagedWatchService:prompt=_build_prompt(watch.message or watch.prefix, result.stdout),):return+ # The delivery count moved in the same transaction as the hook, so the+ # report is durable and every later cycle can see that it was -- after a+ # restart, and after a resume, which is the only reason it lives outside+ # the lifecycle columns. Nothing to carry in memory: the next iteration+ # re-reads the watch.if watch.mode != "forever":returncontinue+ if _is_quiet_cycle(result):+ # A quiet cycle still has to leave a trace. Its output is the ONLY+ # record of what the waiter saw and chose not to report -- a green CI+ # summary, the review comments a filter swallowed -- and no hook+ # carries it, so without this line it is discarded with the process.+ # The stamp says a cycle ran and found nothing; the log says what.+ summary = _squash_tail(result.stderr, limit=NO_EVENT_SUMMARY_LOG_LIMIT) or _squash_tail(+ result.stdout, limit=NO_EVENT_SUMMARY_LOG_LIMIT+ )+ logger.info(+ "Watch cycle found nothing to report watch_id=%s name=%s%s",+ watch.id,+ watch.name or "-",+ f": {summary}" if summary else "",+ )+ # No prompt, prefix or body: ``_hook_request`` returns None, so this+ # commits the cycle WITHOUT authorising a hook. The stamp still lands,+ # so ``vibe watch show`` can say the cycle ran and found nothing.+ #+ # Through the async wrapper like every other result branch: a store+ # failure here must fuse the store and stop the watch, not escape+ # ``_run_cycle`` and kill the task silently -- reconcile would restart+ # the same quiet cycle and hide the storage problem instead of+ # surfacing it.+ if not await self._commit_cycle_result_async(+ watch,+ exit_code=NO_EVENT_EXIT_CODE,+ error=None,+ disable=watch.mode == "once",+ ):+ return+ if watch.mode != "forever":+ return+ # The waiter decides its own polling cadence; the retry delay only+ # keeps a waiter that returns immediately from spinning the cycle loop.+ await asyncio.sleep(watch.retry_delay_seconds)+ continue+if result.timed_out or result.exit_code == 124:error_text = "timed out"if watch.mode == "forever" and 124 in set(watch.retry_exit_codes):@@ -1790,7 +1913,12 @@ class ManagedWatchService:)return- async def _run_cycle(self, watch: ManagedWatch, *, timeout_seconds: float) -> _CycleResult:+ async def _run_cycle(+ self,+ watch: ManagedWatch,+ *,+ timeout_seconds: float,+ ) -> _CycleResult:"""Run one waiter cycle through the shared supervised-command runner.The runner owns the process mechanics; this method owns watch policy:@@ -1823,6 +1951,11 @@ class ManagedWatchService:label=f"watch {watch.id}",on_spawn=_register_spawn,max_output_bytes=None,+ # Which watch this waiter belongs to. A waiter that keeps persistent+ # state per watch -- cursor files, locks -- cannot otherwise tell+ # itself apart from an identically configured sibling watch, and two+ # of them sharing one file lose whichever events the other reports.+ extra_env=_cycle_env(watch),)except SupervisedCommandStartupError as exc:detail = self._localize_watch_worker_error(exc.detail)@@ -2025,8 +2158,48 @@ def _build_prompt(prefix: Optional[str], body: Optional[str]) -> str:return "\n\n".join(parts).strip()+def _is_quiet_cycle(result: "_CycleResult") -> bool:+ """Did the waiter finish and say, in so many words, that nothing happened?++ Both halves are required. The exit code cannot carry this on its own because it+ is also ``sysexits`` EX_USAGE, and the marker cannot carry it on its own because+ a waiter that reports an event prints its findings and exits 0.+ """++ if result.exit_code != NO_EVENT_EXIT_CODE:+ return False+ return _has_no_event_marker(result.stderr) or _has_no_event_marker(result.stdout)+++def _has_no_event_marker(text: Optional[str]) -> bool:+ """Is the marker a line of its own in ``text``?++ A whole line, not a substring: an EX_USAGE failure that merely mentions the+ protocol -- "missing avibe-watch: no-event marker" -- would otherwise be read as+ a quiet cycle, and its failure notice swallowed and, in forever mode, its broken+ command rerun forever.+ """++ return any(line.strip() == NO_EVENT_MARKER for line in (text or "").splitlines())++def _squash_error(text: str, *, limit: int = 240) -> str:compact = " ".join((text or "").split())if len(compact) <= limit:return compactreturn compact[: limit - 1].rstrip() + "…"+++def _squash_tail(text: str, *, limit: int) -> str:+ """The END of ``text``, squashed to ``limit``.++ A quiet cycle's point is its last words. ``wait_action.py --only-on-failure``+ prints its green workflow summary just before exiting, after however many+ "still waiting" lines the poll took, so head-first truncation logs the waiting+ and drops the summary this log line exists to preserve.+ """++ compact = " ".join((text or "").split())+ if len(compact) <= limit:+ return compact+ return "…" + compact[-(limit - 1) :].lstrip()diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdindex 7f8df6c6c..a4371c176 100644--- a/skills/background-watch-hook/SKILL.md+++ b/skills/background-watch-hook/SKILL.md@@ -2,7 +2,7 @@name: background-watch-hookslug: background-watch-hookdescription: 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.8.0+version: 0.11.7---# Background Watch Hook@@ -83,8 +83,23 @@ Management commands: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; no 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:@@ -162,7 +177,7 @@ This skill ships bundled GitHub waiters: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 use exit code `75` for retryable startup errors such as temporary network failures or GitHub `408/429/5xx` responses.+Bundled GitHub waiters use exit code `75` for retryable startup errors such as temporary network failures or GitHub `408/429/5xx` responses, and exit code `64` with the `avibe-watch: no-event` marker when a cycle finished with nothing worth an Agent turn.## GitHub Example Waiter@@ -173,20 +188,43 @@ One-shot watch:```bashvibe watch add \--name "Watch PR 151 reviews" \- --message "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \+ --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 scripts/wait_pr.py \--repo avibe-bot/avibe \--pr 151 \+ --actionable-only \+ --settle 20 \--interval 60```+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.++`--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:```bashvibe watch add \--name "Catch up PR 151 reviews" \- --message "PR #151 already has review activity. Fetch the latest review state and continue handling it if needed." \+ --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 scripts/wait_pr.py \--repo avibe-bot/avibe \@@ -202,18 +240,83 @@ vibe watch add \--forever \--timeout 21600 \--lifetime-timeout 86400 \- --message "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \+ --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 scripts/wait_pr.py \--repo avibe-bot/avibe \--pr 151 \+ --actionable-only \+ --settle 20 \+ --state-file ~/.avibe/state/watch-cursors/pr-151.json \--interval 60```+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 also carries the `since` filters and the resolved GitHub login forward, so+a resumed cycle asks GitHub only for what is new instead of re-reading the whole PR.+The login is reused only while the token still fingerprints to the account it was+resolved for, and an explicit `--since-review-comment-id` /+`--since-issue-comment-id` drops the matching saved `since` so the replay it asks+for is not narrowed away. It is written on every cursor advance and on timeout,+replaced atomically. 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 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-- without `--catch-up`, the waiter snapshots current PR activity as the baseline+- `--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: comment fetches are filtered server-side with `since`,+ reactions 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- PR activity also includes the special case where `chatgpt-codex-connector[bot]` leaves a `+1` reaction on the PR body instead of posting a comment- PR activity also includes lifecycle changes on the PR itself, for example draft/ready, closed, reopened, or merged transitions- self-authored comments are ignored by default when the current authenticated GitHub user can be resolved; pass `--include-self-comments` to keep them@@ -244,7 +347,7 @@ GitHub Actions for a pushed commit:```bashvibe watch add \--name "Watch CI" \- --message "GitHub Actions finished. Inspect the result below and continue with the deployment or fix failures." \+ --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 scripts/wait_action.py \--repo cyhhao/sub2api \@@ -252,12 +355,32 @@ vibe watch add \--sha "$HEAD_SHA" \--workflow CI \--workflow "Security Scan" \+ --only-on-failure \--interval 60```+`--only-on-failure` exits `64` with the no-event marker when every watched workflow succeeded, so a green+build ends the watch silently instead of spending an Agent turn to say so. The+full summary still goes to `stderr`, which the supervisor records in the Avibe log+(`~/.avibe/logs/vibe_remote.log`) beside the watch id; `vibe watch show` reports+that the cycle ran and found nothing, not the summary itself.+Drop the flag when the follow-up should also run on success, for example when a+green build is supposed to trigger a deploy.+## 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.diff --git a/skills/background-watch-hook/scripts/_github_wait_common.py b/skills/background-watch-hook/scripts/_github_wait_common.pyindex 59b81cadd..61000c321 100644--- a/skills/background-watch-hook/scripts/_github_wait_common.py+++ b/skills/background-watch-hook/scripts/_github_wait_common.py@@ -8,13 +8,63 @@ import mathimport osimport shutilimport subprocess+import sysimport urllib.errorimport urllib.request+from datetime import datetime, timedeltafrom typing import AnyRETRY_EXIT_CODE = 75+# Cycle completed, nothing worth waking the Agent for. `vibe watch` records the+# cycle and ends or re-arms without creating a follow-up run.+#+# The code alone is not enough: 64 is BSD `sysexits` EX_USAGE, so a watched command+# that rejects its own arguments exits with it and must keep failing loudly. `vibe+# watch` reads a quiet cycle only when the marker is on the waiter's output too, so+# always exit through `no_event()` rather than returning the bare code.+NO_EVENT_EXIT_CODE = 64+NO_EVENT_MARKER = "avibe-watch: no-event"+# `vibe watch` names the watch a waiter is a cycle of here. A waiter that keeps+# per-watch state on disk should own that state by this id, so two identically+# configured watches cannot silently share one file. Absent for a manual run.+WATCH_ID_ENV = "AVIBE_WATCH_ID"+# How many event reports from this watch `vibe watch` has durably queued as a+# follow-up, or empty for none. Flushing stdout proves nothing: the supervisor only+# sees the output once the process has exited, so a waiter that stages the cursors+# covering a reported event records this value with them and a later cycle promotes+# them only if the value has since CHANGED. Treat it as opaque and compare it, nothing+# more. The supervisor bumps it in the same transaction as the follow-up and keeps it+# out of the lifecycle fields a resume resets, so the answer is still there after a+# restart, or when a `once` watch is resumed long after its one report. Absent for a+# manual run, where printing IS the delivery.+LAST_DELIVERY_ENV = "AVIBE_WATCH_LAST_DELIVERY"+# Socket timeout for one GitHub request. Callers that have their own deadline need+# this to size a request budget: a waiter with 20s left cannot afford a fetch that+# is allowed to block for 30.+REQUEST_TIMEOUT_SECONDS = 30RETRYABLE_HTTP_STATUS_CODES = {408, 429, 500, 502, 503, 504}+NOT_MODIFIED_STATUS = 304+# GitHub compares timestamps at one-second resolution, and a bot that posts a+# review as a batch stamps several comments within the same second. Rewinding the+# `since` filter re-fetches the newest item or two, which the id cursors then+# drop, rather than risking a sibling that lands on the boundary second.+SINCE_REWIND_SECONDS = 2++_MISSING = object()+++def no_event(summary: str = "") -> int:+ """End the cycle with nothing to report, and say so where the watch can see it.++ The summary goes to stderr so it stays in the watch log: it is the only record+ of what the waiter saw and chose not to forward, and no Agent turn carries it.+ """++ if summary:+ print(summary, file=sys.stderr)+ print(NO_EVENT_MARKER, file=sys.stderr)+ return NO_EVENT_EXIT_CODEdef get_token() -> str | None:@@ -50,15 +100,115 @@ def min_interval_for_unauthenticated(return float(max(60, math.ceil((3600 * recurring_requests) / hourly_budget)))-def github_get(url: str, token: str | None) -> Any:+class ResponseCache:+ """Per-URL ETag cache so an unchanged page costs nothing to re-check.++ GitHub answers a revalidated conditional request with 304 and does not charge+ it against the rate limit, so a waiter that sits on a quiet PR can keep+ polling indefinitely for free instead of re-downloading its whole history+ every interval.++ The cache lives for one waiter process. A 304 is only useful while the body it+ stands for is still in memory, so it is deliberately not persisted; the+ savings across cycles come from the cursor state file, which keeps the+ ``since`` filters narrow enough that a fresh fetch is small.+ """++ __slots__ = ("_entries", "revalidated", "downloaded")++ def __init__(self) -> None:+ self._entries: dict[str, tuple[str, Any]] = {}+ self.revalidated = 0+ self.downloaded = 0++ def etag_for(self, url: str) -> str | None:+ entry = self._entries.get(url)+ return entry[0] if entry is not None else None++ def store(self, url: str, etag: str, payload: Any) -> None:+ self._entries[url] = (etag, payload)++ def payload_for(self, url: str) -> Any:+ entry = self._entries.get(url)+ return _MISSING if entry is None else entry[1]++ def summary(self) -> str:+ total = self.revalidated + self.downloaded+ if not total:+ return "no GitHub requests issued"+ return (+ f"{total} GitHub request(s): {self.revalidated} revalidated as 304 "+ f"(free of rate limit), {self.downloaded} downloaded"+ )+++def github_get(url: str, token: str | None, *, cache: ResponseCache | None = None) -> Any:request = urllib.request.Request(url)request.add_header("Accept", "application/vnd.github+json")request.add_header("User-Agent", "background-watch-hook/0.1.0")if token:request.add_header("Authorization", f"Bearer {token}")+ etag = cache.etag_for(url) if cache is not None else None+ if etag:+ request.add_header("If-None-Match", etag)- with urllib.request.urlopen(request, timeout=30) as response:- return json.loads(response.read().decode("utf-8"))+ try:+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:+ payload = json.loads(response.read().decode("utf-8"))+ if cache is not None:+ cache.downloaded += 1+ response_etag = response.headers.get("ETag")+ if response_etag:+ cache.store(url, response_etag, payload)+ return payload+ except urllib.error.HTTPError as err:+ if err.code == NOT_MODIFIED_STATUS and cache is not None:+ payload = cache.payload_for(url)+ if payload is not _MISSING:+ cache.revalidated += 1+ return payload+ raise+++def latest_timestamp(items: list[dict[str, Any]]) -> str | None:+ """Newest ``updated_at``/``created_at`` across items.++ GitHub emits a fixed-width UTC form (``2026-08-04T06:47:12Z``), so a string+ comparison orders these correctly without parsing every candidate.+ """++ newest = ""+ for item in items:+ for key in ("updated_at", "created_at"):+ value = item.get(key)+ if isinstance(value, str) and value > newest:+ newest = value+ return newest or None+++def since_param(items: list[dict[str, Any]]) -> str | None:+ """A ``since`` value for the next poll that cannot skip an item."""++ newest = latest_timestamp(items)+ if not newest:+ return None+ try:+ parsed = datetime.fromisoformat(newest.replace("Z", "+00:00"))+ except ValueError:+ return None+ rewound = parsed - timedelta(seconds=SINCE_REWIND_SECONDS)+ return rewound.strftime("%Y-%m-%dT%H:%M:%SZ")+++def later_since(previous: str | None, items: list[dict[str, Any]]) -> str | None:+ """Advance a ``since`` filter, never rewinding it."""++ candidate = since_param(items)+ if not candidate:+ return previous+ if previous and previous >= candidate:+ return previous+ return candidatedef is_retryable_http_error(err: urllib.error.HTTPError) -> bool:@@ -84,8 +234,13 @@ def get_authenticated_login(token: str | None) -> str | None:return str(login) if isinstance(login, str) and login else None-def list_paginated(base_url: str, token: str | None) -> list[dict[str, Any]]:- items, _request_count = list_paginated_with_count(base_url, token)+def list_paginated(+ base_url: str,+ token: str | None,+ *,+ cache: ResponseCache | None = None,+) -> list[dict[str, Any]]:+ items, _request_count = list_paginated_with_count(base_url, token, cache=cache)return items@@ -95,6 +250,7 @@ def list_paginated_with_count(*,stop_after_id: int | None = None,max_pages: int | None = None,+ cache: ResponseCache | None = None,) -> tuple[list[dict[str, Any]], int]:items: list[dict[str, Any]] = []page = 1@@ -102,7 +258,7 @@ def list_paginated_with_count(while True:separator = "&" if "?" in base_url else "?"url = f"{base_url}{separator}per_page=100&page={page}"- payload = github_get(url, token)+ payload = github_get(url, token, cache=cache)request_count += 1if not isinstance(payload, list):raise RuntimeError(f"Expected a JSON list from {url}")diff --git a/skills/background-watch-hook/scripts/wait_action.py b/skills/background-watch-hook/scripts/wait_action.pyindex 3632ff437..8571b1549 100755--- a/skills/background-watch-hook/scripts/wait_action.py+++ b/skills/background-watch-hook/scripts/wait_action.py@@ -17,11 +17,14 @@ if str(SCRIPT_DIR) not in sys.path:sys.path.insert(0, str(SCRIPT_DIR))from _github_wait_common import ( # noqa: E402+ NO_EVENT_EXIT_CODE,+ NO_EVENT_MARKER,RETRY_EXIT_CODE,get_token,github_get,is_retryable_http_error,min_interval_for_unauthenticated,+ no_event,)DEFAULT_SUCCESS_CONCLUSIONS = {"success", "skipped", "neutral"}@@ -189,6 +192,15 @@ def main() -> int:"Defaults to success,skipped,neutral."),)+ parser.add_argument(+ "--only-on-failure",+ action="store_true",+ help=(+ "Do not wake the Agent when every watched workflow succeeded; exit with the "+ f"no-event code {NO_EVENT_EXIT_CODE} and the '{NO_EVENT_MARKER}' marker instead. "+ "Failures still exit 0 with the full report."+ ),+ )parser.add_argument("--cursor-output", help=argparse.SUPPRESS)parser.add_argument("--allow-unauthenticated",@@ -296,7 +308,7 @@ def main() -> int:branch=args.branch,head_sha=args.sha,)- output, _has_failed_workflow = _render_actions_result(+ output, has_failed_workflow = _render_actions_result(repo=args.repo,branch=args.branch,head_sha=args.sha,@@ -305,6 +317,15 @@ def main() -> int:)if output is not None:_write_cursor_output(args.cursor_output, selected=selected)+ if args.only_on_failure and not has_failed_workflow:+ # The interesting outcome is a broken build. Reporting a green one+ # costs a full Agent turn to say "nothing to do", so keep the+ # summary on stderr where it stays inspectable via the watch log.+ print(output, file=sys.stderr)+ return no_event(+ "All watched workflows succeeded; exiting without an Agent follow-up "+ "because --only-on-failure is set."+ )print(output)return 0diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.pyindex eb02185f2..05e79ee42 100755--- a/skills/background-watch-hook/scripts/wait_pr.py+++ b/skills/background-watch-hook/scripts/wait_pr.py@@ -4,13 +4,24 @@from __future__ import annotationsimport argparse+import hashlibimport json+import os+import reimport sys+import tempfileimport timeimport urllib.errorimport urllib.parse+from contextlib import contextmanager+from functools import partialfrom pathlib import Path-from typing import Any+from typing import Any, Iterator++try: # POSIX only, which is every platform `vibe` runs the waiter on.+ import fcntl+except ImportError: # pragma: no cover - Windows has no flock+ fcntl = None # type: ignore[assignment]SCRIPT_DIR = Path(__file__).resolve().parentif str(SCRIPT_DIR) not in sys.path:@@ -22,18 +33,86 @@ from _github_wait_common import ( # noqa: E402get_token,github_get,is_retryable_http_error,+ LAST_DELIVERY_ENV,+ later_since,list_paginated,list_paginated_with_count,max_id,min_interval_for_unauthenticated,+ REQUEST_TIMEOUT_SECONDS,RETRY_EXIT_CODE,requests_per_poll,+ ResponseCache,squash,+ WATCH_ID_ENV,)CODEX_REVIEW_PASS_REACTION_USER = "chatgpt-codex-connector[bot]"CODEX_REVIEW_PASS_REACTION_CONTENT = "+1"+# 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.+# Anchored at BOTH ends: a trigger comment is only the command. "@codex review" is+# noise; "@author fix the timeout handling" is a person asking for work and must+# survive, because suppressing it still advances the cursor and the request would be+# lost for good rather than merely delayed.+DEFAULT_NOISE_COMMENT_PATTERNS = (+ r"^@[\w\[\]-]+\s+(review|fix|rebase|merge)\s*$",+ r"^/[\w-]+\s*$",+)+# Lifecycle transitions worth interrupting for. Draft toggles are usually the+# Agent's own doing, so they are noise in --actionable-only mode.+ACTIONABLE_PR_STATUSES = frozenset({"merged", "closed"})+STATE_FILE_VERSION = 1+# Cursors that cover a REPORTED event, held here instead of committed, next to the+# supervisor's last-delivery stamp as it read at report time. A waiter cannot see its+# own delivery -- the supervisor reads its output only after the process exits -- so+# committing them at report time loses the event whenever the service stops in+# between. A later cycle that reads a different stamp knows the report was delivered+# and promotes them; an unchanged stamp replays the report.+STAGED_KEY = "pending"+STATE_CURSOR_KEYS = (+ "review_cursor",+ "review_comment_cursor",+ "issue_comment_cursor",+ "reaction_cursor",+)+# A bot review lands as a burst of inline comments plus an envelope. Re-polling a+# few times while the burst is still arriving turns it into one Agent turn instead+# of one turn per fragment that happened to cross a poll boundary.+SETTLE_MAX_ROUNDS = 3+++class StateFileError(RuntimeError):+ """The requested ``--state-file`` cannot do the job it was asked to do.++ Raised rather than warned about because a forever watch that keeps polling+ without usable cursors loses activity instead of reporting it, and does so+ silently: every fresh cycle re-baselines from the current PR.+ """+++class StatePersistenceError(StateFileError):+ """The cursors an explicit ``--state-file`` promised could not be saved."""+++class StateFileUnusableError(StateFileError):+ """An existing ``--state-file`` cannot be read, so its cursors are unknown.++ Not recoverable by starting over: re-baselining from the current PR skips+ everything that arrived after the last cursor this file did hold, and then+ overwrites the evidence. The corrupt file has to be removed deliberately.+ """+++class StateFileOwnershipError(StateFileError):+ """The state file at this path belongs to a different PR, or a different watch.++ Two watches pointed at one file is a configuration error, not a state to+ recover from: each would read the other's cursors as absent, re-baseline, and+ then overwrite them, so both watches keep missing activity between cycles.+ """+def _format_review(review: dict[str, Any]) -> str:review_id = review.get("id")@@ -68,6 +147,55 @@ def _is_self_authored_comment(comment: dict[str, Any], viewer_login: str | None)return str(author).casefold() == viewer_login.casefold()+def _compile_ignore_patterns(values: list[str] | None, *, actionable_only: bool) -> list[re.Pattern[str]]:+ patterns = list(DEFAULT_NOISE_COMMENT_PATTERNS) if actionable_only else []+ patterns.extend(values or [])+ return [re.compile(pattern, re.IGNORECASE) for pattern in patterns]+++def _normalize_authors(values: list[str] | None) -> set[str]:+ return {value.strip().casefold() for value in (values or []) if value.strip()}+++def _is_ignored_author(item: dict[str, Any], ignored_authors: set[str]) -> bool:+ if not ignored_authors:+ return False+ author = ((item.get("user") or {}).get("login")) or ""+ return str(author).casefold() in ignored_authors+++def _matches_ignored_pattern(item: dict[str, Any], patterns: list[re.Pattern[str]]) -> bool:+ if not patterns:+ return False+ text = squash(item.get("body"), limit=1000)+ if not text:+ return False+ return any(pattern.search(text) for pattern in patterns)+++def _is_actionable_review(review: dict[str, Any]) -> bool:+ """A review carries a verdict, or a body worth reading.++ A bodyless ``COMMENTED`` review is the envelope GitHub wraps around inline+ comments; those comments are reported on their own, so the envelope adds a+ turn and no information.+ """++ state = str(review.get("state") or "").lower()+ if state in {"changes_requested", "approved", "dismissed"}:+ return True+ return bool(squash(review.get("body")))+++def _keep_item(+ item: dict[str, Any],+ *,+ ignored_authors: set[str],+ ignore_patterns: list[re.Pattern[str]],+) -> bool:+ return not _is_ignored_author(item, ignored_authors) and not _matches_ignored_pattern(item, ignore_patterns)++def _is_codex_pass_reaction(reaction: dict[str, Any]) -> bool:author = ((reaction.get("user") or {}).get("login")) or ""content = str(reaction.get("content") or "")@@ -133,27 +261,51 @@ def _format_pull_request(pr: dict[str, Any]) -> str:return f"- pull_request #{pr_number} by {author} ({state})\n {title}\n {url}"-def _fetch_state(repo: str, pr_number: int, token: str | None) -> tuple[dict[str, list[dict[str, Any]]], int]:+def _with_since(url: str, since: str | None) -> str:+ if not since:+ return url+ separator = "&" if "?" in url else "?"+ return f"{url}{separator}since={urllib.parse.quote(since)}"+++def _fetch_state(+ repo: str,+ pr_number: int,+ token: str | None,+ *,+ cache: ResponseCache | None = None,+ review_comment_since: str | None = None,+ issue_comment_since: str | None = None,+) -> tuple[dict[str, list[dict[str, Any]]], int]:encoded_repo = urllib.parse.quote(repo, safe="/")- pull_request = github_get(- f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}",- token,- )+ base_url = f"https://api.github.com/repos/{encoded_repo}"+ pull_request = github_get(f"{base_url}/pulls/{pr_number}", token, cache=cache)+ # The reviews endpoint ignores sort/direction (verified against api.github.com:+ # direction=desc returns the same ascending ids), so there is no way to page it+ # newest-first and no `since` support either. An unchanged review list stays+ # cheap by revalidating to 304 rather than by fetching less.reviews, review_requests = list_paginated_with_count(- f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/reviews",+ f"{base_url}/pulls/{pr_number}/reviews",token,+ cache=cache,)review_comments, review_comment_requests = list_paginated_with_count(- f"https://api.github.com/repos/{encoded_repo}/pulls/{pr_number}/comments",+ _with_since(f"{base_url}/pulls/{pr_number}/comments", review_comment_since),token,+ cache=cache,)issue_comments, issue_comment_requests = list_paginated_with_count(- f"https://api.github.com/repos/{encoded_repo}/issues/{pr_number}/comments",+ _with_since(f"{base_url}/issues/{pr_number}/comments", issue_comment_since),token,+ cache=cache,)+ # Only the Codex pass reaction is ever reported, and this endpoint filters by+ # content server-side, so every other reaction on the PR body stays home.reactions, reaction_requests = list_paginated_with_count(- f"https://api.github.com/repos/{encoded_repo}/issues/{pr_number}/reactions",+ f"{base_url}/issues/{pr_number}/reactions"+ f"?content={urllib.parse.quote(CODEX_REVIEW_PASS_REACTION_CONTENT)}",token,+ cache=cache,)return ({@@ -173,6 +325,7 @@ def _fetch_new_pr_state(*,stop_after_id: int | None = None,max_pages: int | None = None,+ cache: ResponseCache | None = None,) -> tuple[dict[str, list[dict[str, Any]]], int]:encoded_repo = urllib.parse.quote(repo, safe="/")pull_requests, request_count = list_paginated_with_count(@@ -180,6 +333,7 @@ def _fetch_new_pr_state(token,stop_after_id=stop_after_id,max_pages=max_pages,+ cache=cache,)return {"pull_requests": pull_requests}, request_count@@ -197,26 +351,34 @@ def _render_activity(event_limit: int,viewer_login: str | None = None,ignore_self_comments: bool = True,+ actionable_only: bool = False,+ ignored_authors: set[str] | None = None,+ ignore_patterns: list[re.Pattern[str]] | None = None,) -> tuple[str | None, int, int, int, int, str]:+ ignored_authors = ignored_authors or set()+ ignore_patterns = ignore_patterns or []current_pr_status = _current_pr_status(state.get("pull_request"))new_reviews = filter_new(state["reviews"], review_cursor)new_review_comments = filter_new(state["review_comments"], review_comment_cursor)new_issue_comments = filter_new(state["issue_comments"], issue_comment_cursor)- visible_reviews = (- [review for review in new_reviews if not _is_self_authored_comment(review, viewer_login)]- if ignore_self_comments- else new_reviews- )- visible_review_comments = (- [comment for comment in new_review_comments if not _is_self_authored_comment(comment, viewer_login)]- if ignore_self_comments- else new_review_comments- )- visible_issue_comments = (- [comment for comment in new_issue_comments if not _is_self_authored_comment(comment, viewer_login)]- if ignore_self_comments- else new_issue_comments- )++ def _visible(items: list[dict[str, Any]]) -> list[dict[str, Any]]:+ # Cursors advance over everything new; only the rendering is filtered, so a+ # dropped item is dropped once and never re-examined on the next poll.+ kept = items if not ignore_self_comments else [+ item for item in items if not _is_self_authored_comment(item, viewer_login)+ ]+ return [+ item+ for item in kept+ if _keep_item(item, ignored_authors=ignored_authors, ignore_patterns=ignore_patterns)+ ]++ visible_reviews = _visible(new_reviews)+ if actionable_only:+ visible_reviews = [review for review in visible_reviews if _is_actionable_review(review)]+ visible_review_comments = _visible(new_review_comments)+ visible_issue_comments = _visible(new_issue_comments)new_reactions = [reactionfor reaction in filter_new(state["reactions"], reaction_cursor)@@ -233,8 +395,12 @@ def _render_activity(next_reaction_cursor = max(reaction_cursor, max_id(state["reactions"]))next_pr_status = current_pr_status+ render_pr_status_event = has_pr_status_event and (+ not actionable_only or current_pr_status in ACTIONABLE_PR_STATUSES+ )+rendered_events: list[str] = []- if has_pr_status_event and isinstance(state.get("pull_request"), dict):+ if render_pr_status_event and isinstance(state.get("pull_request"), dict):rendered_events.append(_format_pr_status_event(state["pull_request"], pr_status, current_pr_status))rendered_events.extend(_format_review(review) for review in visible_reviews)rendered_events.extend(_format_review_comment(comment) for comment in visible_review_comments)@@ -328,7 +494,597 @@ def _write_new_pr_cursor_output(path: str | None, *, pr_cursor: int) -> None:json.dump({"pr_cursor": pr_cursor}, handle)-def main() -> int:+def _watch_identity(args: argparse.Namespace) -> str:+ """A stable digest of the options that decide what this watch reports.++ Ownership by repo and PR alone cannot tell two watches on the same PR apart --+ one ``--actionable-only``, one meant to report everything -- and a shared state+ file then lets whichever polls first advance the cursors past an event the other+ would have reported. That event is gone for good rather than merely late, so the+ filters belong in the identity.++ Only the report-shaping options are in here. ``--interval``, ``--timeout`` and+ ``--settle`` change pacing, not which activity counts, and two watches differing+ only in those can share cursors without losing anything.+ """++ material = json.dumps(+ {+ "mode": "new-prs" if args.new_prs else "pr",+ "actionable_only": bool(args.actionable_only),+ "include_self_comments": bool(args.include_self_comments),+ "ignore_authors": sorted(_normalize_authors(args.ignore_author)),+ "ignore_comment_patterns": sorted(set(args.ignore_comment_pattern or [])),+ },+ sort_keys=True,+ )+ return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{material}".encode()).hexdigest()[:16]+++def _managed_watch_id() -> str | None:+ """The id of the ``vibe watch`` this waiter is a cycle of, when there is one.++ Two separately managed watches on the same PR with the same filters are+ indistinguishable by configuration alone, and sharing a state file means+ whichever polls first advances the cursors past events the other never+ reported. The supervisor hands the id down, so the owner can be exact. A manual+ run has none, which is not a conflict -- only proof of one is.+ """++ value = os.environ.get(WATCH_ID_ENV, "").strip()+ return value or None+++def _owner_conflict(+ owner: tuple[Any, Any, Any, Any] | None,+ *,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None,+ watch_id: str | None,+) -> str | None:+ """Why ``owner`` is somebody else's claim on the path, or ``None`` when it is ours.++ A state file written before identities existed carries no owner, and an absent+ owner is compatible with every run -- that is the file a managed watch adopts.++ A file that DOES name an owner is the opposite: the burden is on this run to+ prove it is that owner, and a manual run cannot. Letting it through would be+ silent data loss rather than a mere sharing of the path -- the manual run polls,+ reports to a terminal nobody is reading, and ``_write_state_file`` stamps+ ``owner: null`` over the managed claim while advancing the cursors past that+ activity. The managed watch then adopts its own file back as ownerless and+ resumes from cursors covering events its Agent follow-up never received.+ """++ if owner is None:+ return None+ saved_repo, saved_pr, saved_watch, saved_owner = owner+ if saved_repo != repo or saved_pr != pr_number:+ return f"belongs to {saved_repo}#{saved_pr}, not {repo}#{pr_number}"+ if saved_watch is not None and watch_identity is not None and saved_watch != watch_identity:+ return (+ f"belongs to another watch on {saved_repo}#{saved_pr} with different "+ "reporting filters"+ )+ if saved_owner is not None and saved_owner != watch_id:+ if watch_id is None:+ return (+ f"belongs to watch {saved_owner}; this run is not managed by that "+ "watch. Use a different --state-file."+ )+ return f"belongs to watch {saved_owner}, not watch {watch_id}"+ return None+++def _load_state_file(+ path: str | None,+ *,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None = None,+ watch_id: str | None = None,+) -> dict[str, Any]:+ """Read cursors left behind by an earlier run of this same waiter.++ A `--forever` watch runs the waiter once per cycle, so without this the next+ cycle re-baselines from whatever the PR looks like at startup and silently+ swallows everything that arrived between the previous cycle's exit and that+ snapshot.+ """++ if not path:+ return {}++ try:+ raw = Path(path).read_text(encoding="utf-8")+ except FileNotFoundError:+ return {}+ except OSError as err:+ raise StateFileUnusableError(f"State file {path} cannot be read: {err}") from err++ # An empty file is the claim below caught between its exclusive create and its+ # first write, so no cursor was ever recorded in it and there is none to lose.+ # Anything else that will not parse HAD cursors, and how far they reached is now+ # unknown -- which is why this is terminal rather than a fresh baseline.+ if not raw.strip():+ return {}+ try:+ payload = json.loads(raw)+ except ValueError as err:+ raise StateFileUnusableError(f"State file {path} is corrupt: {err}") from err+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:+ raise StateFileUnusableError(f"State file {path} is not in a recognised format")+ # Resuming from somebody else's cursors would skip the history they cover, and+ # carrying on would overwrite them on the first cursor advance -- so this is+ # terminal rather than a fresh baseline. A file left behind by another watch has+ # to be removed, or that watch given its own path, deliberately.+ conflict = _owner_conflict(+ (payload.get("repo"), payload.get("pr"), payload.get("watch"), payload.get("owner")),+ repo=repo,+ pr_number=pr_number,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ if conflict is not None:+ raise StateFileOwnershipError(f"State file {path} {conflict}")+ return payload+++def _state_file_scratch(target: Path) -> tuple[int, str]:+ """An exclusively created scratch file beside ``target``.++ ``mkstemp`` rather than a derived name such as ``<state-file>.tmp``: this runs+ in a directory of persisted user state, and a deterministic path both+ truncates whatever already occupies it and lets two waiters sharing a+ directory scribble over each other's half-written file.+ """++ return tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp")+++def _state_file_owner(target: Path) -> tuple[Any, Any, Any, Any] | None:+ """Which watch the file at ``target`` currently claims, or ``None`` if it says nothing.++ Missing and unusable files both answer ``None``, matching ``_load_state_file``:+ there is no owner to respect, so the caller may take the path.+ """++ try:+ with target.open(encoding="utf-8") as handle:+ payload = json.load(handle)+ except (OSError, ValueError):+ return None+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:+ return None+ return payload.get("repo"), payload.get("pr"), payload.get("watch"), payload.get("owner")+++def _claim_state_file(+ target: Path,+ *,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None = None,+ watch_id: str | None = None,+) -> bool:+ """Take a currently missing state file for this PR, atomically.++ ``O_EXCL`` is the whole point: two waiters starting together both see no file,+ and exactly one of them creates it. The loser reads the winner's claim and stops+ on the ownership check instead of quietly sharing the path and overwriting the+ winner's cursors on its next advance -- a silent gap in the review loop.++ Returns False when somebody else got there first; the caller then treats the path+ as pre-existing and lets ``_load_state_file`` judge the owner.+ """++ try:+ handle = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ except FileExistsError:+ return False+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err++ try:+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(+ {+ "version": STATE_FILE_VERSION,+ "repo": repo,+ "pr": pr_number,+ "watch": watch_identity,+ "owner": watch_id,+ },+ stream,+ )+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err+ return True+++@contextmanager+def _state_file_lock(target: Path) -> Iterator[None]:+ """Serialize the ownership decision on ``target`` across processes.++ Deciding who owns a state file is read-then-write, and two managed watches that+ interleave those halves both conclude the path is theirs. A sidecar lock file+ makes the decision one step. It is a separate file precisely because the state+ file itself is replaced rather than rewritten: a lock held on an inode that has+ since been renamed away guards nothing.++ Best effort by design. A filesystem without working locks, or a directory that+ refuses the lock file, must not stop the watch -- the write probe and the+ ownership re-check on every replace still stand.+ """++ if fcntl is None:+ yield+ return++ handle = None+ try:+ handle = os.open(target.with_name(f"{target.name}.lock"), os.O_RDWR | os.O_CREAT, 0o600)+ fcntl.flock(handle, fcntl.LOCK_EX)+ except OSError:+ if handle is not None:+ os.close(handle)+ yield+ return++ try:+ yield+ finally:+ try:+ fcntl.flock(handle, fcntl.LOCK_UN)+ finally:+ os.close(handle)+++def _adopt_state_file(+ target: Path,+ *,+ repo: str,+ pr_number: int | None,+ watch_id: str,+ watch_identity: str | None,+) -> bool:+ """Stamp this managed watch onto an ownerless state file, keeping its cursors.++ A file written before owners existed, or by a manual run, names no owner -- and an+ absent owner is compatible with every managed watch. Two of them would therefore+ both adopt the same path, poll, and overwrite each other's cursors, skipping+ activity for good. Claiming the name here, under the lock and before any polling,+ turns that into a conflict the loser sees while it can still be told about it.++ An EMPTY file is the same hazard wearing different clothes: it is a claim caught+ between its exclusive create and its first write, so ``_load_state_file`` reads it+ as a fresh baseline with no cursors to lose. Left as it is, it names no owner+ either, and two managed watches pointed at that path both clear this preflight and+ poll -- so finish the claim the interrupted run started rather than falling through+ to a byte-for-byte rewrite that preserves the emptiness and the ambiguity with it.++ Returns False when the file says nothing usable, leaving it to the caller's probe.+ """++ try:+ raw = target.read_text(encoding="utf-8")+ except OSError:+ return False++ if not raw.strip():+ payload: dict[str, Any] = {+ "version": STATE_FILE_VERSION,+ "repo": repo,+ "pr": pr_number,+ }+ else:+ try:+ payload = json.loads(raw)+ except ValueError:+ return False+ if not isinstance(payload, dict) or payload.get("version") != STATE_FILE_VERSION:+ return False++ payload["owner"] = watch_id+ if payload.get("watch") is None and watch_identity is not None:+ payload["watch"] = watch_identity++ scratch = None+ try:+ handle, scratch = _state_file_scratch(target)+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(payload, stream)+ os.replace(scratch, target)+ scratch = None+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {target}: {err}") from err+ finally:+ if scratch is not None:+ try:+ os.unlink(scratch)+ except OSError:+ pass+ return True+++def _verify_state_file_writable(+ path: str | None,+ *,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None = None,+ watch_id: str | None = None,+) -> None:+ """Claim the requested state file, and fail before the first poll if it is unusable.++ A forever watch only discovers a read-only parent directory when the cycle it+ spent minutes on tries to save its cursors, and by then the activity that+ cycle observed is already unrecoverable.++ A missing state file is created here holding nothing but this PR's ownership, so+ the path is owned before any polling starts rather than after the first cursor+ advance. It carries no cursors, so this cycle still baselines from the current PR+ exactly as it did before.++ An existing file that names no owner is adopted here too, cursors intact, because+ an absent owner is compatible with every managed watch and would otherwise let two+ of them share the path. Both steps happen under a lock on the path, so the+ read-then-write that decides ownership cannot interleave with another waiter's.++ A file that belongs to somebody else is left untouched and unprobed, and this+ returns without writing anything -- see the conflict branch below.++ For a file that already exists the probe is the whole write, ``os.replace``+ included, because that is the step persistence actually depends on and the step a+ sibling-creation check cannot speak for: a target that is a directory, or one in a+ sticky-bit directory owned by somebody else, accepts new siblings all day and+ still refuses the rename. It is rewritten with the bytes it already holds, so a+ watch resuming from good cursors keeps them either way.+ """++ if not path:+ return++ target = Path(path)+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err++ with _state_file_lock(target):+ try:+ exists = target.exists()+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err++ if not exists and _claim_state_file(+ target,+ repo=repo,+ pr_number=pr_number,+ watch_identity=watch_identity,+ watch_id=watch_id,+ ):+ # Creating the real file in the real directory is the write probe, and the+ # rename in later cycles lands on a file this process owns.+ return++ # Somebody else's file is not ours to touch AT ALL -- not to adopt, and not to+ # probe. The probe below is an ``os.replace`` of bytes read a moment earlier,+ # and the owner's own cursor writes do NOT take this lock, so probing a foreign+ # path can land stale bytes over a cursor it has just advanced or a ``pending``+ # handoff it is mid-way through, making the owning watch replay or lose+ # activity. Returning here costs nothing: ``_load_state_file`` refuses the same+ # file moments later, with the same conflict, before a single poll.+ conflict = _owner_conflict(+ _state_file_owner(target),+ repo=repo,+ pr_number=pr_number,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ if conflict is not None:+ return++ # An ownerless file is adopted, not merely accepted: taking the name is what+ # makes a second managed watch on the same path fail instead of sharing it.+ if watch_id is not None and _adopt_state_file(+ target,+ repo=repo,+ pr_number=pr_number,+ watch_id=watch_id,+ watch_identity=watch_identity,+ ):+ # Rewriting the real file is the write probe, as the claim is above.+ return++ try:+ existing = target.read_bytes()+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err++ scratch = None+ try:+ handle, scratch = _state_file_scratch(target)+ with os.fdopen(handle, "wb") as stream:+ stream.write(existing)+ os.replace(scratch, target)+ scratch = None+ except OSError as err:+ raise StatePersistenceError(f"Cannot write state file {path}: {err}") from err+ finally:+ if scratch is not None:+ try:+ os.unlink(scratch)+ except OSError:+ pass+++def _write_state_file(+ path: str | None,+ *,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None = None,+ watch_id: str | None = None,+ **fields: Any,+) -> None:+ if not path:+ return++ payload = {+ "version": STATE_FILE_VERSION,+ "repo": repo,+ "pr": pr_number,+ "watch": watch_identity,+ "owner": watch_id,+ **fields,+ }+ target = Path(path)+ scratch = None+ # Re-checked on every replace, not just at startup: the claim can lose a race with+ # a waiter that created the file in the same instant, or a person can point another+ # watch at the same path mid-run. Clobbering that watch's cursors would make it+ # re-baseline and skip real activity, so hand the path back and stop instead.+ conflict = _owner_conflict(+ _state_file_owner(target),+ repo=repo,+ pr_number=pr_number,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ if conflict is not None:+ raise StateFileOwnershipError(f"State file {path} now {conflict}")+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ # Written aside and moved into place: a cycle killed mid-write must not+ # leave a truncated file that the next cycle has to discard.+ handle, scratch = _state_file_scratch(target)+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(payload, stream)+ os.replace(scratch, target)+ scratch = None+ except OSError as err:+ # Terminal, not a warning. The caller asked for cursors that survive the+ # process; continuing without them lets the next cycle re-baseline from the+ # current PR and silently drop everything that arrived in between, which is+ # the exact loss ``--state-file`` exists to prevent.+ raise StatePersistenceError(f"Could not write state file {path}: {err}") from err+ finally:+ # A failed write must not leave its scratch file behind in the state dir.+ if scratch is not None:+ try:+ os.unlink(scratch)+ except OSError:+ pass+++def _token_fingerprint(token: str | None) -> str | None:+ """Which credentials a cached ``viewer_login`` was resolved under.++ A one-way digest, never the token itself: the state file lives on disk next to+ the cursors and has no business holding a credential. It exists so a resumed+ cycle can tell "same account, reuse the saved login" from "the token now+ belongs to someone else", which otherwise filtered the wrong author's+ comments out of the review loop.+ """++ if not token:+ return None+ return hashlib.sha256(f"wait_pr/{STATE_FILE_VERSION}/{token}".encode()).hexdigest()[:16]+++def _saved_int(saved: dict[str, Any], key: str) -> int | None:+ value = saved.get(key)+ return int(value) if isinstance(value, int) and not isinstance(value, bool) else None+++def _saved_str(saved: dict[str, Any], key: str) -> str | None:+ value = saved.get(key)+ return value if isinstance(value, str) and value else None+++def _last_delivery() -> str | None:+ """When the supervisor last queued a report from this watch, as it sees it.++ ``None`` for a manual run, which has no supervisor -- and needs none, because+ there printing the report IS delivering it and nothing is ever staged.+ """++ return os.environ.get(LAST_DELIVERY_ENV, "").strip() or None+++def _resolve_staged_state(+ path: str | None,+ saved: dict[str, Any],+ *,+ delivery: str | None,+ repo: str,+ pr_number: int | None,+ watch_identity: str | None,+ watch_id: str | None,+) -> dict[str, Any]:+ """Promote or drop the cursors staged for an earlier cycle's report.++ Promoted when the supervisor's last-delivery stamp has moved since the report was+ staged: the report was queued, so polling may start after it. Dropped when the+ stamp is unchanged, which replays the report -- one repeated Agent turn, against+ an event lost for good. Comparing stamps rather than consuming a one-shot ack is+ what makes this survive a restart, and makes a ``once`` watch resumed long after+ its one report promote instead of replaying. Either way the decision is written+ down before polling, so it is taken once.+ """++ staged = saved.get(STAGED_KEY)+ if not isinstance(staged, dict):+ return saved+ cursors = staged.get("cursors")+ # A staged block this waiter cannot read is dropped, not guessed at: replaying+ # the report it covered costs a turn, promoting cursors of unknown reach loses+ # whatever they skip.+ delivered = isinstance(cursors, dict) and staged.get("delivered_after") != delivery++ resolved = {key: value for key, value in saved.items() if key != STAGED_KEY}+ if delivered:+ resolved.update(cursors)+ print(+ (+ "An earlier report was delivered; advancing past it."+ if delivered+ else "An earlier report was never delivered; reporting it again."+ ),+ file=sys.stderr,+ )+ fields = {+ key: value+ for key, value in resolved.items()+ if key not in {"version", "repo", "pr", "watch", "owner"}+ }+ _write_state_file(+ path,+ repo=repo,+ pr_number=pr_number,+ watch_identity=watch_identity,+ watch_id=watch_id,+ **fields,+ )+ return resolved+++def _deliver(output: str) -> None:+ """Hand the report to the supervisor, and make sure it has left this process.++ The cursors covering a reported event are committed only after this returns, so+ the report must be out of our own buffers first.+ """++ print(output)+ sys.stdout.flush()+++def _build_parser() -> argparse.ArgumentParser:+ """The waiter's CLI surface, separate from main() so it can be inspected directly."""+parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--repo", required=True, help="GitHub repo in owner/name form")mode = parser.add_mutually_exclusive_group(required=True)@@ -348,12 +1104,51 @@ def main() -> int:parser.add_argument("--since-pr-status", help=argparse.SUPPRESS)parser.add_argument("--since-pr-id", type=int, default=None, help="Existing repository pull request cursor")parser.add_argument("--cursor-output", help=argparse.SUPPRESS)+ parser.add_argument(+ "--state-file",+ help=(+ "Path to a JSON file holding this watch's cursors between runs. Strongly recommended for "+ "--forever watches: each cycle resumes where the previous one stopped instead of "+ "re-baselining, so activity arriving between cycles is not lost, and the next fetch only "+ "asks GitHub for what is new."+ ),+ )+ parser.add_argument(+ "--settle",+ type=float,+ default=0.0,+ help=(+ "Seconds to wait after the first new activity before reporting, re-polling until the set "+ f"stops growing (at most {SETTLE_MAX_ROUNDS} extra polls). A batched review that straddles "+ "a poll boundary then costs one Agent turn instead of one per fragment. 0 disables it."+ ),+ )parser.add_argument("--event-limit", type=int, default=8, help="Maximum number of new events to include in stdout")parser.add_argument("--include-self-comments",action="store_true",help="Include reviews and comments authored by the current authenticated GitHub user",)+ parser.add_argument(+ "--actionable-only",+ action="store_true",+ help=(+ "Only wake the Agent for review activity that needs a response: reviews carrying a "+ "verdict or a body, inline review comments, the Codex pass reaction, and merged/closed "+ "transitions. Drops bodyless COMMENTED review envelopes, bot trigger comments such as "+ "'@codex review', and draft toggles."+ ),+ )+ parser.add_argument(+ "--ignore-author",+ action="append",+ help="GitHub login whose reviews and comments never trigger a follow-up; repeatable",+ )+ parser.add_argument(+ "--ignore-comment-pattern",+ action="append",+ help="Case-insensitive regex; matching review/comment bodies never trigger a follow-up. Repeatable",+ )parser.add_argument("--catch-up",action="store_true",@@ -364,10 +1159,27 @@ def main() -> int:action="store_true",help="Allow polling without GitHub auth; the interval will be clamped to a safer minimum",)- args = parser.parse_args()+ return parser+++def main() -> int:+ args = _build_parser().parse_args()token = get_token()- viewer_login = None if args.include_self_comments else get_authenticated_login(token)+ cache = ResponseCache()+ # Everything that can reject the arguments runs BEFORE any state is claimed. A+ # bad --ignore-comment-pattern used to leave a claimed state file behind on its+ # way to exit 2, and fixing the regex changes the watch identity, so the very+ # next run was refused as another watch's until the file was deleted by hand.+ ignored_authors = _normalize_authors(args.ignore_author)+ try:+ ignore_patterns = _compile_ignore_patterns(+ args.ignore_comment_pattern,+ actionable_only=args.actionable_only,+ )+ except re.error as err:+ print(f"Invalid --ignore-comment-pattern: {err}", file=sys.stderr)+ return 2if token is None and not args.allow_unauthenticated:print((@@ -379,19 +1191,95 @@ def main() -> int:)return 2+ watch_identity = _watch_identity(args)+ watch_id = _managed_watch_id()+ delivery_stamp = _last_delivery()+ # Only a managed run has a next cycle to promote staged cursors, and only it gets+ # told whether the report was queued. A manual run is one process whose stdout is+ # the delivery, so staging there would leave cursors nobody ever promotes.+ two_phase = watch_id is not None+ _verify_state_file_writable(+ args.state_file,+ repo=args.repo,+ pr_number=args.pr,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ saved = _load_state_file(+ args.state_file,+ repo=args.repo,+ pr_number=args.pr,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ saved = _resolve_staged_state(+ args.state_file,+ saved,+ delivery=delivery_stamp,+ repo=args.repo,+ pr_number=args.pr,+ watch_identity=watch_identity,+ watch_id=watch_id,+ )+ token_fingerprint = _token_fingerprint(token)+ viewer_login = None+ if not args.include_self_comments:+ # The stored login spares a /user request on every cycle of a forever watch,+ # but only while the token still belongs to the account it was resolved for.+ # A rotated or swapped credential would otherwise keep filtering out the old+ # account's comments and let the new account's own comments wake the Agent.+ if token_fingerprint is not None and _saved_str(saved, "token_fingerprint") == token_fingerprint:+ viewer_login = _saved_str(saved, "viewer_login")+ viewer_login = viewer_login or get_authenticated_login(token)+base_interval = max(args.interval, 1.0)effective_interval = base_interval+ settle_seconds = max(args.settle, 0.0)start = time.monotonic()+ # Resume only from a complete cursor set. A partial one would leave some+ # baseline to be derived from a `since`-narrowed fetch, which no longer+ # contains the PR's full history.+ resume_cursors = {key: _saved_int(saved, key) for key in STATE_CURSOR_KEYS}+ resumed = not args.catch_up and all(value is not None for value in resume_cursors.values())+ # An explicit --since-*-comment-id asks for a replay from that id. The saved+ # `since` timestamp is only ever a shortcut for the saved cursor, so keeping it+ # would narrow the fetch to comments newer than the last poll and hide exactly+ # the history the flag asked to see.+ review_comment_since = (+ _saved_str(saved, "review_comment_since")+ if resumed and args.since_review_comment_id is None+ else None+ )+ issue_comment_since = (+ _saved_str(saved, "issue_comment_since")+ if resumed and args.since_issue_comment_id is None+ else None+ )+ # --catch-up asks for existing activity to count as pending, and it already+ # overrides the saved cursors above. The new-PR cursor follows the same rule:+ # inheriting it would filter the fully fetched history right back down to what+ # the last cycle had already seen, which is the opposite of what was asked for.+ # An explicit --since-pr-id names a replay point and still wins.+ saved_pr_cursor = None if args.catch_up else _saved_int(saved, "pr_cursor")+ since_pr_id = args.since_pr_id if args.since_pr_id is not None else saved_pr_cursor+try:if args.pr is not None:- state, requests_per_poll_count = _fetch_state(args.repo, args.pr, token)+ state, requests_per_poll_count = _fetch_state(+ args.repo,+ args.pr,+ token,+ cache=cache,+ review_comment_since=review_comment_since,+ issue_comment_since=issue_comment_since,+ )else:initial_pr_stop_after_id = Noneinitial_pr_max_pages = None- if args.since_pr_id is not None and not args.catch_up:- initial_pr_stop_after_id = args.since_pr_id+ if since_pr_id is not None and not args.catch_up:+ initial_pr_stop_after_id = since_pr_idelif not args.catch_up:initial_pr_max_pages = 1state, requests_per_poll_count = _fetch_new_pr_state(@@ -399,6 +1287,7 @@ def main() -> int:token,stop_after_id=initial_pr_stop_after_id,max_pages=initial_pr_max_pages,+ cache=cache,)except urllib.error.HTTPError as err:print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)@@ -432,31 +1321,31 @@ def main() -> int:bootstrap_requests = 0if args.pr is not None:- review_cursor = (- args.since_review_id- if args.since_review_id is not None- else (0 if args.catch_up else max_id(state["reviews"]))- )- review_comment_cursor = (- args.since_review_comment_id- if args.since_review_comment_id is not None- else (0 if args.catch_up else max_id(state["review_comments"]))++ def _initial_cursor(flag_value: int | None, saved_key: str, items_key: str) -> int:+ if flag_value is not None:+ return flag_value+ if resumed:+ return resume_cursors[saved_key] or 0+ return 0 if args.catch_up else max_id(state[items_key])++ review_cursor = _initial_cursor(args.since_review_id, "review_cursor", "reviews")+ review_comment_cursor = _initial_cursor(+ args.since_review_comment_id, "review_comment_cursor", "review_comments")- issue_comment_cursor = (- args.since_issue_comment_id- if args.since_issue_comment_id is not None- else (0 if args.catch_up else max_id(state["issue_comments"]))+ issue_comment_cursor = _initial_cursor(+ args.since_issue_comment_id, "issue_comment_cursor", "issue_comments")- reaction_cursor = (- args.since_reaction_id- if args.since_reaction_id is not None- else (0 if args.catch_up else max_id(state["reactions"]))+ reaction_cursor = _initial_cursor(args.since_reaction_id, "reaction_cursor", "reactions")+ pr_status = (+ args.since_pr_status+ or (_saved_str(saved, "pr_status") if resumed else None)+ or _current_pr_status(state.get("pull_request")))- pr_status = args.since_pr_status or _current_pr_status(state.get("pull_request"))print((- "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s reaction=%s pr_status=%s catch_up=%s"+ "Watching GitHub PR %s#%s from cursors: review=%s review_comment=%s issue_comment=%s reaction=%s pr_status=%s catch_up=%s resumed=%s"% (args.repo,args.pr,@@ -466,25 +1355,162 @@ def main() -> int:reaction_cursor,pr_status,args.catch_up,+ resumed,)),file=sys.stderr,)- initial_output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status = _render_activity(- repo=args.repo,- pr_number=args.pr,- state=state,- review_cursor=review_cursor,- review_comment_cursor=review_comment_cursor,- issue_comment_cursor=issue_comment_cursor,- reaction_cursor=reaction_cursor,- pr_status=pr_status,- event_limit=args.event_limit,- viewer_login=viewer_login,- ignore_self_comments=not args.include_self_comments,+ def _render(cursors: tuple[int, int, int, int, str]) -> tuple[str | None, int, int, int, int, str]:+ return _render_activity(+ repo=args.repo,+ pr_number=args.pr,+ state=state,+ review_cursor=cursors[0],+ review_comment_cursor=cursors[1],+ issue_comment_cursor=cursors[2],+ reaction_cursor=cursors[3],+ pr_status=cursors[4],+ event_limit=args.event_limit,+ 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,+ )++ def _advance_since() -> None:+ nonlocal review_comment_since, issue_comment_since+ review_comment_since = later_since(review_comment_since, state["review_comments"])+ issue_comment_since = later_since(issue_comment_since, state["issue_comments"])++ def _pr_state_fields() -> dict[str, Any]:+ return {+ "review_cursor": review_cursor,+ "review_comment_cursor": review_comment_cursor,+ "issue_comment_cursor": issue_comment_cursor,+ "reaction_cursor": reaction_cursor,+ "pr_status": pr_status,+ "review_comment_since": review_comment_since,+ "issue_comment_since": issue_comment_since,+ "viewer_login": viewer_login,+ "token_fingerprint": token_fingerprint,+ }++ def _persist_pr_state(*, previous: dict[str, Any] | None = None) -> None:+ fields = _pr_state_fields()+ if previous is not None:+ # Committed state stays where the reported event is still unseen; the+ # cursors past it wait under STAGED_KEY, stamped with the delivery this+ # waiter started from so a later cycle can tell whether it has moved.+ fields = {+ **previous,+ STAGED_KEY: {"delivered_after": delivery_stamp, "cursors": fields},+ }+ _write_state_file(+ args.state_file,+ repo=args.repo,+ pr_number=args.pr,+ watch_identity=watch_identity,+ watch_id=watch_id,+ **fields,+ )++ def _report_pr(output: str, previous: dict[str, Any]) -> None:+ """Hand one report to the supervisor, staging or committing to match.++ Under ``vibe watch`` the cursors covering the event are staged first, so a+ crash before the supervisor queues the follow-up replays the report instead+ of skipping it. A manual run has no next cycle to promote anything, and+ printing there is the delivery, so it commits straight after.+ """++ if two_phase:+ _persist_pr_state(previous=previous)+ _deliver(output)+ return+ _deliver(output)+ _persist_pr_state()++ def _settle(+ first: tuple[str | None, int, int, int, int, str],+ pending: tuple[int, int, int, int, str],+ ) -> tuple[str | None, int, int, int, int, str]:+ """Re-poll while a batch is still landing so it costs one Agent turn."""++ nonlocal state+ if settle_seconds <= 0:+ return first++ best = first+ for _round in range(SETTLE_MAX_ROUNDS):+ # The batch is already worth a turn, so waiting for the rest of it must+ # not push the waiter past its own deadline: `vibe watch` kills the+ # process on timeout and the report would be lost with it. The sleep is+ # only half the cost — the re-poll behind it is several sequential+ # requests, each free to block for REQUEST_TIMEOUT_SECONDS — so both+ # have to fit in what is left, not just the sleep.+ if args.timeout > 0:+ remaining = args.timeout - (time.monotonic() - start)+ repoll_budget = max(1, requests_per_poll_count) * REQUEST_TIMEOUT_SECONDS+ if remaining <= settle_seconds + repoll_budget:+ print(+ "Settle window plus its re-poll would outlast --timeout; "+ "reporting the batch seen so far.",+ file=sys.stderr,+ )+ return best+ time.sleep(settle_seconds)+ try:+ state, _count = _fetch_state(+ args.repo,+ args.pr,+ token,+ cache=cache,+ review_comment_since=review_comment_since,+ issue_comment_since=issue_comment_since,+ )+ except Exception as err: # noqa: BLE001+ print(+ f"Settle re-poll failed; reporting the batch as first seen: {err}",+ file=sys.stderr,+ )+ return best+ # Rendered from the same cursors as the first hit, so the result is a+ # superset rather than a second, partial report.+ candidate = _render(pending)+ if candidate[0] is None:+ return best+ if candidate[1:] == best[1:]:+ return candidate+ best = candidate+ return best++ pending_cursors = (+ review_cursor,+ review_comment_cursor,+ issue_comment_cursor,+ reaction_cursor,+ pr_status,)- if initial_output is not None:+ pre_event_fields = _pr_state_fields()+ initial_result = _render(pending_cursors)+ if initial_result[0] is not None and not args.catch_up:+ initial_result = _settle(initial_result, pending_cursors)+ (+ initial_output,+ review_cursor,+ review_comment_cursor,+ issue_comment_cursor,+ reaction_cursor,+ pr_status,+ ) = initial_result+ _advance_since()+ if initial_output is None:+ # Persisted even with nothing to report: the baseline this cycle+ # established is exactly what the next cycle must resume from.+ _persist_pr_state()+ else:_write_cursor_output(args.cursor_output,review_cursor=review_cursor,@@ -493,23 +1519,55 @@ def main() -> int:reaction_cursor=reaction_cursor,pr_status=pr_status,)- print(initial_output)+ _report_pr(initial_output, pre_event_fields)return 0else:- pr_cursor = args.since_pr_id if args.since_pr_id is not None else (0 if args.catch_up else max_id(state["pull_requests"]))+ pr_cursor = since_pr_id if since_pr_id is not None else (0 if args.catch_up else max_id(state["pull_requests"]))print(f"Watching GitHub new PRs in {args.repo} from cursor: pr={pr_cursor} catch_up={args.catch_up}",file=sys.stderr,)+ pre_event_pr_cursor = pr_cursorinitial_output, pr_cursor = _render_new_pull_requests(repo=args.repo,state=state,pr_cursor=pr_cursor,event_limit=args.event_limit,)- if initial_output is not None:+ def _persist_new_pr_state(*, previous: int | None = None) -> None:+ fields: dict[str, Any] = {"pr_cursor": pr_cursor}+ if previous is not None:+ fields = {+ "pr_cursor": previous,+ STAGED_KEY: {+ "delivered_after": delivery_stamp,+ "cursors": {"pr_cursor": pr_cursor},+ },+ }+ _write_state_file(+ args.state_file,+ repo=args.repo,+ pr_number=None,+ watch_identity=watch_identity,+ watch_id=watch_id,+ **fields,+ )++ def _report_new_pr(output: str, previous: int) -> None:+ """Same staging contract as ``_report_pr``, over the single new-PR cursor."""++ if two_phase:+ _persist_new_pr_state(previous=previous)+ _deliver(output)+ return+ _deliver(output)+ _persist_new_pr_state()++ if initial_output is None:+ _persist_new_pr_state()+ else:_write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)- print(initial_output)+ _report_new_pr(initial_output, pre_event_pr_cursor)return 0while True:@@ -518,6 +1576,7 @@ def main() -> int:remaining_timeout = args.timeout - (time.monotonic() - start)if remaining_timeout <= 0:print("Timed out while waiting for GitHub PR activity", file=sys.stderr)+ print(cache.summary(), file=sys.stderr)return 124sleep_seconds = min(sleep_seconds, remaining_timeout)@@ -525,12 +1584,20 @@ def main() -> int:try:if args.pr is not None:- state, requests_per_poll_count = _fetch_state(args.repo, args.pr, token)+ state, requests_per_poll_count = _fetch_state(+ args.repo,+ args.pr,+ token,+ cache=cache,+ review_comment_since=review_comment_since,+ issue_comment_since=issue_comment_since,+ )else:state, requests_per_poll_count = _fetch_new_pr_state(args.repo,token,stop_after_id=pr_cursor if pr_cursor > 0 else None,+ cache=cache,)except urllib.error.HTTPError as err:if token is None and err.code in {403, 429}:@@ -573,20 +1640,31 @@ def main() -> int:effective_interval = target_intervalif args.pr is not None:- output, review_cursor, review_comment_cursor, issue_comment_cursor, reaction_cursor, pr_status = _render_activity(- repo=args.repo,- pr_number=args.pr,- state=state,- review_cursor=review_cursor,- review_comment_cursor=review_comment_cursor,- issue_comment_cursor=issue_comment_cursor,- reaction_cursor=reaction_cursor,- pr_status=pr_status,- event_limit=args.event_limit,- viewer_login=viewer_login,- ignore_self_comments=not args.include_self_comments,+ pending_cursors = (+ review_cursor,+ review_comment_cursor,+ issue_comment_cursor,+ reaction_cursor,+ pr_status,)+ pre_event_fields = _pr_state_fields()+ result = _render(pending_cursors)+ if result[0] is not None:+ result = _settle(result, pending_cursors)+ (+ output,+ review_cursor,+ review_comment_cursor,+ issue_comment_cursor,+ reaction_cursor,+ pr_status,+ ) = result+ _advance_since()if output is None:+ # Cursors also move when everything new was filtered out, and that+ # progress has to survive the cycle or the next one re-examines it.+ # Nothing is being reported, so there is no delivery to wait for.+ _persist_pr_state()continue_write_cursor_output(@@ -597,7 +1675,9 @@ def main() -> int:reaction_cursor=reaction_cursor,pr_status=pr_status,)+ report = partial(_report_pr, previous=pre_event_fields)else:+ pre_event_pr_cursor = pr_cursoroutput, pr_cursor = _render_new_pull_requests(repo=args.repo,state=state,@@ -605,12 +1685,35 @@ def main() -> int:event_limit=args.event_limit,)if output is None:+ _persist_new_pr_state()continue_write_new_pr_cursor_output(args.cursor_output, pr_cursor=pr_cursor)+ report = partial(_report_new_pr, previous=pre_event_pr_cursor)- print(output)+ print(cache.summary(), file=sys.stderr)+ report(output)return 0+def run_cli() -> int:+ """``main`` plus the terminal handling of an unusable ``--state-file``.++ Exit 1 and not the retryable 75: a directory that cannot be written to, a path+ already owned by another PR, and a file whose cursors cannot be read do not start+ working on the next cycle, and a forever watch retrying into one would poll+ indefinitely while losing the activity it saw.+ """++ try:+ return main()+ except StateFileError as err:+ print(+ f"{err}. Give this watch its own --state-file path (or fix or remove "+ "this one), then recreate the watch.",+ file=sys.stderr,+ )+ return 1++if __name__ == "__main__":- raise SystemExit(main())+ raise SystemExit(run_cli())diff --git a/storage/background.py b/storage/background.pyindex 44c089946..798dfc38d 100644--- a/storage/background.py+++ b/storage/background.py@@ -328,6 +328,16 @@ _DEFINITION_SESSION_KEY_FIELDS = ("session_key", "deliver_key")# ``core/watches.py`` (the ``timeout`` convention), read here to tell an ending# that ran out of time from one that failed._TIMEOUT_EXIT_CODE = 124+# The exit code a waiter carries when it ran to completion and found nothing worth+# an Agent turn. Written by ``core/watches.py`` (which imports it from here so the+# two layers cannot drift), read here because it is a CLEAN ending: the projections+# below classify every finished non-zero code as a failure, which reported an+# intentionally quiet cycle -- green CI, filtered review chatter -- as an error.+# 64 is also BSD ``sysexits`` EX_USAGE, so the supervisor only records it bare like+# this for a waiter that also printed the no-event marker; a generic command that+# rejects its own arguments is recorded with its error text and stays a failure+# here, because every branch above requires ``no_error``.+NO_EVENT_EXIT_CODE = 64# The runs a definition's own executions are recorded as. A watch's supervisor# heartbeat is *also* an ``agent_runs`` row and is ``running`` for as long as the# waiter lives, so counting it as an execution would make every healthy waiter@@ -635,6 +645,9 @@ def _successful_finished_definition_expression(definition_type: str, lifecycle:or_(run_definitions.c.last_exit_code.is_(None),run_definitions.c.last_exit_code == 0,+ # A quiet cycle is a successful one: the waiter ran, decided there+ # was nothing to report, and retired the ``once`` watch on purpose.+ run_definitions.c.last_exit_code == NO_EVENT_EXIT_CODE,),no_error,)@@ -683,6 +696,11 @@ def definition_resume_clear_columns(Lives here, next to the single UPDATE, because two doorways must agree onit: the Harness UI writes through ``set_definition_enabled`` while the CLIand supervisor write through ``core/watches.py``.++ Anything a resume must NOT rewrite therefore cannot be one of these columns.+ ``core.watches.DELIVERY_ACK_METADATA_KEY`` is the case in point: a waiter's+ proof that its last report reached the user has to outlive the cycle history+ that this clears."""if definition_type != "watch":@@ -754,7 +772,11 @@ def definition_lifecycle_detail(return "timeout"if timed_out is None and last_exit_code == _TIMEOUT_EXIT_CODE:return "timeout"- if last_exit_code not in (None, 0):+ # 64 is a completion, not a failure: the waiter finished its cycle and decided+ # it had nothing worth an Agent turn. Reading it as an ending that "went wrong"+ # made a quiet watch — the whole point of the code — look broken in+ # ``vibe watch show/list`` and in the Harness UI.+ if last_exit_code not in (None, 0, NO_EVENT_EXIT_CODE):return "error"# Scheduled tasks never write an exit code, so the code alone would report# every failed one as a normal ending; ``last_error`` is where their failurediff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.pyindex 39548820f..0c2df7610 100644--- a/tests/test_cli_watch_command.py+++ b/tests/test_cli_watch_command.py@@ -15,6 +15,7 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from core import watchesfrom core.watches import ManagedWatchStore, WatchRuntimeStateStorefrom vibe import cli@@ -2009,3 +2010,16 @@ def test_watch_add_refuses_the_reserved_session_with_no_side_effects(assert started == [accepted["definition"]["id"]], (f"and an admitted watch really does start: {started}")+++def test_watch_add_help_states_the_no_event_marker_contract() -> None:+ """The help is a live caller of the waiter contract, not a description of it.++ A custom waiter written from this text is what the supervisor then judges, so+ guidance that named the exit code but not the marker sent people straight into+ a watch that reports a failure and disables itself.+ """+ text = cli._watch_add_examples_text()++ assert str(watches.NO_EVENT_EXIT_CODE) in text+ assert watches.NO_EVENT_MARKER in textdiff --git a/tests/test_command_runner.py b/tests/test_command_runner.pyindex dc8ba224c..acc39480d 100644--- a/tests/test_command_runner.py+++ b/tests/test_command_runner.py@@ -495,3 +495,26 @@ async def test_no_cap_returns_large_output_in_full(tmp_path: Path) -> None:assert len(result.stdout.encode("utf-8")) == 300000assert result.stdout_truncated is Falseassert result.stderr_truncated is False+++async def test_extra_env_reaches_the_child_without_replacing_its_environment(tmp_path: Path) -> None:+ """Callers can name the child's context without rebuilding the whole env.++ The supervisor owns the rest of the spawn environment (PATH, the isolation+ marker), so an extra variable is merged into it rather than passed instead of it.+ """+ result = await run_supervised_command(+ command=[+ sys.executable,+ "-c",+ "import os; print(os.environ.get('AVIBE_WATCH_ID', 'missing')); print(bool(os.environ.get('PATH')))",+ ],+ cwd=str(tmp_path),+ timeout_seconds=10,+ label="test extra env",+ extra_env={"AVIBE_WATCH_ID": "wat_123"},+ )++ assert result.exit_code == 0+ assert "wat_123" in result.stdout+ assert "True" in result.stdoutdiff --git a/tests/test_github_wait_common.py b/tests/test_github_wait_common.pynew file mode 100644index 000000000..a35e3756c--- /dev/null+++ b/tests/test_github_wait_common.py@@ -0,0 +1,212 @@+from __future__ import annotations++import importlib.util+import json+import urllib.error+from pathlib import Path+from unittest.mock import patch+++def _load_module():+ script_path = (+ Path(__file__).resolve().parents[1]+ / "skills"+ / "background-watch-hook"+ / "scripts"+ / "_github_wait_common.py"+ )+ spec = importlib.util.spec_from_file_location("_github_wait_common", script_path)+ module = importlib.util.module_from_spec(spec)+ assert spec is not None and spec.loader is not None+ spec.loader.exec_module(module)+ return module+++class _FakeResponse:+ def __init__(self, payload, *, etag: str | None = None) -> None:+ self._body = json.dumps(payload).encode("utf-8")+ self.headers = {"ETag": etag} if etag else {}++ def read(self) -> bytes:+ return self._body++ def __enter__(self):+ return self++ def __exit__(self, *_exc_info) -> bool:+ return False+++def _not_modified() -> urllib.error.HTTPError:+ return urllib.error.HTTPError(+ "https://api.github.com/example",+ 304,+ "Not Modified",+ hdrs=None,+ fp=None,+ )+++def test_github_get_without_cache_sends_no_conditional_header() -> None:+ module = _load_module()+ requests: list[object] = []++ def _fake_urlopen(request, timeout=None):+ requests.append(request)+ return _FakeResponse([{"id": 1}], etag='W/"abc"')++ with patch.object(module.urllib.request, "urlopen", side_effect=_fake_urlopen):+ payload = module.github_get("https://api.github.com/example", "token")++ assert payload == [{"id": 1}]+ assert requests[0].get_header("If-none-match") is None+++def test_github_get_revalidates_with_etag_and_reuses_the_cached_body() -> None:+ module = _load_module()+ cache = module.ResponseCache()+ requests: list[object] = []+ calls = 0++ def _fake_urlopen(request, timeout=None):+ nonlocal calls+ calls += 1+ requests.append(request)+ if calls == 1:+ return _FakeResponse([{"id": 1}], etag='W/"abc"')+ raise _not_modified()++ with patch.object(module.urllib.request, "urlopen", side_effect=_fake_urlopen):+ first = module.github_get("https://api.github.com/example", "token", cache=cache)+ second = module.github_get("https://api.github.com/example", "token", cache=cache)++ assert first == [{"id": 1}]+ # A 304 carries no body, so the caller has to get the previous one back.+ assert second == [{"id": 1}]+ assert requests[1].get_header("If-none-match") == 'W/"abc"'+ assert (cache.downloaded, cache.revalidated) == (1, 1)+ assert "1 revalidated as 304" in cache.summary()+++def test_github_get_caches_each_url_separately() -> None:+ module = _load_module()+ cache = module.ResponseCache()++ def _fake_urlopen(request, timeout=None):+ if request.full_url.endswith("/two"):+ return _FakeResponse([{"id": 2}], etag='W/"two"')+ return _FakeResponse([{"id": 1}], etag='W/"one"')++ with patch.object(module.urllib.request, "urlopen", side_effect=_fake_urlopen):+ module.github_get("https://api.github.com/one", "token", cache=cache)+ module.github_get("https://api.github.com/two", "token", cache=cache)++ assert cache.etag_for("https://api.github.com/one") == 'W/"one"'+ assert cache.etag_for("https://api.github.com/two") == 'W/"two"'+++def test_github_get_reraises_not_modified_without_a_cached_body() -> None:+ module = _load_module()+ cache = module.ResponseCache()++ with patch.object(module.urllib.request, "urlopen", side_effect=_not_modified()):+ try:+ module.github_get("https://api.github.com/example", "token", cache=cache)+ except urllib.error.HTTPError as err:+ assert err.code == 304+ else: # pragma: no cover - the call must not succeed+ raise AssertionError("expected the 304 to propagate")++ assert cache.revalidated == 0+++def test_github_get_does_not_cache_a_response_without_an_etag() -> None:+ module = _load_module()+ cache = module.ResponseCache()++ with patch.object(+ module.urllib.request,+ "urlopen",+ side_effect=lambda request, timeout=None: _FakeResponse([{"id": 1}]),+ ):+ module.github_get("https://api.github.com/example", "token", cache=cache)++ assert cache.etag_for("https://api.github.com/example") is None+++def test_list_paginated_passes_the_cache_to_every_page() -> None:+ module = _load_module()+ cache = module.ResponseCache()+ seen: list[object] = []++ def _fake_github_get(url, token, *, cache=None):+ seen.append(cache)+ return [{"id": 1}]++ with patch.object(module, "github_get", side_effect=_fake_github_get):+ module.list_paginated("https://api.github.com/example", "token", cache=cache)++ assert seen == [cache]+++def test_since_param_rewinds_past_the_newest_timestamp() -> None:+ module = _load_module()+ items = [+ {"id": 1, "created_at": "2026-08-04T06:47:10Z", "updated_at": "2026-08-04T06:47:10Z"},+ {"id": 2, "created_at": "2026-08-04T06:47:12Z", "updated_at": "2026-08-04T06:47:12Z"},+ ]++ # Two comments can share the newest second, so the filter has to start before it.+ assert module.since_param(items) == "2026-08-04T06:47:10Z"+++def test_since_param_prefers_the_edited_timestamp() -> None:+ module = _load_module()+ items = [{"id": 1, "created_at": "2026-08-04T06:00:00Z", "updated_at": "2026-08-04T09:00:02Z"}]++ assert module.since_param(items) == "2026-08-04T09:00:00Z"+++def test_since_param_is_none_without_usable_timestamps() -> None:+ module = _load_module()++ assert module.since_param([]) is None+ assert module.since_param([{"id": 1}]) is None+ assert module.since_param([{"id": 1, "created_at": "not-a-timestamp"}]) is None+++def test_later_since_never_rewinds_an_existing_filter() -> None:+ module = _load_module()+ previous = "2026-08-04T12:00:00Z"++ # An empty page means nothing new arrived, not that the cursor should reset.+ assert module.later_since(previous, []) == previous+ assert (+ module.later_since(previous, [{"id": 1, "created_at": "2026-08-01T00:00:00Z"}]) == previous+ )+ assert (+ module.later_since(previous, [{"id": 2, "created_at": "2026-08-04T13:00:02Z"}])+ == "2026-08-04T13:00:00Z"+ )+++def test_later_since_starts_from_nothing() -> None:+ module = _load_module()++ assert module.later_since(None, [{"id": 1, "created_at": "2026-08-04T13:00:02Z"}]) == (+ "2026-08-04T13:00:00Z"+ )+++def test_response_cache_summary_reports_an_idle_run() -> None:+ module = _load_module()+ cache = module.ResponseCache()++ assert "no GitHub requests" in cache.summary()+++def test_get_authenticated_login_still_works_uncached() -> None:+ module = _load_module()++ with patch.object(module, "github_get", return_value={"login": "qiqi"}):+ assert module.get_authenticated_login("token") == "qiqi"diff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.pyindex 057758bc3..869cf00e5 100644--- a/tests/test_harness_definition_lifecycle.py+++ b/tests/test_harness_definition_lifecycle.py@@ -33,6 +33,7 @@ from storage.background import (DEFINITION_RETIREMENT_COLUMNS,DEFINITION_STATUS_COUNTS,DEFINITION_STATUS_FILTERS,+ NO_EVENT_EXIT_CODE,SQLiteBackgroundTaskStore,_id_batches,compute_next_run_at,@@ -243,6 +244,46 @@ def test_counts_and_rows_come_from_one_expression(store) -> None:assert {row["lifecycle_state"] for row in rows} <= set(expected), status+def test_a_one_shot_watch_that_ended_quietly_counts_as_a_success(store) -> None:+ """Exit 64 retires a ``once`` watch cleanly, so the compact list hides it.++ The two projections have to agree with the supervisor about which codes are+ clean endings. While this one recognised only ``None``/``0``, a watch that+ ended on the no-event path stayed pinned to ``vibe watch list`` as unfinished+ business and reported itself as failed — the opposite of what it did.+ """+ _watch(+ store,+ "quiet",+ mode="once",+ enabled=False,+ last_finished_at=NOW,+ retired_at=NOW,+ last_exit_code=NO_EVENT_EXIT_CODE,+ )+ _watch(+ store,+ "broken",+ mode="once",+ enabled=False,+ last_finished_at=NOW,+ retired_at=NOW,+ last_exit_code=1,+ last_error="boom",+ )++ assert _state(store, "quiet") == "finished"+ compact = store.list_watches_page(+ page_request=PageRequest(page=1, limit=10), include_successful_finished=False+ )+ full = store.list_watches_page(+ page_request=PageRequest(page=1, limit=10), include_successful_finished=True+ )++ assert {row["id"] for row in compact.items} == {"broken"}+ assert {row["id"] for row in full.items} == {"quiet", "broken"}++def test_an_unknown_status_is_rejected_rather_than_silently_ignored(store) -> None:with pytest.raises(ValueError):store.list_watches_page(status="enabled", page_request=PageRequest(page=1, limit=5))@@ -270,6 +311,12 @@ def test_an_unknown_status_is_rejected_rather_than_silently_ignored(store) -> No# And the flag outranks the code in the other direction as well: a command# killed by the scheduler that still managed its own exit status.(137, "command timed out after 5 second(s)", True, "timeout"),+ # A waiter that finished its cycle and found nothing worth an Agent turn ended+ # cleanly. Reading 64 as a failure made the quiet path -- the reason the code+ # exists -- look broken everywhere a finished watch is rendered.+ (NO_EVENT_EXIT_CODE, None, None, "normal"),+ # The code does not excuse a real error the waiter also reported.+ (NO_EVENT_EXIT_CODE, "boom", None, "error"),],)def test_lifecycle_detail_names_how_a_finished_row_ended(diff --git a/tests/test_wait_for_github_action_runs.py b/tests/test_wait_for_github_action_runs.pyindex a0d4b772f..6482132b5 100644--- a/tests/test_wait_for_github_action_runs.py+++ b/tests/test_wait_for_github_action_runs.py@@ -346,3 +346,101 @@ def test_main_unexpected_startup_error_fails_fast() -> None:rc = module.main()assert rc == 1+++def test_main_only_on_failure_skips_agent_turn_for_green_run() -> None:+ module = _load_module()++ def _fake_fetch_workflow_runs(repo, token, *, branch=None, head_sha=None, max_pages=3):+ return (+ [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "head_branch": "main",+ "status": "completed",+ "conclusion": "success",+ "html_url": "https://github.com/example/actions/runs/1",+ }+ ],+ 1,+ )++ stdout = io.StringIO()+ stderr = io.StringIO()+ with (+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "_fetch_workflow_runs", side_effect=_fake_fetch_workflow_runs),+ patch(+ "sys.argv",+ [+ "wait_action.py",+ "--repo",+ "cyhhao/sub2api",+ "--branch",+ "main",+ "--sha",+ "abc123",+ "--workflow",+ "CI",+ "--only-on-failure",+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == module.NO_EVENT_EXIT_CODE+ # Nothing on stdout means vibe watch builds no follow-up prompt.+ assert stdout.getvalue() == ""+ # The code alone is sysexits EX_USAGE; the marker is what makes it a quiet cycle+ # rather than a failure, so the waiter has to print it.+ assert module.NO_EVENT_MARKER in stderr.getvalue()+ assert "All watched workflows succeeded" in stderr.getvalue()+++def test_main_only_on_failure_still_reports_failed_run() -> None:+ module = _load_module()++ def _fake_fetch_workflow_runs(repo, token, *, branch=None, head_sha=None, max_pages=3):+ return (+ [+ {+ "id": 1,+ "name": "CI",+ "head_sha": "abc123",+ "head_branch": "main",+ "status": "completed",+ "conclusion": "failure",+ "html_url": "https://github.com/example/actions/runs/1",+ }+ ],+ 1,+ )++ stdout = io.StringIO()+ with (+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "_fetch_workflow_runs", side_effect=_fake_fetch_workflow_runs),+ patch(+ "sys.argv",+ [+ "wait_action.py",+ "--repo",+ "cyhhao/sub2api",+ "--sha",+ "abc123",+ "--workflow",+ "CI",+ "--only-on-failure",+ ],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 0+ assert "GitHub Actions failure" in stdout.getvalue()+ assert "Failed workflow(s): CI" in stdout.getvalue()diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.pyindex deb0e0fa3..a7dd818f6 100644--- a/tests/test_wait_for_github_pr_activity.py+++ b/tests/test_wait_for_github_pr_activity.py@@ -2,11 +2,14 @@ from __future__ import annotationsimport ioimport importlib.util+import jsonimport urllib.errorfrom contextlib import redirect_stdoutfrom pathlib import Pathfrom unittest.mock import patch+import pytest+def _load_module():script_path = (@@ -489,7 +492,7 @@ def test_fetch_new_pr_state_stops_after_cursor() -> None:]]- def _fake_list_paginated_with_count(base_url, token, *, stop_after_id=None, max_pages=None):+ def _fake_list_paginated_with_count(base_url, token, *, stop_after_id=None, max_pages=None, cache=None):assert "pulls?state=all" in base_urlassert stop_after_id == 405assert max_pages is None@@ -510,7 +513,7 @@ def test_main_uses_since_pr_cursor_for_initial_new_pr_fetch() -> None:module = _load_module()calls: list[int | None] = []- def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None):+ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):calls.append((stop_after_id, max_pages))return ({@@ -557,7 +560,7 @@ def test_main_bootstraps_new_pr_watch_from_first_page_only() -> None:module = _load_module()calls: list[tuple[int | None, int | None]] = []- def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None):+ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):calls.append((stop_after_id, max_pages))if len(calls) == 1:return ({"pull_requests": []}, 1)@@ -597,7 +600,7 @@ def test_main_detects_pr_status_change_during_polling() -> None:module = _load_module()fetch_calls = 0- def _fake_fetch_state(repo, pr_number, token):+ def _fake_fetch_state(repo, pr_number, token, **kwargs):nonlocal fetch_callsfetch_calls += 1if fetch_calls == 1:@@ -654,7 +657,7 @@ def test_main_reduces_unauthenticated_new_pr_interval_after_bootstrap() -> None:fetch_calls: list[int | None] = []sleep_calls: list[float] = []- def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None):+ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):fetch_calls.append((stop_after_id, max_pages))if len(fetch_calls) == 1:return ({"pull_requests": []}, 50)@@ -762,3 +765,2339 @@ def test_main_returns_retry_exit_code_for_initial_pr_network_error() -> None:assert rc == 75assert "GitHub network error: temporary network failure" in stderr.getvalue()+++def test_render_activity_actionable_only_drops_bot_trigger_comment_but_advances_cursor() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [+ {+ "id": 301,+ "body": "@codex review",+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-301",+ "user": {"login": "teammate"},+ }+ ],+ "reactions": [],+ }++ output, _review_cursor, _review_comment_cursor, issue_comment_cursor, _reaction_cursor, _pr_status = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=module._compile_ignore_patterns(None, actionable_only=True),+ )++ assert output is None+ # Dropped once, never re-examined.+ assert issue_comment_cursor == 301+++ "body",+ [+ "@author fix the timeout handling",+ "@alice review the migration assumptions",+ "@bob merge after the release freeze",+ ],+)+def test_render_activity_actionable_only_keeps_a_human_request_that_opens_with_a_command_word(body: str) -> None:+ """A mention plus a command word is only noise when that is the whole comment.++ Suppressing one of these still advances the cursor, so the request would not be+ delayed — it would be lost, and the review-fix loop would never answer it.+ """+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [+ {+ "id": 301,+ "body": body,+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-301",+ "user": {"login": "teammate"},+ }+ ],+ "reactions": [],+ }++ output, _review_cursor, _review_comment_cursor, issue_comment_cursor, _reaction_cursor, _pr_status = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=module._compile_ignore_patterns(None, actionable_only=True),+ )++ assert output is not None+ assert body in output+ assert issue_comment_cursor == 301+++def test_render_activity_actionable_only_keeps_bot_trigger_comment_when_disabled() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [+ {+ "id": 301,+ "body": "@codex review",+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-301",+ "user": {"login": "teammate"},+ }+ ],+ "reactions": [],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ )++ assert output is not None+ assert "issue_comment #301" in output+++def test_render_activity_actionable_only_drops_bodyless_commented_review() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [+ {+ "id": 401,+ "state": "COMMENTED",+ "body": "",+ "html_url": "https://github.com/example/repo/pull/1#pullrequestreview-401",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+ ],+ "review_comments": [],+ "issue_comments": [],+ "reactions": [],+ }++ output, review_cursor, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=module._compile_ignore_patterns(None, actionable_only=True),+ )++ assert output is None+ assert review_cursor == 401+++def test_render_activity_actionable_only_keeps_inline_comments_and_verdicts() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [+ {+ "id": 402,+ "state": "CHANGES_REQUESTED",+ "body": "",+ "html_url": "https://github.com/example/repo/pull/1#pullrequestreview-402",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+ ],+ "review_comments": [+ {+ "id": 501,+ "path": "core/watches.py",+ "body": "This drops the cursor advance.",+ "html_url": "https://github.com/example/repo/pull/1#discussion_r501",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+ ],+ "issue_comments": [],+ "reactions": [],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=module._compile_ignore_patterns(None, actionable_only=True),+ )++ assert output is not None+ assert "review #402" in output+ assert "review_comment #501" in output+++def test_render_activity_actionable_only_keeps_codex_pass_reaction() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [],+ "reactions": [+ {+ "id": 601,+ "content": "+1",+ "created_at": "2026-04-02T13:05:42Z",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+ ],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=module._compile_ignore_patterns(None, actionable_only=True),+ )++ assert output is not None+ assert "pr_reaction #601" in output+++def test_render_activity_actionable_only_drops_draft_toggle_but_keeps_merge() -> None:+ module = _load_module()+ ignore_patterns = module._compile_ignore_patterns(None, actionable_only=True)+ draft_state = {+ "pull_request": {"number": 153, "state": "open", "draft": True},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [],+ "reactions": [],+ }++ output, _rc, _rcc, _icc, _reaction_cursor, pr_status = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=draft_state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=ignore_patterns,+ )++ assert output is None+ # The status still moves forward, so the transition is not re-detected.+ assert pr_status == "draft"++ merged_state = {+ "pull_request": {+ "number": 153,+ "state": "closed",+ "merged_at": "2026-04-02T14:00:00Z",+ "html_url": "https://github.com/example/repo/pull/153",+ },+ "reviews": [],+ "review_comments": [],+ "issue_comments": [],+ "reactions": [],+ }++ output, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=merged_state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ actionable_only=True,+ ignore_patterns=ignore_patterns,+ )++ assert output is not None+ assert "pr_status #153 open -> merged" in output+++def test_render_activity_ignores_configured_author_but_advances_cursor() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [+ {+ "id": 701,+ "body": "Looks good to me, shipping soon.",+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-701",+ "user": {"login": "NoisyBot"},+ }+ ],+ "reactions": [],+ }++ output, _rc, _rcc, issue_comment_cursor, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ ignored_authors=module._normalize_authors(["noisybot"]),+ )++ assert output is None+ assert issue_comment_cursor == 701+++def test_render_activity_ignores_custom_comment_pattern() -> None:+ module = _load_module()+ state = {+ "pull_request": {"number": 153, "state": "open", "draft": False},+ "reviews": [],+ "review_comments": [],+ "issue_comments": [+ {+ "id": 801,+ "body": "Deployed to staging: build 42",+ "html_url": "https://github.com/example/repo/pull/1#issuecomment-801",+ "user": {"login": "teammate"},+ }+ ],+ "reactions": [],+ }++ output, _rc, _rcc, issue_comment_cursor, *_rest = module._render_activity(+ repo="avibe-bot/avibe",+ pr_number=153,+ state=state,+ review_cursor=0,+ review_comment_cursor=0,+ issue_comment_cursor=0,+ reaction_cursor=0,+ pr_status="open",+ event_limit=8,+ ignore_patterns=module._compile_ignore_patterns(+ [r"^deployed to staging"], actionable_only=False+ ),+ )++ assert output is None+ assert issue_comment_cursor == 801+++def test_main_rejects_invalid_ignore_comment_pattern() -> None:+ module = _load_module()++ with (+ patch.object(module, "get_token", return_value="token"),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--ignore-comment-pattern",+ "([unclosed",+ ],+ ),+ ):+ rc = module.main()++ assert rc == 2+++def _pr_state(+ *,+ reviews=None,+ review_comments=None,+ issue_comments=None,+ reactions=None,+ pr_state="open",+):+ return {+ "pull_request": {+ "number": 153,+ "state": pr_state,+ "draft": False,+ "html_url": "https://github.com/example/repo/pull/153",+ },+ "reviews": reviews or [],+ "review_comments": review_comments or [],+ "issue_comments": issue_comments or [],+ "reactions": reactions or [],+ }+++def _review_comment(comment_id: int, *, body="Fix this", created_at="2026-08-04T10:00:00Z"):+ return {+ "id": comment_id,+ "body": body,+ "path": "core/watches.py",+ "created_at": created_at,+ "updated_at": created_at,+ "html_url": f"https://github.com/example/repo/pull/153#discussion_r{comment_id}",+ "user": {"login": "chatgpt-codex-connector[bot]"},+ }+++def test_fetch_state_narrows_comments_and_filters_reactions_server_side() -> None:+ module = _load_module()+ urls: list[str] = []++ def _fake_list_paginated_with_count(base_url, token, *, stop_after_id=None, max_pages=None, cache=None):+ urls.append(base_url)+ return [], 1++ with (+ patch.object(module, "list_paginated_with_count", side_effect=_fake_list_paginated_with_count),+ patch.object(module, "github_get", return_value={"number": 153, "state": "open"}),+ ):+ module._fetch_state(+ "avibe-bot/avibe",+ 153,+ "token",+ review_comment_since="2026-08-04T06:47:10Z",+ issue_comment_since="2026-08-04T06:47:10Z",+ )++ reviews_url = next(url for url in urls if url.endswith("/reviews"))+ review_comments_url = next(url for url in urls if "/pulls/153/comments" in url)+ issue_comments_url = next(url for url in urls if "/issues/153/comments" in url)+ reactions_url = next(url for url in urls if "/reactions" in url)++ # The reviews endpoint supports neither `since` nor a newest-first order, so it+ # must stay unfiltered and lean on revalidation instead.+ assert "since=" not in reviews_url+ assert "since=2026-08-04T06%3A47%3A10Z" in review_comments_url+ assert "since=2026-08-04T06%3A47%3A10Z" in issue_comments_url+ # Only the Codex pass reaction is ever reported, so the rest never travel.+ assert "content=%2B1" in reactions_url+++def test_fetch_state_omits_since_when_no_cursor_is_known() -> None:+ module = _load_module()+ urls: list[str] = []++ def _fake_list_paginated_with_count(base_url, token, *, stop_after_id=None, max_pages=None, cache=None):+ urls.append(base_url)+ return [], 1++ with (+ patch.object(module, "list_paginated_with_count", side_effect=_fake_list_paginated_with_count),+ patch.object(module, "github_get", return_value={"number": 153, "state": "open"}),+ ):+ module._fetch_state("avibe-bot/avibe", 153, "token")++ assert all("since=" not in url for url in urls)+++def test_fetch_state_shares_one_cache_across_every_request() -> None:+ module = _load_module()+ caches: list[object] = []+ sentinel = object()++ def _fake_list_paginated_with_count(base_url, token, *, stop_after_id=None, max_pages=None, cache=None):+ caches.append(cache)+ return [], 1++ with (+ patch.object(module, "list_paginated_with_count", side_effect=_fake_list_paginated_with_count),+ patch.object(module, "github_get", return_value={"number": 153, "state": "open"}) as fake_get,+ ):+ module._fetch_state("avibe-bot/avibe", 153, "token", cache=sentinel)++ assert caches == [sentinel, sentinel, sentinel, sentinel]+ assert fake_get.call_args.kwargs["cache"] is sentinel+++def test_main_settle_window_reports_a_batched_review_as_one_event() -> None:+ module = _load_module()+ fetches = 0++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ nonlocal fetches+ fetches += 1+ if fetches == 1:+ return _pr_state(), 1+ if fetches == 2:+ # First fragment of the batch is visible.+ return _pr_state(review_comments=[_review_comment(501)]), 1+ # The rest of the batch lands while the waiter is settling.+ return (+ _pr_state(review_comments=[_review_comment(501), _review_comment(502), _review_comment(503)]),+ 1,+ )++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--interval",+ "1",+ "--settle",+ "5",+ ],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ output = stdout.getvalue()+ assert rc == 0+ # One report, one Agent turn, all three comments in it.+ assert output.count("GitHub PR activity detected") == 1+ assert "review_comment #501" in output+ assert "review_comment #502" in output+ assert "review_comment #503" in output+++def test_main_settle_window_stops_once_the_batch_is_stable() -> None:+ module = _load_module()+ fetches = 0++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ nonlocal fetches+ fetches += 1+ if fetches == 1:+ return _pr_state(), 1+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1", "--settle", "5"],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 0+ # Bootstrap, the poll that found it, and a single confirming re-poll: a quiet+ # batch must not burn all the settle rounds.+ assert fetches == 3+ assert "review_comment #501" in stdout.getvalue()+++def test_main_settle_window_survives_a_failed_re_poll() -> None:+ module = _load_module()+ fetches = 0++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ nonlocal fetches+ fetches += 1+ if fetches == 1:+ return _pr_state(), 1+ if fetches == 2:+ return _pr_state(review_comments=[_review_comment(501)]), 1+ raise urllib.error.URLError("network went away mid-settle")++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1", "--settle", "5"],+ ),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ # A broken re-poll must not lose the event that was already detected.+ assert rc == 0+ assert "review_comment #501" in stdout.getvalue()+++def test_main_writes_the_state_file_even_with_nothing_to_report(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "cursors" / "pr-153.json"++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value="qiqi"),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 124+ saved = json.loads(state_file.read_text(encoding="utf-8"))+ # The baseline this cycle established is what the next cycle must resume from.+ assert saved["review_comment_cursor"] == 501+ assert saved["repo"] == "avibe-bot/avibe"+ assert saved["pr"] == 153+ assert saved["viewer_login"] == "qiqi"+ assert saved["token_fingerprint"] == module._token_fingerprint("token")+ assert saved["review_comment_since"] == "2026-08-04T09:59:58Z"+++def test_main_resumes_from_the_state_file_instead_of_re_baselining(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 400,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "review_comment_since": "2026-08-04T09:00:00Z",+ "issue_comment_since": "2026-08-04T09:00:00Z",+ "viewer_login": "qiqi",+ "token_fingerprint": module._token_fingerprint("token"),+ }+ ),+ encoding="utf-8",+ )+ since_values: list[str | None] = []++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ since_values.append(kwargs.get("review_comment_since"))+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login") as fake_login,+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)]),+ redirect_stdout(stdout),+ ):+ rc = module.main()++ assert rc == 0+ # A comment that arrived between cycles is reported instead of being swallowed+ # by a fresh baseline.+ assert "review_comment #501" in stdout.getvalue()+ # The stored `since` narrows the very first fetch of the new cycle.+ assert since_values == ["2026-08-04T09:00:00Z"]+ # The stored login spares a /user request per cycle.+ fake_login.assert_not_called()+++def test_main_re_resolves_the_login_when_the_token_changed(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 400,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "viewer_login": "someone-else",+ "token_fingerprint": module._token_fingerprint("old-token"),+ }+ ),+ encoding="utf-8",+ )++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="new-token"),+ patch.object(+ module, "get_authenticated_login", return_value="chatgpt-codex-connector[bot]"+ ) as fake_login,+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ # The cached login belonged to the previous credential. Reusing it would let the+ # new account's own comments wake the Agent, so the login is resolved again and+ # it is the fresh login that filters this cycle.+ fake_login.assert_called_once_with("new-token")+ assert rc == 124+ assert stdout.getvalue() == ""+ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["viewer_login"] == "chatgpt-codex-connector[bot]"+ assert saved["token_fingerprint"] == module._token_fingerprint("new-token")+++def test_state_file_never_stores_the_token_itself(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(), 1++ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="ghp_super_secret"),+ patch.object(module, "get_authenticated_login", return_value="qiqi"),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", io.StringIO()),+ ):+ module.main()++ raw = state_file.read_text(encoding="utf-8")+ # The fingerprint identifies the credential; it must never carry it.+ assert "ghp_super_secret" not in raw+ assert json.loads(raw)["token_fingerprint"] == module._token_fingerprint("ghp_super_secret")+++def test_main_replays_from_an_explicit_cursor_without_a_saved_since(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 500,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "review_comment_since": "2026-08-04T09:00:00Z",+ "issue_comment_since": "2026-08-04T09:00:00Z",+ }+ ),+ encoding="utf-8",+ )+ since_values: list[tuple[str | None, str | None]] = []++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ since_values.append((kwargs.get("review_comment_since"), kwargs.get("issue_comment_since")))+ return _pr_state(review_comments=[_review_comment(450)]), 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--state-file",+ str(state_file),+ "--since-review-comment-id",+ "400",+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ # An explicit cursor asks for a replay. The saved `since` would have filtered out+ # comment #450 server-side and the replay would have returned nothing. The stream+ # with no explicit cursor keeps its cheap incremental `since`.+ assert since_values == [(None, "2026-08-04T09:00:00Z")]+ assert rc == 0+ assert "review_comment #450" in stdout.getvalue()+++def test_main_refuses_a_state_file_belonging_to_another_pr(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-999.json"+ foreign = json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 999,+ "review_cursor": 0,+ "review_comment_cursor": 400,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ }+ )+ state_file.write_text(foreign, encoding="utf-8")++ stdout = io.StringIO()+ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ # Two watches sharing one path is a setup mistake, not something to paper over:+ # adopting the foreign cursors would skip this PR's history, and overwriting them+ # would blind the other watch. Stop instead, and leave the other file intact.+ assert rc == 1+ assert stdout.getvalue() == ""+ assert "belongs to avibe-bot/avibe#999" in stderr.getvalue()+ assert state_file.read_text(encoding="utf-8") == foreign+++def test_main_ignores_a_partial_state_file(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_comment_cursor": 400,+ "review_comment_since": "2026-08-04T09:00:00Z",+ }+ ),+ encoding="utf-8",+ )+ since_values: list[str | None] = []++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ since_values.append(kwargs.get("review_comment_since"))+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ # An incomplete cursor set cannot be combined with a narrowed fetch: the+ # missing baselines would have to come from a partial history.+ assert rc == 124+ assert since_values == [None]+++def test_main_refuses_to_poll_past_an_unreadable_state_file(tmp_path) -> None:+ """A corrupt state file is terminal, because its cursors are unknown.++ Warning and re-baselining looks like recovery and is a silent loss: the file DID+ hold a cursor, and everything that arrived between it and the fresh snapshot is+ skipped -- then the only evidence of how far the watch had got is overwritten. A+ forever watch would do that on every cycle. Stopping instead puts the choice with+ whoever can make it.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text("{ this is not json", encoding="utf-8")++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(), 1++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ assert rc == 1+ assert "is corrupt" in stderr.getvalue()+ # Left exactly as found: the operator decides, and the bytes are the evidence.+ assert state_file.read_text(encoding="utf-8") == "{ this is not json"+++def test_main_refuses_a_state_file_it_does_not_recognise(tmp_path) -> None:+ """Valid JSON of the wrong shape or version is unusable for the same reason.++ Its cursors may mean something else, or nothing this waiter can read, so resuming+ from them and overwriting them are both guesses about how far the watch had got.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ original = json.dumps({"version": module.STATE_FILE_VERSION + 1, "review_comment_cursor": 500})+ state_file.write_text(original, encoding="utf-8")++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ assert rc == 1+ assert "not in a recognised format" in stderr.getvalue()+ assert state_file.read_text(encoding="utf-8") == original+++def test_main_starts_over_from_an_empty_state_file(tmp_path) -> None:+ """A zero-byte file is an interrupted claim, not corruption.++ The claim creates the path exclusively and then writes it, so a cycle killed in+ between leaves nothing behind. No cursor was ever recorded there, so there is+ none to lose and refusing would strand the watch on a file only it created.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text("", encoding="utf-8")++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ assert rc == 124+ assert json.loads(state_file.read_text(encoding="utf-8"))["review_comment_cursor"] == 501+++def test_main_refuses_to_poll_when_the_state_file_cannot_be_written(tmp_path) -> None:+ """An unwritable ``--state-file`` is terminal, and terminal BEFORE the first poll.++ Warning and continuing left a forever watch polling without the cursors it was+ asked to keep: every fresh cycle re-baselines from the current PR, so activity+ that arrived between cycles is silently dropped — the exact loss the flag+ exists to prevent. Discovering that only when the cycle tries to save has+ already cost the activity that cycle observed.+ """+ module = _load_module()+ read_only = tmp_path / "read-only"+ read_only.mkdir()+ read_only.chmod(0o500)+ state_file = read_only / "pr-153.json"++ stderr = io.StringIO()+ try:+ with (+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()+ finally:+ read_only.chmod(0o700)++ # 1, not the retryable 75: a read-only directory does not start working next cycle.+ assert rc == 1+ assert "Cannot write state file" in stderr.getvalue()+ assert not state_file.exists()+++def test_main_refuses_to_poll_when_the_state_file_cannot_be_replaced(tmp_path) -> None:+ """The preflight has to probe the replace, not just the parent directory.++ A target that is a directory — a stale path, a mistyped mount — accepts new+ siblings all day and fails only at ``os.replace``. Probing creation alone let a+ fresh forever cycle establish a baseline, poll, and then lose it, which is+ exactly what the fail-before-poll promise rules out.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.mkdir()++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ assert rc == 1+ assert "Cannot write state file" in stderr.getvalue()+ # No scratch file left behind in the directory the probe failed on.+ assert list(state_file.parent.glob(".pr-153.json.*")) == []+++def test_state_file_preflight_leaves_saved_cursors_untouched(tmp_path) -> None:+ """The probe rewrites an existing state file with its own bytes, not with junk.++ Probing the replace means writing to the real path, so a watch resuming from+ good cursors has to come out the other side with exactly those cursors.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ saved = json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 400,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ }+ )+ state_file.write_text(saved, encoding="utf-8")++ module._verify_state_file_writable(str(state_file), repo="avibe-bot/avibe", pr_number=153)++ assert state_file.read_text(encoding="utf-8") == saved+ assert list(tmp_path.glob(".pr-153.json.*")) == []+++def test_state_file_preflight_claims_a_missing_path_before_polling(tmp_path) -> None:+ """A missing state file is owned from the start, and carries no cursors.++ Claiming before the first poll is what stops two watches that start together+ from both seeing an unowned path; writing only ownership is what keeps this+ cycle's baseline identical to the no-state-file case.+ """+ module = _load_module()+ state_file = tmp_path / "cursors" / "pr-153.json"++ module._verify_state_file_writable(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="abc123"+ )++ claim = {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": "abc123",+ "owner": None,+ }+ assert json.loads(state_file.read_text(encoding="utf-8")) == claim+ # No cursors, so a resume is not attempted and the cycle baselines as before.+ assert (+ module._load_state_file(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="abc123"+ )+ == claim+ )+ assert list(state_file.parent.glob(".pr-153.json.*")) == []+++def test_state_file_claim_is_visible_to_a_second_watch(tmp_path) -> None:+ """The loser of the creation race must be turned away, not left sharing the path."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"++ assert module._claim_state_file(state_file, repo="avibe-bot/avibe", pr_number=153) is True+ # A concurrent waiter for another PR reaches its own claim a moment later.+ assert module._claim_state_file(state_file, repo="avibe-bot/avibe", pr_number=158) is False+ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(str(state_file), repo="avibe-bot/avibe", pr_number=158)+++def test_watch_identity_separates_report_filters_but_not_pacing() -> None:+ """Two watches on one PR are the same owner only if they report the same things.++ Pacing options are deliberately outside the identity: a watch differing only in+ interval or settle window sees the same activity, so sharing cursors with it+ loses nothing, while a differing filter set does lose events.+ """+ module = _load_module()++ def _identity(*extra: str) -> str:+ with patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", *extra],+ ):+ return module._watch_identity(module._build_parser().parse_args())++ baseline = _identity("--interval", "60")+ assert _identity("--interval", "5", "--settle", "20", "--timeout", "0") == baseline+ assert _identity("--actionable-only") != baseline+ assert _identity("--include-self-comments") != baseline+ assert _identity("--ignore-author", "dependabot[bot]") != baseline+ assert _identity("--ignore-comment-pattern", "^nit") != baseline+ # Order and duplication are not identity: the same filter set has to hash alike+ # across cycles however the command happened to be written.+ assert _identity(+ "--ignore-author",+ "Renovate[bot]",+ "--ignore-author",+ "dependabot[bot]",+ "--ignore-author",+ "dependabot[bot]",+ ) == _identity("--ignore-author", "dependabot[bot]", "--ignore-author", "renovate[bot]")+++def test_load_state_file_rejects_another_watch_on_the_same_pr(tmp_path) -> None:+ """Same PR, different filters: the filtered watch would advance past the other's events."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": "actionable",+ "review_comment_cursor": 400,+ }+ ),+ encoding="utf-8",+ )++ with pytest.raises(module.StateFileOwnershipError) as err:+ module._load_state_file(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="everything"+ )++ assert "different reporting filters" in str(err.value)+++def test_load_state_file_adopts_a_file_written_before_identities_existed(tmp_path) -> None:+ """An absent identity cannot prove a conflict, so it must not invent one.++ Rejecting it would strand a watch on cursors it wrote itself under an older+ build of this waiter.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ saved = {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_comment_cursor": 400,+ }+ state_file.write_text(json.dumps(saved), encoding="utf-8")++ assert (+ module._load_state_file(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="everything"+ )+ == saved+ )+++def test_write_state_file_refuses_a_path_another_watch_now_owns(tmp_path) -> None:+ """Ownership is verified on every replacement, not only at startup.++ A waiter that lost the creation race by microseconds has already passed the+ preflight, so the replace itself is the last place to notice -- and overwriting+ the winner's cursors would make it re-baseline and skip real activity.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ other = json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 158,+ "review_comment_cursor": 400,+ }+ )+ state_file.write_text(other, encoding="utf-8")++ with pytest.raises(module.StateFileOwnershipError):+ module._write_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ review_comment_cursor=999,+ )++ assert state_file.read_text(encoding="utf-8") == other+++def test_write_state_file_refuses_a_sibling_watch_on_the_same_pr(tmp_path) -> None:+ """The write guard covers the same-PR case too, not just a foreign PR."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ other = json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": "actionable",+ "review_comment_cursor": 400,+ }+ )+ state_file.write_text(other, encoding="utf-8")++ with pytest.raises(module.StateFileOwnershipError):+ module._write_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="everything",+ review_comment_cursor=999,+ )++ assert state_file.read_text(encoding="utf-8") == other+++def _new_pr(pr_id: int, number: int) -> dict[str, object]:+ return {+ "id": pr_id,+ "number": number,+ "title": f"PR {number}",+ "state": "open",+ "html_url": f"https://github.com/example/repo/pull/{number}",+ "user": {"login": "cyhhao"},+ }+++def _run_new_pr_catch_up(module, state_file, *extra: str) -> str:+ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):+ return {"pull_requests": [_new_pr(400, 157), _new_pr(410, 158)]}, 1++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--new-prs",+ "--catch-up",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ *extra,+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 0+ return stdout.getvalue()+++def test_main_new_prs_catch_up_ignores_the_saved_cursor(tmp_path) -> None:+ """--catch-up means "report what is already there", saved cursor or not.++ The PR-activity path already lets --catch-up override saved cursors; inheriting+ the saved new-PR cursor filtered the freshly fetched history back down to what+ the previous cycle had seen, so the flag reported nothing.+ """+ module = _load_module()+ state_file = tmp_path / "new-prs.json"+ state_file.write_text(+ json.dumps({"version": module.STATE_FILE_VERSION, "repo": "avibe-bot/avibe", "pr": None, "pr_cursor": 410}),+ encoding="utf-8",+ )++ output = _run_new_pr_catch_up(module, state_file)++ assert "pull_request #157" in output+ assert "pull_request #158" in output+++def test_main_new_prs_catch_up_still_honours_an_explicit_cursor(tmp_path) -> None:+ """Only an explicitly supplied cursor narrows a catch-up."""+ module = _load_module()+ state_file = tmp_path / "new-prs.json"+ state_file.write_text(+ json.dumps({"version": module.STATE_FILE_VERSION, "repo": "avibe-bot/avibe", "pr": None, "pr_cursor": 300}),+ encoding="utf-8",+ )++ output = _run_new_pr_catch_up(module, state_file, "--since-pr-id", "400")++ assert "pull_request #157" not in output+ assert "pull_request #158" in output+++def test_main_stops_when_persisting_advanced_cursors_fails(tmp_path) -> None:+ """The same rule once polling is under way: losing cursors stops the watch."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ def _replace_then_break(src, dst):+ # The preflight claims the missing file with an exclusive create, so every+ # replace here belongs to a cursor write: the disk goes away while the watch+ # is already polling, which is the case this test is about.+ raise OSError("disk went away")++ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.os, "replace", side_effect=_replace_then_break),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.run_cli()++ assert rc == 1+ assert "Could not write state file" in stderr.getvalue()+++def test_main_state_file_round_trips_new_pr_cursor(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "new-prs.json"++ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):+ return (+ {+ "pull_requests": [+ {+ "id": 410,+ "number": 158,+ "title": "New PR",+ "state": "open",+ "html_url": "https://github.com/example/repo/pull/158",+ "user": {"login": "cyhhao"},+ }+ ]+ },+ 1,+ )++ stdout = io.StringIO()+ with (+ patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep", return_value=None),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--new-prs",+ "--timeout",+ "0.0001",+ "--interval",+ "1",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 124+ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["pr_cursor"] == 410+ assert saved["pr"] is None+++def test_main_rejects_a_bad_ignore_pattern_without_claiming_the_state_file(tmp_path) -> None:+ """Argument validation happens before any state is claimed.++ Claiming first left the file owned by a watch identity derived from the very+ pattern that was rejected, so the corrected re-run was refused as a different+ watch's state until the file was deleted by hand.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ stderr = io.StringIO()++ with (+ patch.object(module, "get_token", return_value="token"),+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--ignore-comment-pattern",+ "[unclosed",+ "--state-file",+ str(state_file),+ ],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 2+ assert "Invalid --ignore-comment-pattern" in stderr.getvalue()+ assert not state_file.exists()+++def test_main_rejects_missing_auth_without_claiming_the_state_file(tmp_path) -> None:+ """The same rule for the auth precondition."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ stderr = io.StringIO()++ with (+ patch.object(module, "get_token", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 2+ assert "GitHub authentication is required" in stderr.getvalue()+ assert not state_file.exists()+++def test_state_file_records_the_managed_watch_that_owns_it() -> None:+ """Two identically configured watches still cannot share one state file.++ The filter digest is equal for both, so only the managed watch id tells them+ apart. It is read from the environment `vibe watch` sets for the cycle.+ """+ module = _load_module()++ with patch.dict("os.environ", {module.WATCH_ID_ENV: "wat_123"}, clear=False):+ assert module._managed_watch_id() == "wat_123"+ with patch.dict("os.environ", {module.WATCH_ID_ENV: " "}, clear=False):+ assert module._managed_watch_id() is None+++def test_load_state_file_rejects_a_sibling_watch_with_the_same_filters(tmp_path) -> None:+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": "abc123",+ "owner": "wat_first",+ }+ ),+ encoding="utf-8",+ )++ with pytest.raises(module.StateFileOwnershipError) as excinfo:+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )++ assert "belongs to watch wat_first" in str(excinfo.value)+ # A manual run has no watch id either, and cannot prove it is ``wat_first`` -- so+ # it is refused too. Adopting it would strip the owner on the next write and leave+ # the watch resuming from cursors covering activity it never delivered.+ with pytest.raises(module.StateFileOwnershipError) as manual:+ module._load_state_file(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="abc123"+ )+ assert "belongs to watch wat_first" in str(manual.value)+++def test_main_skips_the_settle_window_that_would_outlast_the_timeout(tmp_path) -> None:+ """A settle window is never worth losing the report to a timeout kill.++ `vibe watch` terminates the waiter at its deadline, so re-polling past that+ point throws away the batch that was already worth an Agent turn.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 500,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "viewer_login": "qiqi",+ "token_fingerprint": module._token_fingerprint("token"),+ }+ ),+ encoding="utf-8",+ )+ fetches: list[object] = []++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ fetches.append(kwargs)+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ stderr = io.StringIO()+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep") as fake_sleep,+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--settle",+ "30",+ "--timeout",+ "5",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 0+ assert "review_comment #501" in stdout.getvalue()+ assert "Settle window plus its re-poll would outlast --timeout" in stderr.getvalue()+ # No settle sleep, and no settle re-poll: one fetch is the whole run.+ fake_sleep.assert_not_called()+ assert len(fetches) == 1+++def test_main_skips_the_settle_window_when_only_its_sleep_would_fit(tmp_path) -> None:+ """The sleep is only half the settle cost; the re-poll behind it needs room too.++ A supervisor and waiter that share a deadline would otherwise be killed mid-fetch,+ with the already-detected batch still unreported.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 500,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "viewer_login": "qiqi",+ "token_fingerprint": module._token_fingerprint("token"),+ }+ ),+ encoding="utf-8",+ )+ fetches: list[object] = []++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ fetches.append(kwargs)+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ stderr = io.StringIO()+ # A 5s settle fits in the 20s left, but the request budget behind it does not.+ assert module.REQUEST_TIMEOUT_SECONDS > 5+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch.object(module.time, "sleep") as fake_sleep,+ patch(+ "sys.argv",+ [+ "wait_pr.py",+ "--repo",+ "avibe-bot/avibe",+ "--pr",+ "153",+ "--settle",+ "5",+ "--timeout",+ "20",+ "--state-file",+ str(state_file),+ ],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", stderr),+ ):+ rc = module.main()++ assert rc == 0+ assert "review_comment #501" in stdout.getvalue()+ fake_sleep.assert_not_called()+ assert len(fetches) == 1+++def _stdout_at_persist(module, stdout: io.StringIO) -> list[str]:+ """Record what had already been written to stdout each time state was saved."""++ snapshots: list[str] = []+ real_write = module._write_state_file++ def _spy(*args, **kwargs):+ snapshots.append(stdout.getvalue())+ return real_write(*args, **kwargs)++ module._write_state_file = _spy+ return snapshots+++def test_main_commits_cursors_only_after_the_event_is_reported(tmp_path) -> None:+ """A manual run's reported event moves its cursors after the report, not before.++ `vibe watch` builds the follow-up from a completed process, so a kill between+ the two orderings has opposite costs: commit-then-report loses the event for+ good, because the saved cursors have moved past it and no follow-up carried it,+ while report-then-commit costs at most one repeated report next cycle.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_cursor": 0,+ "review_comment_cursor": 500,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ "viewer_login": "qiqi",+ "token_fingerprint": module._token_fingerprint("token"),+ }+ ),+ encoding="utf-8",+ )++ def _fake_fetch_state(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ snapshots = _stdout_at_persist(module, stdout)+ with (+ patch.object(module, "_fetch_state", side_effect=_fake_fetch_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 0+ assert "review_comment #501" in stdout.getvalue()+ # One save, and the report was already out when it happened.+ assert len(snapshots) == 1+ assert "review_comment #501" in snapshots[0]+ assert json.loads(state_file.read_text(encoding="utf-8"))["review_comment_cursor"] == 501+++def test_main_new_prs_commits_the_cursor_only_after_the_event_is_reported(tmp_path) -> None:+ """The new-PR path has the same ordering."""+ module = _load_module()+ state_file = tmp_path / "new-prs.json"+ state_file.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": None,+ "pr_cursor": 400,+ }+ ),+ encoding="utf-8",+ )++ def _fake_fetch_new_pr_state(repo, token, *, stop_after_id=None, max_pages=None, cache=None):+ return {"pull_requests": [_new_pr(400, 157), _new_pr(410, 158)]}, 1++ stdout = io.StringIO()+ snapshots = _stdout_at_persist(module, stdout)+ with (+ patch.object(module, "_fetch_new_pr_state", side_effect=_fake_fetch_new_pr_state),+ patch.object(module, "get_token", return_value="token"),+ patch.object(module, "get_authenticated_login", return_value=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--new-prs", "--state-file", str(state_file)],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 0+ assert "pull_request #158" in stdout.getvalue()+ assert len(snapshots) == 1+ assert "pull_request #158" in snapshots[0]+ assert json.loads(state_file.read_text(encoding="utf-8"))["pr_cursor"] == 410+++def _managed_state(module, path, watch_id: str | None, **fields) -> None:+ """A state file already owned by ``watch_id``, so a managed run resumes from it."""++ path.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "watch": None,+ "owner": watch_id,+ "review_cursor": 0,+ "review_comment_cursor": 500,+ "issue_comment_cursor": 0,+ "reaction_cursor": 0,+ "pr_status": "open",+ **fields,+ }+ ),+ encoding="utf-8",+ )+++def _run_managed(module, state_file, fetch, *, delivery: str = ""):+ """One managed cycle over ``state_file``, told when this watch last delivered."""++ env = {module.WATCH_ID_ENV: "wat_9", module.LAST_DELIVERY_ENV: delivery}+ stdout = io.StringIO()+ 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=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()+ return rc, stdout.getvalue(), json.loads(state_file.read_text(encoding="utf-8"))+++def test_a_managed_run_stages_the_cursors_that_cover_its_report(tmp_path) -> None:+ """Under `vibe watch` the reported event's cursors are staged, not committed.++ Flushing stdout is not delivery: the supervisor reads the report only after the+ process exits, so this process cannot know its report survived. Committing at+ report time therefore drops the event whenever the service dies in between --+ the saved cursors have moved past it and no follow-up ever carried it. So the+ committed cursors stay put and the advanced ones wait under ``STAGED_KEY``,+ written down BEFORE the report leaves, for the next cycle to resolve.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _managed_state(module, state_file, "wat_9")++ def _fetch(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ rc, stdout, payload = _run_managed(module, state_file, _fetch, delivery="2026-08-04T10:00:00+00:00")++ assert rc == 0+ assert "review_comment #501" in stdout+ # Still pointing before the event that was just reported.+ assert payload["review_comment_cursor"] == 500+ assert payload[module.STAGED_KEY]["cursors"]["review_comment_cursor"] == 501+ # Stamped with the delivery this cycle started from, which is what a later cycle+ # compares against to learn whether this report was queued.+ assert payload[module.STAGED_KEY]["delivered_after"] == "2026-08-04T10:00:00+00:00"+++def test_a_managed_run_promotes_the_staged_cursors_once_the_report_was_delivered(tmp_path) -> None:+ """A delivery stamp that has moved since staging means the report was queued.++ The comparison is what makes this survive a restart, and makes a ``once`` watch+ resumed long after its single report promote rather than replay it: the stamp is+ still on the watch, so "was it delivered" is answerable at any later time.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _managed_state(+ module,+ state_file,+ "wat_9",+ **{+ module.STAGED_KEY: {+ "delivered_after": "2026-08-04T10:00:00+00:00",+ "cursors": {"review_comment_cursor": 501, "review_cursor": 0},+ }+ },+ )++ saved = module._load_state_file(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity=None, watch_id="wat_9"+ )+ with patch("sys.stderr", io.StringIO()):+ resolved = module._resolve_staged_state(+ str(state_file),+ saved,+ delivery="2026-08-04T10:05:00+00:00",+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity=None,+ watch_id="wat_9",+ )++ assert resolved["review_comment_cursor"] == 501+ assert module.STAGED_KEY not in resolved+ # Written down before any polling, so the promotion is decided exactly once.+ payload = json.loads(state_file.read_text(encoding="utf-8"))+ assert payload["review_comment_cursor"] == 501+ assert module.STAGED_KEY not in payload+++def test_a_managed_run_reports_the_event_again_when_it_was_never_delivered(tmp_path) -> None:+ """An unchanged delivery stamp means the report was never queued: replay it.++ One repeated Agent turn is the cost of the staged cursors being dropped; the+ alternative -- promoting them anyway -- is an event nobody ever hears about.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _managed_state(+ module,+ state_file,+ "wat_9",+ **{+ module.STAGED_KEY: {+ "delivered_after": "2026-08-04T10:00:00+00:00",+ "cursors": {"review_comment_cursor": 501, "review_cursor": 0},+ }+ },+ )++ def _fetch(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ rc, stdout, payload = _run_managed(module, state_file, _fetch, delivery="2026-08-04T10:00:00+00:00")++ assert rc == 0+ assert "review_comment #501" in stdout+ assert payload["review_comment_cursor"] == 500+ assert payload[module.STAGED_KEY]["cursors"]["review_comment_cursor"] == 501+++def test_a_manual_run_stages_nothing_because_printing_is_its_delivery(tmp_path) -> None:+ """No watch id, no next cycle: staged cursors would be promoted by nobody.++ The file is deliberately ownerless: a manual run is refused a state file that+ names a watch, so an owned one would fail the preflight before this test could+ observe what it stages.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _managed_state(module, state_file, None)++ def _fetch(repo, pr_number, token, **kwargs):+ return _pr_state(review_comments=[_review_comment(501)]), 1++ stdout = io.StringIO()+ with (+ patch.dict("os.environ", {module.WATCH_ID_ENV: "", module.LAST_DELIVERY_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=None),+ patch(+ "sys.argv",+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--state-file", str(state_file)],+ ),+ redirect_stdout(stdout),+ patch("sys.stderr", io.StringIO()),+ ):+ rc = module.main()++ assert rc == 0+ payload = json.loads(state_file.read_text(encoding="utf-8"))+ assert payload["review_comment_cursor"] == 501+ assert module.STAGED_KEY not in payload+++def _ownerless_state(module, path, **fields) -> None:+ path.write_text(+ json.dumps(+ {+ "version": module.STATE_FILE_VERSION,+ "repo": "avibe-bot/avibe",+ "pr": 153,+ "review_comment_cursor": 500,+ **fields,+ }+ ),+ encoding="utf-8",+ )+++def test_preflight_adopts_an_ownerless_state_file_for_a_managed_watch(tmp_path) -> None:+ """An absent owner fits every managed watch, so it must not stay absent.++ A file left by a manual run would otherwise be adopted by two managed watches at+ once; each would poll and then overwrite the other's cursors, skipping the+ activity in between for good.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file)++ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_first",+ )++ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["owner"] == "wat_first"+ assert saved["watch"] == "abc123"+ # Adoption takes the name, not the cursors: a resumed watch keeps its baseline.+ assert saved["review_comment_cursor"] == 500++ # The second managed watch now finds a claim instead of an open path: the preflight+ # leaves it alone and the load refuses it.+ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+ assert json.loads(state_file.read_text(encoding="utf-8"))["owner"] == "wat_first"+ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+++def test_preflight_leaves_an_ownerless_state_file_alone_for_a_manual_run(tmp_path) -> None:+ """Only a managed watch has a name to claim the path with.++ A manual run must not stamp itself on a watch's file, or the watch's next cycle+ would be refused its own state.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file)++ module._verify_state_file_writable(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="abc123"+ )++ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved.get("owner") is None+ assert saved["review_comment_cursor"] == 500+++def test_preflight_does_not_adopt_another_watchs_state_file(tmp_path) -> None:+ """A path that already carries somebody else's claim is left untouched."""+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file, watch="abc123", owner="wat_first")++ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )++ assert json.loads(state_file.read_text(encoding="utf-8"))["owner"] == "wat_first"+ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+++def test_load_state_file_refuses_a_managed_watchs_file_for_a_manual_run(tmp_path) -> None:+ """A manual run cannot prove it is the watch that owns the path, so it is refused.++ Adopting it instead is silent data loss, not sharing: the manual run reports to a+ terminal, then ``_write_state_file`` stamps ``owner: null`` over the claim while+ advancing the cursors. The watch adopts its own file back as ownerless and resumes+ past activity its Agent follow-up was never sent.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file, watch="abc123", owner="wat_first")++ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id=None,+ )++ # The preflight leaves the claim exactly as it found it.+ module._verify_state_file_writable(+ str(state_file), repo="avibe-bot/avibe", pr_number=153, watch_identity="abc123"+ )+ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["owner"] == "wat_first"+ assert saved["review_comment_cursor"] == 500+++def test_preflight_claims_an_empty_state_file_for_a_managed_watch(tmp_path) -> None:+ """An interrupted claim must be finished, not rewritten empty.++ A zero-byte file carries no cursors, so the load treats it as a fresh baseline --+ but it also names no owner. Left that way, two managed watches pointed at the path+ both clear the preflight and poll, and one overwrites the other's cursors.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ state_file.write_text("", encoding="utf-8")++ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_first",+ )++ saved = json.loads(state_file.read_text(encoding="utf-8"))+ assert saved["owner"] == "wat_first"+ assert saved["watch"] == "abc123"+ assert saved["repo"] == "avibe-bot/avibe"+ assert saved["pr"] == 153+ # No cursors were invented: this cycle still baselines from the current PR.+ assert "review_comment_cursor" not in saved++ # The second managed watch now loses on the claim instead of sharing the path.+ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+ assert json.loads(state_file.read_text(encoding="utf-8"))["owner"] == "wat_first"+ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+++def test_preflight_does_not_rewrite_another_watchs_state_file(tmp_path) -> None:+ """A foreign file is left unprobed, not merely unadopted.++ The probe is an ``os.replace`` of bytes read a moment earlier, and the owning+ watch's own cursor writes do NOT take the preflight lock -- so probing its path can+ land stale bytes over a cursor it has just advanced, or over a ``pending`` handoff+ it is midway through, making it replay or lose activity.++ The assertion is on ``os.replace`` itself rather than on the resulting bytes: the+ probe rewrites the file with the bytes it already held, so content alone cannot+ tell a skipped write from a completed round trip.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file, watch="abc123", owner="wat_first")+ before = state_file.read_bytes()++ replaced = []+ real_replace = module.os.replace++ def _spy(src, dst, *args, **kwargs):+ replaced.append((src, dst))+ return real_replace(src, dst, *args, **kwargs)++ # Both shapes of foreign file: another watch on this PR, and another PR entirely.+ with patch.object(module.os, "replace", _spy):+ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+ module._verify_state_file_writable(+ str(state_file), repo="avibe-bot/avibe", pr_number=999, watch_identity="abc123"+ )++ assert replaced == [], f"the preflight wrote to a foreign state file: {replaced}"+ assert state_file.read_bytes() == before++ # Refusal still happens -- it just happens at the load, before any poll.+ with pytest.raises(module.StateFileOwnershipError):+ module._load_state_file(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_second",+ )+++def test_state_file_lock_serializes_the_ownership_decision(tmp_path) -> None:+ """The lock is held on a sidecar, not on the file that gets replaced.++ A lock on the state file's own inode would be released into thin air by the+ first atomic replace, leaving the second half of the decision unguarded.+ """+ module = _load_module()+ state_file = tmp_path / "pr-153.json"+ _ownerless_state(module, state_file)+ lock_file = tmp_path / "pr-153.json.lock"++ with module._state_file_lock(state_file):+ assert lock_file.exists()+ held = lock_file.stat().st_ino++ module._verify_state_file_writable(+ str(state_file),+ repo="avibe-bot/avibe",+ pr_number=153,+ watch_identity="abc123",+ watch_id="wat_first",+ )++ # The state file was replaced; the lock's identity survived it.+ assert lock_file.stat().st_ino == helddiff --git a/tests/test_watches.py b/tests/test_watches.pyindex 228fb8df1..98c09e953 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport json+import loggingimport osimport sysimport threading@@ -24,10 +25,16 @@ from core.process_isolation import (from core.runtime_work import RuntimeWorkItem, RuntimeWorkLane, RuntimeWorkSupervisorfrom core.scheduled_tasks import TaskExecutionStorefrom core.watches import (+ DELIVERY_ACK_METADATA_KEY,+ LAST_DELIVERY_ENV,+ NO_EVENT_EXIT_CODE,+ NO_EVENT_MARKER,+ WATCH_ID_ENV,ManagedWatchService,ManagedWatchStore,WatchRuntimeStateStore,_CycleResult,+ _cycle_env,_ManagedWatchRuntimeWorkHandler,_StaleWorkerRecovery,)@@ -37,6 +44,20 @@ TEST_MARKER = "test-watch-worker"TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)+def _quiet_waiter_command(summary: str = "") -> list[str]:+ """A waiter that ends a cycle the way the no-event protocol asks it to.++ The marker is half the signal: the exit code on its own is ``sysexits`` EX_USAGE+ and stays a failure.+ """++ script = "import sys; "+ if summary:+ script += f"print({summary!r}, file=sys.stderr); "+ script += f"print({NO_EVENT_MARKER!r}, file=sys.stderr); sys.exit({NO_EVENT_EXIT_CODE})"+ return [sys.executable, "-c", script]++class _FakeStdin:def __init__(self) -> None:self.payload = bytearray()@@ -1145,6 +1166,203 @@ def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path:assert request_store.list_pending() == []+def test_managed_watch_service_once_no_event_exit_finishes_without_follow_up(tmp_path: Path) -> None:+ store = ManagedWatchStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Green CI waiter",+ session_key="slack::channel::C123",+ command=_quiet_waiter_command(),+ shell_command=None,+ prefix="CI failed. Fix it.",+ cwd=None,+ mode="once",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ service.start()+ for _ in range(100):+ saved = store.get_watch(watch.id)+ if saved and not saved.enabled:+ break+ await asyncio.sleep(0.02)+ await service.stop()++ asyncio.run(_run())++ saved = store.get_watch(watch.id)+ assert saved is not None+ assert saved.enabled is False+ assert saved.last_exit_code == NO_EVENT_EXIT_CODE+ assert saved.last_error is None+ # The whole point: a completed cycle that found nothing costs no Agent turn.+ assert request_store.list_pending() == []+++def test_managed_watch_service_logs_what_a_quiet_cycle_suppressed(tmp_path: Path, caplog) -> None:+ """A cycle that reports nothing still has to leave its summary somewhere.++ No hook carries a no-event cycle's output, so the waiter's own account of what+ it saw and chose not to report — the green CI table, the filtered comments —+ died with the process. ``--only-on-failure`` documents that summary as+ inspectable, which it was not.+ """+ store = ManagedWatchStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Green CI waiter",+ session_key="slack::channel::C123",+ command=_quiet_waiter_command("All watched workflows succeeded: lint, build"),+ shell_command=None,+ prefix="CI failed. Fix it.",+ cwd=None,+ mode="once",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ service.start()+ for _ in range(100):+ saved = store.get_watch(watch.id)+ if saved and not saved.enabled:+ break+ await asyncio.sleep(0.02)+ await service.stop()++ with caplog.at_level(logging.INFO, logger="core.watches"):+ asyncio.run(_run())++ assert request_store.list_pending() == []+ quiet_logs = [record.getMessage() for record in caplog.records if "found nothing to report" in record.getMessage()]+ assert quiet_logs, caplog.text+ assert watch.id in quiet_logs[0]+ assert "All watched workflows succeeded: lint, build" in quiet_logs[0]+++def test_managed_watch_service_forever_no_event_exit_rearms_without_follow_up(tmp_path: Path) -> None:+ store = ManagedWatchStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Quiet forever waiter",+ session_key="slack::channel::C123",+ command=_quiet_waiter_command(),+ shell_command=None,+ prefix="Something happened.",+ cwd=None,+ mode="forever",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ service.start()+ await asyncio.sleep(0.08)+ await service.stop()++ asyncio.run(_run())++ saved = store.get_watch(watch.id)+ assert saved is not None+ assert saved.enabled is True+ assert saved.last_exit_code == NO_EVENT_EXIT_CODE+ assert saved.last_error is None+ assert request_store.list_pending() == []+++def test_managed_watch_service_treats_an_unmarked_exit_64_as_a_failure(tmp_path: Path) -> None:+ """64 is ``sysexits`` EX_USAGE, not a private Avibe signal.++ A generic watched command that rejects its own arguments exits 64. Reading that+ as a quiet cycle would swallow the failure notice the user relies on and, in+ forever mode, rerun the broken command for as long as the watch lives.+ """+ store = ManagedWatchStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Misconfigured forever waiter",+ session_key="slack::channel::C123",+ command=[+ sys.executable,+ "-c",+ f"import sys; print('usage: mytool [--flag]', file=sys.stderr); sys.exit({NO_EVENT_EXIT_CODE})",+ ],+ shell_command=None,+ prefix="Investigate the failure.",+ cwd=None,+ mode="forever",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ await _start_watch_service(service)+ for _ in range(100):+ if watch.id not in service._active_tasks:+ break+ await asyncio.sleep(0.02)+ await service.stop()++ asyncio.run(_run())++ saved = store.get_watch(watch.id)+ pending = request_store.list_pending()+ assert saved is not None+ # Stopped, recorded with its error text, and reported once — as before the+ # no-event code existed.+ assert saved.enabled is False+ assert saved.last_exit_code == NO_EVENT_EXIT_CODE+ assert saved.last_error and "usage: mytool" in saved.last_error+ assert len(pending) == 1+ assert "usage: mytool" in pending[0].prompt++def test_managed_watch_service_forever_non_retry_error_disables_and_enqueues_failure(tmp_path: Path) -> None:store = ManagedWatchStore(tmp_path / "watches.json")request_store = TaskExecutionStore(tmp_path / "task_requests")@@ -1243,6 +1461,67 @@ def test_managed_watch_service_fuses_watch_after_store_error(tmp_path: Path) ->assert request_store.list_pending() == []+def test_managed_watch_service_fuses_quiet_cycle_after_store_error(tmp_path: Path) -> None:+ """A quiet cycle commits through the same wrapper as every other result branch.++ Called synchronously, a raising ``mark_cycle_result`` escapes ``_run_cycle`` and+ kills the watch task with the store unfused and the cycle unrecorded. Reconcile+ then restarts the same quiet cycle and repeats it, so a real storage failure+ never reaches the user as one.+ """++ class FailingResultStore(ManagedWatchStore):+ def __init__(self, path: Path):+ super().__init__(path)+ self.starts = 0++ def mark_cycle_start(self, watch_id: str) -> bool:+ self.starts += 1+ return super().mark_cycle_start(watch_id)++ def mark_cycle_result(self, *args, **kwargs) -> bool:+ raise RuntimeError("database disk image is malformed")++ store = FailingResultStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Quiet with broken persistence",+ session_key="slack::channel::C123",+ command=_quiet_waiter_command("nothing to report"),+ shell_command=None,+ prefix="Should not storm.",+ cwd=None,+ mode="forever",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ await _start_watch_service(service)+ await asyncio.sleep(0.12)+ assert watch.id in service._fused_watch_ids+ await asyncio.sleep(0.08)+ await service.stop()++ asyncio.run(_run())++ assert store.starts == 1, "the fused store let the quiet cycle restart"+ assert service._store_error_fused is True+ # A quiet cycle authorises no hook, and a failed one must not invent it.+ assert request_store.list_pending() == []++def test_managed_watch_service_fuses_reconcile_after_store_read_error(tmp_path: Path, monkeypatch) -> None:monkeypatch.setattr("core.watches.WATCH_RECONCILE_INTERVAL_SECONDS", 0.01)@@ -3680,3 +3959,246 @@ def test_a_dropped_watch_mirror_recovers_with_no_unrelated_commit_to_wake_it() -"the durable row changed, so the failed write committed something and the ""recovery above was reading a different definition than the one that was dropped")+++def test_quiet_cycle_marker_must_be_a_line_of_its_own() -> None:+ """The marker is a protocol line, not a substring.++ A waiter that prints the marker's name while explaining the protocol — a usage+ message, a log line quoting it — would otherwise have its exit 64 read as a+ quiet cycle, and its failure notice would never reach the user.+ """+ from core.watches import _is_quiet_cycle++ def _result(text: str) -> _CycleResult:+ return _CycleResult(exit_code=NO_EVENT_EXIT_CODE, stdout="", stderr=text, timed_out=False)++ assert _is_quiet_cycle(_result(f"nothing new\n{NO_EVENT_MARKER}\n"))+ # Indentation is still a line of its own; the surrounding prose is not.+ assert _is_quiet_cycle(_result(f" {NO_EVENT_MARKER} "))+ assert not _is_quiet_cycle(_result(f"usage: exit 64 with '{NO_EVENT_MARKER}' to end quietly"))+ assert not _is_quiet_cycle(_result(f"{NO_EVENT_MARKER} is the marker"))+++def test_quiet_cycle_summary_keeps_the_end_of_a_long_waiter_report() -> None:+ """The verdict is at the end of a waiter's report, so truncate from the front.++ A green CI waiter prints the run table first and its conclusion last. Squashing+ from the front kept the table and dropped the one line worth logging.+ """+ from core.watches import NO_EVENT_SUMMARY_LOG_LIMIT, _squash_tail++ short = "All watched workflows succeeded: lint, build"+ assert _squash_tail(f" {short}\n", limit=NO_EVENT_SUMMARY_LOG_LIMIT) == short++ long_report = ("workflow line\n" * 500) + short+ squashed = _squash_tail(long_report, limit=NO_EVENT_SUMMARY_LOG_LIMIT)+ assert len(squashed) <= NO_EVENT_SUMMARY_LOG_LIMIT+ assert squashed.endswith(short)+ assert squashed.startswith("…")+++def test_a_cycle_is_told_when_this_watch_last_had_a_report_delivered(tmp_path: Path) -> None:+ """A waiter learns whether an earlier report of its own was ever delivered.++ A waiter cannot observe its own delivery: its stdout reaches the supervisor only+ after the process exits, so a waiter that wants to advance its own cursors past a+ reported event has to be told. What it is told is a count of delivered reports,+ bumped by ``_commit_cycle_result`` in the same transaction as the follow-up hook --+ so a waiter that staged cursors alongside the value it saw can compare, and a+ CHANGED value means its report was queued.++ A durable count rather than a one-shot flag handed to the next cycle: it is still+ correct after a restart, and for a ``once`` watch, whose one report is followed by+ no cycle at all until the user resumes it -- where a lost flag would replay an+ event that was delivered long ago. And it must NOT move on a quiet cycle, which+ queued nothing: a waiter would then promote cursors covering a report that was+ never delivered and skip the activity for good.+ """+ store = ManagedWatchStore()+ assert store._sqlite is not None, "this test needs the SQLite-backed store"+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ session_id = _bare_watch_session_row(workdir=tmp_path, anchor="slack_C_ack")+ watch = store.add_watch(+ name="Watch PR",+ session_key="",+ session_id=session_id,+ session_policy="existing",+ command=[sys.executable, "-c", "print('event')"],+ shell_command=None,+ prefix="PR activity.",+ cwd=None,+ mode="forever",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ metadata={"origin": "cli"},+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )+ service._running = True+ service._requires_service_lease = False++ # One event, one quiet cycle, then stop: the three states the flag has to+ # distinguish, in the order a forever watch meets them.+ scripted = [+ _CycleResult(exit_code=0, stdout="review_comment #501", stderr="", timed_out=False),+ _CycleResult(exit_code=NO_EVENT_EXIT_CODE, stdout="", stderr=NO_EVENT_MARKER, timed_out=False),+ _CycleResult(exit_code=NO_EVENT_EXIT_CODE, stdout="", stderr=NO_EVENT_MARKER, timed_out=False),+ ]+ told: list[str] = []++ async def _spy_cycle(watch_arg, *, timeout_seconds): # noqa: ANN001+ told.append(_cycle_env(watch_arg)[LAST_DELIVERY_ENV])+ if len(told) >= len(scripted):+ service._running = False+ return scripted[min(len(told) - 1, len(scripted) - 1)]++ service._run_cycle = _spy_cycle # type: ignore[method-assign]++ asyncio.run(service._run_watch(watch.id))++ assert told[0] == "", "nothing has been reported yet"+ assert told[1], "the event was delivered, so the stamp has to have moved"+ assert told[2] == told[1], "a quiet cycle queued no hook; the stamp must not move"+++def test_resuming_a_once_watch_keeps_what_it_already_delivered(tmp_path: Path) -> None:+ """A resume clears the cycle history and NOT the delivery acknowledgement.++ A ``once`` watch reports, retires, and is resumed by the user days later. That+ resume deliberately clears ``last_event_at`` -- the resumed watch begins a distinct+ cycle and its row must not claim an event it has not seen. But the waiter's staged+ cursors are still on disk beside the count they were staged against, and if that+ count resets too, the first cycle after the resume concludes its report never left+ and reports the same activity all over again.+ """+ store = ManagedWatchStore()+ assert store._sqlite is not None, "this test needs the SQLite-backed store"+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ session_id = _bare_watch_session_row(workdir=tmp_path, anchor="slack_C_resume_ack")+ watch = store.add_watch(+ name="Watch PR once",+ session_key="",+ session_id=session_id,+ session_policy="existing",+ command=[sys.executable, "-c", "print('event')"],+ shell_command=None,+ prefix="PR activity.",+ cwd=None,+ mode="once",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ metadata={"origin": "cli"},+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )+ service._running = True+ service._requires_service_lease = False++ async def _one_event(watch_arg, *, timeout_seconds): # noqa: ANN001+ return _CycleResult(exit_code=0, stdout="review_comment #501", stderr="", timed_out=False)++ service._run_cycle = _one_event # type: ignore[method-assign]+ asyncio.run(service._run_watch(watch.id))++ reported = store.get_watch(watch.id)+ assert reported is not None and not reported.enabled, "a once watch retires on its report"+ delivered = _cycle_env(reported)[LAST_DELIVERY_ENV]+ assert delivered == "1"++ resumed = store.set_enabled(watch.id, True)+ assert resumed.last_event_at is None, "the resume clears the cycle history it owns"+ assert _cycle_env(resumed)[LAST_DELIVERY_ENV] == delivered+ assert resumed.metadata["origin"] == "cli", "the ack rides along with the rest of the metadata"+++def test_the_cycle_environment_carries_the_watch_and_its_delivery_count() -> None:+ """Both facts reach the waiter as environment variables, empty for never.++ Metadata a writer never touched, or left as something other than a positive count,+ reads as "nothing delivered yet" -- the direction that reports a staged event twice+ rather than advancing past one that never left.+ """+ assert _cycle_env(SimpleNamespace(id="wat_9", metadata={})) == {+ WATCH_ID_ENV: "wat_9",+ LAST_DELIVERY_ENV: "",+ }+ assert _cycle_env(SimpleNamespace(id="wat_9", metadata={DELIVERY_ACK_METADATA_KEY: 3})) == {+ WATCH_ID_ENV: "wat_9",+ LAST_DELIVERY_ENV: "3",+ }+ for broken in ("3", True, 0, -1, None, {"count": 3}):+ assert _cycle_env(SimpleNamespace(id="wat_9", metadata={DELIVERY_ACK_METADATA_KEY: broken})) == {+ WATCH_ID_ENV: "wat_9",+ LAST_DELIVERY_ENV: "",+ }+++def test_managed_watch_service_names_the_watch_in_the_cycle_environment(tmp_path: Path) -> None:+ """A waiter can tell which watch it is a cycle of.++ Waiters that keep per-watch state on disk own that state by this id, so two+ identically configured watches cannot silently share one state file.+ """+ store = ManagedWatchStore(tmp_path / "watches.json")+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ echoed = tmp_path / "watch-id.txt"+ watch = store.add_watch(+ name="Identity echo waiter",+ session_key="slack::channel::C123",+ command=[+ sys.executable,+ "-c",+ (+ "import os, pathlib; "+ f"pathlib.Path({str(echoed)!r}).write_text(os.environ.get('AVIBE_WATCH_ID', ''))"+ ),+ ],+ shell_command=None,+ prefix="Something happened.",+ cwd=None,+ mode="once",+ timeout_seconds=5,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=0.01,+ post_to=None,+ deliver_key=None,+ )+ service = ManagedWatchService(+ controller=SimpleNamespace(),+ store=store,+ request_store=request_store,+ runtime_store=runtime_store,+ )++ async def _run() -> None:+ service.start()+ for _ in range(100):+ if echoed.exists() and echoed.read_text(encoding="utf-8"):+ break+ await asyncio.sleep(0.02)+ await service.stop()++ asyncio.run(_run())++ assert echoed.read_text(encoding="utf-8") == watch.iddiff --git a/vibe/cli.py b/vibe/cli.pyindex ab08f9dac..46e12ff16 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -52,6 +52,7 @@ from core.command_runner import command_line_previewfrom core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backendfrom core.watches import (DEFAULT_RETRY_EXIT_CODE,+ NO_EVENT_EXIT_CODE,WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS,WATCH_RECONCILE_INTERVAL_SECONDS,ManagedWatchStore,@@ -1204,6 +1205,11 @@ def _watch_add_examples_text() -> str:Prefer --message or --message-file for follow-up instructions; --prefix is legacy-compatible.Terminal failures also send a follow-up and disable the watch.In forever mode, failures are retried only when the waiter exits with an allowed `--retry-exit-code`.+ Waiter exit codes: 0 detected an event and sends the follow-up; 124 timed out and sends a timeout follow-up;+ 64 PLUS the line 'avibe-watch: no-event' on stderr means the cycle ran and found nothing worth reporting,+ so the watch ends or re-arms WITHOUT an Agent turn; any other non-zero is a failure.+ The marker is required: 64 alone is also sysexits EX_USAGE, so a bare 64 stays a failure and stops the watch.+ Use it in waiters whose normal outcome is uninteresting, such as green CI.Pass either --shell '<command>' or a command after '--'.--timeout applies to each cycle. --lifetime-timeout applies only to the whole forever watch lifetime.@@ -3058,7 +3064,14 @@ def _wait_for_watch_startup(help_command=inspect_command,details={"watch": _watch_mutation_payload(watch, runtime_entry)},)- if watch.mode == "once" and watch.last_finished_at and not watch.last_error and watch.last_exit_code == 0:+ # NO_EVENT_EXIT_CODE is a clean finish too: a once watch whose first cycle+ # already decided there is nothing to report has completed, not hung.+ if (+ watch.mode == "once"+ and watch.last_finished_at+ and not watch.last_error+ and watch.last_exit_code in (0, NO_EVENT_EXIT_CODE)+ ):return watch, runtime_entryif runtime_entry and runtime_entry.get("running"):stable_for = _seconds_since_iso(runtime_entry.get("started_at")) or _seconds_since_iso(watch.last_started_at)