Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(harness): prevent Watch follow-up Run storms (#1304)

Call White02aae993739d
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index e05debf32..b8b10b921 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -113,6 +113,7 @@ from storage.background import (
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
SweptRun,
+ WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
WATCH_HOOK_OUTCOME_EVENT,
WATCH_HOOK_OUTCOME_METADATA_KEY,
WATCH_HOOK_OUTCOME_WAITER_FAILURE,
@@ -2665,6 +2666,23 @@ class TaskExecutionStore:
return self._sqlite.list_runs(status=status)
return self._list_file_runs(status=status)
+ def get_unsettled_watch_run(self, definition_id: str) -> Optional[dict[str, Any]]:
+ """Return the oldest queued/running Watch follow-up for the admission fence."""
+
+ if self._sqlite is not None:
+ return self._sqlite.get_unsettled_watch_run(definition_id)
+ for run in self._list_file_runs():
+ if str(run.get("task_id") or run.get("definition_id") or "") != str(
+ definition_id
+ ):
+ continue
+ if str(run.get("request_type") or run.get("run_type") or "") != "watch":
+ continue
+ status = _normalize_requested_run_status(run.get("status"))
+ if status in {"queued", "running"}:
+ return run
+ return None
+
def consecutive_definition_failures_with_code(
self,
definition_id: str,
@@ -6703,6 +6721,18 @@ class ScheduledTaskService:
)
elif is_watch and str(
((run.get("metadata") or {}).get(WATCH_HOOK_OUTCOME_METADATA_KEY) or "")
+ ).strip() == WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR:
+ if watch is not None and not watch.get("enabled") and not watch.get(
+ "retired_at"
+ ):
+ headline = self._t(
+ "harness.notice.watchCircuitRepairFailed",
+ name=name,
+ )
+ else:
+ headline = self._t("harness.notice.watchFollowUpFailed", name=name)
+ elif is_watch and str(
+ ((run.get("metadata") or {}).get(WATCH_HOOK_OUTCOME_METADATA_KEY) or "")
).strip() == WATCH_HOOK_OUTCOME_EVENT:
headline = self._t("harness.notice.watchProcessingFailed", name=name)
elif is_watch and str(
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 6c2a99363..0bc844998 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -323,6 +323,8 @@ Useful Harness queries include schema discovery, current session lookup, existin
`vibe watch add` creates a managed monitor, usually backed by a small script or command, for any observable condition that must be watched until true: product signals, business events, files, logs, CI/reviews/deploys, service health, data freshness, and similar signals. Watches created from an Avibe Agent shell follow up in this conversation by default. If `--cwd` is omitted, Avibe runs the waiter from the caller working directory when available.
+Watch waiter contract: exit `0` only for one NEW reportable event. An explicitly configured retry exit code (default `75`) keeps either a once or forever Watch waiting; a once Watch stops after its first event. Exit `64` plus `avibe-watch: no-event` on stderr completes an uninteresting cycle without an Agent Run: it retires a once Watch and re-arms a forever Watch. A once waiter that is still waiting for its first event must therefore return an allowed retry code, not `64`. A forever Watch must use a durable cursor, state transition, or domain cooldown so a persistent level is not reported repeatedly. Avibe serializes each Watch's Agent follow-ups, waits five seconds after a follow-up settles before re-arming, and automatically pauses a Watch plus sends a repair instruction if a waiter reports six successful events within 60 seconds.
+
Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. By default this creates a background Session in the caller's scope and returns immediately; when the run completes, the final result is sent back to this conversation. Background Sessions stay out of the session list and never deliver outward, but remain visible in the Agents run graph, where the user can open their full chat history or promote them at any time. Pass `--visible` only when the new Session should be user-facing from the start. Pass `--sync` only when the current process must wait for the result. Pass `--no-callback` only when you intentionally want no automatic follow-up and will inspect the run later; pass `--callback-session-id <id>` only to route the final result elsewhere. Add `--scope-id <scopes.id>` only when placing the new Session in a specific existing scope.
Use `vibe agent run --fork-self --message ...` when work should branch from this current Session's native backend context without mutating it. Use `--fork-session <source-session-id>` only when branching from a different explicit Session. Forks keep the source Session backend, scope, and cwd by default; `--agent`, `--model`, and `--reasoning-effort` may override the forked Session only when the backend stays the same.
diff --git a/core/watches.py b/core/watches.py
index b2b4b0bd1..d627de229 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -40,13 +40,19 @@ from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStore
from storage.background import (
DEFINITION_CYCLE_COLUMNS,
NO_EVENT_EXIT_CODE,
+ WATCH_CIRCUIT_BREAKER_METADATA_KEY as CIRCUIT_BREAKER_METADATA_KEY,
+ WATCH_FOLLOW_UP_RUN_ID_METADATA_KEY as FOLLOW_UP_RUN_ID_METADATA_KEY,
+ WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
WATCH_HOOK_OUTCOME_EVENT,
WATCH_HOOK_OUTCOME_METADATA_KEY,
WATCH_HOOK_OUTCOME_WAITER_FAILURE,
+ WATCH_LIFETIME_STARTED_AT_METADATA_KEY as LIFETIME_STARTED_AT_METADATA_KEY,
+ WATCH_RECENT_EVENT_TIMESTAMPS_METADATA_KEY as RECENT_EVENT_TIMESTAMPS_METADATA_KEY,
DefinitionWriteConflict,
DefinitionWriteExpectation,
SQLiteBackgroundTaskStore,
definition_resume_clear_columns,
+ watch_metadata_after_resume,
)
from vibe import runtime
from vibe.i18n import t as i18n_t
@@ -101,6 +107,14 @@ LAST_DELIVERY_ENV = "AVIBE_WATCH_LAST_DELIVERY"
#: 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_MIN_REARM_SECONDS = 5.0
+WATCH_FOLLOW_UP_POLL_SECONDS = 2.0
+WATCH_EVENT_BURST_WINDOW_SECONDS = 60.0
+WATCH_EVENT_BURST_LIMIT = 5
+WATCH_CIRCUIT_OUTPUT_LIMIT = 2000
+FOLLOW_UP_SLOT_READY = "ready"
+FOLLOW_UP_SLOT_STOPPED = "stopped"
+FOLLOW_UP_SLOT_LIFETIME_EXPIRED = "lifetime_expired"
WATCH_RECONCILE_INTERVAL_SECONDS = 2.0
WATCH_STORE_RECONCILE_FUSE_FAILURES = 3
WATCH_RECOVERY_ENTRY_TIMEOUT_SECONDS = 2 * DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS
@@ -119,6 +133,47 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _parse_utc_timestamp(value: Any) -> datetime | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _lifetime_started_monotonic(watch: "ManagedWatch") -> float:
+ """Project the durable armed-episode origin onto this event loop's clock."""
+
+ now = datetime.now(timezone.utc)
+ started_at = _parse_utc_timestamp(
+ watch.metadata.get(LIFETIME_STARTED_AT_METADATA_KEY)
+ ) or _parse_utc_timestamp(watch.created_at)
+ elapsed = max(0.0, (now - started_at).total_seconds()) if started_at else 0.0
+ return asyncio.get_running_loop().time() - elapsed
+
+
+def _recent_event_timestamps(
+ metadata: dict[str, Any],
+ *,
+ now: datetime,
+) -> list[str]:
+ values = metadata.get(RECENT_EVENT_TIMESTAMPS_METADATA_KEY)
+ if not isinstance(values, list):
+ return []
+ cutoff = now.timestamp() - WATCH_EVENT_BURST_WINDOW_SECONDS
+ recent: list[tuple[datetime, str]] = []
+ for value in values:
+ parsed = _parse_utc_timestamp(value)
+ if parsed is not None and cutoff <= parsed.timestamp() <= now.timestamp():
+ recent.append((parsed, str(value)))
+ recent.sort(key=lambda item: item[0])
+ return [value for _parsed, value in recent[-WATCH_EVENT_BURST_LIMIT:]]
+
+
def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
try:
stat = path.stat()
@@ -587,6 +642,7 @@ class ManagedWatchStore:
deliver_key=deliver_key,
metadata=dict(metadata or {}),
)
+ watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY] = watch.created_at
return self.upsert_watch(
watch,
expected_enabled_agent_id=expected_enabled_agent_id,
@@ -627,6 +683,10 @@ class ManagedWatchStore:
watch,
definition_resume_clear_columns("watch", watch.mode),
)
+ watch.metadata = watch_metadata_after_resume(
+ watch.metadata,
+ resumed_at=_utc_now_iso(),
+ )
watch.enabled = enabled
watch.updated_at = _utc_now_iso()
if not self._write_watch(watch, expect):
@@ -665,6 +725,12 @@ class ManagedWatchStore:
# Captured before the first mutation: the state ``vibe watch update`` read and
# resolved its payload from.
expect = self._read_state(watch)
+ waiter_lifecycle_changed = (
+ mode != watch.mode
+ or command != watch.command
+ or shell_command != watch.shell_command
+ or cwd != watch.cwd
+ )
if mode != watch.mode:
# A mode change starts a new lifecycle. Completion and failure
# metadata from the old mode remains available in run history, but
@@ -691,6 +757,9 @@ class ManagedWatchStore:
watch.deliver_key = deliver_key
if metadata is not None:
watch.metadata = dict(metadata)
+ if waiter_lifecycle_changed:
+ watch.metadata = dict(watch.metadata)
+ watch.metadata.pop(RECENT_EVENT_TIMESTAMPS_METADATA_KEY, None)
watch.updated_at = _utc_now_iso()
if not self._write_watch(
watch,
@@ -733,7 +802,10 @@ class ManagedWatchStore:
exit_code: Optional[int],
error: Optional[str],
event_detected: bool = False,
+ acknowledge_event: bool = True,
disable: bool = False,
+ pause: bool = False,
+ metadata_updates: Optional[dict[str, Any]] = None,
queued_run: Optional[dict[str, Any]] = None,
) -> bool:
"""Stamp a cycle's outcome; ``False`` means the store refused the write.
@@ -744,6 +816,8 @@ class ManagedWatchStore:
``once`` watch while losing the hook that tells the user it finished.
"""
+ if disable and pause:
+ raise ValueError("a watch cycle cannot retire and pause at the same time")
self.maybe_reload()
watch = self._watches.get(watch_id)
if watch is None:
@@ -756,19 +830,22 @@ class ManagedWatchStore:
# must likewise not erase a genuine earlier retirement.
was_enabled = watch.enabled
if was_enabled:
- watch.last_finished_at = now if disable else None
+ watch.last_finished_at = now if disable or pause else None
watch.retired_at = now if disable else None
watch.last_exit_code = exit_code
watch.last_error = error
if event_detected:
watch.last_event_at = now
+ if metadata_updates or (event_detected and acknowledge_event):
# 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,
+ **(metadata_updates or {}),
}
- if disable:
+ if event_detected and acknowledge_event:
+ watch.metadata[DELIVERY_ACK_METADATA_KEY] = _delivered_reports(watch) + 1
+ if disable or pause:
watch.enabled = False
watch.updated_at = _utc_now_iso()
# Guarded for the reason ``mark_task_result`` is: a cycle result landing after a
@@ -861,6 +938,12 @@ class _CycleResult:
timed_out: bool
+@dataclass(frozen=True)
+class _FollowUpSlot:
+ state: str
+ blocking_run_id: str | None = None
+
+
def _cycle_env(watch: ManagedWatch) -> dict[str, str]:
"""What one waiter cycle is told about itself.
@@ -1657,8 +1740,8 @@ class ManagedWatchService:
# concurrent lifecycle change. Fusing would disable reconciliation for a
# healthy database, so the watch is stopped and the store left alone.
logger.warning(
- "Watch %s stopping: the store refused %s because the definition's "
- "Session binding, enabled state, deletion or reclaim snapshot changed",
+ "Watch %s stopping: the store refused %s because a guarded lifecycle "
+ "or follow-up admission prerequisite changed",
watch_id,
operation,
)
@@ -1714,8 +1797,265 @@ class ManagedWatchService:
self._begin_stop()
return False
+ def _circuit_repair_prompt(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ event_timestamps: list[str],
+ ) -> str:
+ return self._t(
+ "harness.watch.circuitRepairPrompt",
+ name=watch.name or watch.id,
+ id=watch.id,
+ count=len(event_timestamps),
+ window=int(WATCH_EVENT_BURST_WINDOW_SECONDS),
+ timestamps="\n".join(f"- {value}" for value in event_timestamps),
+ stdout=_squash_tail(result.stdout, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ or self._t("harness.watch.emptyOutput"),
+ stderr=_squash_tail(result.stderr, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ or self._t("harness.watch.emptyOutput"),
+ retry_codes=", ".join(str(code) for code in watch.retry_exit_codes),
+ )
+
+ def _commit_success_cycle(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ ) -> bool:
+ now = datetime.now(timezone.utc)
+ now_iso = now.isoformat()
+ recent = _recent_event_timestamps(watch.metadata, now=now)
+ observed = [*recent, now_iso]
+ if watch.mode == "forever" and len(observed) > WATCH_EVENT_BURST_LIMIT:
+ stdout = _squash_tail(result.stdout, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ stderr = _squash_tail(result.stderr, limit=WATCH_CIRCUIT_OUTPUT_LIMIT)
+ request = self._hook_request(
+ watch,
+ event_detected=True,
+ hook_outcome=WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
+ prompt=self._circuit_repair_prompt(watch, result, observed),
+ )
+ if request is None:
+ return False
+ incident = {
+ "status": "tripped",
+ "triggered_at": now_iso,
+ "event_timestamps": observed,
+ "exit_code": 0,
+ "stdout": stdout,
+ "stderr": stderr,
+ "repair_run_id": request.id,
+ }
+ return self._persist_cycle_result(
+ watch,
+ request=request,
+ exit_code=0,
+ error=self._t(
+ "harness.watch.circuitPausedError",
+ count=len(observed),
+ window=int(WATCH_EVENT_BURST_WINDOW_SECONDS),
+ run_id=request.id,
+ ),
+ event_detected=True,
+ acknowledge_event=False,
+ disable=False,
+ pause=True,
+ metadata_updates={
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY: observed,
+ CIRCUIT_BREAKER_METADATA_KEY: incident,
+ },
+ )
+
+ metadata_updates = (
+ {RECENT_EVENT_TIMESTAMPS_METADATA_KEY: observed}
+ if watch.mode == "forever"
+ else None
+ )
+ return self._commit_cycle_result(
+ watch,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=watch.mode == "once",
+ prompt=_build_prompt(watch.message or watch.prefix, result.stdout),
+ metadata_updates=metadata_updates,
+ )
+
+ async def _commit_success_cycle_async(
+ self,
+ watch: ManagedWatch,
+ result: _CycleResult,
+ ) -> bool:
+ try:
+ return await self._run_runtime_sync(
+ self._commit_success_cycle,
+ watch,
+ result,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "commit successful watch cycle",
+ exc,
+ watch_id=watch.id,
+ )
+ return False
+
+ async def _wait_for_follow_up_slot(
+ self,
+ watch_id: str,
+ *,
+ lifetime_started: float,
+ ) -> _FollowUpSlot:
+ """Wait for the prior Agent work without letting Watch lifetime drift."""
+
+ terminal_statuses = {"succeeded", "failed", "canceled"}
+ future_completion_seen: tuple[str, float] | None = None
+ while self._running:
+ if not self._owns_service_instance():
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if not await self._watch_store_call_async(
+ watch_id,
+ "reload before follow-up fence",
+ self.store.maybe_reload,
+ ):
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ watch = self.store.get_watch(watch_id)
+ if watch is None or not watch.enabled:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ lifetime_remaining = None
+ if watch.lifetime_timeout_seconds > 0:
+ lifetime_remaining = watch.lifetime_timeout_seconds - (
+ asyncio.get_running_loop().time() - lifetime_started
+ )
+ try:
+ unsettled = await self._run_runtime_sync(
+ self.request_store.get_unsettled_watch_run,
+ watch_id,
+ )
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "read follow-up fence",
+ exc,
+ watch_id=watch_id,
+ )
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if unsettled:
+ blocking_run_id = str(unsettled["id"])
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(
+ FOLLOW_UP_SLOT_LIFETIME_EXPIRED,
+ blocking_run_id=blocking_run_id,
+ )
+ delay = WATCH_FOLLOW_UP_POLL_SECONDS
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ continue
+
+ run_id = str(watch.metadata.get(FOLLOW_UP_RUN_ID_METADATA_KEY) or "").strip()
+ if not run_id:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ try:
+ run = await self._run_runtime_sync(self.request_store.get_run, run_id)
+ except Exception as exc:
+ self._fuse_store_after_error(
+ "read previous follow-up",
+ exc,
+ watch_id=watch_id,
+ )
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+ if run is None:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ status = str(run.get("status") or "").strip().lower()
+ if status not in terminal_statuses:
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(
+ FOLLOW_UP_SLOT_LIFETIME_EXPIRED,
+ blocking_run_id=run_id,
+ )
+ delay = WATCH_FOLLOW_UP_POLL_SECONDS
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ continue
+ if lifetime_remaining is not None and lifetime_remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_LIFETIME_EXPIRED)
+ if watch.mode != "forever":
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ completed_at = _parse_utc_timestamp(
+ run.get("completed_at") or run.get("updated_at")
+ )
+ if completed_at is None:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ wall_elapsed = (datetime.now(timezone.utc) - completed_at).total_seconds()
+ if wall_elapsed >= 0:
+ elapsed = wall_elapsed
+ else:
+ loop_now = asyncio.get_running_loop().time()
+ if future_completion_seen is None or future_completion_seen[0] != run_id:
+ future_completion_seen = (run_id, loop_now)
+ elapsed = loop_now - future_completion_seen[1]
+ remaining = WATCH_MIN_REARM_SECONDS - elapsed
+ if remaining <= 0:
+ return _FollowUpSlot(FOLLOW_UP_SLOT_READY)
+ delay = min(remaining, WATCH_FOLLOW_UP_POLL_SECONDS)
+ if lifetime_remaining is not None:
+ delay = min(delay, lifetime_remaining)
+ await asyncio.sleep(delay)
+ return _FollowUpSlot(FOLLOW_UP_SLOT_STOPPED)
+
+ async def _commit_lifetime_timeout_async(
+ self,
+ watch: ManagedWatch,
+ *,
+ blocking_run_id: str | None = None,
+ ) -> bool:
+ kwargs: dict[str, Any] = {}
+ if blocking_run_id is None:
+ kwargs = {
+ "prefix": watch.message
+ or watch.prefix
+ or self._t("harness.watch.lifetimeTimeoutPrefix"),
+ "body": self._t(
+ "harness.watch.lifetimeTimeoutBody",
+ name=watch.name or watch.id,
+ seconds=int(watch.lifetime_timeout_seconds),
+ ),
+ }
+ else:
+ kwargs["error"] = self._t(
+ "harness.watch.lifetimeExpiredWithActiveFollowUp",
+ run_id=blocking_run_id,
+ )
+ return await self._commit_cycle_result_async(
+ watch,
+ exit_code=124,
+ error=kwargs.pop("error", None),
+ disable=True,
+ **kwargs,
+ )
+
+ async def _sleep_before_retry(
+ self,
+ watch: ManagedWatch,
+ *,
+ lifetime_started: float,
+ ) -> None:
+ delay = watch.retry_delay_seconds
+ if watch.lifetime_timeout_seconds > 0:
+ elapsed = asyncio.get_running_loop().time() - lifetime_started
+ delay = min(
+ delay,
+ max(0.0, watch.lifetime_timeout_seconds - elapsed),
+ )
+ await asyncio.sleep(delay)
+
async def _run_watch(self, watch_id: str) -> None:
- lifetime_started = asyncio.get_running_loop().time()
+ lifetime_started: float | None = None
self._watch_started_at[watch_id] = _utc_now_iso()
self._runtime_state_dirty = True
self._write_runtime_state()
@@ -1734,28 +2074,31 @@ class ManagedWatchService:
watch = self.store.get_watch(watch_id)
if watch is None or not watch.enabled:
return
+ if lifetime_started is None:
+ lifetime_started = _lifetime_started_monotonic(watch)
+
+ follow_up_slot = await self._wait_for_follow_up_slot(
+ watch_id,
+ lifetime_started=lifetime_started,
+ )
+ if follow_up_slot.state == FOLLOW_UP_SLOT_STOPPED:
+ return
+ watch = self.store.get_watch(watch_id)
+ if watch is None or not watch.enabled:
+ return
+ if follow_up_slot.state == FOLLOW_UP_SLOT_LIFETIME_EXPIRED:
+ await self._commit_lifetime_timeout_async(
+ watch,
+ blocking_run_id=follow_up_slot.blocking_run_id,
+ )
+ return
- if watch.mode == "forever" and watch.lifetime_timeout_seconds > 0:
+ if watch.lifetime_timeout_seconds > 0:
elapsed = asyncio.get_running_loop().time() - lifetime_started
remaining_lifetime = watch.lifetime_timeout_seconds - elapsed
if remaining_lifetime <= 0:
- # ONE DECISION (HFR-269), not a stamp followed by a hook. See
- # ``_commit_cycle_result``.
- await self._commit_cycle_result_async(
+ await self._commit_lifetime_timeout_async(
watch,
- # Running out of lifetime is a timeout, and the row has
- # to be able to say so: ``definition_lifecycle_detail``
- # reads the exit code, and a ``None`` here made the
- # supervisor's own deadline read as a normal ending.
- # 124 is the same convention the per-cycle timeout uses.
- exit_code=124,
- error=None,
- disable=True,
- prefix=watch.message or watch.prefix or "Watch stopped after reaching its lifetime timeout.",
- body=(
- f"Watch '{watch.name or watch.id}' reached its lifetime timeout after "
- f"{int(watch.lifetime_timeout_seconds)} second(s)."
- ),
)
return
cycle_timeout = watch.timeout_seconds
@@ -1808,16 +2151,7 @@ class ManagedWatchService:
return
if result.exit_code == 0:
- # Building the prompt is pure; the stamp and the hook it authorises are
- # committed together (HFR-269).
- if not await self._commit_cycle_result_async(
- watch,
- exit_code=0,
- error=None,
- event_detected=True,
- disable=watch.mode == "once",
- prompt=_build_prompt(watch.message or watch.prefix, result.stdout),
- ):
+ if not await self._commit_success_cycle_async(watch, result):
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
@@ -1863,12 +2197,15 @@ class ManagedWatchService:
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)
+ await self._sleep_before_retry(
+ watch,
+ lifetime_started=lifetime_started,
+ )
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):
+ if 124 in set(watch.retry_exit_codes):
# A retry authorises no hook: the watch keeps running, and there is
# nothing to tell the user yet.
if not await self._commit_cycle_result_async(
@@ -1878,7 +2215,10 @@ class ManagedWatchService:
disable=False,
):
return
- await asyncio.sleep(watch.retry_delay_seconds)
+ await self._sleep_before_retry(
+ watch,
+ lifetime_started=lifetime_started,
+ )
continue
await self._commit_cycle_result_async(
watch,
@@ -1895,7 +2235,7 @@ class ManagedWatchService:
return
error_text = _squash_error(result.stderr) or f"watch command exited with status {result.exit_code}"
- if watch.mode == "forever" and result.exit_code in set(watch.retry_exit_codes):
+ if result.exit_code in set(watch.retry_exit_codes):
if not await self._commit_cycle_result_async(
watch,
exit_code=result.exit_code,
@@ -1903,7 +2243,10 @@ class ManagedWatchService:
disable=False,
):
return
- await asyncio.sleep(watch.retry_delay_seconds)
+ await self._sleep_before_retry(
+ watch,
+ lifetime_started=lifetime_started,
+ )
continue
await self._commit_cycle_result_async(
@@ -1991,6 +2334,7 @@ class ManagedWatchService:
watch: ManagedWatch,
*,
event_detected: bool = False,
+ hook_outcome: Optional[str] = None,
prompt: Optional[str] = None,
prefix: Optional[str] = None,
body: Optional[str] = None,
@@ -2017,7 +2361,8 @@ class ManagedWatchService:
source_kind="watch",
metadata={
**watch.metadata,
- WATCH_HOOK_OUTCOME_METADATA_KEY: (
+ WATCH_HOOK_OUTCOME_METADATA_KEY: hook_outcome
+ or (
WATCH_HOOK_OUTCOME_EVENT
if event_detected
else WATCH_HOOK_OUTCOME_WAITER_FAILURE
@@ -2025,6 +2370,56 @@ class ManagedWatchService:
},
)
+ def _persist_cycle_result(
+ self,
+ watch: ManagedWatch,
+ *,
+ request: Optional[TaskExecutionRequest],
+ exit_code: Optional[int],
+ error: Optional[str],
+ event_detected: bool,
+ acknowledge_event: bool,
+ disable: bool,
+ pause: bool,
+ metadata_updates: Optional[dict[str, Any]],
+ ) -> bool:
+ updates = dict(metadata_updates or {})
+ if request is not None:
+ updates[FOLLOW_UP_RUN_ID_METADATA_KEY] = request.id
+ request.metadata = {
+ **watch.metadata,
+ **updates,
+ WATCH_HOOK_OUTCOME_METADATA_KEY: request.metadata.get(
+ WATCH_HOOK_OUTCOME_METADATA_KEY
+ ),
+ }
+ if event_detected and acknowledge_event:
+ request.metadata[DELIVERY_ACK_METADATA_KEY] = _delivered_reports(watch) + 1
+ atomic = request is not None and _shared_run_ledger_backend(
+ self.store, self.request_store
+ ) is not None
+ queued_run = self.request_store.queued_run_payload(request) if atomic and request else None
+ if not self._watch_store_call(
+ watch.id,
+ "mark_cycle_result",
+ lambda: self.store.mark_cycle_result(
+ watch.id,
+ exit_code=exit_code,
+ error=error,
+ event_detected=event_detected,
+ acknowledge_event=acknowledge_event,
+ disable=disable,
+ pause=pause,
+ metadata_updates=updates,
+ queued_run=queued_run,
+ ),
+ guarded=True,
+ ):
+ return False
+ if request is not None and queued_run is None:
+ self.request_store.enqueue(request)
+ return True
+
def _commit_cycle_result(
self,
watch: ManagedWatch,
@@ -2032,7 +2427,11 @@ class ManagedWatchService:
exit_code: Optional[int],
error: Optional[str],
event_detected: bool = False,
+ acknowledge_event: bool = True,
disable: bool = False,
+ pause: bool = False,
+ metadata_updates: Optional[dict[str, Any]] = None,
+ hook_outcome: Optional[str] = None,
prompt: Optional[str] = None,
prefix: Optional[str] = None,
body: Optional[str] = None,
@@ -2069,29 +2468,22 @@ class ManagedWatchService:
request = self._hook_request(
watch,
event_detected=event_detected,
+ hook_outcome=hook_outcome,
prompt=prompt,
prefix=prefix,
body=body,
)
- atomic = request is not None and _shared_run_ledger_backend(self.store, self.request_store) is not None
- queued_run = self.request_store.queued_run_payload(request) if atomic and request else None
- if not self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(
- watch.id,
- exit_code=exit_code,
- error=error,
- event_detected=event_detected,
- disable=disable,
- queued_run=queued_run,
- ),
- guarded=True,
- ):
- return False
- if request is not None and queued_run is None:
- self.request_store.enqueue(request)
- return True
+ return self._persist_cycle_result(
+ watch,
+ request=request,
+ exit_code=exit_code,
+ error=error,
+ event_detected=event_detected,
+ acknowledge_event=acknowledge_event,
+ disable=disable,
+ pause=pause,
+ metadata_updates=metadata_updates,
+ )
async def _commit_cycle_result_async(
self,
diff --git a/docs/plans/watch-follow-up-circuit-breaker.md b/docs/plans/watch-follow-up-circuit-breaker.md
new file mode 100644
index 000000000..4adca6b42
--- /dev/null
+++ b/docs/plans/watch-follow-up-circuit-breaker.md
@@ -0,0 +1,109 @@
+# Watch Follow-up Serialization and Circuit Breaker
+
+## Background
+
+Issue #953 recorded a level-triggered `forever` Watch whose waiter kept exiting
+successfully while the condition stayed true. The supervisor treated every exit `0`
+as a new event and immediately re-ran the waiter. In 18.139 seconds it created 274
+Agent Runs: 174 completed no-op Runs and 100 more queued Runs.
+
+The failure is not primarily a queue-capacity problem. A Watch event is unfinished
+until its Agent follow-up has settled, and a level that remains true is not a new
+event. The runtime currently loses both facts between cycles.
+
+## User Contract
+
+- `once` means wait until the first reportable event. An explicitly configured retry
+ exit code, including the default `75`, re-runs the waiter after `--retry-delay`
+ instead of retiring the Watch.
+- `forever` means monitor a sequence of distinct reportable events. Exit `0` means
+ one new event. A waiter that is still waiting returns an allowed retry exit code;
+ a completed but uninteresting cycle may use exit `64` plus
+ `avibe-watch: no-event`.
+- Other non-zero exits are terminal failures. Exit `124` is retryable only when it is
+ explicitly listed.
+- `--lifetime-timeout` bounds one armed episode in either mode. Creation or explicit
+ resume starts that episode; supervisor and service restarts retain its deadline.
+- The lifetime deadline also bounds time spent behind the follow-up fence. If an
+ earlier Agent Run is still queued or running at the deadline, the Watch retires
+ immediately and records that Run's actual ID, but does not create a second
+ concurrent Run. If no Run owns the slot, the timeout follow-up uses the configured
+ language.
+
+## Runtime Invariants
+
+1. A Watch definition owns at most one queued or running Watch follow-up Run.
+2. A `forever` Watch does not start its next waiter until the prior follow-up Run is
+ terminal, then waits at least five seconds before re-arming.
+3. The accepted event timestamp and follow-up Run ID are stored on the Watch in the
+ same transaction that queues the Run.
+4. At most five successful events are accepted in a rolling 60-second window. The
+ sixth successful waiter output is diagnostic evidence, not a normal event.
+5. The sixth success atomically pauses the Watch and queues one circuit-repair Run to
+ the same Session. A restart can observe that durable decision and cannot queue a
+ second repair Run.
+6. Resume clears the live burst window but retains the last follow-up Run ID. If the
+ repair Agent resumes the Watch before its own Run settles, the waiter still waits
+ for that Run and the five-second re-arm delay.
+7. An allowed retry exit is healthy while the Watch remains enabled, regardless of
+ mode. The same exit is failing once the Watch retires because no retry remains.
+
+The SQLite outbox transaction also rejects a new Watch follow-up while an older one
+for the same definition is queued or running. The runtime-level wait handles normal
+flow and legacy rows; the transaction-level check closes admission races.
+
+## Circuit Repair Message
+
+The repair Run receives the Watch ID and name, the six observed timestamps, exit
+code, bounded stdout/stderr, the Watch exit-code contract, and commands to inspect,
+update, and resume the Watch. It must inspect and fix the waiter so persistent levels
+return retry/no-event rather than success. It may resume only after an unambiguous,
+reversible fix is verified; otherwise it leaves the Watch paused and reports why.
+
+## Persistence and Recovery
+
+No schema migration is required. Watch metadata owns:
+
+- the latest follow-up Run ID, used for terminal-state and re-arm checks;
+- the rolling accepted-event timestamps;
+- the last circuit-breaker incident and repair Run ID;
+- the current armed episode's lifetime origin.
+
+Existing Watches without a lifetime-origin key derive it from their durable
+`created_at`; the next explicit resume writes a new origin. On upgrade, the runtime
+also queries queued/running Watch Runs by definition before starting a waiter, so
+legacy backlog drains without admitting another event. That queried row, rather than
+possibly absent or stale Watch metadata, is also the source of the blocking Run ID
+recorded on lifetime expiry. File-backed stores retain the same behavior for tests and
+legacy operation, without pretending to provide a cross-file transaction.
+
+Changing the waiter command, shell command, mode, or cwd starts a new waiter lifecycle
+and clears the old burst window, but does not reset the armed episode's lifetime.
+Session routing and follow-up copy changes do not reset either one.
+
+## Observability
+
+The circuit decision leaves the definition disabled with no retirement timestamp, so
+it reads as paused after the repair Run settles. `last_error` states the threshold and
+the repair Run ID; the incident metadata preserves the six timestamps. The repair Run
+uses a distinct Watch outcome value so failure notices do not misclassify it as an
+ordinary event or waiter failure.
+
+## Verification
+
+- `once`: retry, timeout-as-retry, first success, terminal failure, and lifetime limit.
+- `forever`: queued/running single-flight, terminal re-arm delay, quiet and retry
+ cycles, legitimate edge-triggered recurring monitoring, and terminal failures.
+- Circuit: five accepted events, sixth pause, no sixth ordinary Run, one repair Run,
+ bounded evidence, resume behavior, and restart idempotence.
+- Storage: atomic queued-run admission rejects an existing unfinished Watch follow-up.
+- Contracts: CLI help, Agent system prompt, background-watch skill, and scenario
+ catalog describe the same exit-code and repair semantics.
+
+## Delivery Risk
+
+The main risk is reducing observation cadence for waiters that relied on re-arming
+while their Agent was still processing. That behavior is the source of the incident;
+the supported replacement is a durable cursor or state transition in the waiter. A
+five-second post-Run delay is intentionally fixed rather than user-configurable: it is
+a runtime safety floor, not domain polling policy.
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index f525eb0f3..9c2325ff7 100644
--- a/skills/background-watch-hook/SKILL.md
+++ b/skills/background-watch-hook/SKILL.md
@@ -2,7 +2,7 @@
name: background-watch-hook
slug: background-watch-hook
description: Use `vibe watch` to run a managed Harness waiter that returns to the same conversation later. Best for reviews, CI, files, logs, and other wait-now-continue-later workflows.
-version: 0.13.0
+version: 0.14.0
---
# Background Watch Hook
@@ -159,10 +159,23 @@ For `vibe watch add`:
- default is `21600` seconds
- `0` means no per-cycle timeout
- `--forever` means re-arm after each detected event
-- forever retries only when the waiter exits with an allowed `--retry-exit-code`; other failures stop the watch and send a failure follow-up
+- an allowed `--retry-exit-code` keeps either mode waiting; a once Watch stops after its first event
- `--lifetime-timeout` limits the whole long-running watch; default is `0` meaning run until killed
-This separation matters: a forever watch can still use a bounded timeout for each cycle.
+This separation matters: a once Watch may now have several retry cycles, and a forever
+Watch can still use a bounded timeout for each cycle.
+
+Exit `0` means one new reportable event, never merely that a condition remains true.
+For a persistent level, return an allowed retry code (default `75`) until a new edge is
+observed. Exit `64` plus `avibe-watch: no-event` on stderr is a completed cycle with
+nothing worth reporting. A forever waiter must keep a durable cursor, state transition,
+or domain cooldown so it cannot emit the same level repeatedly.
+
+Avibe admits only one queued/running follow-up per Watch. A forever Watch re-arms after
+that Agent Run settles and a five-second safety delay. If the waiter still produces six
+successful events within 60 seconds, Avibe pauses the Watch and sends the target Agent
+one repair message containing the bounded latest waiter output. The Agent should inspect
+and fix the waiter, and resume only after verifying an unambiguous, reversible fix.
## Bundled Waiter Example
diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.md
index ec9a92223..f2e2308e7 100644
--- a/skills/use-avibe/SKILL.md
+++ b/skills/use-avibe/SKILL.md
@@ -2,7 +2,7 @@
name: use-avibe
slug: use-avibe
description: Safely inspect and modify local Avibe configuration, routing, runtime settings, watches, scheduled tasks, Avibe Cloud remote access, and operational state.
-version: 0.5.0
+version: 0.6.1
---
# Use Avibe
@@ -830,6 +830,8 @@ Operational guidance:
- use `vibe task list` before editing or deleting an existing task; use `vibe watch list` before touching a managed watch
- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches and command tasks both accept `--shell` and `--timeout` (per-cycle for watches, per-run for tasks), while `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay` stay watch-only
+- for Watch waiters, exit `0` means one new reportable event; an allowed retry exit code keeps either mode waiting, while `64` plus `avibe-watch: no-event` ends a once Watch or re-arms a forever Watch without an Agent Run; a once waiter that is still waiting must use a retry exit code
+- a forever waiter must keep a durable cursor, state transition, or domain cooldown; Avibe serializes its event follow-ups and automatically pauses plus sends a repair Run after six successful events within 60 seconds
- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target
- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options
- Agent-facing collection commands return 20 compact rows per page, cap `--limit` at 100, and have no unpaginated `--all` mode; follow `pagination.next_command` when more rows exist
diff --git a/storage/background.py b/storage/background.py
index ffb090e42..7c0ac1f27 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1479,6 +1479,33 @@ HEALTH_UNKNOWN = "unknown"
WATCH_HOOK_OUTCOME_METADATA_KEY = "watch_hook_outcome"
WATCH_HOOK_OUTCOME_EVENT = "event"
WATCH_HOOK_OUTCOME_WAITER_FAILURE = "waiter_failure"
+WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR = "circuit_repair"
+# Durable Watch admission state. These values move with the Agent Run outbox row,
+# so the definition owns them instead of the in-memory supervisor.
+WATCH_FOLLOW_UP_RUN_ID_METADATA_KEY = "watch_follow_up_run_id"
+WATCH_RECENT_EVENT_TIMESTAMPS_METADATA_KEY = "watch_recent_event_timestamps"
+WATCH_CIRCUIT_BREAKER_METADATA_KEY = "watch_circuit_breaker"
+WATCH_LIFETIME_STARTED_AT_METADATA_KEY = "watch_lifetime_started_at"
+
+
+def watch_metadata_after_resume(
+ metadata: dict[str, Any],
+ *,
+ resumed_at: str,
+) -> dict[str, Any]:
+ """Start a new armed episode while retaining the repair Run admission fence."""
+
+ updated = dict(metadata)
+ updated.pop(WATCH_RECENT_EVENT_TIMESTAMPS_METADATA_KEY, None)
+ updated[WATCH_LIFETIME_STARTED_AT_METADATA_KEY] = resumed_at
+ incident = updated.get(WATCH_CIRCUIT_BREAKER_METADATA_KEY)
+ if isinstance(incident, dict) and incident.get("status") == "tripped":
+ updated[WATCH_CIRCUIT_BREAKER_METADATA_KEY] = {
+ **incident,
+ "status": "resumed",
+ "resumed_at": resumed_at,
+ }
+ return updated
#: The health window: the last N verdicts OR the last T hours, whichever is
#: shorter. Both bounds live in the ``WHERE``/``LIMIT`` of one query rather than
@@ -2880,6 +2907,7 @@ class SQLiteBackgroundTaskStore:
run_definitions.c.definition_type,
run_definitions.c.mode,
run_definitions.c.enabled,
+ run_definitions.c.metadata_json,
)
.where(run_definitions.c.id == definition_id)
.where(run_definitions.c.deleted_at.is_(None))
@@ -2892,6 +2920,14 @@ class SQLiteBackgroundTaskStore:
current["definition_type"], current["mode"]
)
values.update(dict.fromkeys(clear_columns, None))
+ if current["definition_type"] == "watch":
+ metadata = _json_loads(current["metadata_json"], {})
+ values["metadata_json"] = _json_dumps(
+ watch_metadata_after_resume(
+ metadata if isinstance(metadata, dict) else {},
+ resumed_at=values["updated_at"],
+ )
+ )
stmt = (
update(run_definitions)
.where(run_definitions.c.id == definition_id)
@@ -3055,6 +3091,20 @@ class SQLiteBackgroundTaskStore:
run_values = self._run_values(run_payload)
with run_update_event_transaction(self.engine) as conn:
reserve_write_lock(conn)
+ unsettled = conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.definition_id == values["id"])
+ .where(agent_runs.c.run_type == "watch")
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued")
+ + _status_query_values("running")
+ )
+ )
+ .limit(1)
+ ).first()
+ if unsettled is not None:
+ return False
if not upsert_definition_in_connection(
conn, values, expect=expect, definition_type="watch"
):
@@ -3767,6 +3817,25 @@ class SQLiteBackgroundTaskStore:
return None
return self._enrich_runs([self._run_from_row(row)], conn)[0]
+ def get_unsettled_watch_run(self, definition_id: str) -> Optional[dict[str, Any]]:
+ """Return the oldest queued/running Agent follow-up owned by one Watch."""
+
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(agent_runs.c.run_type == "watch")
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued")
+ + _status_query_values("running")
+ )
+ )
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ ).mappings().first()
+ return self._run_from_row(row) if row is not None else None
+
def list_deferred_runs(self) -> list[dict[str, Any]]:
"""Return non-terminal Runs carrying a durable terminal intent."""
@@ -7631,11 +7700,7 @@ class SQLiteBackgroundTaskStore:
or exit_code is not None
or str(row.get("last_error") or "").strip()
)
- retry_is_healthy = (
- row.get("mode") == "forever"
- and bool(row.get("enabled"))
- and exit_code in retry_codes
- )
+ retry_is_healthy = bool(row.get("enabled")) and exit_code in retry_codes
successful_exit_codes = {0, NO_EVENT_EXIT_CODE}
waiter_failed = bool(
(
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index cb06eae41..27ce795a8 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4153,6 +4153,88 @@ scenarios:
# The handler-to-facade contract forwards the resolved route at Turn start;
# the refreshed chat header remains a residual manual UI check.
test: tests/test_message_handler_typing.py::MessageHandlerTypingTests::test_workbench_inherited_route_materializes_at_turn_start
+ - id: HFR-463
+ name: once Watch retries until its first reportable event
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ backend: shared
+ # An explicitly allowed retry result keeps a once Watch armed. The first exit
+ # zero queues exactly one follow-up and retires the definition.
+ test: tests/test_watches.py::test_managed_watch_service_once_retries_until_first_success
+ - id: HFR-464
+ name: forever Watch follow-ups serialize waiter re-arm
+ status: covered
+ kind: concurrency
+ layer: scenario
+ backend: shared
+ # A queued/running event Run holds the next waiter closed. Terminal settlement
+ # starts the fixed safety delay, and only then may the next cycle begin.
+ test: tests/test_watches.py::test_forever_watch_waits_for_previous_follow_up_before_rearming
+ - id: HFR-465
+ name: rapid successful waiter circuit pauses once and preserves evidence
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ # Five successes are delivered. The sixth pauses without an ordinary event
+ # Run, atomically records bounded evidence and queues one repair Run; restart
+ # cannot create a second repair request.
+ test: tests/test_watches.py::test_forever_watch_sixth_rapid_success_pauses_and_queues_one_repair_run
+ - id: HFR-466
+ name: Watch outbox rejects concurrent unfinished follow-ups
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The SQLite writer checks queued/running Watch Runs under the same writer lock
+ # as the definition stamp and outbox insert, closing a second-admission race.
+ test: tests/test_watches.py::test_atomic_watch_outbox_rejects_a_second_unsettled_follow_up
+ - id: HFR-467
+ name: circuit resume clears burst state but retains the repair fence
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Resume starts a fresh rate window but keeps the repair Run id, so the waiter
+ # cannot re-arm while the Agent that resumed it is still finishing.
+ test: tests/test_watches.py::test_resuming_circuit_paused_watch_clears_window_but_keeps_repair_fence
+ - id: HFR-468
+ name: storage and CLI circuit resume rules stay identical
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The Web UI storage doorway clears the active burst window and marks the
+ # incident resumed without deleting the repair Run fence.
+ test: tests/test_watches.py::test_storage_resume_applies_the_same_circuit_reset_as_cli
+ - id: HFR-469
+ name: edge-triggered forever Watch re-arms without duplicate delivery
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ backend: shared
+ # After the event Run settles, the next cycle sees the durable delivery stamp;
+ # quiet cycles keep the Watch armed without moving that acknowledgement.
+ test: tests/test_watches.py::test_a_cycle_is_told_when_this_watch_last_had_a_report_delivered
+ - id: HFR-470
+ name: Watch lifetime is one durable armed episode
+ status: covered
+ kind: timeout
+ layer: contract
+ backend: shared
+ # Creation or explicit resume starts the deadline. Supervisor restarts retain it,
+ # including legacy rows derived from created_at; retry sleeps cannot extend it.
+ test: tests/test_watches.py::test_watch_lifetime_origin_survives_supervisor_restart
+ - id: HFR-471
+ name: once Watch timeout retries only by explicit policy
+ status: covered
+ kind: timeout
+ layer: contract
+ backend: shared
+ # Exit 124 keeps a once Watch waiting only when listed, then the first event
+ # queues one Run and retires normally.
+ test: tests/test_watches.py::test_once_watch_retries_timeout_only_when_124_is_allowed
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
@@ -4161,3 +4243,4 @@ plans:
- docs/plans/harness-session-failure-recovery.md
- docs/plans/agent-run-zombie-settlement.md
- docs/plans/harness-watch-run-failure-boundary.md
+ - docs/plans/watch-follow-up-circuit-breaker.md
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index dc23870b1..6a8e752f9 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -287,3 +287,16 @@ observations:
belongs to the Turn and waiter health belongs to the waiter. Linked Runs need
only one Turn-scoped fallback when the primary backend notification cannot be
acknowledged; downstream processing health must remain a separate projection.
+ - id: HFR-OBS-024
+ date: 2026-08-08
+ source: issue #953 Watch and Agent Run history
+ result: confirmed
+ detail: >-
+ A level-triggered forever Watch returned exit zero while the observed
+ condition remained true. The supervisor immediately re-ran the waiter after
+ every success and treated each identical level as a new event. In 18.139
+ seconds the one definition created 274 Agent Runs: 174 completed no-op Runs
+ and 100 more queued Runs. Queue coalescing cannot repair this because the
+ producer has already asserted 274 distinct events. The event lifecycle must
+ include its Agent follow-up, and the Watch owner must stop admitting events
+ when successful exits remain implausibly dense.
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 0c2df7610..f276e19ef 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -107,6 +107,12 @@ def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:
assert "watches follow up in this conversation by default" in captured.out
assert "Prefer --message or --message-file for follow-up instructions" in captured.out
assert "Terminal failures also send a follow-up and disable the watch." in captured.out
+ assert "an allowed `--retry-exit-code` keeps waiting" in captured.out
+ assert "A once Watch stops after its first event" in captured.out
+ assert "five-second safety delay" in captured.out
+ assert "automatically pause the Watch" in captured.out
+ assert "a once Watch ends and a forever Watch re-arms" in captured.out
+ assert "A once waiter that is still waiting must use a retry exit code" in captured.out
assert "If this is your first time using this command, read this whole help entry before creating a watch." in captured.out
assert "--same-scope" in captured.out
assert "--scope-id" in captured.out
@@ -224,7 +230,10 @@ def test_watch_add_missing_command_is_structured_json() -> None:
assert payload["help_command"] == "vibe watch add --help"
-def test_watch_add_rejects_lifetime_timeout_without_forever() -> None:
+def test_watch_add_accepts_lifetime_timeout_for_retrying_once_watch(
+ tmp_path: Path,
+ capsys,
+) -> None:
args = _parse_watch_add(
[
"--session-key",
@@ -236,11 +245,25 @@ def test_watch_add_rejects_lifetime_timeout_without_forever() -> None:
]
)
- with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
- result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch(
+ "vibe.cli._wait_for_watch_startup",
+ side_effect=lambda *values, **kwargs: _startup_ok(
+ store, runtime_store, values[2]
+ ),
+ ),
+ ):
+ result = cli.cmd_watch_add(args)
- assert result == 1
- assert payload["code"] == "invalid_watch_lifetime_timeout"
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["definition"]["mode"] == "once"
+ assert payload["definition"]["lifetime_timeout_seconds"] == 10
def test_watch_add_rejects_missing_cwd() -> None:
@@ -443,6 +466,12 @@ def test_watch_add_records_caller_context_metadata(tmp_path: Path, capsys) -> No
"AVIBE_CALLER_SOURCE": "agent_turn",
"AVIBE_CALLER_BACKEND": "opencode",
"AVIBE_NATIVE_SESSION_ID": "native-opencode-1",
+ "AVIBE_CALLER_PLATFORM": "",
+ "AVIBE_CALLER_USER_ID": "",
+ "AVIBE_CALLER_CHANNEL_ID": "",
+ "AVIBE_CALLER_SESSION_KEY": "",
+ "AVIBE_CALLER_MESSAGE_ID": "",
+ "AVIBE_CALLER_WORKSPACE_ID": "",
}
with (
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index 59cabd9e3..ddf3f40aa 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -2053,15 +2053,17 @@ def test_a_failed_watch_notice_renders_watch_commands(tmp_path: Path) -> None:
@pytest.mark.parametrize(
- ("outcome", "headline_key"),
+ ("outcome", "definition_enabled", "headline_key"),
[
- ("event", "harness.notice.watchProcessingFailed"),
- ("waiter_failure", "harness.notice.watchFailureReportFailed"),
+ ("event", True, "harness.notice.watchProcessingFailed"),
+ ("waiter_failure", False, "harness.notice.watchFailureReportFailed"),
+ ("circuit_repair", False, "harness.notice.watchCircuitRepairFailed"),
],
)
def test_watch_notice_copy_preserves_the_waiter_outcome(
tmp_path: Path,
outcome: str,
+ definition_enabled: bool,
headline_key: str,
) -> None:
"""A failed reporting Turn cannot turn a waiter failure into an event."""
@@ -2073,7 +2075,12 @@ def test_watch_notice_copy_preserves_the_waiter_outcome(
from vibe.i18n import t as i18n_t
sqlite, requests = _store(tmp_path)
- _watch(sqlite, "watch-copy", name="CI waiter")
+ _watch(
+ sqlite,
+ "watch-copy",
+ name="CI waiter",
+ enabled=definition_enabled,
+ )
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
store._sqlite = sqlite
store.load()
@@ -2111,6 +2118,61 @@ def test_watch_notice_copy_preserves_the_waiter_outcome(
assert "detected an event" not in body
[email protected]("definition_state", ["resumed", "deleted"])
+def test_circuit_repair_failure_copy_does_not_claim_a_stale_pause_state(
+ tmp_path: Path,
+ definition_state: str,
+) -> None:
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+ from storage.background import WATCH_HOOK_OUTCOME_METADATA_KEY
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _watch(sqlite, "watch-repair-state", name="Disk waiter", enabled=True)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ run = requests.enqueue_hook_send(
+ session_key="slack::channel::C1",
+ prompt="repair the Watch",
+ run_type="watch",
+ definition_id="watch-repair-state",
+ metadata={WATCH_HOOK_OUTCOME_METADATA_KEY: "circuit_repair"},
+ )
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(
+ claimed,
+ ok=False,
+ error="repair Agent failed",
+ task_id="watch-repair-state",
+ )
+ if definition_state == "deleted":
+ assert sqlite.remove_task("watch-repair-state")
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(
+ platform_settings_managers={},
+ session_turn_gate=None,
+ )
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ body = service._failure_notice_body(
+ sqlite.get_run(run.id),
+ sqlite.owed_failure_notice(run.id),
+ )
+
+ generic = i18n_t("harness.notice.watchFollowUpFailed", "en").format(
+ name="Disk waiter" if definition_state == "resumed" else "watch-repair-state"
+ )
+ assert generic in body
+ assert "remains paused" not in body
+
+
def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> None:
"""The task-side twin of the retired-watch copy fix — FINISHED IS NOT PAUSED.
@@ -12287,17 +12349,56 @@ def test_a_forever_watch_repeating_the_field_failure_notifies_once(
runtime_store=runtime_store,
)
+ # HFR-464 serializes Watch follow-ups. This scenario is about failure-notice
+ # deduplication, so settle each event Run before allowing the next event and
+ # remove the unrelated five-second production cooldown from the test clock.
+ monkeypatch.setattr("core.watches.WATCH_MIN_REARM_SECONDS", 0)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ executor = _execution_service(tmp_path, controller, sqlite, requests)
+
+ asyncio.run(
+ _drive_watch_service(
+ service,
+ watch.id,
+ until=lambda: len(_watch_hook_runs(requests)) == 1,
+ )
+ )
+ first_hook = _watch_hook_runs(requests)[0]
+ first_claim = requests.claim(first_hook.id)
+ assert first_claim is not None
+ asyncio.run(executor._execute_claimed_request(first_claim))
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=watch_store,
+ request_store=requests,
+ runtime_store=runtime_store,
+ )
+ asyncio.run(
+ _drive_watch_service(
+ service,
+ watch.id,
+ until=lambda: len(_watch_hook_runs(requests)) == 1,
+ )
+ )
+ second_hook = _watch_hook_runs(requests)[0]
+ second_claim = requests.claim(second_hook.id)
+ assert second_claim is not None
+ asyncio.run(executor._execute_claimed_request(second_claim))
+
def _ready() -> bool:
row = watch_store.get_watch(watch.id)
- return (
- len(_watch_hook_runs(requests)) >= 2
- and row is not None
- and row.last_exit_code == 75
- )
+ return row is not None and row.last_exit_code == 75
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=watch_store,
+ request_store=requests,
+ runtime_store=runtime_store,
+ )
asyncio.run(_drive_watch_service(service, watch.id, until=_ready, limit=800))
- hooks = sorted(_watch_hook_runs(requests), key=lambda row: (row.created_at, row.id))
+ hooks = [first_hook, second_hook]
assert len(hooks) == 2, f"two events must queue two follow-up deliveries: {hooks}"
saved = watch_store.get_watch(watch.id)
@@ -12313,13 +12414,6 @@ def test_a_forever_watch_repeating_the_field_failure_notifies_once(
f"the premise for the last assertion below — the last cycle was a retry: {saved}"
)
- controller, _dispatcher, _touched = _live_turn_dispatcher()
- executor = _execution_service(tmp_path, controller, sqlite, requests)
- for hook in hooks:
- claimed = requests.claim(hook.id)
- assert claimed is not None
- asyncio.run(executor._execute_claimed_request(claimed))
-
for hook in hooks:
run = sqlite.get_run(hook.id)
assert run["status"] == "failed", f"both deliveries fail the same way: {run}"
diff --git a/tests/test_harness_health_projection.py b/tests/test_harness_health_projection.py
index add777965..f19225480 100644
--- a/tests/test_harness_health_projection.py
+++ b/tests/test_harness_health_projection.py
@@ -25,6 +25,8 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
+import pytest
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core import scheduled_tasks as scheduled_tasks_module
@@ -335,62 +337,24 @@ def test_watch_health_separates_waiter_from_event_processing(tmp_path, monkeypat
assert projected["processing_consecutive_failures"] == 2
-def test_once_watch_retry_exit_is_a_terminal_waiter_failure(tmp_path, monkeypatch) -> None:
- """Retry codes are healthy only while a forever Watch can actually retry."""
-
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- watch_store = ManagedWatchStore()
- watch = watch_store.add_watch(
- name="one attempt",
- session_key="slack::channel::C123",
- command=[],
- shell_command="exit 75",
- prefix=None,
- cwd=None,
- mode="once",
- timeout_seconds=30,
- lifetime_timeout_seconds=0,
- retry_exit_codes=[75],
- retry_delay_seconds=0,
- post_to=None,
- deliver_key=None,
- )
- assert watch_store.mark_cycle_start(watch.id)
- assert watch_store.mark_cycle_result(
- watch.id,
- exit_code=75,
- error="watch command exited with status 75",
- disable=True,
- )
-
- sqlite = SQLiteBackgroundTaskStore()
- try:
- projected = sqlite.get_watch(watch.id)
- finally:
- sqlite.close()
-
- assert projected is not None
- assert projected["lifecycle_state"] == "finished"
- assert projected["health"] == "failing"
- assert projected["consecutive_failures"] == 1
-
-
-def test_forever_watch_retry_health_requires_an_enabled_definition(
[email protected]("mode", ["once", "forever"])
+def test_watch_retry_health_depends_on_enabled_state_not_mode(
tmp_path,
monkeypatch,
+ mode,
) -> None:
- """The same retry code becomes failing when the Watch retires."""
+ """An allowed retry is healthy exactly while the Watch remains armed."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
watch_store = ManagedWatchStore()
watch = watch_store.add_watch(
- name="bounded retries",
+ name=f"{mode} bounded retries",
session_key="slack::channel::C123",
command=[],
shell_command="exit 75",
prefix=None,
cwd=None,
- mode="forever",
+ mode=mode,
timeout_seconds=30,
lifetime_timeout_seconds=60,
retry_exit_codes=[75],
@@ -413,7 +377,9 @@ def test_forever_watch_retry_health_requires_an_enabled_definition(
sqlite.close()
assert retrying is not None
assert retrying["enabled"] is True
+ assert retrying["lifecycle_state"] == "waiting"
assert retrying["health"] == "healthy"
+ assert retrying["consecutive_failures"] == 0
assert watch_store.mark_cycle_start(watch.id)
assert watch_store.mark_cycle_result(
@@ -431,3 +397,4 @@ def test_forever_watch_retry_health_requires_an_enabled_definition(
assert retired["enabled"] is False
assert retired["lifecycle_state"] == "finished"
assert retired["health"] == "failing"
+ assert retired["consecutive_failures"] == 1
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index c6d18a4e8..b42a825eb 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1619,6 +1619,12 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Watches created from an Avibe Agent shell follow up in this conversation by default", prompt)
self.assertIn("`vibe watch add` creates a managed monitor", prompt)
self.assertIn("product signals, business events, files, logs, CI/reviews/deploys", prompt)
+ self.assertIn("exit `0` only for one NEW reportable event", prompt)
+ self.assertIn("default `75`) keeps either a once or forever Watch waiting", prompt)
+ self.assertIn("it retires a once Watch and re-arms a forever Watch", prompt)
+ self.assertIn("must therefore return an allowed retry code, not `64`", prompt)
+ self.assertIn("waits five seconds after a follow-up settles before re-arming", prompt)
+ self.assertIn("six successful events within 60 seconds", prompt)
delegate_guidance = (
"Use `vibe agent run --agent <agent-name> --message ...` when one Agent delegates work to another Agent. "
"By default this creates a background Session in the caller's scope and returns immediately; when the run "
diff --git a/tests/test_watches.py b/tests/test_watches.py
index cee32ab2e..7afedc3b5 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -7,7 +7,7 @@ import os
import sys
import threading
import time
-from datetime import datetime
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
@@ -25,10 +25,15 @@ from core.process_isolation import (
from core.runtime_work import RuntimeWorkItem, RuntimeWorkLane, RuntimeWorkSupervisor
from core.scheduled_tasks import TaskExecutionStore
from core.watches import (
+ CIRCUIT_BREAKER_METADATA_KEY,
DELIVERY_ACK_METADATA_KEY,
+ FOLLOW_UP_RUN_ID_METADATA_KEY,
LAST_DELIVERY_ENV,
+ LIFETIME_STARTED_AT_METADATA_KEY,
NO_EVENT_EXIT_CODE,
NO_EVENT_MARKER,
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY,
+ WATCH_CIRCUIT_OUTPUT_LIMIT,
WATCH_ID_ENV,
ManagedWatchService,
ManagedWatchStore,
@@ -36,9 +41,11 @@ from core.watches import (
_CycleResult,
_cycle_env,
_ManagedWatchRuntimeWorkHandler,
+ _recent_event_timestamps,
_StaleWorkerRecovery,
)
from storage.background import (
+ WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR,
WATCH_HOOK_OUTCOME_EVENT,
WATCH_HOOK_OUTCOME_METADATA_KEY,
WATCH_HOOK_OUTCOME_WAITER_FAILURE,
@@ -1179,6 +1186,709 @@ def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path:
assert request_store.list_pending() == []
+def test_managed_watch_service_once_retries_until_first_success(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-463: a retry result keeps a once Watch armed until its first event."""
+
+ 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="Wait until ready",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Continue after the event.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ results = iter(
+ [
+ _CycleResult(exit_code=75, stdout="", stderr="not ready", timed_out=False),
+ _CycleResult(exit_code=0, stdout="ready", stderr="", timed_out=False),
+ ]
+ )
+ calls = 0
+
+ async def fake_run_cycle(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ return next(results)
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+ service._running = True
+ service._requires_service_lease = False
+
+ asyncio.run(service._run_watch(watch.id))
+
+ saved = store.get_watch(watch.id)
+ pending = request_store.list_pending()
+ assert calls == 2
+ assert saved is not None and saved.enabled is False
+ assert saved.last_exit_code == 0
+ assert len(pending) == 1
+ assert pending[0].prompt.endswith("ready")
+
+
+ ("language", "expected_prefix", "expected_body"),
+ [
+ (
+ "en",
+ "Watch stopped after reaching its lifetime timeout.",
+ "Watch 'Bounded wait' reached its lifetime timeout after 0 second(s).",
+ ),
+ (
+ "zh",
+ "Watch 达到生命周期上限后已停止。",
+ "Watch「Bounded wait」已达到 0 秒的生命周期上限。",
+ ),
+ ],
+)
+def test_retrying_once_watch_lifetime_bounds_a_long_retry_delay(
+ tmp_path: Path,
+ monkeypatch,
+ language: str,
+ expected_prefix: str,
+ expected_body: str,
+) -> None:
+ """HFR-470: the overall lifetime truncates a once Watch retry delay."""
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ watch = store.add_watch(
+ name="Bounded wait",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0.05,
+ retry_exit_codes=[75],
+ retry_delay_seconds=10,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(config=SimpleNamespace(language=language)),
+ store=store,
+ request_store=request_store,
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+
+ async def fake_run_cycle(*args, **kwargs):
+ return _CycleResult(exit_code=75, stdout="", stderr="not ready", timed_out=False)
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+ service._running = True
+ service._requires_service_lease = False
+
+ started = time.monotonic()
+ asyncio.run(service._run_watch(watch.id))
+
+ saved = store.get_watch(watch.id)
+ assert time.monotonic() - started < 1
+ assert saved is not None and saved.enabled is False
+ assert saved.last_exit_code == 124
+ pending = request_store.list_pending()
+ assert len(pending) == 1
+ assert expected_prefix in pending[0].prompt
+ assert expected_body in pending[0].prompt
+
+
[email protected]("mode", ["once", "forever"])
[email protected]("origin_source", ["metadata", "legacy_created_at"])
+def test_watch_lifetime_origin_survives_supervisor_restart(
+ tmp_path: Path,
+ monkeypatch,
+ mode: str,
+ origin_source: str,
+) -> None:
+ """HFR-470: one armed episode keeps its deadline across supervisor restarts."""
+
+ path = tmp_path / "watches.json"
+ store = ManagedWatchStore(path)
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ watch = store.add_watch(
+ name="Bounded wait",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode=mode,
+ timeout_seconds=5,
+ lifetime_timeout_seconds=1,
+ retry_exit_codes=[75],
+ retry_delay_seconds=10,
+ post_to=None,
+ deliver_key=None,
+ )
+ expired_origin = (datetime.now(timezone.utc) - timedelta(seconds=5)).isoformat()
+ if origin_source == "metadata":
+ watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY] = expired_origin
+ else:
+ watch.metadata.pop(LIFETIME_STARTED_AT_METADATA_KEY)
+ watch.created_at = expired_origin
+ store.upsert_watch(watch)
+
+ restarted_store = ManagedWatchStore(path)
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=restarted_store,
+ request_store=request_store,
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+
+ async def unexpected_cycle(*args, **kwargs):
+ raise AssertionError("a supervisor restart must not grant another cycle")
+
+ monkeypatch.setattr(service, "_run_cycle", unexpected_cycle)
+ service._running = True
+ service._requires_service_lease = False
+
+ asyncio.run(service._run_watch(watch.id))
+
+ saved = restarted_store.get_watch(watch.id)
+ assert saved is not None and saved.enabled is False
+ assert saved.last_exit_code == 124
+ assert len(request_store.list_pending()) == 1
+
+
[email protected]("metadata_run_id", [None, "stale-run"])
+def test_watch_lifetime_retires_while_an_existing_follow_up_is_active(
+ tmp_path: Path,
+ monkeypatch,
+ metadata_run_id: str | None,
+) -> None:
+ """The actual queued Run owns expiry even when Watch metadata is absent or stale."""
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ watch = store.add_watch(
+ name="Bounded follow-up",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Inspect the event.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0.05,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ if metadata_run_id is not None:
+ assert store.mark_cycle_result(
+ watch.id,
+ exit_code=None,
+ error=None,
+ metadata_updates={FOLLOW_UP_RUN_ID_METADATA_KEY: metadata_run_id},
+ )
+ active = request_store.enqueue_hook_send(
+ session_key=watch.session_key,
+ prompt="existing event",
+ run_type="watch",
+ definition_id=watch.id,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+
+ async def unexpected_cycle(*args, **kwargs):
+ raise AssertionError("the follow-up fence must not admit another waiter")
+
+ monkeypatch.setattr(service, "_run_cycle", unexpected_cycle)
+ monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0.005)
+ service._running = True
+ service._requires_service_lease = False
+
+ started = time.monotonic()
+ asyncio.run(service._run_watch(watch.id))
+
+ saved = store.get_watch(watch.id)
+ assert time.monotonic() - started < 1
+ assert saved is not None and saved.enabled is False
+ assert saved.last_exit_code == 124
+ assert "retired without starting another Run" in str(saved.last_error)
+ assert active.id in str(saved.last_error)
+ pending = request_store.list_pending()
+ assert [request.id for request in pending] == [active.id]
+
+
+def test_once_watch_retries_timeout_only_when_124_is_allowed(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-471: timeout retries require explicit policy on a once Watch."""
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ watch = store.add_watch(
+ name="Retry one timeout",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Continue after the event.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[124],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+ results = iter(
+ [
+ _CycleResult(exit_code=124, stdout="", stderr="", timed_out=True),
+ _CycleResult(exit_code=0, stdout="ready", stderr="", timed_out=False),
+ ]
+ )
+
+ async def fake_run_cycle(*args, **kwargs):
+ return next(results)
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+ service._running = True
+ service._requires_service_lease = False
+
+ asyncio.run(service._run_watch(watch.id))
+
+ saved = store.get_watch(watch.id)
+ assert saved is not None and saved.enabled is False
+ assert saved.last_exit_code == 0
+ assert len(request_store.list_pending()) == 1
+
+
+def test_forever_watch_waits_for_previous_follow_up_before_rearming(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-464: queued/running follow-ups and cooldown both hold re-arm closed."""
+
+ 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="Disk pressure",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Inspect the new pressure event.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ calls = 0
+
+ async def fake_run_cycle(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return _CycleResult(exit_code=0, stdout="event 1", stderr="", timed_out=False)
+ service._running = False
+ return _CycleResult(
+ exit_code=NO_EVENT_EXIT_CODE,
+ stdout="",
+ stderr=NO_EVENT_MARKER,
+ timed_out=False,
+ )
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+ monkeypatch.setattr(watches_module, "WATCH_MIN_REARM_SECONDS", 0.1)
+ monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0.005)
+ service._running = True
+ service._requires_service_lease = False
+
+ async def _run() -> None:
+ task = asyncio.create_task(service._run_watch(watch.id))
+ for _ in range(100):
+ if request_store.list_pending():
+ break
+ await asyncio.sleep(0.01)
+ assert calls == 1
+ await asyncio.sleep(0.05)
+ assert calls == 1, "an unfinished event Run must hold the waiter closed"
+ request = request_store.list_pending()[0]
+ claimed = request_store.claim(request.id)
+ assert claimed is not None
+ request_store.complete(claimed, ok=True)
+ await asyncio.sleep(0.03)
+ assert calls == 1, "the post-Run re-arm delay must hold the waiter closed"
+ await asyncio.wait_for(task, timeout=2)
+
+ asyncio.run(_run())
+
+ assert calls == 2
+
+
+def test_atomic_watch_outbox_rejects_a_second_unsettled_follow_up(
+ tmp_path: Path,
+) -> None:
+ """HFR-466: atomic admission rejects a second unfinished Watch follow-up."""
+
+ store = ManagedWatchStore()
+ request_store = TaskExecutionStore()
+ assert store.sqlite_backend is not None
+ assert request_store.sqlite_backend is not None
+ assert store.sqlite_backend.db_path == request_store.sqlite_backend.db_path
+ session_id = _bare_watch_session_row(workdir=tmp_path, anchor="single_flight")
+ watch = store.add_watch(
+ name="Single-flight watch",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Inspect it.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=WatchRuntimeStateStore(tmp_path / "watch_runtime.json"),
+ )
+
+ assert service._commit_cycle_result(
+ watch,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ prompt="first event",
+ )
+ reloaded = store.get_watch(watch.id)
+ assert reloaded is not None
+ assert not service._commit_cycle_result(
+ reloaded,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ prompt="duplicate event",
+ )
+
+ assert len(request_store.list_pending()) == 1
+ unsettled = request_store.get_unsettled_watch_run(watch.id)
+ assert unsettled is not None
+ assert unsettled["prompt"] == "first event"
+ saved = store.get_watch(watch.id)
+ assert saved is not None
+ assert saved.metadata[DELIVERY_ACK_METADATA_KEY] == 1
+
+
+def test_forever_watch_sixth_rapid_success_pauses_and_queues_one_repair_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-465: the sixth rapid event pauses once and preserves repair evidence."""
+
+ store = ManagedWatchStore()
+ request_store = TaskExecutionStore()
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ session_id = _bare_watch_session_row(workdir=tmp_path, anchor="circuit_repair")
+ watch = store.add_watch(
+ name="Level-triggered disk alert",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix="Inspect the disk alert.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ calls = 0
+
+ async def fake_run_cycle(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ stdout = f"persistent level {calls}"
+ stderr = "diagnostic stderr"
+ if calls == 6:
+ stdout = ("old stdout\n" * 500) + stdout
+ stderr = ("old stderr\n" * 500) + stderr
+ return _CycleResult(
+ exit_code=0,
+ stdout=stdout,
+ stderr=stderr,
+ timed_out=False,
+ )
+
+ monkeypatch.setattr(service, "_run_cycle", fake_run_cycle)
+ monkeypatch.setattr(watches_module, "WATCH_MIN_REARM_SECONDS", 0)
+ monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0.001)
+ service._running = True
+ service._requires_service_lease = False
+
+ async def _run() -> None:
+ task = asyncio.create_task(service._run_watch(watch.id))
+ while not task.done():
+ for request in request_store.list_pending():
+ outcome = request.metadata.get(WATCH_HOOK_OUTCOME_METADATA_KEY)
+ if outcome != WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR:
+ claimed = request_store.claim(request.id)
+ assert claimed is not None
+ request_store.complete(claimed, ok=True)
+ await asyncio.sleep(0.001)
+ await task
+
+ asyncio.run(_run())
+
+ saved = store.get_watch(watch.id)
+ pending = request_store.list_pending()
+ completed = request_store.list_runs(status="succeeded")
+ assert calls == 6
+ assert saved is not None and saved.enabled is False
+ assert saved.retired_at is None
+ assert saved.last_error is not None
+ assert "60 seconds" in saved.last_error
+ assert saved.metadata[DELIVERY_ACK_METADATA_KEY] == 5
+ assert len(saved.metadata[RECENT_EVENT_TIMESTAMPS_METADATA_KEY]) == 6
+ incident = saved.metadata[CIRCUIT_BREAKER_METADATA_KEY]
+ assert incident["repair_run_id"] == saved.metadata[FOLLOW_UP_RUN_ID_METADATA_KEY]
+ assert len(incident["stdout"]) <= WATCH_CIRCUIT_OUTPUT_LIMIT
+ assert len(incident["stderr"]) <= WATCH_CIRCUIT_OUTPUT_LIMIT
+ assert incident["stdout"].endswith("persistent level 6")
+ assert incident["stderr"].endswith("diagnostic stderr")
+ assert len(completed) == 5
+ assert len(pending) == 1
+ assert pending[0].id in saved.last_error
+ assert (
+ pending[0].metadata[WATCH_HOOK_OUTCOME_METADATA_KEY]
+ == WATCH_HOOK_OUTCOME_CIRCUIT_REPAIR
+ )
+ assert "Level-triggered disk alert" in pending[0].prompt
+ assert "persistent level 6" in pending[0].prompt
+ assert "allowed retry exit codes: 75" in pending[0].prompt
+ assert "vibe watch resume" in pending[0].prompt
+
+ restarted = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=ManagedWatchStore(),
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ restarted._running = True
+ restarted._requires_service_lease = False
+ asyncio.run(restarted._run_watch(watch.id))
+ assert len(request_store.list_pending()) == 1
+
+
+def test_watch_event_burst_window_excludes_successes_older_than_sixty_seconds() -> None:
+ now = datetime(2026, 8, 10, 12, 0, tzinfo=timezone.utc)
+ timestamps = [
+ (now - timedelta(seconds=61)).isoformat(),
+ (now - timedelta(seconds=59)).isoformat(),
+ now.isoformat(),
+ ]
+
+ recent = _recent_event_timestamps(
+ {RECENT_EVENT_TIMESTAMPS_METADATA_KEY: timestamps},
+ now=now,
+ )
+
+ assert recent == timestamps[1:]
+
+
+def test_resuming_circuit_paused_watch_clears_window_but_keeps_repair_fence(
+ tmp_path: Path,
+) -> None:
+ """HFR-467: resume clears burst state without releasing the active repair Run."""
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = store.add_watch(
+ name="Disk alert",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ metadata={
+ FOLLOW_UP_RUN_ID_METADATA_KEY: "run-repair",
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY: ["2026-08-10T00:00:00+00:00"],
+ CIRCUIT_BREAKER_METADATA_KEY: {
+ "status": "tripped",
+ "repair_run_id": "run-repair",
+ },
+ },
+ )
+ store.set_enabled(watch.id, False)
+ prior_lifetime_origin = watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY]
+
+ resumed = store.set_enabled(watch.id, True)
+
+ assert RECENT_EVENT_TIMESTAMPS_METADATA_KEY not in resumed.metadata
+ assert resumed.metadata[FOLLOW_UP_RUN_ID_METADATA_KEY] == "run-repair"
+ assert resumed.metadata[CIRCUIT_BREAKER_METADATA_KEY]["status"] == "resumed"
+ assert resumed.metadata[LIFETIME_STARTED_AT_METADATA_KEY] != prior_lifetime_origin
+
+
+def test_storage_resume_applies_the_same_circuit_reset_as_cli() -> None:
+ """HFR-468: storage and CLI resume paths apply the same circuit reset."""
+
+ store = ManagedWatchStore()
+ assert store.sqlite_backend is not None
+ watch = store.add_watch(
+ name="Disk alert",
+ session_key="slack::channel::C123",
+ command=[sys.executable, "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ metadata={
+ FOLLOW_UP_RUN_ID_METADATA_KEY: "run-repair",
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY: ["2026-08-10T00:00:00+00:00"],
+ CIRCUIT_BREAKER_METADATA_KEY: {
+ "status": "tripped",
+ "repair_run_id": "run-repair",
+ },
+ },
+ )
+ assert store.sqlite_backend.set_definition_enabled(
+ watch.id,
+ False,
+ definition_type="watch",
+ )
+ prior_lifetime_origin = watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY]
+ assert store.sqlite_backend.set_definition_enabled(
+ watch.id,
+ True,
+ definition_type="watch",
+ )
+
+ store.load()
+ resumed = store.get_watch(watch.id)
+ assert resumed is not None
+ assert RECENT_EVENT_TIMESTAMPS_METADATA_KEY not in resumed.metadata
+ assert resumed.metadata[FOLLOW_UP_RUN_ID_METADATA_KEY] == "run-repair"
+ assert resumed.metadata[CIRCUIT_BREAKER_METADATA_KEY]["status"] == "resumed"
+ assert resumed.metadata[LIFETIME_STARTED_AT_METADATA_KEY] != prior_lifetime_origin
+
+
+def test_changing_watch_cwd_starts_a_fresh_burst_window(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ old_cwd = tmp_path / "old"
+ new_cwd = tmp_path / "new"
+ watch = store.add_watch(
+ name="Relative waiter",
+ session_key="slack::channel::C123",
+ command=["./wait.py"],
+ shell_command=None,
+ prefix="Inspect it.",
+ cwd=str(old_cwd),
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ metadata={
+ RECENT_EVENT_TIMESTAMPS_METADATA_KEY: ["2026-08-10T00:00:00+00:00"],
+ FOLLOW_UP_RUN_ID_METADATA_KEY: "run-before-cwd-change",
+ },
+ )
+ lifetime_origin = watch.metadata[LIFETIME_STARTED_AT_METADATA_KEY]
+
+ updated = store.update_watch(
+ watch.id,
+ name=watch.name,
+ session_key=watch.session_key,
+ session_id=watch.session_id,
+ command=watch.command,
+ shell_command=watch.shell_command,
+ prefix=watch.prefix,
+ cwd=str(new_cwd),
+ mode=watch.mode,
+ timeout_seconds=watch.timeout_seconds,
+ lifetime_timeout_seconds=watch.lifetime_timeout_seconds,
+ retry_exit_codes=watch.retry_exit_codes,
+ retry_delay_seconds=watch.retry_delay_seconds,
+ post_to=watch.post_to,
+ deliver_key=watch.deliver_key,
+ agent_name=watch.agent_name,
+ session_policy=watch.session_policy,
+ message=watch.message,
+ metadata=watch.metadata,
+ )
+
+ assert RECENT_EVENT_TIMESTAMPS_METADATA_KEY not in updated.metadata
+ assert updated.metadata[FOLLOW_UP_RUN_ID_METADATA_KEY] == "run-before-cwd-change"
+ assert updated.metadata[LIFETIME_STARTED_AT_METADATA_KEY] == lifetime_origin
+
+
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")
@@ -4016,8 +4726,11 @@ def test_quiet_cycle_summary_keeps_the_end_of_a_long_waiter_report() -> None:
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.
+def test_a_cycle_is_told_when_this_watch_last_had_a_report_delivered(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-469: a waiter learns whether its earlier report was 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
@@ -4081,8 +4794,20 @@ def test_a_cycle_is_told_when_this_watch_last_had_a_report_delivered(tmp_path: P
return scripted[min(len(told) - 1, len(scripted) - 1)]
service._run_cycle = _spy_cycle # type: ignore[method-assign]
+ monkeypatch.setattr(watches_module, "WATCH_MIN_REARM_SECONDS", 0)
+ monkeypatch.setattr(watches_module, "WATCH_FOLLOW_UP_POLL_SECONDS", 0.001)
- asyncio.run(service._run_watch(watch.id))
+ async def _run() -> None:
+ task = asyncio.create_task(service._run_watch(watch.id))
+ while not task.done():
+ for request in request_store.list_pending():
+ claimed = request_store.claim(request.id)
+ if claimed is not None:
+ request_store.complete(claimed, ok=True)
+ await asyncio.sleep(0.001)
+ await task
+
+ asyncio.run(_run())
assert told[0] == "", "nothing has been reported yet"
assert told[1], "the event was delivered, so the stamp has to have moved"
diff --git a/vibe/cli.py b/vibe/cli.py
index b7ab5c4c1..d46fa6583 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1361,14 +1361,17 @@ def _watch_add_examples_text() -> str:
Use --create-session with --same-scope only from an Avibe Agent shell, where the caller Session scope is available.
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;
+ In either mode, an allowed `--retry-exit-code` keeps waiting. A once Watch stops after its first event.
+ A forever Watch waits for each event's Agent Run to finish before re-arming, then applies a five-second safety delay.
+ Exit 0 must mean one new reportable event, not a condition that merely remains true. Repeated rapid successes automatically pause the Watch and send the Agent a repair message.
+ Waiter exit codes: 0 detected an event and sends the follow-up; 124 timed out and is terminal unless explicitly allowed for retry;
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.
+ so a once Watch ends and a forever Watch re-arms WITHOUT an Agent turn. A once waiter that is still waiting must use a retry exit code.
+ 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.
+ --timeout applies to each cycle. --lifetime-timeout applies to the whole Watch lifetime across retries and re-arms.
Examples:
vibe watch add --session-id sesk8m4q2p7x --message 'The export finished. Inspect it and continue.' --shell 'python3 scripts/wait_for_export.py'
@@ -1757,7 +1760,6 @@ def _validate_watch_timing(
timeout_seconds: float,
retry_delay_seconds: float,
lifetime_timeout_seconds: float,
- mode: str,
help_command: str,
) -> None:
if timeout_seconds < 0:
@@ -1784,13 +1786,6 @@ def _validate_watch_timing(
help_command=help_command,
details={"lifetime_timeout": lifetime_timeout_seconds},
)
- if lifetime_timeout_seconds and mode != "forever":
- raise TaskCliError(
- "--lifetime-timeout requires --forever",
- code="invalid_watch_lifetime_timeout",
- hint="Use --lifetime-timeout only on forever watches.",
- help_command=help_command,
- )
def _task_message_preview(message: str, *, max_chars: int = 72) -> str:
@@ -9615,7 +9610,6 @@ def cmd_watch_add(args):
timeout_seconds=float(args.timeout),
retry_delay_seconds=float(args.retry_delay),
lifetime_timeout_seconds=float(args.lifetime_timeout),
- mode=mode,
help_command="vibe watch add --help",
)
prefix = _normalize_task_name(getattr(args, "prefix", None))
@@ -9931,7 +9925,6 @@ def cmd_watch_update(args):
timeout_seconds=timeout_seconds,
retry_delay_seconds=retry_delay_seconds,
lifetime_timeout_seconds=lifetime_timeout_seconds,
- mode=mode,
help_command="vibe watch update --help",
)
session_policy = _definition_session_policy_for_update(
@@ -15234,7 +15227,7 @@ def build_parser():
epilog=_watch_add_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe watch add --help",
- error_hint="Use --session-id and either --shell or a command after '--'. Add --forever only when the waiter should re-arm after successful cycles and only retry failures for explicit retry exit codes.",
+ error_hint="Use --session-id and either --shell or a command after '--'. Retry exit codes keep either mode waiting; add --forever only when distinct successful events should re-arm the Watch.",
)
watch_add_parser.add_argument("--name", help="Optional human-friendly watch name")
watch_add_parser.add_argument(
@@ -15279,13 +15272,13 @@ def build_parser():
watch_add_parser.add_argument(
"--forever",
action="store_true",
- help="Keep re-arming the watch after each successful cycle instead of stopping after the first event. Terminal failures still stop the watch unless a retry exit code is allowed.",
+ help="Monitor distinct events continuously. After each event's Agent Run settles, the Watch re-arms; terminal failures still stop it unless their exit code is retryable.",
)
watch_add_parser.add_argument(
"--lifetime-timeout",
type=float,
default=0,
- help="Overall forever-watch lifetime timeout in seconds. Use 0 for no lifetime limit. Requires --forever.",
+ help="Overall Watch lifetime timeout in seconds across retries and re-arms. Use 0 for no lifetime limit.",
)
watch_add_parser.add_argument(
"--retry-exit-code",
@@ -15293,13 +15286,13 @@ def build_parser():
action="append",
type=int,
default=None,
- help=f"Cycle exit code that should be retried in forever mode. Repeat to add more. Default: {DEFAULT_RETRY_EXIT_CODE}",
+ help=f"Cycle exit code that should keep waiting. Repeat to add more. Default: {DEFAULT_RETRY_EXIT_CODE}",
)
watch_add_parser.add_argument(
"--retry-delay",
type=float,
default=30,
- help="Delay in seconds before retrying an allowed forever cycle failure. Default: 30",
+ help="Delay in seconds before retrying an allowed cycle result. Default: 30",
)
watch_add_parser.add_argument(
"--shell",
@@ -15372,7 +15365,7 @@ def build_parser():
watch_update_parser.add_argument(
"--lifetime-timeout",
type=float,
- help="Set overall forever-watch lifetime timeout in seconds. Use 0 for no lifetime limit.",
+ help="Set the overall Watch lifetime timeout across retries and re-arms. Use 0 for no lifetime limit.",
)
watch_update_parser.add_argument(
"--retry-exit-code",
@@ -15380,7 +15373,7 @@ def build_parser():
action="append",
type=int,
default=None,
- help="Replace retryable forever-mode exit codes. Repeat to add more.",
+ help="Replace exit codes that keep this Watch waiting. Repeat to add more.",
)
watch_update_parser.add_argument("--retry-delay", type=float, help="Set retry delay in seconds")
watch_update_parser.add_argument("--shell", help="Replace waiter with a shell command")
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 77d66836c..34c9131e7 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -35,6 +35,12 @@
"supervisorFailed": "Watch worker supervisor failed: {detail}",
"supervisorExitedDuringStartup": "Watch worker supervisor exited during startup.",
"unknownSupervisorFailure": "Unknown supervisor failure.",
+ "emptyOutput": "(empty)",
+ "circuitPausedError": "Automatically paused after {count} successful waiter exits within {window} seconds; repair Run {run_id} was queued.",
+ "lifetimeTimeoutPrefix": "Watch stopped after reaching its lifetime timeout.",
+ "lifetimeTimeoutBody": "Watch '{name}' reached its lifetime timeout after {seconds} second(s).",
+ "lifetimeExpiredWithActiveFollowUp": "Watch lifetime expired while follow-up Run {run_id} was still active; the Watch retired without starting another Run.",
+ "circuitRepairPrompt": "[Avibe Harness] Watch \"{name}\" was automatically paused because its waiter exited successfully {count} times within {window} seconds. This pattern can create duplicate Agent Runs when a persistent level is reported as a new event on every cycle.\n\nWatch ID: {id}\nSuccessful exit timestamps:\n{timestamps}\nLatest exit code: 0\nLatest stdout:\n{stdout}\nLatest stderr:\n{stderr}\n\nInspect the Watch with `vibe watch show {id}` and inspect the waiter implementation. Fix it so exit 0 means one new reportable event. While the condition is unchanged or not ready, return one of this Watch's allowed retry exit codes: {retry_codes}. For a completed cycle with nothing reportable, return 64 and print `avibe-watch: no-event` to stderr. A recurring waiter must keep a durable cursor, state transition, or domain cooldown so the same level is not emitted repeatedly.\n\nAfter an unambiguous, reversible fix, verify the waiter behavior, update the Watch if needed, and resume it with `vibe watch resume {id}`. If the correct fix is uncertain or cannot be verified safely, leave the Watch paused and report the blocker. Do not process the latest stdout as an ordinary event; it was retained as diagnostic evidence for this repair.",
"protocolErrors": {
"specTooLarge": "The watch worker specification is too large.",
"invalidEncoding": "The watch worker specification is not valid UTF-8.",
@@ -93,6 +99,7 @@
"failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",
"watchProcessingFailed": "[Avibe Harness] Watch \"{name}\" detected an event, but Agent processing failed.",
"watchFailureReportFailed": "[Avibe Harness] Watch \"{name}\" stopped because its waiter failed, but the Agent could not report that failure.",
+ "watchCircuitRepairFailed": "[Avibe Harness] Watch \"{name}\" remains paused because its circuit-repair Agent Run failed.",
"watchFollowUpFailed": "[Avibe Harness] Watch \"{name}\" follow-up Agent processing failed.",
"interrupted": "[Avibe Harness] Scheduled work \"{name}\" was interrupted ({reason}). Nothing is wrong with the definition itself.",
"commandLine": "Command: {command}",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 119abef25..5bd976cb5 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -35,6 +35,12 @@
"supervisorFailed": "Watch 监控进程失败:{detail}",
"supervisorExitedDuringStartup": "Watch 监控进程在启动期间退出。",
"unknownSupervisorFailure": "未知的监控进程错误。",
+ "emptyOutput": "(空)",
+ "circuitPausedError": "{window} 秒内 waiter 成功退出 {count} 次,Watch 已自动暂停,并已创建修复 Run {run_id}。",
+ "lifetimeTimeoutPrefix": "Watch 达到生命周期上限后已停止。",
+ "lifetimeTimeoutBody": "Watch「{name}」已达到 {seconds} 秒的生命周期上限。",
+ "lifetimeExpiredWithActiveFollowUp": "Watch 生命周期已到期,但后续 Run {run_id} 仍在执行;Watch 已停止,且没有再创建另一个 Run。",
+ "circuitRepairPrompt": "[Avibe Harness] Watch「{name}」已自动暂停:它的 waiter 在 {window} 秒内成功退出了 {count} 次。持续成立的条件如果每轮都被当作新事件,会批量制造重复 Agent Runs。\n\nWatch ID:{id}\n成功退出时间:\n{timestamps}\n最近退出码:0\n最近 stdout:\n{stdout}\n最近 stderr:\n{stderr}\n\n请先用 `vibe watch show {id}` 检查 Watch,再检查 waiter 的实现。修正后的契约应为:退出码 0 只表示一个新的、值得报告的事件;条件仍未变化或尚未就绪时,返回这个 Watch 已允许的重试退出码之一:{retry_codes}。一轮检查已经完成但没有值得报告的内容时,返回 64,并向 stderr 输出 `avibe-watch: no-event`。周期性 waiter 必须使用持久化游标、状态变化或业务冷却,避免反复报告同一个 level。\n\n只有在修复明确、可逆并且 waiter 行为已经验证后,才按需更新 Watch,并用 `vibe watch resume {id}` 恢复。如果无法安全确认修复,请保持暂停并报告阻碍。不要把最近 stdout 当作普通事件处理;它是为本次修复保留的诊断证据。",
"protocolErrors": {
"specTooLarge": "Watch 工作进程配置过大。",
"invalidEncoding": "Watch 工作进程配置不是有效的 UTF-8。",
@@ -93,6 +99,7 @@
"failed": "[Avibe Harness] 后台任务「{name}」执行失败。",
"watchProcessingFailed": "[Avibe Harness] Watch「{name}」已检测到事件,但 Agent 处理失败。",
"watchFailureReportFailed": "[Avibe Harness] Watch「{name}」因 waiter 失败而停止,但 Agent 未能报告该故障。",
+ "watchCircuitRepairFailed": "[Avibe Harness] Watch「{name}」的熔断修复 Agent Run 失败,Watch 将保持暂停。",
"watchFollowUpFailed": "[Avibe Harness] Watch「{name}」的后续 Agent 处理失败。",
"interrupted": "[Avibe Harness] 后台任务「{name}」被中断({reason}),任务本身没有问题。",
"commandLine": "命令:{command}",