Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(watch): report startup failures and gate retries

cyh2b1ccbf990b2
diff --git a/core/watches.py b/core/watches.py
index 820a199f3..687b7c116 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -17,6 +17,8 @@ from core.scheduled_tasks import TaskExecutionStore
logger = logging.getLogger(__name__)
+DEFAULT_RETRY_EXIT_CODE = 75
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -48,7 +50,7 @@ class ManagedWatch:
mode: str = "once"
timeout_seconds: float = 21600.0
lifetime_timeout_seconds: float = 0.0
- retry_exit_codes: list[int] = field(default_factory=lambda: [1])
+ retry_exit_codes: list[int] = field(default_factory=lambda: [DEFAULT_RETRY_EXIT_CODE])
retry_delay_seconds: float = 30.0
post_to: Optional[str] = None
deliver_key: Optional[str] = None
@@ -77,7 +79,7 @@ class ManagedWatch:
mode=str(payload.get("mode") or "once"),
timeout_seconds=_payload_float(payload, "timeout_seconds", 21600.0),
lifetime_timeout_seconds=_payload_float(payload, "lifetime_timeout_seconds", 0.0),
- retry_exit_codes=[int(code) for code in (payload.get("retry_exit_codes") or [1])],
+ retry_exit_codes=[int(code) for code in (payload.get("retry_exit_codes") or [DEFAULT_RETRY_EXIT_CODE])],
retry_delay_seconds=_payload_float(payload, "retry_delay_seconds", 30.0),
post_to=payload.get("post_to"),
deliver_key=payload.get("deliver_key"),
@@ -434,15 +436,13 @@ class ManagedWatchService:
continue
if result.timed_out or result.exit_code == 124:
- if watch.mode == "forever":
- self.store.mark_cycle_result(watch.id, exit_code=124, error=None, disable=False)
- continue
- self._enqueue_hook(
+ error_text = "timed out"
+ self._enqueue_failure_hook(
watch,
- prefix=watch.prefix,
- body=f"Watch timed out after {int(cycle_timeout)} second(s).",
+ exit_code=124,
+ error_text=f"Watch timed out after {int(cycle_timeout)} second(s).",
)
- self.store.mark_cycle_result(watch.id, exit_code=124, error="timed out", disable=True)
+ self.store.mark_cycle_result(watch.id, exit_code=124, error=error_text, disable=True)
return
error_text = _squash_error(result.stderr) or f"watch command exited with status {result.exit_code}"
@@ -451,6 +451,7 @@ class ManagedWatchService:
await asyncio.sleep(watch.retry_delay_seconds)
continue
+ self._enqueue_failure_hook(watch, exit_code=result.exit_code, error_text=error_text)
self.store.mark_cycle_result(watch.id, exit_code=result.exit_code, error=error_text, disable=True)
return
@@ -514,6 +515,22 @@ class ManagedWatchService:
prompt=final_prompt,
)
+ def _enqueue_failure_hook(self, watch: ManagedWatch, *, exit_code: int, error_text: str) -> None:
+ watch_label = watch.name or watch.id
+ if exit_code == 124:
+ body = (
+ f"Watch '{watch_label}' stopped because the waiter timed out.\n"
+ f"Check whether the timeout is too short or the waiter is blocked, then recreate the watch if monitoring should continue.\n"
+ f"Details: {error_text}"
+ )
+ else:
+ body = (
+ f"Watch '{watch_label}' stopped because the waiter exited with code {exit_code}.\n"
+ f"Review the error below, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.\n"
+ f"Error: {error_text}"
+ )
+ self._enqueue_hook(watch, prefix=watch.prefix, body=body)
+
def _build_prompt(prefix: Optional[str], body: Optional[str]) -> str:
parts = []
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index cba662a8f..fd03b1ad6 100644
--- a/skills/background-watch-hook/SKILL.md
+++ b/skills/background-watch-hook/SKILL.md
@@ -26,7 +26,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or
## Main Tools
- `vibe watch add`
- Main entrypoint. Starts a managed background watch and sends a follow-up hook after the waiter succeeds or times out.
+ Main entrypoint. Starts a managed background watch and sends a follow-up hook after the waiter succeeds or reaches a terminal failure.
- `vibe watch list`, `vibe watch show`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`
Use these to inspect and manage the watch after creation.
- `scripts/wait_pr.py`
@@ -56,7 +56,7 @@ Default behavior:
- returns immediately
- keeps the waiter managed by Vibe Remote
- lets the agent inspect or stop the watch later
-- sends a follow-up after the waiter succeeds or times out
+- sends a follow-up after the waiter succeeds or reaches a terminal failure
Use `--forever` when the same waiter should re-arm after each detected event instead of exiting after one follow-up.
@@ -146,6 +146,7 @@ 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
- `--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.
@@ -161,6 +162,7 @@ This skill ships bundled GitHub waiters:
Use bundled waiters as examples or as ready-to-run building blocks. The main skill is still `vibe watch`; the waiter is only the thing that blocks until the condition is met.
When running a bundled script through `uv`, prefer `uv run --no-project ...` so the script does not accidentally attach itself to an unrelated parent project.
+Bundled GitHub waiters use exit code `75` for retryable startup errors such as temporary network failures or GitHub `408/429/5xx` responses.
## GitHub Example Waiter
diff --git a/skills/background-watch-hook/scripts/_github_wait_common.py b/skills/background-watch-hook/scripts/_github_wait_common.py
index 10242e8c3..59b81cadd 100644
--- a/skills/background-watch-hook/scripts/_github_wait_common.py
+++ b/skills/background-watch-hook/scripts/_github_wait_common.py
@@ -8,10 +8,15 @@ import math
import os
import shutil
import subprocess
+import urllib.error
import urllib.request
from typing import Any
+RETRY_EXIT_CODE = 75
+RETRYABLE_HTTP_STATUS_CODES = {408, 429, 500, 502, 503, 504}
+
+
def get_token() -> str | None:
for env_name in ("GITHUB_TOKEN", "GH_TOKEN"):
value = os.environ.get(env_name)
@@ -56,6 +61,14 @@ def github_get(url: str, token: str | None) -> Any:
return json.loads(response.read().decode("utf-8"))
+def is_retryable_http_error(err: urllib.error.HTTPError) -> bool:
+ try:
+ code = int(err.code)
+ except Exception:
+ return False
+ return code in RETRYABLE_HTTP_STATUS_CODES
+
+
def get_authenticated_login(token: str | None) -> str | None:
if not token:
return None
diff --git a/skills/background-watch-hook/scripts/wait_issue.py b/skills/background-watch-hook/scripts/wait_issue.py
index 3e43cbf21..98b623b31 100644
--- a/skills/background-watch-hook/scripts/wait_issue.py
+++ b/skills/background-watch-hook/scripts/wait_issue.py
@@ -20,9 +20,11 @@ from _github_wait_common import ( # noqa: E402
filter_new,
get_authenticated_login,
get_token,
+ is_retryable_http_error,
list_paginated_with_count,
max_id,
min_interval_for_unauthenticated,
+ RETRY_EXIT_CODE,
requests_per_poll,
squash,
)
@@ -247,7 +249,10 @@ def main() -> int:
)
except urllib.error.HTTPError as err:
print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)
- return 1
+ return RETRY_EXIT_CODE if is_retryable_http_error(err) else 1
+ except urllib.error.URLError as err:
+ print(f"GitHub network error: {err.reason}", file=sys.stderr)
+ return RETRY_EXIT_CODE
except Exception as err: # noqa: BLE001
print(f"Failed to fetch initial issue state: {err}", file=sys.stderr)
return 1
diff --git a/skills/background-watch-hook/scripts/wait_pr.py b/skills/background-watch-hook/scripts/wait_pr.py
index f75e2dc83..eb02185f2 100755
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@ -21,10 +21,12 @@ from _github_wait_common import ( # noqa: E402
get_authenticated_login,
get_token,
github_get,
+ is_retryable_http_error,
list_paginated,
list_paginated_with_count,
max_id,
min_interval_for_unauthenticated,
+ RETRY_EXIT_CODE,
requests_per_poll,
squash,
)
@@ -400,7 +402,10 @@ def main() -> int:
)
except urllib.error.HTTPError as err:
print(f"GitHub API error: {err.code} {err.reason}", file=sys.stderr)
- return 1
+ return RETRY_EXIT_CODE if is_retryable_http_error(err) else 1
+ except urllib.error.URLError as err:
+ print(f"GitHub network error: {err.reason}", file=sys.stderr)
+ return RETRY_EXIT_CODE
except Exception as err: # noqa: BLE001
print(f"Failed to fetch initial PR state: {err}", file=sys.stderr)
return 1
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 3042589dc..2e0477850 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -330,7 +330,7 @@ Delivery controls:
- do not combine `--post-to` and `--deliver-key` in the same command
- `vibe task add` stores the text from `--prompt` or `--prompt-file` and injects it each time the task runs
- `vibe hook send` queues the text from `--prompt` or `--prompt-file` once without storing a task
-- `vibe watch add` uses `--prefix` as follow-up instruction text; on a successful cycle Vibe Remote prepends it before waiter stdout, joined with a blank line when both exist
+- `vibe watch add` uses `--prefix` as follow-up instruction text; on a successful cycle Vibe Remote prepends it before waiter stdout, joined with a blank line when both exist, and terminal failures also send a follow-up before disabling the watch
Session key format:
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index bd3cd61da..ca3e82fc8 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -44,6 +44,10 @@ def _capture_stderr_json(func, *args):
return result, json.loads(stderr.getvalue())
+def _startup_ok(store: ManagedWatchStore, runtime_store: WatchRuntimeStateStore, watch_id: str):
+ return store.get_watch(watch_id), runtime_store.load().get("watches", {}).get(watch_id)
+
+
def test_watch_help_describes_session_key_guidance(capsys) -> None:
parser = cli.build_parser()
@@ -69,6 +73,7 @@ def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:
assert "--lifetime-timeout" in captured.out
assert "vibe watch add --session-key 'slack::channel::C123'" in captured.out
assert "`--prefix` becomes the instruction text of the follow-up hook." in captured.out
+ assert "Terminal failures also send a follow-up and disable the watch." 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
@@ -157,6 +162,7 @@ def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
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 *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
):
result = cli.cmd_watch_add(args)
@@ -167,6 +173,7 @@ def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
assert payload["watch"]["shell_command"] == "python3 scripts/wait.py"
assert payload["watch"]["command"] == []
assert payload["watch"]["mode"] == "once"
+ assert payload["watch"]["retry_exit_codes"] == [75]
def test_watch_add_creates_exec_watch_with_retry_codes(tmp_path: Path, capsys) -> None:
@@ -197,6 +204,7 @@ def test_watch_add_creates_exec_watch_with_retry_codes(tmp_path: Path, capsys) -
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 *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
):
result = cli.cmd_watch_add(args)
@@ -229,6 +237,7 @@ def test_watch_add_persists_absolute_cwd(tmp_path: Path, capsys, monkeypatch: py
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 *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
):
result = cli.cmd_watch_add(args)
@@ -237,6 +246,42 @@ def test_watch_add_persists_absolute_cwd(tmp_path: Path, capsys, monkeypatch: py
assert payload["watch"]["cwd"] == str(workdir.resolve())
+def test_watch_add_returns_structured_error_when_startup_fails(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--shell",
+ "python3 scripts/wait.py",
+ ]
+ )
+
+ 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=cli.TaskCliError(
+ "watch failed during startup and has already been disabled",
+ code="watch_startup_failed",
+ hint="Inspect the stored watch error, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.",
+ example="vibe watch show abc",
+ help_command="vibe watch show abc",
+ ),
+ ),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+
+ assert result == 1
+ assert payload["code"] == "watch_startup_failed"
+ assert payload["hint"].startswith("Inspect the stored watch error")
+ assert payload["example"] == "vibe watch show abc"
+ assert payload["help_command"] == "vibe watch show abc"
+
+
def test_watch_list_brief_includes_runtime_state(tmp_path: Path, capsys) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -250,7 +295,7 @@ def test_watch_list_brief_includes_runtime_state(tmp_path: Path, capsys) -> None
mode="forever",
timeout_seconds=600,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=30,
post_to=None,
deliver_key=None,
@@ -300,7 +345,7 @@ def test_watch_pause_resume_and_remove_update_store(tmp_path: Path, capsys) -> N
mode="once",
timeout_seconds=600,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=30,
post_to=None,
deliver_key=None,
diff --git a/tests/test_wait_for_github_issue_activity.py b/tests/test_wait_for_github_issue_activity.py
index d9ef4c7a2..283ce1449 100644
--- a/tests/test_wait_for_github_issue_activity.py
+++ b/tests/test_wait_for_github_issue_activity.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import importlib.util
+import urllib.error
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
@@ -475,3 +476,57 @@ def test_main_reduces_unauthenticated_new_issue_interval_after_bootstrap() -> No
assert sleep_calls == [3600.0, 60.0]
assert fetch_calls == [(None, 1), (None, None), (None, None)]
assert "issue #41" in stdout.getvalue()
+
+
+def test_main_returns_retry_exit_code_for_retryable_initial_issue_http_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.HTTPError("https://api.github.com/example", 503, "Service Unavailable", hdrs=None, fp=None)
+
+ with (
+ patch.object(module, "_fetch_issue_comment_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_issue.py", "--repo", "cyhhao/vibe-remote", "--issue", "24"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 75
+ assert "GitHub API error: 503 Service Unavailable" in stderr.getvalue()
+
+
+def test_main_returns_terminal_exit_code_for_non_retryable_initial_issue_http_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.HTTPError("https://api.github.com/example", 404, "Not Found", hdrs=None, fp=None)
+
+ with (
+ patch.object(module, "_fetch_issue_comment_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_issue.py", "--repo", "cyhhao/vibe-remote", "--issue", "24"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 1
+ assert "GitHub API error: 404 Not Found" in stderr.getvalue()
+
+
+def test_main_returns_retry_exit_code_for_initial_issue_network_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.URLError("temporary network failure")
+
+ with (
+ patch.object(module, "_fetch_issue_comment_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_issue.py", "--repo", "cyhhao/vibe-remote", "--issue", "24"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 75
+ assert "GitHub network error: temporary network failure" in stderr.getvalue()
diff --git a/tests/test_wait_for_github_pr_activity.py b/tests/test_wait_for_github_pr_activity.py
index 816e3799c..7e6c0c23a 100644
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import io
import importlib.util
+import urllib.error
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
@@ -707,3 +708,57 @@ def test_main_reduces_unauthenticated_new_pr_interval_after_bootstrap() -> None:
assert sleep_calls == [3600.0, 60.0]
assert fetch_calls == [(None, 1), (None, None), (None, None)]
assert "pull_request #158" in stdout.getvalue()
+
+
+def test_main_returns_retry_exit_code_for_retryable_initial_pr_http_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.HTTPError("https://api.github.com/example", 503, "Service Unavailable", hdrs=None, fp=None)
+
+ with (
+ patch.object(module, "_fetch_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_pr.py", "--repo", "cyhhao/vibe-remote", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 75
+ assert "GitHub API error: 503 Service Unavailable" in stderr.getvalue()
+
+
+def test_main_returns_terminal_exit_code_for_non_retryable_initial_pr_http_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.HTTPError("https://api.github.com/example", 404, "Not Found", hdrs=None, fp=None)
+
+ with (
+ patch.object(module, "_fetch_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_pr.py", "--repo", "cyhhao/vibe-remote", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 1
+ assert "GitHub API error: 404 Not Found" in stderr.getvalue()
+
+
+def test_main_returns_retry_exit_code_for_initial_pr_network_error() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+ err = urllib.error.URLError("temporary network failure")
+
+ with (
+ patch.object(module, "_fetch_state", side_effect=err),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value=None),
+ patch("sys.argv", ["wait_pr.py", "--repo", "cyhhao/vibe-remote", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 75
+ assert "GitHub network error: temporary network failure" in stderr.getvalue()
diff --git a/tests/test_watches.py b/tests/test_watches.py
index f81f4c4d7..8eed1b5f4 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -28,7 +28,7 @@ def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
mode="forever",
timeout_seconds=600,
lifetime_timeout_seconds=3600,
- retry_exit_codes=[1, 75],
+ retry_exit_codes=[75],
retry_delay_seconds=45,
post_to="channel",
deliver_key=None,
@@ -42,7 +42,7 @@ def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
assert saved is not None
assert saved.name == "Watch CI"
assert saved.mode == "forever"
- assert saved.retry_exit_codes == [1, 75]
+ assert saved.retry_exit_codes == [75]
assert saved.post_to == "channel"
@@ -58,7 +58,7 @@ def test_managed_watch_store_preserves_zero_values_on_reload(tmp_path: Path) ->
mode="forever",
timeout_seconds=0,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=0,
post_to=None,
deliver_key=None,
@@ -87,7 +87,7 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
mode="once",
timeout_seconds=5,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=30,
post_to=None,
deliver_key=None,
@@ -121,7 +121,7 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
assert saved.last_event_at is not None
-def test_managed_watch_service_forever_timeout_is_silent_per_cycle(tmp_path: Path) -> None:
+def test_managed_watch_service_forever_timeout_disables_and_enqueues_failure(tmp_path: Path) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
request_store = TaskExecutionStore(tmp_path / "task_requests")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
@@ -135,7 +135,7 @@ def test_managed_watch_service_forever_timeout_is_silent_per_cycle(tmp_path: Pat
mode="forever",
timeout_seconds=0.05,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=0.01,
post_to=None,
deliver_key=None,
@@ -156,9 +156,12 @@ def test_managed_watch_service_forever_timeout_is_silent_per_cycle(tmp_path: Pat
saved = store.get_watch(watch.id)
- assert request_store.list_pending() == []
+ pending = request_store.list_pending()
assert saved is not None
- assert saved.enabled is True
+ assert len(pending) == 1
+ assert "stopped because the waiter timed out" in pending[0].prompt
+ assert "Check whether the timeout is too short or the waiter is blocked" in pending[0].prompt
+ assert saved.enabled is False
assert saved.last_exit_code == 124
@@ -176,7 +179,7 @@ def test_managed_watch_service_stop_terminates_running_waiter(tmp_path: Path) ->
mode="forever",
timeout_seconds=0,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=0.01,
post_to=None,
deliver_key=None,
@@ -220,7 +223,7 @@ def test_managed_watch_service_records_wall_clock_started_at(tmp_path: Path) ->
mode="forever",
timeout_seconds=0,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=0.01,
post_to=None,
deliver_key=None,
@@ -261,7 +264,7 @@ def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Pat
mode="once",
timeout_seconds=5,
lifetime_timeout_seconds=0,
- retry_exit_codes=[1],
+ retry_exit_codes=[75],
retry_delay_seconds=0.01,
post_to=None,
deliver_key=None,
@@ -284,8 +287,97 @@ def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Pat
asyncio.run(_run())
saved = store.get_watch(watch.id)
+ pending = request_store.list_pending()
assert saved is not None
assert saved.enabled is False
assert saved.last_exit_code == 1
assert saved.last_error
+ assert len(pending) == 1
+ assert "stopped because the waiter exited with code 1" in pending[0].prompt
+ assert "fix the waiter or its dependencies" in pending[0].prompt
+
+
+def test_managed_watch_service_forever_retries_only_allowed_exit_code(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Retry waiter",
+ session_key="slack::channel::C123",
+ command=["/bin/sh", "-lc", "exit 75"],
+ shell_command=None,
+ prefix="Retry only.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0.01,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+
+ async def _run() -> None:
+ service.start()
+ await asyncio.sleep(0.08)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ saved = store.get_watch(watch.id)
+ assert saved is not None
+ assert saved.enabled is True
+ assert saved.last_exit_code == 75
assert request_store.list_pending() == []
+
+
+def test_managed_watch_service_forever_non_retry_error_disables_and_enqueues_failure(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Broken forever waiter",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "import sys; sys.exit(1)"],
+ shell_command=None,
+ prefix="Investigate the failure.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0.01,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+
+ async def _run() -> None:
+ service.start()
+ for _ in range(100):
+ if watch.id not in service._active_tasks:
+ break
+ await asyncio.sleep(0.02)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ saved = store.get_watch(watch.id)
+ pending = request_store.list_pending()
+ assert saved is not None
+ assert saved.enabled is False
+ assert saved.last_exit_code == 1
+ assert saved.last_error
+ assert len(pending) == 1
+ assert pending[0].prompt.startswith("Investigate the failure.\n\nWatch 'Broken forever waiter' stopped because the waiter exited with code 1.")
diff --git a/vibe/cli.py b/vibe/cli.py
index 1d3141b14..b15ddda52 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -29,7 +29,7 @@ from config.v2_config import (
V2Config,
)
from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key
-from core.watches import ManagedWatchStore, WatchRuntimeStateStore
+from core.watches import DEFAULT_RETRY_EXIT_CODE, ManagedWatchStore, WatchRuntimeStateStore
from vibe import __version__, api, runtime
from vibe.upgrade import build_upgrade_plan, cache_running_vibe_path, get_latest_version_info, get_safe_cwd
@@ -206,7 +206,7 @@ def _watch_examples_text() -> str:
Examples:
vibe watch add --session-key 'slack::channel::C123' --name 'Wait for export' --shell 'python3 scripts/wait_for_export.py'
vibe watch add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prefix 'The CI job finished.' -- python3 scripts/wait_for_ci.py --build 42
- vibe watch add --session-key 'slack::channel::C123' --forever --retry-exit-code 1 --retry-delay 60 --shell 'bash scripts/wait_for_log_pattern.sh'
+ vibe watch add --session-key 'slack::channel::C123' --forever --retry-exit-code 75 --retry-delay 60 --shell 'bash scripts/wait_for_log_pattern.sh'
vibe watch list --brief
vibe watch show 12ab34cd56ef
vibe watch pause 12ab34cd56ef
@@ -225,7 +225,7 @@ def _watch_add_examples_text() -> str:
Guidance:
If this is your first time using this command, read this whole help entry before creating a watch.
- Use a watch when a script should wait in the background and send one hook only after a condition is met.
+ Use a watch when a script should wait in the background and send a follow-up when it detects an event or reaches a terminal failure.
`--session-key` chooses which session Vibe Remote will continue using for follow-up messages from the watch.
Keep the current session key when follow-up should continue in the same session.
When you want to leave the current thread session and start or reuse the higher-level session instead, use the higher-level key. Example:
@@ -234,13 +234,15 @@ def _watch_add_examples_text() -> str:
`--post-to channel` changes where the follow-up is posted, not which session is continued.
Use --deliver-key only when delivery must go to a different explicit target.
`--prefix` becomes the instruction text of the follow-up hook. On a successful cycle, Vibe Remote prepends `--prefix` before waiter stdout and joins them with a blank line when both exist.
+ 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`.
Pass either --shell '<command>' or a command after '--'.
--timeout applies to each cycle. --lifetime-timeout applies only to the whole forever watch lifetime.
Examples:
vibe watch add --session-key 'slack::channel::C123' --shell 'python3 scripts/wait_for_export.py'
vibe watch add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prefix 'The export finished.' -- bash -lc 'sleep 120; echo done'
- vibe watch add --session-key 'slack::channel::C123' --forever --timeout 600 --lifetime-timeout 86400 --retry-exit-code 1 --retry-delay 30 -- uv run --no-project scripts/wait_pr.py --repo cyhhao/vibe-remote --pr 153
+ vibe watch add --session-key 'slack::channel::C123' --forever --timeout 600 --lifetime-timeout 86400 --retry-exit-code 75 --retry-delay 30 -- uv run --no-project scripts/wait_pr.py --repo cyhhao/vibe-remote --pr 153
"""
)
@@ -812,6 +814,68 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
return payload
+def _wait_for_watch_startup(
+ store: ManagedWatchStore,
+ runtime_store: WatchRuntimeStateStore,
+ watch_id: str,
+ *,
+ timeout_seconds: float = 4.0,
+ poll_interval_seconds: float = 0.1,
+):
+ inspect_command = f"vibe watch show {watch_id}"
+ deadline = time.monotonic() + timeout_seconds
+ while time.monotonic() < deadline:
+ store.maybe_reload()
+ watch = store.get_watch(watch_id)
+ if watch is None:
+ raise TaskCliError(
+ f"watch '{watch_id}' could not be verified because it disappeared during startup",
+ code="watch_startup_failed",
+ hint="Recreate the watch, then inspect its first-cycle state before reporting that monitoring is active.",
+ example=inspect_command,
+ help_command=inspect_command,
+ details={"watch_id": watch_id},
+ )
+ runtime_entry = runtime_store.load().get("watches", {}).get(watch_id)
+ if watch.last_error and not watch.enabled:
+ raise TaskCliError(
+ f"watch '{watch.name or watch.id}' failed during startup and has already been disabled",
+ code="watch_startup_failed",
+ hint="Inspect the stored watch error, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.",
+ example=inspect_command,
+ help_command=inspect_command,
+ details={"watch": _watch_payload(watch, runtime_entry)},
+ )
+ if runtime_entry and runtime_entry.get("running"):
+ return watch, runtime_entry
+ if watch.last_started_at:
+ return watch, runtime_entry
+ if watch.mode == "once" and watch.last_finished_at:
+ return watch, runtime_entry
+ time.sleep(poll_interval_seconds)
+
+ store.maybe_reload()
+ watch = store.get_watch(watch_id)
+ runtime_entry = runtime_store.load().get("watches", {}).get(watch_id)
+ if watch is not None and watch.last_error and not watch.enabled:
+ raise TaskCliError(
+ f"watch '{watch.name or watch.id}' failed during startup and has already been disabled",
+ code="watch_startup_failed",
+ hint="Inspect the stored watch error, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.",
+ example=inspect_command,
+ help_command=inspect_command,
+ details={"watch": _watch_payload(watch, runtime_entry)},
+ )
+ raise TaskCliError(
+ f"watch '{watch_id}' was created but startup was not confirmed within {timeout_seconds:.0f} second(s)",
+ code="watch_startup_unconfirmed",
+ hint="Confirm that the Vibe Remote service is running, then inspect the watch state before reporting that monitoring is active.",
+ example=inspect_command,
+ help_command=inspect_command,
+ details={"watch": _watch_payload(watch, runtime_entry) if watch is not None else {"id": watch_id}},
+ )
+
+
def cmd_task_add(args):
try:
session_target, delivery_target = _validate_delivery_args(
@@ -1259,7 +1323,7 @@ def cmd_watch_add(args):
)
cwd = str(resolved)
- retry_exit_codes = sorted(set(args.retry_exit_code or [1]))
+ retry_exit_codes = sorted(set(args.retry_exit_code or [DEFAULT_RETRY_EXIT_CODE]))
store = _watch_store()
watch = store.add_watch(
name=_normalize_watch_name(getattr(args, "name", None)),
@@ -1276,8 +1340,9 @@ def cmd_watch_add(args):
post_to=args.post_to,
deliver_key=args.deliver_key,
)
+ runtime_store = _watch_runtime_store()
+ watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
warnings = _collect_target_warnings(session_target, delivery_target)
- runtime_entry = _watch_runtime_store().load().get("watches", {}).get(watch.id)
print(json.dumps({"ok": True, "watch": _watch_payload(watch, runtime_entry), "warnings": warnings}, indent=2))
return 0
except Exception as exc:
@@ -2101,11 +2166,11 @@ def build_parser():
watch_add_parser = watch_subparsers.add_parser(
"add",
help="Create a managed background watch",
- description="Create a managed background watch that runs a waiter command and sends a hook when it succeeds.",
+ description="Create a managed background watch that runs a waiter command and sends a follow-up on success or terminal failure.",
epilog=_watch_add_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe watch add --help",
- error_hint="Use --session-key and either --shell or a command after '--'. Add --forever only when the waiter should re-arm after each successful cycle.",
+ error_hint="Use --session-key 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.",
)
watch_add_parser.add_argument("--name", help="Optional human-friendly watch name")
watch_add_parser.add_argument(
@@ -2137,7 +2202,7 @@ 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.",
+ 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.",
)
watch_add_parser.add_argument(
"--lifetime-timeout",
@@ -2151,13 +2216,13 @@ def build_parser():
action="append",
type=int,
default=None,
- help="Cycle exit code that should be retried in forever mode. Repeat to add more. Default: 1",
+ help=f"Cycle exit code that should be retried in forever mode. 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 a retryable forever cycle failure. Default: 30",
+ help="Delay in seconds before retrying an allowed forever cycle failure. Default: 30",
)
watch_add_parser.add_argument(
"--shell",