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.

refactor(harness): unify definition read projections (#1061)

Call White18a44043ecdc
diff --git a/docs/CLI.md b/docs/CLI.md
index 1e15756f9..5aebe80d0 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -319,6 +319,13 @@ definitions are hidden by default. Add `--include-finished` to page through
history. List output is always bounded; there is no unpaginated `--all` mode.
Task and watch commands use `definition` for one record and `definitions` for
lists; they do not duplicate those records under command-specific aliases.
+Both list and show read the same Harness projection as the Workbench:
+`lifecycle_state`, `lifecycle_detail`, `next_run_at`, `waiting_since`, and
+`running_since`; watch rows also include `process_alive`. For watches,
+`process_alive: null` means no waiter runtime has ever been observed, while
+`false` means an observed waiter has exited. The older `state` and task
+`last_status` fields remain compatibility-only display fields and do not define
+the lifecycle.
The waiter command is passed positionally after `--` (or as a single shell
string via `--shell`). Use `vibe watch add --help` for the full surface,
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 9cab1c713..2695a4435 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -296,6 +296,11 @@ vibe watch remove <watch-id>
`--include-finished` 分页查看历史。列表输出始终有上限,不提供无分页的 `--all` 模式。
task 和 watch 命令用 `definition` 表示单条记录、用 `definitions` 表示列表,
不会再通过命令专属别名重复输出同一份记录。
+list 和 show 与 Workbench 读取同一份 Harness 投影:`lifecycle_state`、
+`lifecycle_detail`、`next_run_at`、`waiting_since` 和 `running_since`;
+watch 还会返回 `process_alive`。对 watch 来说,`process_alive: null`
+表示从未观测到 waiter runtime,`false` 表示曾观测到的 waiter 已退出。
+旧的 `state` 和 task 的 `last_status` 仅作为兼容展示字段保留,不定义 lifecycle。
waiter 命令放在 `--` 后面;或者通过 `--shell` 传入一整段 shell 字符串。
完整参数请看 `vibe watch add --help`,包括 `--timeout`、`--lifetime-timeout`、
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index ce7e6f166..6d0cb5eb1 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -768,6 +768,9 @@ vibe task list [--include-finished] [--page N] [--limit N]
Returns compact rows, 20 per page by default and at most 100. Use
`pagination.next_command` to continue; use `vibe task show <task_id>` for detail.
+List and show expose the Workbench lifecycle projection. Watch rows additionally
+include tri-state `process_alive`; compatibility `state` / `last_status` fields
+do not define lifecycle.
### `vibe task show`
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index a71fd3424..97c5fa982 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -746,6 +746,8 @@ vibe task list [--include-finished] [--page N] [--limit N]
默认每页返回 20 条紧凑记录,单页最多 100 条。按 `pagination.next_command`
继续翻页;需要完整详情时使用 `vibe task show <task_id>`。
+list 和 show 会返回与 Workbench 相同的 lifecycle 投影。watch 还包含三态的
+`process_alive`;兼容字段 `state` / `last_status` 不定义 lifecycle。
### `vibe task show`
diff --git a/storage/background.py b/storage/background.py
index a69cace36..5dce6d24e 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -253,6 +253,36 @@ def definition_lifecycle_expression(definition_type: str):
)
+def _successful_finished_definition_expression(definition_type: str, lifecycle: Any):
+ """Successful one-shot history hidden by the compact CLI lists.
+
+ This predicate is deliberately anchored to the canonical lifecycle
+ expression first. A queued execution therefore keeps a disabled definition
+ visible as ``running`` instead of letting historical completion fields hide
+ live work.
+ """
+
+ no_error = func.trim(func.coalesce(run_definitions.c.last_error, "")) == ""
+ if definition_type == "watch":
+ successful_one_shot = and_(
+ run_definitions.c.mode == "once",
+ run_definitions.c.last_finished_at.is_not(None),
+ or_(
+ run_definitions.c.last_exit_code.is_(None),
+ run_definitions.c.last_exit_code == 0,
+ ),
+ no_error,
+ )
+ else:
+ successful_one_shot = and_(
+ run_definitions.c.schedule_type == "at",
+ run_definitions.c.enabled == 0,
+ run_definitions.c.last_run_at.is_not(None),
+ no_error,
+ )
+ return and_(lifecycle == "finished", successful_one_shot)
+
+
# One completed cycle's worth of state: when the row last ran, how that ending
# went, and what it caught.
DEFINITION_RETIREMENT_COLUMNS = (
@@ -947,15 +977,28 @@ class SQLiteBackgroundTaskStore:
session_id: Optional[str] = None,
page_request: PageRequest | None,
newest_first: bool = True,
+ include_successful_finished: bool = True,
+ enabled_first: bool = False,
) -> PageResult[dict[str, Any]]:
- stmt = self._definitions_query("scheduled", status=status, query=query, session_id=session_id)
+ stmt = self._definitions_query(
+ "scheduled",
+ status=status,
+ query=query,
+ session_id=session_id,
+ include_successful_finished=include_successful_finished,
+ )
activity = func.coalesce(
run_definitions.c.last_run_at,
run_definitions.c.updated_at,
run_definitions.c.created_at,
"",
)
- if newest_first:
+ if enabled_first:
+ # Offset pagination needs a persisted ordering key. Lifecycle can
+ # change when the clock crosses run_at between page requests.
+ enabled_rank = case((run_definitions.c.enabled != 0, 0), else_=1)
+ stmt = stmt.order_by(enabled_rank, run_definitions.c.created_at, run_definitions.c.id)
+ elif newest_first:
stmt = stmt.order_by(activity.desc(), run_definitions.c.id.desc())
else:
stmt = stmt.order_by(activity, run_definitions.c.id)
@@ -1063,8 +1106,16 @@ class SQLiteBackgroundTaskStore:
session_id: Optional[str] = None,
page_request: PageRequest | None,
newest_first: bool = True,
+ include_successful_finished: bool = True,
+ enabled_first: bool = False,
) -> PageResult[dict[str, Any]]:
- stmt = self._definitions_query("watch", status=status, query=query, session_id=session_id)
+ stmt = self._definitions_query(
+ "watch",
+ status=status,
+ query=query,
+ session_id=session_id,
+ include_successful_finished=include_successful_finished,
+ )
activity = func.coalesce(
run_definitions.c.last_event_at,
run_definitions.c.last_started_at,
@@ -1072,7 +1123,12 @@ class SQLiteBackgroundTaskStore:
run_definitions.c.created_at,
"",
)
- if newest_first:
+ if enabled_first:
+ # Runtime and execution state may change between pages; the stored
+ # switch keeps the list order stable while those facts are enriched.
+ enabled_rank = case((run_definitions.c.enabled != 0, 0), else_=1)
+ stmt = stmt.order_by(enabled_rank, run_definitions.c.created_at, run_definitions.c.id)
+ elif newest_first:
stmt = stmt.order_by(activity.desc(), run_definitions.c.id.desc())
else:
stmt = stmt.order_by(activity, run_definitions.c.id)
@@ -1412,6 +1468,7 @@ class SQLiteBackgroundTaskStore:
status: Optional[str] = None,
query: Optional[str] = None,
session_id: Optional[str] = None,
+ include_successful_finished: bool = True,
columns: Any = None,
):
lifecycle = definition_lifecycle_expression(definition_type)
@@ -1434,6 +1491,10 @@ class SQLiteBackgroundTaskStore:
if not states:
raise ValueError("status must be one of: " + ", ".join(DEFINITION_STATUS_FILTERS))
stmt = stmt.where(lifecycle.in_(states))
+ if not include_successful_finished:
+ stmt = stmt.where(
+ ~_successful_finished_definition_expression(definition_type, lifecycle)
+ )
if query:
pattern = _like_contains_pattern(query)
fields = [
@@ -2921,7 +2982,7 @@ class SQLiteBackgroundTaskStore:
row["running_since"] = started.get(row.get("id") or "") if state == "running" else None
if definition_type == "watch":
runtime = runtimes.get(row.get("id") or "")
- row["runtime"] = runtime or {"running": False}
+ row["runtime"] = runtime or {}
# ``None``, not ``False``: no heartbeat row at all means we have
# never seen this waiter, which is not the same as having seen it
# exit — and the row must not claim a waiter is dead on the
diff --git a/tests/test_cli_definition_read_projection.py b/tests/test_cli_definition_read_projection.py
new file mode 100644
index 000000000..96c5de350
--- /dev/null
+++ b/tests/test_cli_definition_read_projection.py
@@ -0,0 +1,318 @@
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+
+from sqlalchemy import select, update
+
+from storage.background import SQLiteBackgroundTaskStore
+from storage.models import agent_runs, run_definitions
+from storage.pagination import PageRequest
+from vibe import cli
+from vibe.ui_server import app
+
+NOW = "2026-07-27T12:00:00+00:00"
+FUTURE = (datetime.now(timezone.utc) + timedelta(days=2)).isoformat()
+PAST = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
+CANONICAL_FIELDS = (
+ "lifecycle_state",
+ "lifecycle_detail",
+ "next_run_at",
+ "waiting_since",
+ "running_since",
+)
+
+
+def _task(store: SQLiteBackgroundTaskStore, task_id: str, **overrides) -> None:
+ payload = {
+ "id": task_id,
+ "name": task_id,
+ "prompt": "run it",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "timezone": "UTC",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ payload.update(overrides)
+ store.upsert_scheduled_task(payload)
+
+
+def _watch(store: SQLiteBackgroundTaskStore, watch_id: str, **overrides) -> None:
+ payload = {
+ "id": watch_id,
+ "name": watch_id,
+ "shell_command": "true",
+ "mode": "once",
+ "enabled": True,
+ "created_at": NOW,
+ "updated_at": NOW,
+ "last_started_at": NOW,
+ }
+ payload.update(overrides)
+ store.upsert_watch(payload)
+
+
+def _rows(store: SQLiteBackgroundTaskStore, table) -> list[dict]:
+ with store.engine.connect() as conn:
+ return [
+ dict(row)
+ for row in conn.execute(select(table).order_by(table.c.id)).mappings()
+ ]
+
+
+def _canonical(row: dict, *, watch: bool = False) -> dict:
+ fields = CANONICAL_FIELDS + (("process_alive",) if watch else ())
+ return {field: row.get(field) for field in fields}
+
+
+def test_cli_and_workbench_share_the_definition_read_projection(capsys) -> None:
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _task(
+ store,
+ "queued-disabled",
+ schedule_type="at",
+ cron=None,
+ run_at=FUTURE,
+ enabled=False,
+ last_run_at=NOW,
+ )
+ store.enqueue_run(
+ {
+ "id": "queued-run",
+ "request_type": "scheduled",
+ "status": "queued",
+ "definition_id": "queued-disabled",
+ "created_at": NOW,
+ "updated_at": NOW,
+ }
+ )
+
+ _watch(store, "waiting-live")
+ _watch(store, "waiting-dead")
+ _watch(store, "waiting-never")
+ _watch(store, "paused", enabled=False, last_started_at=None)
+ _watch(
+ store,
+ "finished-normal",
+ enabled=False,
+ retired_at=NOW,
+ last_finished_at=NOW,
+ last_exit_code=0,
+ )
+ _watch(
+ store,
+ "finished-timeout",
+ enabled=False,
+ retired_at=NOW,
+ last_finished_at=NOW,
+ last_exit_code=124,
+ )
+ _watch(
+ store,
+ "finished-error",
+ enabled=False,
+ retired_at=NOW,
+ last_finished_at=NOW,
+ last_exit_code=1,
+ last_error="waiter failed",
+ )
+ store.write_watch_runtime(
+ {
+ "watches": {
+ "waiting-live": {
+ "running": True,
+ "pid": 1234,
+ "started_at": NOW,
+ "updated_at": NOW,
+ },
+ "waiting-dead": {
+ "running": False,
+ "pid": 2345,
+ "started_at": NOW,
+ "updated_at": NOW,
+ },
+ }
+ },
+ updated_at=NOW,
+ )
+
+ before_definitions = _rows(store, run_definitions)
+ before_runs = _rows(store, agent_runs)
+
+ assert cli.cmd_task_list(page_request=PageRequest(limit=20)) == 0
+ cli_tasks = {
+ row["id"]: row
+ for row in json.loads(capsys.readouterr().out)["definitions"]
+ }
+ assert cli.cmd_watch_list(include_finished=True, page_request=PageRequest(limit=20)) == 0
+ cli_watches = {
+ row["id"]: row
+ for row in json.loads(capsys.readouterr().out)["definitions"]
+ }
+ assert cli.cmd_task_show("queued-disabled") == 0
+ cli_task_detail = json.loads(capsys.readouterr().out)["definition"]
+ assert cli.cmd_watch_show("waiting-live") == 0
+ cli_watch_detail = json.loads(capsys.readouterr().out)["definition"]
+ assert cli.cmd_watch_show("waiting-never") == 0
+ cli_unknown_watch_detail = json.loads(capsys.readouterr().out)["definition"]
+
+ client = app.test_client()
+ api_tasks = {
+ row["id"]: row
+ for row in client.get("/api/harness/tasks?page=1&limit=20").get_json()["tasks"]
+ }
+ api_watches = {
+ row["id"]: row
+ for row in client.get("/api/harness/watches?page=1&limit=20").get_json()["watches"]
+ }
+
+ assert _canonical(cli_tasks["queued-disabled"]) == _canonical(
+ api_tasks["queued-disabled"]
+ )
+ assert _canonical(cli_task_detail) == _canonical(api_tasks["queued-disabled"])
+ assert cli_tasks["queued-disabled"]["lifecycle_state"] == "running"
+ assert cli_tasks["queued-disabled"]["running_since"] is None
+ assert cli_tasks["queued-disabled"]["state"] == "active"
+
+ for watch_id in api_watches:
+ assert _canonical(cli_watches[watch_id], watch=True) == _canonical(
+ api_watches[watch_id], watch=True
+ )
+ assert _canonical(cli_watch_detail, watch=True) == _canonical(
+ api_watches["waiting-live"], watch=True
+ )
+ assert cli_watch_detail["runtime"]["pid"] == 1234
+ assert cli_unknown_watch_detail["process_alive"] is None
+ assert cli_unknown_watch_detail["runtime"] == {}
+ assert api_watches["waiting-never"]["runtime"] == {}
+
+ expected = {
+ "waiting-live": ("waiting", None, True),
+ "waiting-dead": ("waiting", None, False),
+ "waiting-never": ("waiting", None, None),
+ "paused": ("paused", None, None),
+ "finished-normal": ("finished", "normal", None),
+ "finished-timeout": ("finished", "timeout", None),
+ "finished-error": ("finished", "error", None),
+ }
+ actual = {
+ watch_id: (
+ row["lifecycle_state"],
+ row["lifecycle_detail"],
+ row["process_alive"],
+ )
+ for watch_id, row in cli_watches.items()
+ }
+ assert actual == expected
+ assert cli_watches["waiting-live"]["state"] == "running"
+ assert cli_watches["waiting-live"]["waiting_since"] == NOW
+ assert cli_watches["waiting-dead"]["state"] == "pending"
+ assert cli_watches["waiting-dead"]["waiting_since"] == NOW
+ assert cli_watches["waiting-never"]["state"] == "pending"
+ assert cli_watches["waiting-never"]["waiting_since"] == NOW
+ assert cli_watches["finished-normal"]["state"] == "completed"
+ assert cli_watches["finished-timeout"]["state"] == "failed"
+ assert cli_watches["finished-error"]["state"] == "failed"
+
+ assert _rows(store, run_definitions) == before_definitions
+ assert _rows(store, agent_runs) == before_runs
+ finally:
+ store.close()
+
+
+def test_cli_definition_lists_page_before_enrichment(monkeypatch, capsys) -> None:
+ store = SQLiteBackgroundTaskStore()
+ try:
+ for index in range(25):
+ _task(store, f"task-{index:02d}")
+ _watch(store, f"watch-{index:02d}")
+ finally:
+ store.close()
+
+ enriched_sizes: list[tuple[str, int]] = []
+ original = SQLiteBackgroundTaskStore._enrich_definitions
+
+ def record_page(self, rows, conn, *, definition_type):
+ enriched_sizes.append((definition_type, len(rows)))
+ return original(self, rows, conn, definition_type=definition_type)
+
+ monkeypatch.setattr(SQLiteBackgroundTaskStore, "_enrich_definitions", record_page)
+
+ page_request = PageRequest(page=1, limit=2)
+ assert cli.cmd_task_list(page_request=page_request) == 0
+ task_payload = json.loads(capsys.readouterr().out)
+ assert cli.cmd_watch_list(page_request=page_request) == 0
+ watch_payload = json.loads(capsys.readouterr().out)
+
+ assert task_payload["pagination"]["next_command"] == "vibe task list --page 2 --limit 2"
+ assert watch_payload["pagination"]["next_command"] == "vibe watch list --page 2 --limit 2"
+ assert enriched_sizes == [("scheduled", 3), ("watch", 3)]
+
+
+def test_task_list_pagination_is_stable_across_run_at_boundary(capsys) -> None:
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _task(
+ store,
+ "boundary",
+ schedule_type="at",
+ cron=None,
+ run_at=FUTURE,
+ created_at="2026-07-27T12:00:00+00:00",
+ )
+ _task(store, "still-waiting", created_at="2026-07-27T12:01:00+00:00")
+
+ assert cli.cmd_task_list(page_request=PageRequest(page=1, limit=1)) == 0
+ first_page = json.loads(capsys.readouterr().out)
+
+ # Simulate the wall clock crossing run_at between offset pages.
+ with store.engine.begin() as conn:
+ conn.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == "boundary")
+ .values(run_at=PAST)
+ )
+
+ assert cli.cmd_task_list(page_request=PageRequest(page=2, limit=1)) == 0
+ second_page = json.loads(capsys.readouterr().out)
+
+ assert [first_page["definitions"][0]["id"], second_page["definitions"][0]["id"]] == [
+ "boundary",
+ "still-waiting",
+ ]
+ finally:
+ store.close()
+
+
+def test_task_list_does_not_hide_an_enabled_one_shot_after_manual_run(capsys) -> None:
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _task(
+ store,
+ "manual-run",
+ schedule_type="at",
+ cron=None,
+ run_at=PAST,
+ enabled=True,
+ last_run_at=NOW,
+ )
+ _task(
+ store,
+ "scheduler-completed",
+ schedule_type="at",
+ cron=None,
+ run_at=PAST,
+ enabled=False,
+ last_run_at=NOW,
+ )
+
+ assert cli.cmd_task_list(page_request=PageRequest(limit=20)) == 0
+ rows = json.loads(capsys.readouterr().out)["definitions"]
+
+ assert [row["id"] for row in rows] == ["manual-run"]
+ assert rows[0]["lifecycle_state"] == "finished"
+ finally:
+ store.close()
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index fc03e2c9c..fc1ad74f1 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -975,8 +975,7 @@ def test_task_run_missing_id_returns_guidance(tmp_path: Path) -> None:
def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys) -> None:
- store_path = tmp_path / "scheduled_tasks.json"
- store = cli.ScheduledTaskStore(store_path)
+ store = cli.ScheduledTaskStore()
store.add_task(
session_key="slack::channel::C123",
prompt="recurring",
@@ -1013,8 +1012,7 @@ def test_task_list_hides_completed_one_shots_by_default(tmp_path: Path, capsys)
def test_task_list_brief_returns_scheduling_focused_view(tmp_path: Path, capsys) -> None:
- store_path = tmp_path / "scheduled_tasks.json"
- store = cli.ScheduledTaskStore(store_path)
+ store = cli.ScheduledTaskStore()
task = store.add_task(
name="Hourly summary",
session_key="slack::channel::C123",
@@ -1041,7 +1039,7 @@ def test_paused_recurring_task_keeps_failed_run_in_last_status(
tmp_path: Path,
capsys,
) -> None:
- store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store = cli.ScheduledTaskStore()
task = store.add_task(
name="Paused after failure",
session_key="slack::channel::C123",
@@ -1062,7 +1060,7 @@ def test_paused_recurring_task_keeps_failed_run_in_last_status(
def test_task_list_defaults_to_first_page(tmp_path: Path, capsys) -> None:
- store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store = cli.ScheduledTaskStore()
for index in range(25):
store.add_task(
name=f"Task {index:02d}",
@@ -1095,7 +1093,7 @@ def test_task_list_keeps_enabled_tasks_ahead_of_paused_history(
tmp_path: Path,
capsys,
) -> None:
- store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store = cli.ScheduledTaskStore()
for index in range(21):
paused = store.add_task(
name=f"Paused {index:02d}",
@@ -1129,7 +1127,7 @@ def test_task_list_cli_dispatches_pagination_flags(
capsys,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store = cli.ScheduledTaskStore()
for index in range(3):
store.add_task(
name=f"Task {index}",
@@ -1153,8 +1151,7 @@ def test_task_list_cli_dispatches_pagination_flags(
def test_task_list_order_is_stable_across_cron_boundaries(
tmp_path: Path, capsys, monkeypatch: pytest.MonkeyPatch
) -> None:
- store_path = tmp_path / "scheduled_tasks.json"
- store = cli.ScheduledTaskStore(store_path)
+ store = cli.ScheduledTaskStore()
later = store.add_task(
name="Later run",
session_key="slack::channel::C123",
@@ -1173,11 +1170,16 @@ def test_task_list_order_is_stable_across_cron_boundaries(
)
later.created_at = "2026-04-01T00:00:00+00:00"
earlier.created_at = "2026-04-01T00:00:01+00:00"
+ store.upsert_task(later)
+ store.upsert_task(earlier)
first_next_runs = {
- later.id: "2026-04-01T09:30:00+08:00",
- earlier.id: "2026-04-01T01:00:00+00:00",
+ "UTC": "2026-04-01T09:30:00+08:00",
+ "Asia/Shanghai": "2026-04-01T01:00:00+00:00",
}
- monkeypatch.setattr(cli, "_task_next_run_at", lambda task: first_next_runs[task.id])
+ monkeypatch.setattr(
+ "storage.background.compute_next_run_at",
+ lambda **kwargs: first_next_runs[str(kwargs["timezone_name"])],
+ )
with patch("vibe.cli._task_store", return_value=store):
assert cli.cmd_task_list(brief=True) == 0
@@ -1185,10 +1187,13 @@ def test_task_list_order_is_stable_across_cron_boundaries(
first_ids = [item["id"] for item in json.loads(capsys.readouterr().out)["definitions"]]
second_next_runs = {
- later.id: "2026-04-01T02:00:00+00:00",
- earlier.id: "2026-04-01T10:00:00+00:00",
+ "UTC": "2026-04-01T02:00:00+00:00",
+ "Asia/Shanghai": "2026-04-01T10:00:00+00:00",
}
- monkeypatch.setattr(cli, "_task_next_run_at", lambda task: second_next_runs[task.id])
+ monkeypatch.setattr(
+ "storage.background.compute_next_run_at",
+ lambda **kwargs: second_next_runs[str(kwargs["timezone_name"])],
+ )
with patch("vibe.cli._task_store", return_value=store):
assert cli.cmd_task_list(brief=True) == 0
@@ -1197,8 +1202,7 @@ def test_task_list_order_is_stable_across_cron_boundaries(
def test_task_show_includes_derived_schedule_fields(tmp_path: Path, capsys) -> None:
- store_path = tmp_path / "scheduled_tasks.json"
- store = cli.ScheduledTaskStore(store_path)
+ store = cli.ScheduledTaskStore()
task = store.add_task(
name="Hourly summary",
session_key="slack::channel::C123",
@@ -1221,8 +1225,7 @@ def test_task_show_includes_derived_schedule_fields(tmp_path: Path, capsys) -> N
def test_task_list_include_finished_includes_completed_one_shots(tmp_path: Path, capsys) -> None:
- store_path = tmp_path / "scheduled_tasks.json"
- store = cli.ScheduledTaskStore(store_path)
+ store = cli.ScheduledTaskStore()
done = store.add_task(
session_key="slack::channel::C123",
prompt="one-shot",
@@ -1243,7 +1246,7 @@ def test_task_list_include_finished_includes_completed_one_shots(tmp_path: Path,
def test_task_list_include_finished_keeps_history_paginated(tmp_path: Path, capsys) -> None:
- store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store = cli.ScheduledTaskStore()
for index in range(3):
done = store.add_task(
session_key="slack::channel::C123",
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 17c16e7cd..9379a13f5 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -838,8 +838,8 @@ def test_wait_for_watch_startup_rejects_watch_that_fails_before_stable_window(tm
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")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
watch = store.add_watch(
name="Watch CI",
session_key="slack::channel::C123",
@@ -881,8 +881,8 @@ def test_watch_list_brief_includes_runtime_state(tmp_path: Path, capsys) -> None
def test_watch_list_hides_finished_one_shots_by_default(tmp_path: Path, capsys) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
active = _add_test_watch(store, name="Active")
completed = _add_test_watch(store, name="Completed")
failed = _add_test_watch(store, name="Failed")
@@ -908,8 +908,8 @@ def test_watch_list_hides_finished_one_shots_by_default(tmp_path: Path, capsys)
def test_resumed_then_paused_one_shot_remains_in_default_list(tmp_path: Path, capsys) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
watch = _add_test_watch(store, name="Resumable")
store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=True)
@@ -931,8 +931,8 @@ def test_paused_forever_watch_changed_to_once_starts_new_lifecycle(
tmp_path: Path,
capsys,
) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
watch = _add_test_watch(store, name="Change mode", mode="forever")
store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=False)
store.set_enabled(watch.id, False)
@@ -967,8 +967,8 @@ def test_paused_forever_watch_changed_to_once_starts_new_lifecycle(
def test_watch_list_defaults_to_first_page(tmp_path: Path, capsys) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
for index in range(25):
_add_test_watch(store, name=f"Watch {index:02d}")
@@ -997,8 +997,8 @@ def test_watch_list_cli_dispatches_pagination_flags(
capsys,
monkeypatch: pytest.MonkeyPatch,
) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
for index in range(3):
_add_test_watch(store, name=f"Watch {index}")
@@ -1017,8 +1017,8 @@ def test_watch_list_cli_dispatches_pagination_flags(
def test_watch_list_include_finished_keeps_history_paginated(tmp_path: Path, capsys) -> None:
- store = ManagedWatchStore(tmp_path / "watches.json")
- runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
for index in range(3):
watch = _add_test_watch(store, name=f"Finished {index}")
store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True, disable=True)
diff --git a/vibe/cli.py b/vibe/cli.py
index 50c144230..8afbf2ccd 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -65,7 +65,11 @@ from vibe.upgrade import (
should_skip_show_runtime_prepare,
)
from storage.db import create_sqlite_engine
-from storage.background import compute_next_run_at, normalize_run_status
+from storage.background import (
+ SQLiteBackgroundTaskStore,
+ compute_next_run_at,
+ normalize_run_status,
+)
from storage.models import scope_settings, scopes
from storage.pagination import (
DEFAULT_PAGE_LIMIT,
@@ -286,18 +290,16 @@ def _paginated_fields(page_result, *, command: list[str], include_next_command:
def _print_definition_list_payload(
- items,
+ page_result,
*,
payload_for_item,
command: list[str],
- page_request: PageRequest,
) -> None:
- result = page_sequence(items, page_request)
- item_payloads = [payload_for_item(item) for item in result.items]
+ item_payloads = [payload_for_item(item) for item in page_result.items]
_print_cli_payload(
"run_definitions",
definitions=item_payloads,
- **_paginated_fields(result, command=command),
+ **_paginated_fields(page_result, command=command),
)
@@ -1526,11 +1528,19 @@ def _task_next_run_at(task) -> Optional[str]:
def _task_schedule_summary(task) -> str:
- if task.schedule_type == "cron":
- return f"cron:{task.cron}" if task.cron else "cron"
- if task.schedule_type == "at":
- return f"at:{task.run_at}" if task.run_at else "at"
- return task.schedule_type
+ if isinstance(task, Mapping):
+ schedule_type = str(task.get("schedule_type") or "")
+ cron = task.get("cron")
+ run_at = task.get("run_at")
+ else:
+ schedule_type = task.schedule_type
+ cron = task.cron
+ run_at = task.run_at
+ if schedule_type == "cron":
+ return f"cron:{cron}" if cron else "cron"
+ if schedule_type == "at":
+ return f"at:{run_at}" if run_at else "at"
+ return schedule_type
def _task_payload(task, *, brief: bool = False):
@@ -1565,18 +1575,87 @@ def _task_payload(task, *, brief: bool = False):
return payload
-def _sort_tasks_for_display(tasks):
- # Offset pagination requires an order that does not change merely because
- # wall-clock time crossed a cron boundary between page requests. Keep
- # schedulable tasks ahead of paused/history rows without using next-run
- # timestamps, which are time-dependent.
- return sorted(tasks, key=lambda item: (item.enabled is False, item.created_at, item.id))
+_CANONICAL_DEFINITION_FIELDS = (
+ "lifecycle_state",
+ "lifecycle_detail",
+ "next_run_at",
+ "waiting_since",
+ "running_since",
+)
+
+
+def _task_projection_state(task: Mapping[str, object]) -> str:
+ """Compatibility ``state`` derived from the canonical lifecycle fields."""
+
+ lifecycle_state = task.get("lifecycle_state")
+ if lifecycle_state in {"waiting", "running"}:
+ return "active"
+ if lifecycle_state == "finished":
+ return "failed" if task.get("lifecycle_detail") in {"timeout", "error"} else "completed"
+ if lifecycle_state == "paused":
+ return "paused"
+ return "unknown"
+
+
+def _task_projection_last_status(task: Mapping[str, object]) -> str:
+ """Historical compatibility field; never used to determine lifecycle."""
+
+ if task.get("last_run_at") and task.get("last_error"):
+ return "failed"
+ if task.get("last_run_at"):
+ return "succeeded"
+ return "never_run"
+
+
+def _task_projection_payload(task: Mapping[str, object], *, brief: bool = False) -> dict:
+ prompt = str(task.get("prompt") or "")
+ name = task.get("name")
+ derived = {
+ "display_name": str(name) if name else _task_message_preview(prompt),
+ "message_preview": _task_message_preview(prompt),
+ "state": _task_projection_state(task),
+ "last_status": _task_projection_last_status(task),
+ "schedule_summary": _task_schedule_summary(task),
+ }
+ if brief:
+ payload = {
+ "id": task.get("id"),
+ "name": name,
+ "display_name": derived["display_name"],
+ "state": derived["state"],
+ "last_status": derived["last_status"],
+ "schedule_type": task.get("schedule_type"),
+ "schedule_summary": derived["schedule_summary"],
+ "session_id": task.get("session_id"),
+ "session_key": task.get("session_key"),
+ "agent_name": task.get("agent_name"),
+ "post_to": task.get("post_to"),
+ "deliver_key": task.get("deliver_key"),
+ "timezone": task.get("timezone"),
+ "enabled": task.get("enabled"),
+ }
+ payload.update({field: task.get(field) for field in _CANONICAL_DEFINITION_FIELDS})
+ return payload
+ payload = dict(task)
+ payload.update(derived)
+ return payload
def _task_store() -> ScheduledTaskStore:
return ScheduledTaskStore()
+def _definition_read_store():
+ """Own the canonical read projection store used by CLI list/show commands."""
+
+ store = SQLiteBackgroundTaskStore()
+ try:
+ yield store
+ finally:
+ store.close()
+
+
def _task_request_store() -> TaskExecutionStore:
return TaskExecutionStore()
@@ -1646,16 +1725,6 @@ def _is_failed_one_shot(task) -> bool:
)
-def _is_finished_one_shot_watch(watch) -> bool:
- return (
- watch.mode == "once"
- and not watch.enabled
- and bool(watch.last_finished_at)
- and not watch.last_error
- and watch.last_exit_code in (None, 0)
- )
-
-
def _parse_validated_session_key(
session_key: str,
*,
@@ -2389,6 +2458,61 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
return payload
+def _watch_projection_state(watch: Mapping[str, object]) -> str:
+ """Compatibility ``state`` derived from canonical lifecycle and liveness."""
+
+ lifecycle_state = watch.get("lifecycle_state")
+ if lifecycle_state == "running":
+ return "running"
+ if lifecycle_state == "waiting":
+ if watch.get("process_alive") is True:
+ return "running"
+ return "armed" if watch.get("mode") == "forever" else "pending"
+ if lifecycle_state == "finished":
+ return "failed" if watch.get("lifecycle_detail") in {"timeout", "error"} else "completed"
+ if lifecycle_state == "paused":
+ return "paused"
+ return "unknown"
+
+
+def _watch_projection_payload(watch: Mapping[str, object], *, brief: bool = False) -> dict:
+ shell_command = str(watch.get("shell_command") or "")
+ command = watch.get("command")
+ command_values = [str(value) for value in command] if isinstance(command, list) else []
+ command_preview = shell_command or shlex.join(command_values)
+ name = watch.get("name")
+ derived = {
+ "display_name": str(name) if name else _task_message_preview(command_preview, max_chars=120),
+ "command_preview": _task_message_preview(command_preview, max_chars=120),
+ "state": _watch_projection_state(watch),
+ }
+ if brief:
+ payload = {
+ "id": watch.get("id"),
+ "name": name,
+ "display_name": derived["display_name"],
+ "state": derived["state"],
+ "mode": watch.get("mode"),
+ "session_id": watch.get("session_id"),
+ "session_key": watch.get("session_key"),
+ "agent_name": watch.get("agent_name"),
+ "message_preview": _task_message_preview(
+ str(watch.get("message") or watch.get("prefix") or "")
+ ),
+ "timeout_seconds": watch.get("timeout_seconds"),
+ "lifetime_timeout_seconds": watch.get("lifetime_timeout_seconds"),
+ "enabled": watch.get("enabled"),
+ "last_event_at": watch.get("last_event_at"),
+ "last_error": watch.get("last_error"),
+ "process_alive": watch.get("process_alive"),
+ }
+ payload.update({field: watch.get(field) for field in _CANONICAL_DEFINITION_FIELDS})
+ return payload
+ payload = dict(watch)
+ payload.update(derived)
+ return payload
+
+
def _agent_payload(agent, *, brief: bool = False) -> dict:
payload = agent.to_dict()
if brief:
@@ -2684,26 +2808,26 @@ def cmd_task_list(
brief: bool = True,
page_request: PageRequest = PageRequest(),
):
- store = _task_store()
- tasks = store.list_tasks()
- if not include_finished:
- tasks = [task for task in tasks if not _is_completed_one_shot(task)]
- tasks = _sort_tasks_for_display(tasks)
+ with _definition_read_store() as store:
+ page_result = store.list_scheduled_tasks_page(
+ page_request=page_request,
+ include_successful_finished=include_finished,
+ enabled_first=True,
+ )
command = ["vibe", "task", "list"]
if include_finished:
command.append("--include-finished")
_print_definition_list_payload(
- tasks,
- payload_for_item=lambda task: _task_payload(task, brief=True),
+ page_result,
+ payload_for_item=lambda task: _task_projection_payload(task, brief=brief),
command=command,
- page_request=page_request,
)
return 0
def cmd_task_show(task_id: str):
- store = _task_store()
- task = store.get_task(task_id)
+ with _definition_read_store() as store:
+ task = store.get_scheduled_task(task_id)
if task is None:
_print_task_error(
TaskCliError(
@@ -2715,7 +2839,7 @@ def cmd_task_show(task_id: str):
)
)
return 1
- task_payload = _task_payload(task)
+ task_payload = _task_projection_payload(task)
_print_definition_payload(task_payload)
return 0
@@ -7840,27 +7964,26 @@ def cmd_watch_list(
brief: bool = True,
page_request: PageRequest = PageRequest(),
):
- store = _watch_store()
- runtime_state = _watch_runtime_store().load().get("watches", {})
- watches = store.list_watches()
- if not include_finished:
- watches = [watch for watch in watches if not _is_finished_one_shot_watch(watch)]
- watches.sort(key=lambda item: (item.enabled is False, item.created_at, item.id))
+ with _definition_read_store() as store:
+ page_result = store.list_watches_page(
+ page_request=page_request,
+ include_successful_finished=include_finished,
+ enabled_first=True,
+ )
command = ["vibe", "watch", "list"]
if include_finished:
command.append("--include-finished")
_print_definition_list_payload(
- watches,
- payload_for_item=lambda watch: _watch_payload(watch, runtime_state.get(watch.id), brief=True),
+ page_result,
+ payload_for_item=lambda watch: _watch_projection_payload(watch, brief=brief),
command=command,
- page_request=page_request,
)
return 0
def cmd_watch_show(watch_id: str):
- store = _watch_store()
- watch = store.get_watch(watch_id)
+ with _definition_read_store() as store:
+ watch = store.get_watch(watch_id)
if watch is None:
_print_task_error(
TaskCliError(
@@ -7872,8 +7995,7 @@ def cmd_watch_show(watch_id: str):
)
)
return 1
- runtime_entry = _watch_runtime_store().load().get("watches", {}).get(watch.id)
- watch_payload = _watch_payload(watch, runtime_entry)
+ watch_payload = _watch_projection_payload(watch)
_print_definition_payload(watch_payload)
return 0