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.

feat(cli): explain removed definitions and data-query schema (#2970)

Call White05d7cd9c67bf
diff --git a/docs/CLI.md b/docs/CLI.md
index 1fb50cf19..28b594268 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -272,6 +272,27 @@ session and observation state are keyed by Avibe Session and are retired when
the Session is explicitly ended or archived, rather than at every Turn
boundary.
+### `vibe data query`
+
+Run one guarded read-only SQL statement against the local SQLite state database.
+Results return 20 rows per page by default and at most 100.
+
+```bash
+vibe data query --sql "select group_concat(name, ', ') as tables from pragma_table_list where schema = 'main'"
+vibe data query --sql "select group_concat(name, ', ') as columns from pragma_table_info('run_definitions')"
+vibe data query --sql "PRAGMA table_info(run_definitions)" --limit 100 # with types and keys
+vibe data query --sql "select id, status, created_at from agent_runs order by created_at desc"
+vibe data query --sql-file query.sql --limit 50
+```
+
+The connection is read-only: writes, schema changes, `ATTACH`, and transactions
+are refused. The schema PRAGMAs `table_list`, `table_info`, `table_xinfo`,
+`index_list`, `index_info`, and `foreign_key_list` run as statements or as
+`pragma_*` table-valued functions; every other PRAGMA is refused. A
+`no such table` or `no such column` error carries a `hint` with the closest
+names and the table list, or the referenced tables' columns. Tasks and Watches
+are rows of `run_definitions` (`definition_type` is `scheduled` or `watch`).
+
### `vibe data skill-usage`
Instance Owner-only local maintenance; these commands return JSON diagnostics,
@@ -603,6 +624,13 @@ Both list and show read the same Harness projection as the Workbench:
`last_status` fields remain compatibility-only display fields and do not define
the lifecycle.
+`vibe task show` and `vibe watch show` also read a removed definition: the same
+projection with `lifecycle_state: "removed"` and `removed_at`. Lists never
+include removed definitions. `pause`, `resume`, `update`, `run`, and `remove` on
+a removed definition fail with `task_removed` / `watch_removed`, whose
+`details.removed_at` says when it was removed; `task_not_found` /
+`watch_not_found` means the id never existed.
+
The waiter command is passed positionally after `--` (or as a single shell
string via `--shell`). Use `vibe watch add --help` for the full surface,
including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index ef2c12d00..eec5249e0 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -191,6 +191,25 @@ SQLite 数据库的 `agent_events` 与 `skill_usage_daily` 中,没有统计面
记录器每次写入前都会重新读取此设置,无需重启。关闭统计不影响 Skill 发现或
加载,也不会删除已有历史。若希望既不再记录,也不保留历史,请先关闭,再清除。
+### `vibe data query`
+
+对本地 SQLite 状态数据库执行一条受保护的只读 SQL 语句。结果默认每页 20 行,最多 100 行。
+
+```bash
+vibe data query --sql "select group_concat(name, ', ') as tables from pragma_table_list where schema = 'main'"
+vibe data query --sql "select group_concat(name, ', ') as columns from pragma_table_info('run_definitions')"
+vibe data query --sql "PRAGMA table_info(run_definitions)" --limit 100 # 含类型与主键
+vibe data query --sql "select id, status, created_at from agent_runs order by created_at desc"
+vibe data query --sql-file query.sql --limit 50
+```
+
+连接是只读的:写入、schema 变更、`ATTACH` 和事务都会被拒绝。schema PRAGMA
+`table_list`、`table_info`、`table_xinfo`、`index_list`、`index_info` 和
+`foreign_key_list` 可以作为语句执行,也可以作为 `pragma_*` 表值函数使用;其他
+PRAGMA 一律拒绝。`no such table` 或 `no such column` 错误会带上 `hint`,给出最接近的
+名称以及表清单,或所引用表的列。Task 和 Watch 都是 `run_definitions` 的行
+(`definition_type` 为 `scheduled` 或 `watch`)。
+
### `vibe data skill-usage`
仅限实例所有者使用的本地维护命令,返回 JSON 诊断信息,不是 Skill 热度排名。
@@ -489,6 +508,12 @@ watch 还会返回 `process_alive`。对 watch 来说,`process_alive: null`
表示从未观测到 waiter runtime,`false` 表示曾观测到的 waiter 已退出。
旧的 `state` 和 task 的 `last_status` 仅作为兼容展示字段保留,不定义 lifecycle。
+`vibe task show` 和 `vibe watch show` 也能读取已删除的 definition:返回同一份投影,
+其中 `lifecycle_state: "removed"`,并带有 `removed_at`。列表从不包含已删除的
+definition。对已删除的 definition 执行 `pause`、`resume`、`update`、`run` 或
+`remove` 会以 `task_removed` / `watch_removed` 失败,`details.removed_at` 给出删除
+时间;`task_not_found` / `watch_not_found` 表示该 id 从未存在。
+
waiter 命令放在 `--` 后面;或者通过 `--shell` 传入一整段 shell 字符串。
完整参数请看 `vibe watch add --help`,包括 `--timeout`、`--lifetime-timeout`、
`--forever`、`--retry-exit-code`、`--retry-delay`、`--name` 和 session creation 参数。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index f1e1f378a..328a19021 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -870,6 +870,10 @@ do not define lifecycle.
vibe task show <task_id>
```
+A removed task still reads here, with `lifecycle_state: "removed"` and
+`removed_at`. Other `vibe task` commands on it fail with `task_removed`;
+`task_not_found` means the id never existed.
+
### `vibe task pause`
```bash
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index abdf0f8af..29371cbc2 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -804,6 +804,9 @@ list 和 show 会返回与 Workbench 相同的 lifecycle 投影。watch 还包
vibe task show <task_id>
```
+已删除的 task 仍可在这里读取,返回 `lifecycle_state: "removed"` 和 `removed_at`。
+对它执行其他 `vibe task` 命令会以 `task_removed` 失败;`task_not_found` 表示该 id 从未存在。
+
### `vibe task pause`
```bash
diff --git a/docs/plans/cli-query-pagination.md b/docs/plans/cli-query-pagination.md
index 04082ba26..66d3ee167 100644
--- a/docs/plans/cli-query-pagination.md
+++ b/docs/plans/cli-query-pagination.md
@@ -89,10 +89,19 @@ Safety layers:
- open SQLite with `file:...?mode=ro`
- set `PRAGMA query_only = ON`
- use `sqlite3.Connection.set_authorizer()` to deny writes, schema changes,
- attaching databases, transactions, and write PRAGMAs
+ attaching databases, transactions, and every PRAGMA except the schema-reading
+ `table_list`, `table_info`, `table_xinfo`, `index_list`, `index_info`, and
+ `foreign_key_list` (statement or `pragma_*` table-valued form), so Agents can
+ discover the schema with the query they already reach for
- execute one statement with `execute()`, never `executescript()`
- use progress handler limits to avoid runaway queries
- force pagination/default limit behavior on result output
+- on `no such table` / `no such column`, return a `hint` with the closest names
+ and the table list or the referenced tables' columns; on a refused PRAGMA,
+ name the allowed ones. The hint is advisory: if reading the schema fails, the
+ query's own error is returned unchanged
+- the connection keeps Python's default 5 s busy timeout, the same bound as
+ `storage/db.py`; WAL readers do not wait on writers
The SQL command is Agent-facing and should emit JSON by default through the same
CLI payload style.
diff --git a/docs/plans/harness-watch-task-readability.md b/docs/plans/harness-watch-task-readability.md
index 78bd95a70..85e3d02c7 100644
--- a/docs/plans/harness-watch-task-readability.md
+++ b/docs/plans/harness-watch-task-readability.md
@@ -111,7 +111,10 @@ retirement_reason: 'schedule_consumed' | 'schedule_missed' | null # Tasks only
```
`running_since` was added during review, and is the one change to this frozen
-list. It cannot be `last_started_at`: that column is the *definition's* last
+list. The CLI's by-id reads (`vibe task show`, `vibe watch show`) add one state
+outside it: a removed definition reads `lifecycle_state: 'removed'` with
+`removed_at`. Lists, counts, and the Workbench never return removed rows, so
+the Workbench vocabulary above is unchanged. It cannot be `last_started_at`: that column is the *definition's* last
cycle, so a `forever` watch that fired yesterday and began a fresh run a minute
ago would report a day of running — a duration stitched together from two
cycles. It comes from the same in-flight `agent_runs` row that made the state
diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.md
index 058fbf970..da4182cd0 100644
--- a/skills/use-avibe-harness/SKILL.md
+++ b/skills/use-avibe-harness/SKILL.md
@@ -33,7 +33,9 @@ Relationship: Scope routes work; Agent defines who acts; Session holds continuit
### Inspecting Harness state
Use `vibe harness status` first for this Session's active Runs, armed Watches, upcoming Tasks, runtime, and live anomalies. Session-owned lists (`vibe harness status`, `vibe runs list`, `vibe task list`, `vibe watch list`, `vibe show list`) read this Session by default; add `--session-id <id>` for another Session or `--global` for every Session. Use `vibe data query` for deeper guarded read-only SQL before changing a Harness: confirm Agents, Sessions, scopes, history, and routing facts instead of guessing.
-Examples: use `vibe data query --sql "select name from sqlite_master where type='table' order by name" --limit 100` for a broad schema inventory; use `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --limit 20` for the focused Harness tables. Follow `pagination.next_command` if either result has more pages.
+Discover the schema before guessing names: `vibe data query --sql "select group_concat(name, ', ') as tables from pragma_table_list where schema = 'main'"` lists the tables in one row, and `vibe data query --sql "select group_concat(name, ', ') as columns from pragma_table_info('agent_runs')"` lists one table's columns; `PRAGMA table_info(agent_runs)` adds types and keys at one row per column. Schema PRAGMAs are the only PRAGMAs allowed. The Harness tables are `agents`, `agent_sessions`, `agent_runs`, `messages`, `scopes`, `scope_settings`, and `run_definitions`, which holds both Tasks and Watches (`definition_type` is `scheduled` or `watch`). A `no such table` or `no such column` error carries a `hint` with the closest names and the real columns, so read it before retrying.
+
+`vibe task show <id>` and `vibe watch show <id>` still read a removed definition, with `lifecycle_state: "removed"` and `removed_at`; other commands on it fail with `task_removed` / `watch_removed`. `task_not_found` / `watch_not_found` means the id never existed.
Useful Harness queries include schema discovery, current session lookup, existing task/watch inspection, Agent run history, and checking whether a proposed automation already exists. Prefer this CLI over direct SQLite access.
diff --git a/storage/background.py b/storage/background.py
index bdb15ff74..b09195f28 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1103,6 +1103,16 @@ def _row_lifecycle_state(row: Any) -> Optional[str]:
return None
+def _removed_at_field(row: Any) -> dict[str, Any]:
+ """``removed_at`` for a removed definition; nothing for a live one.
+
+ Only by-id reads admit removed rows, so list and Workbench payloads keep
+ their shape.
+ """
+
+ return {"removed_at": row["deleted_at"]} if row["deleted_at"] else {}
+
+
def _definition_timed_out(metadata: Any) -> Optional[bool]:
"""Whether the scheduler stopped this definition's last fire, or ``None`` if unknown.
@@ -3462,8 +3472,19 @@ class SQLiteBackgroundTaskStore:
) -> dict[str, int]:
return self._definition_counts("scheduled", query=query, session_id=session_id)
- def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
- stmt = self._definitions_query("scheduled").where(run_definitions.c.id == definition_id).limit(1)
+ def get_scheduled_task(
+ self, definition_id: str, *, include_removed: bool = False
+ ) -> Optional[dict[str, Any]]:
+ """One live task, or with ``include_removed`` also a removed one.
+
+ A removed row reads ``lifecycle_state: removed`` and carries ``removed_at``.
+ """
+
+ stmt = (
+ self._definitions_query("scheduled", include_removed=include_removed)
+ .where(run_definitions.c.id == definition_id)
+ .limit(1)
+ )
with self.engine.connect() as conn:
row = conn.execute(stmt).mappings().first()
if row is None:
@@ -3718,8 +3739,14 @@ class SQLiteBackgroundTaskStore:
) -> dict[str, int]:
return self._definition_counts("watch", query=query, session_id=session_id)
- def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
- stmt = self._definitions_query("watch").where(run_definitions.c.id == watch_id).limit(1)
+ def get_watch(self, watch_id: str, *, include_removed: bool = False) -> Optional[dict[str, Any]]:
+ """One live watch, or with ``include_removed`` also a removed one; see ``get_scheduled_task``."""
+
+ stmt = (
+ self._definitions_query("watch", include_removed=include_removed)
+ .where(run_definitions.c.id == watch_id)
+ .limit(1)
+ )
with self.engine.connect() as conn:
row = conn.execute(stmt).mappings().first()
if row is None:
@@ -4948,6 +4975,7 @@ class SQLiteBackgroundTaskStore:
query: Optional[str] = None,
session_id: Optional[str] = None,
include_successful_finished: bool = True,
+ include_removed: bool = False,
columns: Any = None,
):
lifecycle = definition_lifecycle_expression(definition_type)
@@ -4956,11 +4984,20 @@ class SQLiteBackgroundTaskStore:
else:
# Every row carries its state, resolved by the same expression the
# counts group by.
- stmt = select(run_definitions, lifecycle.label("lifecycle_state"))
- stmt = (
- stmt.where(run_definitions.c.definition_type == definition_type)
- .where(run_definitions.c.deleted_at.is_(None))
- )
+ state = lifecycle
+ if include_removed:
+ # Only a by-id read admits removed rows, so ``removed`` never reaches
+ # a list or a count. Removal outranks every live fact: the switch, a
+ # retirement, and even a Run still in flight no longer describe what
+ # the definition will do.
+ state = case(
+ (run_definitions.c.deleted_at.is_not(None), "removed"),
+ else_=lifecycle,
+ )
+ stmt = select(run_definitions, state.label("lifecycle_state"))
+ stmt = stmt.where(run_definitions.c.definition_type == definition_type)
+ if not include_removed:
+ stmt = stmt.where(run_definitions.c.deleted_at.is_(None))
# This Session filter powers the Harness "只看本会话" chip that the
# background-work banner navigates into. Scheduled Tasks use creation
# provenance as the authoritative owner: a create-per-run or pure command
@@ -9126,6 +9163,7 @@ class SQLiteBackgroundTaskStore:
"metadata": metadata,
"resume_blocked": task_resume_block(metadata, row["session_id"]),
"lifecycle_state": _row_lifecycle_state(row),
+ **_removed_at_field(row),
}
@staticmethod
@@ -9173,6 +9211,7 @@ class SQLiteBackgroundTaskStore:
"last_exit_code": row["last_exit_code"],
"metadata": metadata,
"lifecycle_state": _row_lifecycle_state(row),
+ **_removed_at_field(row),
}
@staticmethod
@@ -9439,7 +9478,8 @@ class SQLiteBackgroundTaskStore:
else:
row["lifecycle_finished_at"] = row.get("last_finished_at")
row["next_run_at"] = compute_next_run_at(
- enabled=bool(row.get("enabled")),
+ # A removed definition keeps its switch but never fires again.
+ enabled=bool(row.get("enabled")) and state != "removed",
schedule_type=row.get("schedule_type"),
cron=row.get("cron"),
run_at=row.get("run_at"),
diff --git a/storage/read_only_query.py b/storage/read_only_query.py
index e5e43aedc..031d56d5d 100644
--- a/storage/read_only_query.py
+++ b/storage/read_only_query.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import difflib
+import re
import sqlite3
from dataclasses import dataclass
from pathlib import Path
@@ -18,11 +20,40 @@ DEFAULT_QUERY_STEP_LIMIT = 250_000
# Sibling vault tables (requests/links/grants/audit) stay queryable for inspection.
_DENIED_TABLES = frozenset({"vault_secrets"})
+# The PRAGMAs a query may run: each only describes the schema and has no setter.
+# Every other PRAGMA stays denied: some change connection state, such as ``query_only``.
+SCHEMA_PRAGMAS = frozenset(
+ {"table_list", "table_info", "table_xinfo", "index_list", "index_info", "foreign_key_list"}
+)
+
+# Harness concepts whose table name shares nothing a fuzzy match could find.
+_CONCEPT_TABLES = {
+ "task": "run_definitions",
+ "tasks": "run_definitions",
+ "scheduled_tasks": "run_definitions",
+ "watch": "run_definitions",
+ "watches": "run_definitions",
+}
+
+_NO_SUCH_TABLE = re.compile(r"no such table: (?:main\.)?(\S+)")
+_NO_SUCH_COLUMN = re.compile(r"no such column: (\S+)")
+_TABLE_REFERENCE = re.compile(
+ r"\b(?:from|join)\s+(?:main\.)?[\"`\[]?(\w+)[\"`\]]?(?:\s+(?:as\s+)?(\w+))?", re.IGNORECASE
+)
+_SQL_KEYWORDS = frozenset(
+ {
+ "as", "cross", "except", "full", "group", "having", "inner", "intersect", "join", "left",
+ "limit", "natural", "on", "order", "outer", "right", "union", "using", "where", "window",
+ }
+)
+_COLUMNS_HINT = "Read a table's columns with PRAGMA table_info(<table>)."
+
class ReadOnlyQueryError(ValueError):
- def __init__(self, message: str, *, code: str = "query_failed"):
+ def __init__(self, message: str, *, code: str = "query_failed", hint: str | None = None):
super().__init__(message)
self.code = code
+ self.hint = hint
@dataclass(frozen=True)
@@ -51,6 +82,7 @@ def run_read_only_query(
conn = sqlite3.connect(uri, uri=True)
conn.row_factory = sqlite3.Row
steps = 0
+ denials: list[tuple[int, str | None]] = []
def progress() -> int:
nonlocal steps
@@ -64,8 +96,12 @@ def run_read_only_query(
# agent_events, so roles below Member cannot query that table wholesale.
if (not allow_skill_statistics and action == sqlite3.SQLITE_READ
and arg1 in {"skill_usage_daily", "agent_events"}):
- return sqlite3.SQLITE_DENY
- return _authorizer(action, arg1, arg2, db_name, source)
+ verdict = sqlite3.SQLITE_DENY
+ else:
+ verdict = _authorizer(action, arg1, arg2, db_name, source)
+ if verdict == sqlite3.SQLITE_DENY:
+ denials.append((action, arg1))
+ return verdict
conn.set_authorizer(authorize)
conn.set_progress_handler(progress, 1000)
@@ -87,11 +123,113 @@ def run_read_only_query(
except sqlite3.DatabaseError as exc:
message = str(exc)
code = "query_interrupted" if "interrupted" in message.lower() else "query_failed"
- raise ReadOnlyQueryError(message, code=code) from exc
+ conn.set_progress_handler(None, 0)
+ hint = _error_hint(conn, statement, message, denials)
+ raise ReadOnlyQueryError(message, code=code, hint=hint) from exc
finally:
conn.close()
+def _error_hint(
+ conn: sqlite3.Connection,
+ statement: str,
+ message: str,
+ denials: list[tuple[int, str | None]],
+) -> str | None:
+ """What to change so the next attempt can succeed, when the error alone does not say."""
+
+ if denials:
+ action, name = denials[0]
+ if action == sqlite3.SQLITE_PRAGMA:
+ return (
+ "Only schema PRAGMAs are allowed: " + ", ".join(sorted(SCHEMA_PRAGMAS)) + ". "
+ + _COLUMNS_HINT
+ )
+ if action == sqlite3.SQLITE_READ:
+ return f"Rows of '{name}' are not readable through vibe data query."
+ return "vibe data query is read-only: run one SELECT or WITH statement, or a schema PRAGMA."
+ table = _NO_SUCH_TABLE.search(message)
+ column = _NO_SUCH_COLUMN.search(message)
+ if not (table or column):
+ return None
+ try:
+ schema = _schema_columns(conn)
+ except sqlite3.DatabaseError:
+ # The hint is advice; the query's own error is the answer and must survive.
+ return None
+ if table:
+ return _unknown_table_hint(schema, table.group(1))
+ return _unknown_column_hint(schema, statement, column.group(1))
+
+
+def _schema_columns(conn: sqlite3.Connection) -> dict[str, list[str]]:
+ """Every queryable table's columns, in declaration order."""
+
+ columns: dict[str, list[str]] = {}
+ rows = conn.execute(
+ "select m.name, p.name from sqlite_master m join pragma_table_info(m.name) p "
+ "where m.type = 'table' and m.name not like 'sqlite_%' order by m.name, p.cid"
+ )
+ for table, column in rows:
+ if table not in _DENIED_TABLES:
+ columns.setdefault(table, []).append(column)
+ return columns
+
+
+def _similar(name: str, candidates: list[str]) -> list[str]:
+ lowered = name.lower()
+ matches = [candidate for candidate in candidates if lowered in candidate.lower()]
+ matches += difflib.get_close_matches(name, candidates, n=3, cutoff=0.75)
+ return list(dict.fromkeys(matches))[:3]
+
+
+def _unknown_table_hint(schema: dict[str, list[str]], name: str) -> str:
+ tables = list(schema)
+ similar = _similar(name, tables)
+ concept = _CONCEPT_TABLES.get(name.lower())
+ if concept in schema and concept not in similar:
+ similar.insert(0, concept)
+ parts = [f"No table named '{name}'."]
+ if similar:
+ parts.append(f"Did you mean {', '.join(similar)}?")
+ parts.append(f"Tables: {', '.join(tables)}.")
+ parts.append(_COLUMNS_HINT)
+ return " ".join(parts)
+
+
+def _unknown_column_hint(schema: dict[str, list[str]], statement: str, reference: str) -> str:
+ qualifier, _, column = reference.rpartition(".")
+ aliases: dict[str, str] = {}
+ referenced: list[str] = []
+ for match in _TABLE_REFERENCE.finditer(statement):
+ table, alias = match.group(1), match.group(2)
+ if table not in schema:
+ continue
+ referenced.append(table)
+ aliases[table] = table
+ if alias and alias.lower() not in _SQL_KEYWORDS:
+ aliases[alias] = table
+ if qualifier in aliases:
+ referenced = [aliases[qualifier]]
+ referenced = list(dict.fromkeys(referenced))
+ owners = [table for table, columns in schema.items() if column in columns]
+ parts = []
+ if referenced:
+ parts.append(f"No column '{column}' on {', '.join(referenced)}.")
+ similar = _similar(column, [name for table in referenced for name in schema[table]])
+ if similar:
+ parts.append(f"Did you mean {', '.join(similar)}?")
+ else:
+ parts.append(f"No column '{column}' on the tables this query reads.")
+ if owners:
+ parts.append(f"'{column}' is a column of {', '.join(owners)}.")
+ for table in referenced:
+ parts.append(f"{table} columns: {', '.join(schema[table])}.")
+ if not referenced:
+ parts.append(_COLUMNS_HINT)
+ return " ".join(parts)
+
+
def _validate_single_statement(sql: str) -> str:
statement = (sql or "").strip()
if not statement:
@@ -137,5 +275,7 @@ def _authorizer(action: int, arg1: str | None, arg2: str | None, db_name: str |
if action in denied_actions:
return sqlite3.SQLITE_DENY
if action == sqlite3.SQLITE_PRAGMA:
- return sqlite3.SQLITE_DENY
+ # ``arg1`` is the PRAGMA's name as typed, for both the statement and the
+ # ``pragma_table_info(...)`` table-valued form.
+ return sqlite3.SQLITE_OK if (arg1 or "").lower() in SCHEMA_PRAGMAS else sqlite3.SQLITE_DENY
return sqlite3.SQLITE_OK
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index a6c858aab..d6dd312ad 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -8,6 +8,8 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
+import pytest
+
from config import paths
from core.system_prompt_injection import build_system_prompt_injection
from modules.im.base import MessageContext
@@ -497,6 +499,37 @@ def test_data_query_cli_omits_next_command_for_stdin_sql(monkeypatch, tmp_path,
assert payload["message"] == "More records are available. Add --page to continue."
+ ("sql", "fragments"),
+ [
+ ("select * from sessions", ["Did you mean agent_sessions", "Tables: ", "run_definitions"]),
+ ("select * from watches", ["Did you mean run_definitions"]),
+ (
+ "select m.turn_id from messages m join agent_sessions s on s.id = m.session_id",
+ ["No column 'turn_id' on messages.", "is a column of agent_events", "messages columns: id,"],
+ ),
+ (
+ "select content from agent_events",
+ ["Did you mean content_text, content_json?", "agent_events columns: id,"],
+ ),
+ ],
+)
+def test_data_query_cli_explains_unknown_tables_and_columns(
+ monkeypatch, tmp_path, capsys, sql, fragments
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ SQLiteBackgroundTaskStore().close()
+
+ args = cli.build_parser().parse_args(["data", "query", "--sql", sql])
+ assert cli.cmd_data_query(args) == 1
+
+ payload = json.loads(capsys.readouterr().err)
+ assert payload["code"] == "query_failed"
+ for fragment in fragments:
+ assert fragment in payload["hint"]
+
+
def test_data_query_cli_rejects_writes(monkeypatch, tmp_path, capsys) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index aeb15c1ad..b7e2f0cd7 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -853,6 +853,44 @@ def test_task_show_missing_id_returns_guidance(tmp_path: Path) -> None:
assert payload["help_command"] == "vibe task list"
+def test_removed_task_reads_as_removed_and_refuses_mutations(capsys) -> None:
+ store = cli.ScheduledTaskStore()
+ task = store.add_task(
+ name="Hourly summary",
+ session_key="slack::channel::C123",
+ prompt="recurring summary prompt",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ )
+ assert store.remove_task(task.id) is True
+
+ assert cli.cmd_task_show(task.id) == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["id"] == task.id
+ assert definition["name"] == "Hourly summary"
+ assert definition["lifecycle_state"] == "removed"
+ assert definition["state"] == "removed"
+ # The removed row keeps ``enabled``, but it will never fire again.
+ assert definition["next_run_at"] is None
+ removed_at = definition["removed_at"]
+ assert removed_at
+
+ update_args = cli.build_parser().parse_args(["task", "update", task.id, "--name", "Renamed"])
+ mutations = [
+ (cli.cmd_task_set_enabled, (task.id, False)),
+ (cli.cmd_task_set_enabled, (task.id, True)),
+ (cli.cmd_task_update, (update_args,)),
+ (cli.cmd_task_run, (task.id,)),
+ (cli.cmd_task_remove, (task.id,)),
+ ]
+ for command, args in mutations:
+ result, payload = _capture_stderr_json(command, *args)
+ assert result == 1
+ assert payload["code"] == "task_removed"
+ assert payload["details"] == {"task_id": task.id, "removed_at": removed_at}
+
+
def test_remote_editor_task_add_persists_authorization_context(
tmp_path: Path,
monkeypatch,
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 0846d0267..f32f7cbc0 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -1278,6 +1278,35 @@ def test_watch_show_missing_returns_structured_error() -> None:
assert payload["code"] == "watch_not_found"
+def test_removed_watch_reads_as_removed_and_refuses_mutations(capsys) -> None:
+ # Watches are removed at close-out and checked again later; a bare
+ # ``watch_not_found`` could not be told apart from a mistyped id.
+ store = ManagedWatchStore()
+ watch = _add_test_watch(store, name="Watch CI")
+ assert store.remove_watch(watch.id) is True
+
+ assert cli.cmd_watch_show(watch.id) == 0
+ definition = json.loads(capsys.readouterr().out)["definition"]
+ assert definition["id"] == watch.id
+ assert definition["name"] == "Watch CI"
+ assert definition["lifecycle_state"] == "removed"
+ assert definition["state"] == "removed"
+ removed_at = definition["removed_at"]
+ assert removed_at
+
+ mutations = [
+ (cli.cmd_watch_set_enabled, (watch.id, False)),
+ (cli.cmd_watch_set_enabled, (watch.id, True)),
+ (cli.cmd_watch_update, (_parse_watch_update([watch.id, "--name", "Renamed"]),)),
+ (cli.cmd_watch_remove, (watch.id,)),
+ ]
+ for command, args in mutations:
+ result, payload = _capture_stderr_json(command, *args)
+ assert result == 1
+ assert payload["code"] == "watch_removed"
+ assert payload["details"] == {"watch_id": watch.id, "removed_at": removed_at}
+
+
def test_watch_pause_resume_and_remove_update_store(tmp_path: Path, capsys) -> None:
store = ManagedWatchStore(tmp_path / "watches.json")
runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
diff --git a/tests/test_read_only_query.py b/tests/test_read_only_query.py
index c9077f77c..d93b085f6 100644
--- a/tests/test_read_only_query.py
+++ b/tests/test_read_only_query.py
@@ -50,16 +50,22 @@ def test_read_only_query_rejects_writes(tmp_path: Path) -> None:
assert conn.execute("select count(*) from runs").fetchone()[0] == 25
-def test_read_only_query_rejects_pragmas(tmp_path: Path) -> None:
+def test_read_only_query_allows_only_schema_pragmas(tmp_path: Path) -> None:
db_path = tmp_path / "state.sqlite"
_seed_db(db_path)
- try:
- run_read_only_query("pragma table_info(runs)", db_path=db_path, page_request=PageRequest())
- except ReadOnlyQueryError as exc:
- assert exc.code == "query_failed"
- else:
- raise AssertionError("PRAGMA should be rejected")
+ for sql in ("PRAGMA table_info(runs)", "select name from pragma_table_info('runs')"):
+ result = run_read_only_query(sql, db_path=db_path, page_request=PageRequest())
+ assert [row["name"] for row in result.rows] == ["id", "status", "created_at"]
+
+ for sql in ("pragma query_only = off", "pragma writable_schema = on", "select * from pragma_query_only"):
+ try:
+ run_read_only_query(sql, db_path=db_path, page_request=PageRequest())
+ except ReadOnlyQueryError as exc:
+ assert exc.code == "query_failed"
+ assert exc.hint.startswith("Only schema PRAGMAs are allowed")
+ else:
+ raise AssertionError(f"{sql!r} should be rejected")
def test_read_only_query_rejects_multiple_statements(tmp_path: Path) -> None:
diff --git a/vibe/cli.py b/vibe/cli.py
index 7157425e7..c91b791ed 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -131,7 +131,7 @@ from storage.pagination import (
page_sequence,
pagination_payload,
)
-from storage.read_only_query import ReadOnlyQueryError, run_read_only_query
+from storage.read_only_query import SCHEMA_PRAGMAS, ReadOnlyQueryError, run_read_only_query
from storage.settings_service import make_scope_id
logger = logging.getLogger(__name__)
@@ -2745,8 +2745,8 @@ def _task_projection_state(task: Mapping[str, object]) -> str:
if lifecycle_detail == "normal":
return "completed"
return "unknown"
- if lifecycle_state == "paused":
- return "paused"
+ if lifecycle_state in {"paused", "removed"}:
+ return lifecycle_state
return "unknown"
@@ -2816,6 +2816,40 @@ def _definition_read_store():
store.close()
+def _missing_definition_error(definition_type: str, definition_id: str, *, action: str) -> TaskCliError:
+ """Why a command found no live task or watch: it was removed, or never existed.
+
+ Watches are routinely removed at close-out and checked again later, so a bare
+ ``not_found`` would leave a caller unable to tell that from a mistyped id.
+ """
+
+ noun = "task" if definition_type == "scheduled" else "watch"
+ with _definition_read_store() as store:
+ read = store.get_scheduled_task if definition_type == "scheduled" else store.get_watch
+ definition = read(definition_id, include_removed=True)
+ removed_at = (definition or {}).get("removed_at")
+ if removed_at:
+ return TaskCliError(
+ f"{noun} '{definition_id}' was removed at {removed_at}",
+ code=f"{noun}_removed",
+ hint=(
+ f"The {noun} is already removed; nothing to do."
+ if action == "remove"
+ else f"A removed {noun} cannot be changed. Use 'vibe {noun} show {definition_id}' "
+ f"to read it, or 'vibe {noun} add' to create a new one."
+ ),
+ help_command=f"vibe {noun} show {definition_id}",
+ details={f"{noun}_id": definition_id, "removed_at": removed_at},
+ )
+ return TaskCliError(
+ f"{noun} '{definition_id}' not found",
+ code=f"{noun}_not_found",
+ hint=f"Use 'vibe {noun} list' to find a valid {noun} ID before calling {action}.",
+ help_command=f"vibe {noun} list",
+ details={f"{noun}_id": definition_id},
+ )
+
+
def _read_definition_projection(
read: Callable[[SQLiteBackgroundTaskStore], Optional[dict[str, Any]]],
) -> Optional[dict[str, Any]]:
@@ -4029,8 +4063,8 @@ def _watch_projection_state(watch: Mapping[str, object]) -> str:
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"
+ if lifecycle_state in {"paused", "removed"}:
+ return lifecycle_state
return "unknown"
@@ -4770,17 +4804,9 @@ def cmd_task_list(
def cmd_task_show(task_id: str):
with _definition_read_store() as store:
- task = store.get_scheduled_task(task_id)
+ task = store.get_scheduled_task(task_id, include_removed=True)
if task is None:
- _print_task_error(
- TaskCliError(
- f"task '{task_id}' not found",
- code="task_not_found",
- hint="Use 'vibe task list' to find a valid task ID before calling show.",
- help_command="vibe task list",
- details={"task_id": task_id},
- )
- )
+ _print_task_error(_missing_definition_error("scheduled", task_id, action="show"))
return 1
task_payload = _task_projection_payload(task)
_print_definition_payload(task_payload)
@@ -4792,15 +4818,7 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):
task = store.get_task(task_id)
if task is None:
action = "resume" if enabled else "pause"
- _print_task_error(
- TaskCliError(
- f"task '{task_id}' not found",
- code="task_not_found",
- hint=f"Use 'vibe task list' to find a valid task ID before calling {action}.",
- help_command="vibe task list",
- details={"task_id": task_id},
- )
- )
+ _print_task_error(_missing_definition_error("scheduled", task_id, action=action))
return 1
try:
updated = store.set_enabled(task_id, enabled)
@@ -4852,15 +4870,7 @@ def cmd_task_remove(task_id: str):
store = _task_store()
removed = store.remove_task(task_id)
if not removed:
- _print_task_error(
- TaskCliError(
- f"task '{task_id}' not found",
- code="task_not_found",
- hint="Use 'vibe task list' to find a valid task ID before calling remove.",
- help_command="vibe task list",
- details={"task_id": task_id},
- )
- )
+ _print_task_error(_missing_definition_error("scheduled", task_id, action="remove"))
return 1
_print_cli_payload("run_definition", removed_id=task_id)
return 0
@@ -5102,13 +5112,7 @@ def cmd_task_update(args):
store = _task_store()
task = store.get_task(args.task_id)
if task is None:
- raise TaskCliError(
- f"task '{args.task_id}' not found",
- code="task_not_found",
- hint="Use 'vibe task list' to find a valid task ID before calling update.",
- help_command="vibe task list",
- details={"task_id": args.task_id},
- )
+ raise _missing_definition_error("scheduled", args.task_id, action="update")
# A definition is either a scheduled Agent message or a scheduled command, and
# the two shapes are not convertible in place: switching would leave the other
@@ -5594,15 +5598,7 @@ def cmd_task_run(task_id: str):
store = _task_store()
task = store.get_task(task_id)
if task is None:
- _print_task_error(
- TaskCliError(
- f"task '{task_id}' not found",
- code="task_not_found",
- hint="Use 'vibe task list' to find a valid task ID before calling run.",
- help_command="vibe task list",
- details={"task_id": task_id},
- )
- )
+ _print_task_error(_missing_definition_error("scheduled", task_id, action="run"))
return 1
request = _task_request_store().enqueue_task_run(task.id, task=task)
_print_cli_payload(
@@ -7998,7 +7994,9 @@ def cmd_data_query(args):
_print_cli_payload("data_query", **payload)
return 0
except ReadOnlyQueryError as exc:
- _print_task_error(TaskCliError(str(exc), code=exc.code, help_command="vibe data query --help"))
+ _print_task_error(
+ TaskCliError(str(exc), code=exc.code, hint=exc.hint, help_command="vibe data query --help")
+ )
return 1
except Exception as exc:
_print_task_error(exc, help_command="vibe data query --help")
@@ -11700,17 +11698,9 @@ def cmd_watch_list(
def cmd_watch_show(watch_id: str):
with _definition_read_store() as store:
- watch = store.get_watch(watch_id)
+ watch = store.get_watch(watch_id, include_removed=True)
if watch is None:
- _print_task_error(
- TaskCliError(
- f"watch '{watch_id}' not found",
- code="watch_not_found",
- hint="Use 'vibe watch list' to find a valid watch ID before calling show.",
- help_command="vibe watch list",
- details={"watch_id": watch_id},
- )
- )
+ _print_task_error(_missing_definition_error("watch", watch_id, action="show"))
return 1
watch_payload = _watch_projection_payload(watch)
_print_definition_payload(watch_payload)
@@ -11722,15 +11712,7 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):
watch = store.get_watch(watch_id)
if watch is None:
action = "resume" if enabled else "pause"
- _print_task_error(
- TaskCliError(
- f"watch '{watch_id}' not found",
- code="watch_not_found",
- hint=f"Use 'vibe watch list' to find a valid watch ID before calling {action}.",
- help_command="vibe watch list",
- details={"watch_id": watch_id},
- )
- )
+ _print_task_error(_missing_definition_error("watch", watch_id, action=action))
return 1
try:
updated = store.set_enabled(watch_id, enabled)
@@ -11767,13 +11749,7 @@ def cmd_watch_update(args):
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},
- )
+ raise _missing_definition_error("watch", args.watch_id, action="update")
if getattr(args, "reset_delivery", False) and (
getattr(args, "post_to", None) is not None
@@ -12176,15 +12152,7 @@ def cmd_watch_remove(watch_id: str):
store = _watch_store()
removed = store.remove_watch(watch_id)
if not removed:
- _print_task_error(
- TaskCliError(
- f"watch '{watch_id}' not found",
- code="watch_not_found",
- hint="Use 'vibe watch list' to find a valid watch ID before calling remove.",
- help_command="vibe watch list",
- details={"watch_id": watch_id},
- )
- )
+ _print_task_error(_missing_definition_error("watch", watch_id, action="remove"))
return 1
_print_cli_payload("run_definition", removed_id=watch_id)
return 0
@@ -18798,11 +18766,19 @@ def build_parser():
"query",
help="Run one read-only SQL query",
description="Run one guarded read-only SQL query against the local SQLite state database.",
+ epilog=(
+ "Discover the schema before guessing names:\n"
+ " vibe data query --sql \"select group_concat(name, ', ') as tables from pragma_table_list where schema = 'main'\"\n"
+ " vibe data query --sql \"select group_concat(name, ', ') as columns from pragma_table_info('run_definitions')\"\n"
+ " vibe data query --sql \"PRAGMA table_info(run_definitions)\" --limit 100 # with types and keys\n"
+ f"Only schema PRAGMAs run: {', '.join(sorted(SCHEMA_PRAGMAS))}.\n"
+ "Tasks and Watches are rows of run_definitions (definition_type is scheduled or watch)."
+ ),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe data query --help",
)
sql_group = data_query_parser.add_mutually_exclusive_group(required=True)
- sql_group.add_argument("--sql", help="SQL SELECT/WITH statement to run.")
+ sql_group.add_argument("--sql", help="SQL SELECT/WITH statement or schema PRAGMA to run.")
sql_group.add_argument("--sql-file", help="Read SQL from a UTF-8 file, or '-' for stdin.")
_add_pagination_args(data_query_parser, help_command="vibe data query --help")
_add_json_noop(data_query_parser)