Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(tasks): harden background task management
cyh64ba9bffbc42
diff --git a/core/watches.py b/core/watches.pyindex 323b4222e..1e6042561 100644--- a/core/watches.py+++ b/core/watches.py@@ -237,6 +237,47 @@ class ManagedWatchStore:self._save()return watch+ def update_watch(+ self,+ watch_id: str,+ *,+ name: Optional[str],+ session_key: str,+ session_id: Optional[str],+ command: list[str],+ shell_command: Optional[str],+ prefix: Optional[str],+ cwd: Optional[str],+ mode: str,+ timeout_seconds: float,+ lifetime_timeout_seconds: float,+ retry_exit_codes: list[int],+ retry_delay_seconds: float,+ post_to: Optional[str],+ deliver_key: Optional[str],+ ) -> ManagedWatch:+ watch = self._watches[watch_id]+ watch.name = name+ watch.session_key = session_key+ watch.session_id = session_id+ watch.command = command+ watch.shell_command = shell_command+ watch.prefix = prefix+ watch.cwd = cwd+ watch.mode = mode+ watch.timeout_seconds = timeout_seconds+ watch.lifetime_timeout_seconds = lifetime_timeout_seconds+ watch.retry_exit_codes = retry_exit_codes+ watch.retry_delay_seconds = retry_delay_seconds+ watch.post_to = post_to+ watch.deliver_key = deliver_key+ watch.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_watch(watch.to_dict())+ return watch+ self._save()+ return watch+def mark_cycle_start(self, watch_id: str) -> bool:self.maybe_reload()watch = self._watches.get(watch_id)diff --git a/docs/CLI.md b/docs/CLI.mdindex 8b9fa69d4..4e45a90b8 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -192,7 +192,7 @@ Use this when you want one delayed or background follow-up without persisting a### `vibe watch`-Create, inspect, pause, resume, or remove a managed background watch. A watch+Create, update, inspect, pause, resume, or remove a managed background watch. A watchruns a long-lived waiter command (for example a build or a status poll) and,when the command finishes successfully, prepends `--prefix` to the capturedstdout and delivers it through the chosen session as a follow-up message.@@ -211,6 +211,7 @@ vibe watch add \vibe watch list --briefvibe watch show <watch-id>+vibe watch update <watch-id> --name 'Watch deployment' --timeout 1200vibe watch pause <watch-id>vibe watch resume <watch-id>vibe watch remove <watch-id>@@ -222,7 +223,9 @@ including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`(total wall-clock limit), `--forever`, `--retry-exit-code`, `--retry-delay`,`--post-to channel`, `--deliver-key`, and `--name`. Watches share`--session-id`, `--post-to`, and `--deliver-key` semantics with `vibe task`-and `vibe hook send`. Prefer `vibe watch` over ad-hoc `nohup` jobs when the+and `vibe hook send`. `vibe watch remove` hides the watch from management+views while preserving existing run history in SQLite. Prefer `vibe watch`+over ad-hoc `nohup` jobs when theuser wants a managed background task with a guaranteed follow-up message.### `vibe version`diff --git a/docs/plans/background-session-id-tasks.md b/docs/plans/background-session-id-tasks.mdindex 3fe7da9ee..81878fdf6 100644--- a/docs/plans/background-session-id-tasks.md+++ b/docs/plans/background-session-id-tasks.md@@ -152,6 +152,7 @@ runtime snapshots, and execution history.| `legacy_session_key` | TEXT | compatibility target for old tasks and old CLI || `name` | TEXT | user-visible name || `enabled` | INTEGER | enabled flag |+| `deleted_at` | TEXT | soft-delete timestamp; hidden from active task/watch lists || `post_to` | TEXT | delivery shortcut || `deliver_key` | TEXT | explicit delivery override || `prompt` | TEXT | scheduled task prompt |diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdindex 9f3b57d8c..491aed01e 100644--- a/skills/background-watch-hook/SKILL.md+++ b/skills/background-watch-hook/SKILL.md@@ -27,7 +27,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or- `vibe watch add`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`+- `vibe watch list`, `vibe watch show`, `vibe watch update`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`Use these to inspect and manage the watch after creation.- `scripts/wait_pr.py`Bundled waiter example for one common case: GitHub PR review activity.@@ -73,9 +73,10 @@ Management commands:- `vibe watch list`- `vibe watch show <watch-id>`+- `vibe watch update <watch-id> --name '...'`- `vibe watch pause <watch-id>`- `vibe watch resume <watch-id>`-- `vibe watch remove <watch-id>`+- `vibe watch remove <watch-id>` hides the watch while keeping prior run history## Waiter Contractdiff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.mdindex 0d690f6de..6ec9151e9 100644--- a/skills/use-vibe-remote/SKILL.md+++ b/skills/use-vibe-remote/SKILL.md@@ -18,7 +18,7 @@ Typical requests include:- show or hide intermediate message types- configure an outbound proxy (`proxy_url`) for an IM platform that cannot reach its API directly- pair, start, stop, or inspect Vibe Cloud remote Web UI access-- create, inspect, pause, resume, or remove a managed background watch with `vibe watch`+- create, update, inspect, pause, resume, or remove a managed background watch with `vibe watch`- create, inspect, run, pause, resume, or remove a scheduled task with `vibe task`- queue a one-shot asynchronous hook with `vibe hook send`- check or apply Vibe Remote updates (`vibe check-update`, `vibe upgrade`)@@ -758,6 +758,7 @@ Preferred CLI shape:- immediate rerun: `vibe task run <id>`- one-shot async hook: `vibe hook send --session-id '<session-id>' --prompt '...'`- managed background watch: `vibe watch add --session-id '<session-id>' --prefix '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)+- update a watch: `vibe watch update <id> --name '...' --timeout 1200`Delivery controls (apply to `vibe task add`, `vibe hook send`, and `vibe watch add`):@@ -780,7 +781,7 @@ 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 hook send`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`- use `vibe task update <id>` to keep the same task ID while changing name, schedule, prompt, or target-- watches do not have an `update` subcommand; remove and re-add when you must change the waiter+- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options- use `vibe task list --brief` and `vibe watch list --brief` for scheduling-focused summaries- `vibe task list` hides completed one-shot tasks by default; use `vibe task list --all` when you need full history- use `vibe task show <id>` or `vibe watch show <id>` to inspect stored fields and derived runtime state (such as `next_run_at` or `pid`)@@ -938,7 +939,7 @@ Async hooks:Watches:-- `vibe watch add`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`+- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`For any subcommand, prefer `<command> --help` before composing a new invocation. The delivery flags shared by all three commands are `--session-id`, `--post-to`, and `--deliver-key`. The remaining surface differs: `vibe task add` and `vibe hook send` take `--prompt` / `--prompt-file`; `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; and `vibe watch add` takes its own set (`--prefix`, `--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy task or hook flags into a watch invocation, and do not pass `--name` to `vibe hook send`.diff --git a/storage/alembic/versions/20260515_0002_background_tasks.py b/storage/alembic/versions/20260515_0002_background_tasks.pyindex d21823149..5c6ac59a7 100644--- a/storage/alembic/versions/20260515_0002_background_tasks.py+++ b/storage/alembic/versions/20260515_0002_background_tasks.py@@ -41,6 +41,7 @@ def upgrade() -> None:sa.Column("post_to", sa.String(), nullable=True),sa.Column("deliver_key", sa.Text(), nullable=True),sa.Column("enabled", sa.Integer(), nullable=False),+ sa.Column("deleted_at", sa.String(), nullable=True),sa.Column("created_at", sa.String(), nullable=False),sa.Column("updated_at", sa.String(), nullable=False),sa.Column("last_started_at", sa.String(), nullable=True),diff --git a/storage/background.py b/storage/background.pyindex 653e6f862..b307e45b5 100644--- a/storage/background.py+++ b/storage/background.py@@ -2,10 +2,11 @@ from __future__ import annotationsimport jsonimport logging+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Optional-from sqlalchemy import delete, insert, select, update+from sqlalchemy import insert, select, updatefrom config import pathsfrom storage.db import SqliteInvalidationProbe, create_sqlite_engine@@ -28,16 +29,20 @@ def _json_loads(value: Optional[str], default: Any) -> Any:return default+def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()++class SQLiteBackgroundTaskStore:def __init__(self, db_path: Optional[Path] = None):self.db_path = db_path or paths.get_sqlite_state_path()self.db_path.parent.mkdir(parents=True, exist_ok=True)- if not background_tables_ready(self.db_path):- initialize_background_tables(self.db_path)if db_path is None:from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_configensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))+ if not background_tables_ready(self.db_path):+ initialize_background_tables(self.db_path)self.engine = create_sqlite_engine(self.db_path)self._probe = SqliteInvalidationProbe(self.engine)@@ -53,6 +58,7 @@ class SQLiteBackgroundTaskStore:rows = conn.execute(select(background_tasks).where(background_tasks.c.task_type == "scheduled")+ .where(background_tasks.c.deleted_at.is_(None)).order_by(background_tasks.c.created_at, background_tasks.c.id)).mappings()return [self._scheduled_task_from_row(row) for row in rows]@@ -63,6 +69,7 @@ class SQLiteBackgroundTaskStore:select(background_tasks).where(background_tasks.c.task_type == "scheduled").where(background_tasks.c.id == task_id)+ .where(background_tasks.c.deleted_at.is_(None)).limit(1)).mappings().first()return self._scheduled_task_from_row(row) if row else None@@ -78,9 +85,14 @@ class SQLiteBackgroundTaskStore:else:conn.execute(insert(background_tasks).values(**values))- def remove_task(self, task_id: str) -> bool:+ def remove_task(self, task_id: str, *, deleted_at: Optional[str] = None) -> bool:with self.engine.begin() as conn:- result = conn.execute(delete(background_tasks).where(background_tasks.c.id == task_id))+ result = conn.execute(+ update(background_tasks)+ .where(background_tasks.c.id == task_id)+ .where(background_tasks.c.deleted_at.is_(None))+ .values(deleted_at=deleted_at or _utc_now_iso())+ )return bool(result.rowcount)def list_watches(self) -> list[dict[str, Any]]:@@ -88,6 +100,7 @@ class SQLiteBackgroundTaskStore:rows = conn.execute(select(background_tasks).where(background_tasks.c.task_type == "watch")+ .where(background_tasks.c.deleted_at.is_(None)).order_by(background_tasks.c.created_at, background_tasks.c.id)).mappings()return [self._watch_from_row(row) for row in rows]@@ -98,6 +111,7 @@ class SQLiteBackgroundTaskStore:select(background_tasks).where(background_tasks.c.task_type == "watch").where(background_tasks.c.id == watch_id)+ .where(background_tasks.c.deleted_at.is_(None)).limit(1)).mappings().first()return self._watch_from_row(row) if row else None@@ -261,6 +275,7 @@ class SQLiteBackgroundTaskStore:"post_to": payload.get("post_to"),"deliver_key": payload.get("deliver_key"),"enabled": 1 if payload.get("enabled", True) else 0,+ "deleted_at": payload.get("deleted_at"),"created_at": payload.get("created_at") or payload.get("updated_at"),"updated_at": payload.get("updated_at") or payload.get("created_at"),"last_started_at": None,@@ -296,6 +311,7 @@ class SQLiteBackgroundTaskStore:"post_to": payload.get("post_to"),"deliver_key": payload.get("deliver_key"),"enabled": 1 if payload.get("enabled", True) else 0,+ "deleted_at": payload.get("deleted_at"),"created_at": payload.get("created_at") or payload.get("updated_at"),"updated_at": payload.get("updated_at") or payload.get("created_at"),"last_started_at": payload.get("last_started_at"),diff --git a/storage/importer.py b/storage/importer.pyindex 225e5e747..3caa4f5e0 100644--- a/storage/importer.py+++ b/storage/importer.py@@ -451,6 +451,7 @@ def _import_scheduled_tasks(conn: Connection, source: Path) -> int:post_to=item.get("post_to"),deliver_key=item.get("deliver_key"),enabled=1 if item.get("enabled", True) else 0,+ deleted_at=None,created_at=item.get("created_at") or _utc_now_iso(),updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),last_started_at=None,@@ -496,6 +497,7 @@ def _import_watches(conn: Connection, source: Path) -> int:post_to=item.get("post_to"),deliver_key=item.get("deliver_key"),enabled=1 if item.get("enabled", True) else 0,+ deleted_at=None,created_at=item.get("created_at") or _utc_now_iso(),updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),last_started_at=item.get("last_started_at"),diff --git a/storage/migrations.py b/storage/migrations.pyindex 1004e268d..71d38955a 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -19,6 +19,9 @@ INITIAL_TABLES = {"runtime_records",}HEAD_TABLES = INITIAL_TABLES | {"background_tasks", "background_runs"}+HEAD_REQUIRED_COLUMNS = {+ "background_tasks": {"deleted_at"},+}UNRELEASED_OLD_INITIAL_TABLES = ["session_messages","chat_sessions",@@ -53,6 +56,7 @@ def run_migrations(db_path: Path | None = None, *, revision: str = "head") -> Notarget_db = db_path or paths.get_sqlite_state_path()cfg = alembic_config(target_db)_reset_unreleased_initial_schema_drift(target_db)+ _repair_unreleased_head_schema_drift(target_db)_stamp_existing_initial_schema(target_db, cfg)command.upgrade(cfg, revision)@@ -70,6 +74,7 @@ def initialize_background_tables(db_path: Path | None = None) -> None:target_db = db_path or paths.get_sqlite_state_path()cfg = alembic_config(target_db)command.ensure_version(cfg)+ _repair_unreleased_head_schema_drift(target_db)_stamp_existing_initial_schema(target_db, cfg)command.upgrade(cfg, "head")@@ -98,6 +103,28 @@ def _reset_unreleased_initial_schema_drift(db_path: Path) -> None:conn.commit()+def _repair_unreleased_head_schema_drift(db_path: Path) -> None:+ path = db_path.expanduser().resolve()+ if not path.exists():+ return++ with sqlite3.connect(path) as conn:+ tables = _table_names(conn)+ if not HEAD_TABLES.issubset(tables):+ return+ if "alembic_version" not in tables:+ return+ version = conn.execute("select version_num from alembic_version").fetchone()+ if version != ("20260515_0002",):+ return++ for table, required_columns in HEAD_REQUIRED_COLUMNS.items():+ existing_columns = _column_names(conn, table)+ if table == "background_tasks" and "deleted_at" not in existing_columns:+ conn.execute('alter table "background_tasks" add column "deleted_at" VARCHAR')+ conn.commit()++def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:path = db_path.expanduser().resolve()if not path.exists():@@ -127,3 +154,7 @@ def _table_names(conn: sqlite3.Connection) -> set[str]:"select name from sqlite_master where type = 'table'",)}+++def _column_names(conn: sqlite3.Connection, table: str) -> set[str]:+ return {row[1] for row in conn.execute(f'pragma table_info("{table}")')}diff --git a/storage/models.py b/storage/models.pyindex 370681f33..dbdf5ca55 100644--- a/storage/models.py+++ b/storage/models.py@@ -145,6 +145,7 @@ background_tasks = Table(Column("post_to", String, nullable=True),Column("deliver_key", Text, nullable=True),Column("enabled", Integer, nullable=False),+ Column("deleted_at", String, nullable=True),Column("created_at", String, nullable=False),Column("updated_at", String, nullable=False),Column("last_started_at", String, nullable=True),diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.pyindex f928a1dc0..222dbfaf4 100644--- a/tests/test_cli_watch_command.py+++ b/tests/test_cli_watch_command.py@@ -38,6 +38,11 @@ def _parse_watch_add(argv: list[str]):return parser.parse_args(["watch", "add", *argv])+def _parse_watch_update(argv: list[str]):+ parser = cli.build_parser()+ return parser.parse_args(["watch", "update", *argv])++def _capture_stderr_json(func, *args):stderr = io.StringIO()with redirect_stderr(stderr):@@ -59,7 +64,7 @@ def test_watch_help_describes_session_id_guidance(capsys) -> None:captured = capsys.readouterr()assert "managed background watchers" in captured.outassert "vibe watch add --session-id sesk8m4q2p7x" in captured.out- assert "{add,list,show,pause,resume,remove}" in captured.out+ assert "{add,update,list,show,pause,resume,remove}" in captured.outdef test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:@@ -482,3 +487,99 @@ def test_watch_pause_resume_and_remove_update_store(tmp_path: Path, capsys) -> Nassert cli.cmd_watch_remove(watch.id) == 0removed = json.loads(capsys.readouterr().out)assert removed["removed_id"] == watch.id+++def test_watch_update_renames_and_retargets_watch(tmp_path: Path, capsys) -> None:+ store = ManagedWatchStore(tmp_path / "watches.json")+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")+ watch = store.add_watch(+ name="Watch CI",+ session_key="slack::channel::C123",+ command=["python3", "wait.py"],+ shell_command=None,+ prefix=None,+ cwd=None,+ mode="once",+ timeout_seconds=600,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=30,+ post_to=None,+ deliver_key=None,+ )+ args = _parse_watch_update(+ [+ watch.id,+ "--name",+ "Watch deploy",+ "--session-key",+ "slack::channel::C456",+ "--post-to",+ "channel",+ "--prefix",+ "Deploy finished.",+ "--forever",+ "--timeout",+ "1200",+ "--lifetime-timeout",+ "7200",+ "--retry-exit-code",+ "1",+ "--retry-exit-code",+ "75",+ "--retry-delay",+ "10",+ "--shell",+ "python3 wait_deploy.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),+ ):+ result = cli.cmd_watch_update(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["watch"]["id"] == watch.id+ assert payload["watch"]["name"] == "Watch deploy"+ assert payload["watch"]["session_key"] == "slack::channel::C456"+ assert payload["watch"]["post_to"] == "channel"+ assert payload["watch"]["prefix"] == "Deploy finished."+ assert payload["watch"]["mode"] == "forever"+ assert payload["watch"]["timeout_seconds"] == 1200+ assert payload["watch"]["lifetime_timeout_seconds"] == 7200+ assert payload["watch"]["retry_exit_codes"] == [1, 75]+ assert payload["watch"]["retry_delay_seconds"] == 10+ assert payload["watch"]["shell_command"] == "python3 wait_deploy.py"+++def test_watch_update_no_changes_returns_structured_error(tmp_path: Path) -> None:+ store = ManagedWatchStore(tmp_path / "watches.json")+ watch = store.add_watch(+ name="Watch CI",+ session_key="slack::channel::C123",+ command=["python3", "wait.py"],+ shell_command=None,+ prefix=None,+ cwd=None,+ mode="once",+ timeout_seconds=600,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=30,+ post_to=None,+ deliver_key=None,+ )+ args = _parse_watch_update([watch.id])++ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._watch_store", return_value=store),+ ):+ result, payload = _capture_stderr_json(cli.cmd_watch_update, args)++ assert result == 1+ assert payload["code"] == "no_watch_changes"diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex a4a77d7be..bd3af4149 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -229,6 +229,42 @@ def test_mark_task_result_skips_deleted_task_after_reload(tmp_path: Path) -> Nonassert reloaded.get_task(task.id) is None+def test_sqlite_remove_task_soft_deletes_task_but_keeps_runs(tmp_path: Path) -> None:+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ store._sqlite = sqlite+ task = store.add_task(+ session_key="slack::channel::C123",+ session_id="sesk8m4q2p7x",+ prompt="send digest",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="Asia/Shanghai",+ )+ sqlite.enqueue_run(+ {+ "id": "run-1",+ "request_type": "task_run",+ "status": "completed",+ "task_id": task.id,+ "session_id": "sesk8m4q2p7x",+ "created_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:00+00:00",+ "completed_at": "2026-05-15T00:01:00+00:00",+ }+ )++ assert store.remove_task(task.id) is True++ reloaded = ScheduledTaskStore(tmp_path / "scheduled_tasks-reloaded.json")+ reloaded._sqlite = sqlite+ reloaded.load()++ assert reloaded.get_task(task.id) is None+ assert sqlite.get_scheduled_task(task.id) is None+ assert sqlite.get_run("run-1")["task_id"] == task.id++def test_store_reload_uses_size_when_mtime_does_not_change(tmp_path: Path) -> None:path = tmp_path / "scheduled_tasks.json"writer = ScheduledTaskStore(path)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex cc3ef90b2..c90164881 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -33,6 +33,13 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert "runtime_records" in tablesassert "background_tasks" in tablesassert "background_runs" in tables+ background_columns = {+ row[1]+ for row in conn.execute(+ "pragma table_info(background_tasks)",+ )+ }+ assert "deleted_at" in background_columnsversion = conn.execute("select version_num from alembic_version").fetchone()assert version == ("20260515_0002",)diff --git a/tests/test_watches.py b/tests/test_watches.pyindex ef2605d62..431f6b311 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -104,6 +104,51 @@ def test_managed_watch_store_uses_sqlite_when_path_is_default(tmp_path: Path, moassert sqlite.get_watch(watch.id)["command"] == ["python3", "wait.py"]+def test_sqlite_remove_watch_soft_deletes_watch_but_keeps_runtime(tmp_path: Path) -> None:+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+ store = ManagedWatchStore(tmp_path / "watches.json")+ store._sqlite = sqlite+ watch = store.add_watch(+ name="Watch CI",+ session_key="slack::channel::C123",+ session_id="sesk8m4q2p7x",+ command=["python3", "wait.py"],+ shell_command=None,+ prefix="CI finished.",+ cwd=None,+ mode="forever",+ timeout_seconds=600,+ lifetime_timeout_seconds=3600,+ retry_exit_codes=[75],+ retry_delay_seconds=45,+ post_to="channel",+ deliver_key=None,+ )+ sqlite.write_watch_runtime(+ {+ "watches": {+ watch.id: {+ "running": True,+ "pid": 1234,+ "started_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:00+00:00",+ }+ }+ },+ updated_at="2026-05-15T00:00:00+00:00",+ )++ assert store.remove_watch(watch.id) is True++ reloaded = ManagedWatchStore(tmp_path / "watches-reloaded.json")+ reloaded._sqlite = sqlite+ reloaded.load()++ assert reloaded.get_watch(watch.id) is None+ assert sqlite.get_watch(watch.id) is None+ assert sqlite.get_run(f"runtime:{watch.id}")["task_id"] == watch.id++def test_watch_runtime_store_uses_sqlite_when_path_is_default(tmp_path: Path, monkeypatch) -> None:monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))store = WatchRuntimeStateStore()diff --git a/vibe/cli.py b/vibe/cli.pyindex 273191c84..1541ac51e 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -506,7 +506,7 @@ def _normalize_task_name(value: Optional[str], *, allow_none: bool = True) -> Opreturn normalized-def _normalize_watch_name(value: Optional[str]) -> Optional[str]:+def _normalize_watch_name(value: Optional[str], *, help_command: str = "vibe watch add --help") -> Optional[str]:if value is None:return Nonenormalized = value.strip()@@ -515,11 +515,67 @@ def _normalize_watch_name(value: Optional[str]) -> Optional[str]:"watch name cannot be empty",code="empty_watch_name",hint="Pass a short non-empty name, or omit --name.",- help_command="vibe watch add --help",+ help_command=help_command,)return normalized+def _resolve_watch_cwd(value: Optional[str], *, help_command: str) -> Optional[str]:+ if not value:+ return None+ resolved = Path(value).expanduser().resolve()+ if not resolved.exists() or not resolved.is_dir():+ raise TaskCliError(+ f"watch cwd does not exist: {value}",+ code="invalid_watch_cwd",+ hint="Point --cwd to an existing directory, or omit it to inherit the service working directory.",+ help_command=help_command,+ details={"cwd": value},+ )+ return str(resolved)+++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:+ raise TaskCliError(+ "--timeout must be >= 0",+ code="invalid_watch_timeout",+ hint="Use 0 for no per-cycle timeout, or a positive number of seconds.",+ help_command=help_command,+ details={"timeout": timeout_seconds},+ )+ if retry_delay_seconds < 0:+ raise TaskCliError(+ "--retry-delay must be >= 0",+ code="invalid_watch_retry_delay",+ hint="Use 0 to retry immediately, or a positive number of seconds.",+ help_command=help_command,+ details={"retry_delay": retry_delay_seconds},+ )+ if lifetime_timeout_seconds < 0:+ raise TaskCliError(+ "--lifetime-timeout must be >= 0",+ code="invalid_watch_lifetime_timeout",+ hint="Use 0 for no overall lifetime limit, or a positive number of seconds.",+ 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_prompt_preview(prompt: str, *, max_chars: int = 72) -> str:compact = " ".join((prompt or "").split())if len(compact) <= max_chars:@@ -1440,49 +1496,15 @@ def cmd_watch_add(args):)command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")- if args.timeout < 0:- raise TaskCliError(- "--timeout must be >= 0",- code="invalid_watch_timeout",- hint="Use 0 for no per-cycle timeout, or a positive number of seconds.",- help_command="vibe watch add --help",- details={"timeout": args.timeout},- )- if args.retry_delay < 0:- raise TaskCliError(- "--retry-delay must be >= 0",- code="invalid_watch_retry_delay",- hint="Use 0 to retry immediately, or a positive number of seconds.",- help_command="vibe watch add --help",- details={"retry_delay": args.retry_delay},- )- if args.lifetime_timeout < 0:- raise TaskCliError(- "--lifetime-timeout must be >= 0",- code="invalid_watch_lifetime_timeout",- hint="Use 0 for no overall lifetime limit, or a positive number of seconds.",- help_command="vibe watch add --help",- details={"lifetime_timeout": args.lifetime_timeout},- )- if args.lifetime_timeout and not args.forever:- raise TaskCliError(- "--lifetime-timeout requires --forever",- code="invalid_watch_lifetime_timeout",- hint="Use --lifetime-timeout only on forever watches.",- help_command="vibe watch add --help",- )- cwd = args.cwd- if cwd:- resolved = Path(cwd).expanduser().resolve()- if not resolved.exists() or not resolved.is_dir():- raise TaskCliError(- f"watch cwd does not exist: {cwd}",- code="invalid_watch_cwd",- hint="Point --cwd to an existing directory, or omit it to inherit the service working directory.",- help_command="vibe watch add --help",- details={"cwd": cwd},- )- cwd = str(resolved)+ mode = "forever" if args.forever else "once"+ _validate_watch_timing(+ 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",+ )+ cwd = _resolve_watch_cwd(args.cwd, help_command="vibe watch add --help")retry_exit_codes = sorted(set(args.retry_exit_code or [DEFAULT_RETRY_EXIT_CODE]))store = _watch_store()@@ -1494,7 +1516,7 @@ def cmd_watch_add(args):shell_command=shell_command,prefix=_normalize_task_name(getattr(args, "prefix", None)),cwd=cwd,- mode="forever" if args.forever else "once",+ mode=mode,timeout_seconds=float(args.timeout),lifetime_timeout_seconds=float(args.lifetime_timeout),retry_exit_codes=retry_exit_codes,@@ -1566,6 +1588,172 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):return 0+def cmd_watch_update(args):+ try:+ store = _watch_store()+ watch = store.get_watch(args.watch_id)+ if watch is None:+ raise TaskCliError(+ f"watch '{args.watch_id}' not found",+ code="watch_not_found",+ hint="Use 'vibe watch list' to find a valid watch ID before calling update.",+ help_command="vibe watch list",+ details={"watch_id": args.watch_id},+ )++ if getattr(args, "reset_delivery", False) and (+ getattr(args, "post_to", None) is not None or getattr(args, "deliver_key", None) is not None+ ):+ raise TaskCliError(+ "use either --reset-delivery or a new delivery flag, not both",+ code="conflicting_delivery_target",+ hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--deliver-key to replace them.",+ help_command="vibe watch update --help",+ )+ if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):+ raise TaskCliError(+ "use either --name or --clear-name, not both",+ code="conflicting_name_update",+ hint="Pass a new name with --name, or remove the stored name with --clear-name.",+ help_command="vibe watch update --help",+ )+ if getattr(args, "clear_name", False):+ name = None+ elif getattr(args, "name", None) is not None:+ name = _normalize_watch_name(args.name, help_command="vibe watch update --help")+ else:+ name = watch.name++ session_id_update, session_key_update = _resolve_session_target_args(+ args,+ required=False,+ help_command="vibe watch update --help",+ )+ session_id = session_id_update if session_id_update is not None else watch.session_id+ session_key = session_key_update if session_key_update else ("" if session_id_update else watch.session_key)+ if getattr(args, "reset_delivery", False):+ post_to = None+ deliver_key = None+ else:+ requested_post_to = getattr(args, "post_to", None)+ requested_deliver_key = getattr(args, "deliver_key", None)+ if requested_post_to is not None:+ post_to = requested_post_to+ deliver_key = None+ elif requested_deliver_key is not None:+ post_to = None+ deliver_key = requested_deliver_key+ else:+ post_to = watch.post_to+ deliver_key = watch.deliver_key++ session_target, delivery_target = _validate_delivery_args(+ session_id=session_id,+ session_key=session_key,+ post_to=post_to,+ deliver_key=deliver_key,+ help_command="vibe watch update --help",+ )++ command = list(watch.command)+ shell_command = watch.shell_command+ waiter_command = getattr(args, "waiter_command", None)+ if waiter_command == ["--"]:+ waiter_command = []+ if getattr(args, "shell", None) is not None or waiter_command:+ command, shell_command = _resolve_watch_command(args, help_command="vibe watch update --help")+ prefix = (+ None+ if getattr(args, "clear_prefix", False)+ else (+ _normalize_task_name(getattr(args, "prefix", None))+ if getattr(args, "prefix", None) is not None+ else watch.prefix+ )+ )+ cwd = (+ None+ if getattr(args, "clear_cwd", False)+ else (+ _resolve_watch_cwd(getattr(args, "cwd", None), help_command="vibe watch update --help")+ if getattr(args, "cwd", None) is not None+ else watch.cwd+ )+ )+ mode = "forever" if getattr(args, "forever", False) else ("once" if getattr(args, "once", False) else watch.mode)+ timeout_seconds = float(args.timeout) if getattr(args, "timeout", None) is not None else watch.timeout_seconds+ lifetime_timeout_seconds = (+ float(args.lifetime_timeout)+ if getattr(args, "lifetime_timeout", None) is not None+ else watch.lifetime_timeout_seconds+ )+ retry_delay_seconds = (+ float(args.retry_delay) if getattr(args, "retry_delay", None) is not None else watch.retry_delay_seconds+ )+ retry_exit_codes = (+ sorted(set(args.retry_exit_code))+ if getattr(args, "retry_exit_code", None) is not None+ else list(watch.retry_exit_codes)+ )+ _validate_watch_timing(+ timeout_seconds=timeout_seconds,+ retry_delay_seconds=retry_delay_seconds,+ lifetime_timeout_seconds=lifetime_timeout_seconds,+ mode=mode,+ help_command="vibe watch update --help",+ )++ changes = {+ "name": name,+ "session_id": session_id,+ "session_key": session_key,+ "command": command,+ "shell_command": shell_command,+ "prefix": prefix,+ "cwd": cwd,+ "mode": mode,+ "timeout_seconds": timeout_seconds,+ "lifetime_timeout_seconds": lifetime_timeout_seconds,+ "retry_exit_codes": retry_exit_codes,+ "retry_delay_seconds": retry_delay_seconds,+ "post_to": post_to,+ "deliver_key": deliver_key,+ }+ current = {+ "name": watch.name,+ "session_id": watch.session_id,+ "session_key": watch.session_key,+ "command": watch.command,+ "shell_command": watch.shell_command,+ "prefix": watch.prefix,+ "cwd": watch.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,+ }+ if changes == current:+ raise TaskCliError(+ "no watch fields were changed",+ code="no_watch_changes",+ hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --deliver-key.",+ help_command="vibe watch update --help",+ details={"watch_id": args.watch_id},+ )++ updated = store.update_watch(args.watch_id, **changes)+ runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)+ warnings = _collect_target_warnings(session_target, delivery_target)+ print(json.dumps({"ok": True, "watch": _watch_payload(updated, runtime_entry), "warnings": warnings}, indent=2))+ return 0+ except Exception as exc:+ _print_task_error(exc, help_command="vibe watch update --help")+ return 1++def cmd_watch_remove(watch_id: str):store = _watch_store()removed = store.remove_watch(watch_id)@@ -2694,7 +2882,7 @@ def build_parser():task_rm_parser = task_subparsers.add_parser("remove",help="Remove a scheduled task",- description="Delete one scheduled task permanently.",+ description="Remove one scheduled task from active management while preserving existing run history.",epilog="Find task IDs with: vibe task list",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe task remove --help",@@ -2754,7 +2942,7 @@ def build_parser():)watch_subparsers = watch_parser.add_subparsers(dest="watch_command",- metavar="{add,list,show,pause,resume,remove}",+ metavar="{add,update,list,show,pause,resume,remove}",)watch_subparsers.required = True@@ -2832,11 +3020,73 @@ def build_parser():help="Waiter command to run after '--'. Example: vibe watch add ... -- python3 script.py --flag value",)+ watch_update_parser = watch_subparsers.add_parser(+ "update",+ help="Update one background watch",+ description="Update stored watch metadata, target, delivery, command, or runtime options.",+ epilog="Find watch IDs with: vibe watch list",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe watch update --help",+ error_hint="Pass at least one field to update, such as --name, --shell, --timeout, --session-id, or --deliver-key.",+ )+ watch_update_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")+ watch_update_parser.add_argument("--name", help="Set a human-friendly watch name")+ watch_update_parser.add_argument("--clear-name", action="store_true", help="Clear the stored watch name")+ watch_update_parser.add_argument(+ "--session-id",+ help="Agent Session ID to continue for follow-up messages from this watch.",+ )+ watch_update_parser.add_argument(+ "--session-key",+ help="Legacy compatibility target; prefer --session-id.",+ )+ watch_update_delivery_group = watch_update_parser.add_mutually_exclusive_group()+ watch_update_delivery_group.add_argument(+ "--post-to",+ choices=("thread", "channel"),+ help="Delivery location override. This changes where the follow-up is posted, not which session is continued.",+ )+ watch_update_delivery_group.add_argument(+ "--deliver-key",+ help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",+ )+ watch_update_delivery_group.add_argument(+ "--reset-delivery",+ action="store_true",+ help="Clear any stored delivery override and deliver back to the continued session target.",+ )+ watch_update_parser.add_argument(+ "--prefix",+ help="Set follow-up instruction text prepended before waiter stdout.",+ )+ watch_update_parser.add_argument("--clear-prefix", action="store_true", help="Clear the stored follow-up prefix")+ watch_update_parser.add_argument("--cwd", help="Set working directory for the waiter process")+ watch_update_parser.add_argument("--clear-cwd", action="store_true", help="Clear the stored waiter working directory")+ watch_update_parser.add_argument("--timeout", type=float, help="Set per-cycle timeout in seconds")+ watch_update_mode_group = watch_update_parser.add_mutually_exclusive_group()+ watch_update_mode_group.add_argument("--forever", action="store_true", help="Switch this watch to forever mode")+ watch_update_mode_group.add_argument("--once", action="store_true", help="Switch this watch to one-shot mode")+ watch_update_parser.add_argument(+ "--lifetime-timeout",+ type=float,+ help="Set overall forever-watch lifetime timeout in seconds. Use 0 for no lifetime limit.",+ )+ watch_update_parser.add_argument(+ "--retry-exit-code",+ dest="retry_exit_code",+ action="append",+ type=int,+ default=None,+ help="Replace retryable forever-mode exit codes. 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")+watch_list_parser = watch_subparsers.add_parser("list",help="List background watches",description="List stored managed background watches.",- epilog="Use the returned watch IDs with 'vibe watch show', 'vibe watch pause', 'vibe watch resume', or 'vibe watch remove'.",+ epilog="Use the returned watch IDs with 'vibe watch show', 'vibe watch update', 'vibe watch pause', 'vibe watch resume', or 'vibe watch remove'.",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe watch list --help",)@@ -2880,7 +3130,7 @@ def build_parser():watch_remove_parser = watch_subparsers.add_parser("remove",help="Remove one background watch",- description="Delete one managed background watch permanently.",+ description="Remove one managed background watch from active management while preserving existing run history.",epilog="Find watch IDs with: vibe watch list",formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe watch remove --help",@@ -2950,6 +3200,8 @@ def main():if args.command == "watch":if args.watch_command == "add":sys.exit(cmd_watch_add(args))+ if args.watch_command == "update":+ sys.exit(cmd_watch_update(args))if args.watch_command in {"list", "ls"}:sys.exit(cmd_watch_list(brief=getattr(args, "brief", False)))if args.watch_command == "show":