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
Add paginated CLI data queries
cyh15940c1a48de
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 371be2896..6176c8ce1 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -24,6 +24,7 @@ from modules.im import MessageContextfrom storage.db import create_sqlite_enginefrom storage.background import SQLiteBackgroundTaskStorefrom storage.models import agent_sessions, scope_settings, scopes+from storage.pagination import PageRequest, PageResult, page_sequencelogger = logging.getLogger(__name__)@@ -784,6 +785,64 @@ class TaskExecutionStore:def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:if self._sqlite is not None:return self._sqlite.list_runs(status=status)+ return self._list_file_runs(status=status)++ def list_runs_page(+ self,+ *,+ status: Optional[str] = None,+ run_type: Optional[str] = None,+ agent_name: Optional[str] = None,+ agent_backend: Optional[str] = None,+ session_id: Optional[str] = None,+ definition_id: Optional[str] = None,+ created_after: Optional[str] = None,+ created_before: Optional[str] = None,+ query: Optional[str] = None,+ page_request: PageRequest | None,+ newest_first: bool = True,+ ) -> PageResult[dict[str, Any]]:+ if self._sqlite is not None:+ return self._sqlite.list_runs_page(+ status=status,+ run_type=run_type,+ agent_name=agent_name,+ agent_backend=agent_backend,+ session_id=session_id,+ definition_id=definition_id,+ created_after=created_after,+ created_before=created_before,+ query=query,+ page_request=page_request,+ newest_first=newest_first,+ )+ runs = self._list_file_runs(status=status)+ if run_type:+ runs = [item for item in runs if (item.get("run_type") or item.get("request_type")) == run_type]+ if agent_name:+ runs = [item for item in runs if item.get("agent_name") == agent_name]+ if agent_backend:+ runs = [item for item in runs if item.get("agent_backend") == agent_backend]+ if session_id:+ runs = [item for item in runs if item.get("session_id") == session_id]+ if definition_id:+ runs = [item for item in runs if (item.get("definition_id") or item.get("task_id")) == definition_id]+ if created_after:+ runs = [item for item in runs if str(item.get("created_at") or "") >= created_after]+ if created_before:+ runs = [item for item in runs if str(item.get("created_at") or "") <= created_before]+ if query:+ needle = query.casefold()+ fields = ("id", "definition_id", "task_id", "agent_name", "session_id", "prompt", "message", "result_text", "error", "stdout", "stderr")+ runs = [+ item+ for item in runs+ if any(needle in str(item.get(field) or "").casefold() for field in fields)+ ]+ runs = sorted(runs, key=lambda item: (item.get("created_at") or "", item.get("id") or ""), reverse=newest_first)+ return page_sequence(runs, page_request)++ def _list_file_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:status_filter = _run_file_state_for_status(status)runs: list[dict[str, Any]] = []for state, directory in {diff --git a/core/show_pages.py b/core/show_pages.pyindex 07908228d..30972ca18 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -8,13 +8,14 @@ from pathlib import Pathfrom typing import Anyfrom urllib.parse import urljoin-from sqlalchemy import insert, select, update+from sqlalchemy import insert, or_, select, updatefrom config import pathsfrom config.v2_config import V2Configfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_configfrom storage.models import show_pages+from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_oneVISIBILITY_PRIVATE = "private"VISIBILITY_PUBLIC = "public"@@ -149,15 +150,45 @@ class ShowPageStore:return _page_from_row(row) if row else Nonedef list(self, *, visibility: str | None = None) -> list[ShowPage]:+ result = self.list_page(visibility=visibility, page_request=None)+ return result.items++ def list_page(+ self,+ *,+ visibility: str | None = None,+ session_id: str | None = None,+ updated_after: str | None = None,+ updated_before: str | None = None,+ query: str | None = None,+ page_request: PageRequest | None,+ ) -> PageResult[ShowPage]:if visibility is not None and visibility not in VISIBILITIES:raise ShowPageError(f"Unsupported visibility: {visibility}", code="invalid_visibility")statement = select(show_pages)if visibility is not None:statement = statement.where(show_pages.c.visibility == visibility)+ if session_id:+ statement = statement.where(show_pages.c.session_id.like(f"{session_id}%"))+ if updated_after:+ statement = statement.where(show_pages.c.updated_at >= updated_after)+ if updated_before:+ statement = statement.where(show_pages.c.updated_at <= updated_before)+ if query:+ pattern = f"%{query}%"+ statement = statement.where(+ or_(+ show_pages.c.session_id.like(pattern),+ show_pages.c.share_id.like(pattern),+ show_pages.c.visibility.like(pattern),+ )+ )statement = statement.order_by(show_pages.c.updated_at.desc(), show_pages.c.session_id.asc())+ if page_request is not None:+ statement = statement.offset(page_request.offset).limit(page_request.limit + 1)with self.engine.connect() as conn:rows = conn.execute(statement).mappings().all()- return [_page_from_row(row) for row in rows]+ return page_result_from_limit_plus_one((_page_from_row(row) for row in rows), page_request)def ensure(self, session_id: str) -> ShowPage:session_id = validate_session_id(session_id)diff --git a/docs/plans/cli-query-pagination.md b/docs/plans/cli-query-pagination.mdnew file mode 100644index 000000000..5716e726b--- /dev/null+++ b/docs/plans/cli-query-pagination.md@@ -0,0 +1,107 @@+# CLI Query Pagination and Read-Only SQL Plan++## Background++Agent-facing list commands currently return all matching records. `vibe runs list`+only exposes `--status`, while `vibe show list` only exposes `--visibility`.+As Agent Runs and Show Pages accumulate, these commands need bounded defaults,+clear next-page hints, and a reusable path for future list commands.++Agents also need a more flexible exploration path for ad hoc conditions that do+not deserve first-class CLI flags. That path should be read-only SQL, not a+write-capable database escape hatch.++## Goals++- Add a shared pagination contract for CLI list/query commands.+- Default list commands to 20 records and include a next-page hint when more+ records exist.+- Add high-value filters to `vibe runs list` and `vibe show list`.+- Add a guarded `vibe data query` read-only SQLite query command.+- Keep simple, stable CLI flags as the primary day-to-day interface; use SQL for+ exploratory and low-frequency conditions.++## Design++### Shared Pagination++Introduce a small reusable module with:++- `PageRequest(page=1, limit=20, max_limit=100)`+- `PageResult(items, page_request, has_more)`+- helpers to clamp/validate CLI input, slice `limit + 1`, and build JSON+ pagination payloads.++All list/query commands should return:++- `pagination.page`+- `pagination.limit`+- `pagination.returned`+- `pagination.has_more`+- `pagination.next_page`+- `pagination.next_command`++Text output should append a concise "more records" hint when `has_more` is true.++### Runs List++Extend `vibe runs list` with:++- `--page`, `--limit`, `--all`+- `--status`+- `--type`+- `--agent`+- `--backend`+- `--session-id`+- `--definition-id`+- `--created-after`+- `--created-before`+- `--q`++SQLite-backed runs should filter in SQL. File-backed fallback can filter in+memory; it is compatibility-only.++### Show Page List++Extend `vibe show list` with:++- `--page`, `--limit`, `--all`+- `--visibility`+- `--session-id`+- `--updated-after`+- `--updated-before`+- `--q`++`ShowPageStore.list()` should support these filters and pagination using the+same shared result type.++### Read-Only SQL++Add `vibe data query`:++```bash+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+```++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+- execute one statement with `execute()`, never `executescript()`+- use progress handler limits to avoid runaway queries+- force pagination/default limit behavior on result output++The SQL command is Agent-facing and should emit JSON by default through the same+CLI payload style.++## Validation++- Unit tests for pagination helpers.+- Runs store tests for filtering and pagination.+- Show Page store/CLI tests for pagination hints and filters.+- SQL query tests for SELECT success and write/DDL/multi-statement rejection.+- CLI parser tests for new arguments.+- Targeted ruff and pytest checks.diff --git a/storage/background.py b/storage/background.pyindex e3cef5e21..94833aafb 100644--- a/storage/background.py+++ b/storage/background.py@@ -6,12 +6,13 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Optional-from sqlalchemy import insert, select, update+from sqlalchemy import insert, or_, select, updatefrom config import pathsfrom storage.db import SqliteInvalidationProbe, create_sqlite_enginefrom storage.migrations import background_tables_ready, initialize_background_tablesfrom storage.models import agent_runs, run_definitions+from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_onelogger = logging.getLogger(__name__)@@ -161,12 +162,93 @@ class SQLiteBackgroundTaskStore:conn.execute(insert(agent_runs).values(**values))def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:+ stmt = self._runs_query(status=status).order_by(agent_runs.c.created_at, agent_runs.c.id)+ with self.engine.connect() as conn:+ return [self._run_from_row(row) for row in conn.execute(stmt).mappings()]++ def list_runs_page(+ self,+ *,+ status: Optional[str] = None,+ run_type: Optional[str] = None,+ agent_name: Optional[str] = None,+ agent_backend: Optional[str] = None,+ session_id: Optional[str] = None,+ definition_id: Optional[str] = None,+ created_after: Optional[str] = None,+ created_before: Optional[str] = None,+ query: Optional[str] = None,+ page_request: PageRequest | None,+ newest_first: bool = True,+ ) -> PageResult[dict[str, Any]]:+ stmt = self._runs_query(+ status=status,+ run_type=run_type,+ agent_name=agent_name,+ agent_backend=agent_backend,+ session_id=session_id,+ definition_id=definition_id,+ created_after=created_after,+ created_before=created_before,+ query=query,+ )+ if newest_first:+ stmt = stmt.order_by(agent_runs.c.created_at.desc(), agent_runs.c.id.desc())+ else:+ stmt = stmt.order_by(agent_runs.c.created_at, agent_runs.c.id)+ if page_request is not None:+ stmt = stmt.offset(page_request.offset).limit(page_request.limit + 1)+ with self.engine.connect() as conn:+ rows = [self._run_from_row(row) for row in conn.execute(stmt).mappings()]+ return page_result_from_limit_plus_one(rows, page_request)++ def _runs_query(+ self,+ *,+ status: Optional[str] = None,+ run_type: Optional[str] = None,+ agent_name: Optional[str] = None,+ agent_backend: Optional[str] = None,+ session_id: Optional[str] = None,+ definition_id: Optional[str] = None,+ created_after: Optional[str] = None,+ created_before: Optional[str] = None,+ query: Optional[str] = None,+ ):stmt = select(agent_runs)if status:stmt = stmt.where(agent_runs.c.status.in_(_status_query_values(status)))- stmt = stmt.order_by(agent_runs.c.created_at, agent_runs.c.id)- with self.engine.connect() as conn:- return [self._run_from_row(row) for row in conn.execute(stmt).mappings()]+ if run_type:+ stmt = stmt.where(agent_runs.c.run_type == run_type)+ if agent_name:+ stmt = stmt.where(agent_runs.c.agent_name == agent_name)+ if agent_backend:+ stmt = stmt.where(agent_runs.c.agent_backend == agent_backend)+ if session_id:+ stmt = stmt.where(agent_runs.c.session_id == session_id)+ if definition_id:+ stmt = stmt.where(agent_runs.c.definition_id == definition_id)+ if created_after:+ stmt = stmt.where(agent_runs.c.created_at >= created_after)+ if created_before:+ stmt = stmt.where(agent_runs.c.created_at <= created_before)+ if query:+ pattern = f"%{query}%"+ stmt = stmt.where(+ or_(+ agent_runs.c.id.like(pattern),+ agent_runs.c.definition_id.like(pattern),+ agent_runs.c.agent_name.like(pattern),+ agent_runs.c.session_id.like(pattern),+ agent_runs.c.prompt.like(pattern),+ agent_runs.c.message.like(pattern),+ agent_runs.c.result_text.like(pattern),+ agent_runs.c.error.like(pattern),+ agent_runs.c.stdout.like(pattern),+ agent_runs.c.stderr.like(pattern),+ )+ )+ return stmtdef get_run(self, run_id: str) -> Optional[dict[str, Any]]:with self.engine.connect() as conn:diff --git a/storage/pagination.py b/storage/pagination.pynew file mode 100644index 000000000..2f2d66e4c--- /dev/null+++ b/storage/pagination.py@@ -0,0 +1,98 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Generic, Iterable, Sequence, TypeVar++T = TypeVar("T")++DEFAULT_PAGE_LIMIT = 20+MAX_PAGE_LIMIT = 100+++@dataclass(frozen=True)+class PageRequest:+ page: int = 1+ limit: int = DEFAULT_PAGE_LIMIT++ @property+ def offset(self) -> int:+ return (self.page - 1) * self.limit+++@dataclass(frozen=True)+class PageResult(Generic[T]):+ items: list[T]+ page: int+ limit: int+ has_more: bool++ @property+ def next_page(self) -> int | None:+ return self.page + 1 if self.has_more else None+++def make_page_request(+ *,+ page: int | None = None,+ limit: int | None = None,+ all_items: bool = False,+ default_limit: int = DEFAULT_PAGE_LIMIT,+ max_limit: int = MAX_PAGE_LIMIT,+) -> PageRequest | None:+ if all_items:+ return None+ resolved_page = page if page is not None else 1+ resolved_limit = limit if limit is not None else default_limit+ if resolved_page < 1:+ raise ValueError("page must be >= 1")+ if resolved_limit < 1:+ raise ValueError("limit must be >= 1")+ if resolved_limit > max_limit:+ raise ValueError(f"limit must be <= {max_limit}")+ return PageRequest(page=resolved_page, limit=resolved_limit)+++def page_sequence(items: Sequence[T], page_request: PageRequest | None) -> PageResult[T]:+ if page_request is None:+ values = list(items)+ return PageResult(items=values, page=1, limit=len(values), has_more=False)+ start = page_request.offset+ limit = page_request.limit+ window = list(items[start : start + limit + 1])+ return PageResult(+ items=window[:limit],+ page=page_request.page,+ limit=page_request.limit,+ has_more=len(window) > limit,+ )+++def page_limit_plus_one(page_request: PageRequest | None) -> int | None:+ if page_request is None:+ return None+ return page_request.limit + 1+++def page_result_from_limit_plus_one(items: Iterable[T], page_request: PageRequest | None) -> PageResult[T]:+ values = list(items)+ if page_request is None:+ return PageResult(items=values, page=1, limit=len(values), has_more=False)+ return PageResult(+ items=values[: page_request.limit],+ page=page_request.page,+ limit=page_request.limit,+ has_more=len(values) > page_request.limit,+ )+++def pagination_payload(result: PageResult[object], *, next_command: str | None = None) -> dict:+ payload = {+ "page": result.page,+ "limit": result.limit,+ "returned": len(result.items),+ "has_more": result.has_more,+ "next_page": result.next_page,+ }+ if next_command:+ payload["next_command"] = next_command+ return payloaddiff --git a/storage/read_only_query.py b/storage/read_only_query.pynew file mode 100644index 000000000..09b75b7f7--- /dev/null+++ b/storage/read_only_query.py@@ -0,0 +1,118 @@+from __future__ import annotations++import sqlite3+from dataclasses import dataclass+from pathlib import Path+from typing import Any+from urllib.parse import quote++from config import paths+from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config+from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one++DEFAULT_QUERY_STEP_LIMIT = 250_000+++class ReadOnlyQueryError(ValueError):+ def __init__(self, message: str, *, code: str = "query_failed"):+ super().__init__(message)+ self.code = code+++@dataclass(frozen=True)+class QueryResult:+ columns: list[str]+ rows: list[dict[str, Any]]+ pagination: PageResult[dict[str, Any]]+++def run_read_only_query(+ sql: str,+ *,+ page_request: PageRequest | None,+ db_path: Path | None = None,+ step_limit: int = DEFAULT_QUERY_STEP_LIMIT,+) -> QueryResult:+ statement = _validate_single_statement(sql)+ resolved_db_path = db_path or paths.get_sqlite_state_path()+ if db_path is None:+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))+ uri = f"file:{quote(str(resolved_db_path), safe='/')}?mode=ro"+ conn = sqlite3.connect(uri, uri=True)+ conn.row_factory = sqlite3.Row+ steps = 0++ def progress() -> int:+ nonlocal steps+ steps += 1+ return 1 if steps > step_limit else 0++ try:+ conn.execute("PRAGMA query_only = ON")+ conn.set_authorizer(_authorizer)+ conn.set_progress_handler(progress, 1000)+ cursor = conn.execute(statement)+ columns = [item[0] for item in cursor.description or []]+ if page_request is None:+ raw_rows = cursor.fetchall()+ else:+ skip = page_request.offset+ while skip > 0:+ chunk = cursor.fetchmany(min(skip, 1000))+ if not chunk:+ break+ skip -= len(chunk)+ raw_rows = cursor.fetchmany(page_request.limit + 1)+ rows = [dict(row) for row in raw_rows]+ page = page_result_from_limit_plus_one(rows, page_request)+ return QueryResult(columns=columns, rows=page.items, pagination=page)+ 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+ finally:+ conn.close()+++def _validate_single_statement(sql: str) -> str:+ statement = (sql or "").strip()+ if not statement:+ raise ReadOnlyQueryError("SQL statement is required.", code="missing_sql")+ return statement+++def _authorizer(action: int, arg1: str | None, arg2: str | None, db_name: str | None, source: str | None) -> int:+ del arg1, arg2, db_name, source+ denied_actions = {+ sqlite3.SQLITE_ALTER_TABLE,+ sqlite3.SQLITE_ATTACH,+ sqlite3.SQLITE_CREATE_INDEX,+ sqlite3.SQLITE_CREATE_TABLE,+ sqlite3.SQLITE_CREATE_TEMP_INDEX,+ sqlite3.SQLITE_CREATE_TEMP_TABLE,+ sqlite3.SQLITE_CREATE_TEMP_TRIGGER,+ sqlite3.SQLITE_CREATE_TEMP_VIEW,+ sqlite3.SQLITE_CREATE_TRIGGER,+ sqlite3.SQLITE_CREATE_VIEW,+ sqlite3.SQLITE_CREATE_VTABLE,+ sqlite3.SQLITE_DELETE,+ sqlite3.SQLITE_DETACH,+ sqlite3.SQLITE_DROP_INDEX,+ sqlite3.SQLITE_DROP_TABLE,+ sqlite3.SQLITE_DROP_TEMP_INDEX,+ sqlite3.SQLITE_DROP_TEMP_TABLE,+ sqlite3.SQLITE_DROP_TEMP_TRIGGER,+ sqlite3.SQLITE_DROP_TEMP_VIEW,+ sqlite3.SQLITE_DROP_TRIGGER,+ sqlite3.SQLITE_DROP_VIEW,+ sqlite3.SQLITE_DROP_VTABLE,+ sqlite3.SQLITE_INSERT,+ sqlite3.SQLITE_REINDEX,+ sqlite3.SQLITE_TRANSACTION,+ sqlite3.SQLITE_UPDATE,+ }+ if action in denied_actions:+ return sqlite3.SQLITE_DENY+ if action == sqlite3.SQLITE_PRAGMA:+ return sqlite3.SQLITE_DENY+ return sqlite3.SQLITE_OKdiff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.pynew file mode 100644index 000000000..7437e52b6--- /dev/null+++ b/tests/test_cli_pagination.py@@ -0,0 +1,123 @@+from __future__ import annotations++import json++from config import paths+from storage.background import SQLiteBackgroundTaskStore+from vibe import cli+++def test_runs_list_cli_defaults_to_first_page(monkeypatch, tmp_path, capsys) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ store = SQLiteBackgroundTaskStore()+ try:+ for index in range(25):+ store.enqueue_run(+ {+ "id": f"run-{index:02d}",+ "request_type": "agent_run",+ "status": "succeeded",+ "agent_name": "helper",+ "agent_backend": "codex",+ "session_id": "ses-alpha",+ "message": f"message {index}",+ "created_at": f"2026-05-25T00:{index:02d}:00+00:00",+ "updated_at": f"2026-05-25T00:{index:02d}:00+00:00",+ }+ )+ finally:+ store.close()++ args = cli.build_parser().parse_args(["runs", "list", "--brief"])+ assert cli.cmd_runs_list(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert payload["kind"] == "agent_runs"+ assert len(payload["runs"]) == 20+ assert payload["runs"][0]["id"] == "run-24"+ assert payload["pagination"]["has_more"] is True+ assert payload["pagination"]["next_command"] == "vibe runs list --brief --page 2 --limit 20"+ assert "还有更多记录" in payload["message"]+++def test_runs_list_cli_filters_status_and_query(monkeypatch, tmp_path, capsys) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ store = SQLiteBackgroundTaskStore()+ try:+ store.enqueue_run(+ {+ "id": "run-success",+ "request_type": "agent_run",+ "status": "succeeded",+ "agent_name": "helper",+ "agent_backend": "codex",+ "session_id": "ses-alpha",+ "message": "weekly report",+ "created_at": "2026-05-25T00:00:00+00:00",+ "updated_at": "2026-05-25T00:00:00+00:00",+ }+ )+ store.enqueue_run(+ {+ "id": "run-failed",+ "request_type": "agent_run",+ "status": "failed",+ "agent_name": "helper",+ "agent_backend": "codex",+ "session_id": "ses-alpha",+ "message": "weekly report",+ "created_at": "2026-05-25T00:01:00+00:00",+ "updated_at": "2026-05-25T00:01:00+00:00",+ }+ )+ finally:+ store.close()++ args = cli.build_parser().parse_args(["runs", "list", "--status", "succeeded", "--q", "weekly", "--brief"])+ assert cli.cmd_runs_list(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert [item["id"] for item in payload["runs"]] == ["run-success"]+ assert payload["pagination"]["has_more"] is False+++def test_data_query_cli_runs_read_only_sql(monkeypatch, tmp_path, capsys) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ store = SQLiteBackgroundTaskStore()+ try:+ store.enqueue_run(+ {+ "id": "run-1",+ "request_type": "agent_run",+ "status": "succeeded",+ "created_at": "2026-05-25T00:00:00+00:00",+ "updated_at": "2026-05-25T00:00:00+00:00",+ }+ )+ finally:+ store.close()++ args = cli.build_parser().parse_args(["data", "query", "--sql", "select id, status from agent_runs"])+ assert cli.cmd_data_query(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert payload["kind"] == "data_query"+ assert payload["columns"] == ["id", "status"]+ assert payload["rows"] == [{"id": "run-1", "status": "succeeded"}]+++def test_data_query_cli_rejects_writes(monkeypatch, tmp_path, capsys) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ store = SQLiteBackgroundTaskStore()+ store.close()++ args = cli.build_parser().parse_args(["data", "query", "--sql", "delete from agent_runs"])+ assert cli.cmd_data_query(args) == 1++ payload = json.loads(capsys.readouterr().err)+ assert payload["ok"] is False+ assert payload["help_command"] == "vibe data query --help"diff --git a/tests/test_pagination.py b/tests/test_pagination.pynew file mode 100644index 000000000..0536c805a--- /dev/null+++ b/tests/test_pagination.py@@ -0,0 +1,28 @@+from __future__ import annotations++import pytest++from storage.pagination import make_page_request, page_sequence, pagination_payload+++def test_page_sequence_uses_limit_plus_one_for_has_more() -> None:+ request = make_page_request(page=2, limit=3)++ result = page_sequence(list(range(8)), request)+ payload = pagination_payload(result, next_command="vibe runs list --page 3 --limit 3")++ assert result.items == [3, 4, 5]+ assert result.has_more is True+ assert result.next_page == 3+ assert payload["returned"] == 3+ assert payload["next_command"] == "vibe runs list --page 3 --limit 3"+++def test_make_page_request_validates_bounds() -> None:+ with pytest.raises(ValueError, match="page must be >= 1"):+ make_page_request(page=0)++ with pytest.raises(ValueError, match="limit must be <= 100"):+ make_page_request(limit=101)++ assert make_page_request(all_items=True) is Nonediff --git a/tests/test_read_only_query.py b/tests/test_read_only_query.pynew file mode 100644index 000000000..c9077f77c--- /dev/null+++ b/tests/test_read_only_query.py@@ -0,0 +1,74 @@+from __future__ import annotations++import sqlite3+from pathlib import Path++from storage.pagination import PageRequest+from storage.read_only_query import ReadOnlyQueryError, run_read_only_query+++def _seed_db(path: Path) -> None:+ with sqlite3.connect(path) as conn:+ conn.execute("create table runs (id text primary key, status text, created_at text)")+ for index in range(25):+ conn.execute(+ "insert into runs (id, status, created_at) values (?, ?, ?)",+ (f"run-{index:02d}", "succeeded", f"2026-05-25T00:{index:02d}:00+00:00"),+ )+ conn.commit()+++def test_read_only_query_pages_select_results(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_db(db_path)++ result = run_read_only_query(+ "select id, status from runs order by created_at desc",+ db_path=db_path,+ page_request=PageRequest(page=1, limit=20),+ )++ assert result.columns == ["id", "status"]+ assert len(result.rows) == 20+ assert result.rows[0]["id"] == "run-24"+ assert result.pagination.has_more is True+ assert result.pagination.next_page == 2+++def test_read_only_query_rejects_writes(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_db(db_path)++ try:+ run_read_only_query("delete from runs", db_path=db_path, page_request=PageRequest())+ except ReadOnlyQueryError as exc:+ assert exc.code == "query_failed"+ else:+ raise AssertionError("write SQL should be rejected")++ with sqlite3.connect(db_path) as conn:+ assert conn.execute("select count(*) from runs").fetchone()[0] == 25+++def test_read_only_query_rejects_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")+++def test_read_only_query_rejects_multiple_statements(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_db(db_path)++ try:+ run_read_only_query("select 1; select 2", db_path=db_path, page_request=PageRequest())+ except ReadOnlyQueryError as exc:+ assert exc.code == "query_failed"+ else:+ raise AssertionError("multiple statements should be rejected")diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex a7f993b07..7fae77052 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -22,6 +22,7 @@ from core.scheduled_tasks import (from modules.im import MessageContextfrom storage.db import create_sqlite_enginefrom storage.background import SQLiteBackgroundTaskStore+from storage.pagination import PageRequestclass _StubScheduler:@@ -560,7 +561,7 @@ def test_build_context_separates_delivery_target_from_session_target() -> None:assert context.thread_id == "171717.123"assert context.platform_specific["delivery_override"]["thread_id"] is None- assert context.platform_specific["delivery_scope_session_key"] == "slack::C123"+ assert context.platform_specific["delivery_scope_session_key"] == "slack::channel::C123"assert context.platform_specific["scheduled_delivery_alias"]["mode"] == "sent_message"assert context.platform_specific["scheduled_delivery_alias"]["clear_source"] is False@@ -694,6 +695,43 @@ def test_request_store_file_backend_filters_public_run_statuses(tmp_path: Path)assert [item["id"] for item in store.list_runs(status="completed")] == [succeeded.id]+def test_sqlite_run_listing_pages_and_filters(tmp_path: Path) -> None:+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+ try:+ for index in range(25):+ sqlite.enqueue_run(+ {+ "id": f"run-{index:02d}",+ "request_type": "agent_run" if index % 2 == 0 else "hook_send",+ "status": "succeeded",+ "agent_name": "helper" if index % 2 == 0 else "ops",+ "agent_backend": "codex",+ "session_id": "ses-alpha" if index < 20 else "ses-beta",+ "message": f"message {index}",+ "created_at": f"2026-05-25T00:{index:02d}:00+00:00",+ "updated_at": f"2026-05-25T00:{index:02d}:00+00:00",+ }+ )++ first_page = sqlite.list_runs_page(page_request=PageRequest(page=1, limit=20))+ second_page = sqlite.list_runs_page(page_request=PageRequest(page=2, limit=20))+ filtered = sqlite.list_runs_page(+ agent_name="helper",+ session_id="ses-beta",+ created_after="2026-05-25T00:20:00+00:00",+ query="message 24",+ page_request=PageRequest(page=1, limit=20),+ )++ assert first_page.has_more is True+ assert [item["id"] for item in first_page.items[:2]] == ["run-24", "run-23"]+ assert second_page.has_more is False+ assert [item["id"] for item in second_page.items] == ["run-04", "run-03", "run-02", "run-01", "run-00"]+ assert [item["id"] for item in filtered.items] == ["run-24"]+ finally:+ sqlite.close()++def test_runtime_session_reservation_uses_legacy_scope_backend(tmp_path: Path, monkeypatch) -> None:db_path = tmp_path / "state" / "vibe.sqlite"monkeypatch.setattr(paths, "get_state_dir", lambda: db_path.parent)diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex a95ee1bb2..e91708b08 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -3,6 +3,7 @@ import jsonfrom config import pathsfrom config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Configfrom core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir, show_page_payload+from storage.pagination import PageRequestfrom vibe import cli@@ -111,6 +112,29 @@ def test_store_lists_pages_by_updated_time_and_visibility(monkeypatch, tmp_path)store.close()+def test_store_lists_show_pages_with_page_and_query(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _save_config()++ store = ShowPageStore()+ try:+ for index in range(25):+ store.ensure(f"ses-{index:02d}")++ first_page = store.list_page(page_request=PageRequest(page=1, limit=20))+ second_page = store.list_page(page_request=PageRequest(page=2, limit=20))+ filtered = store.list_page(session_id="ses-2", query="ses-24", page_request=PageRequest(page=1, limit=20))++ assert first_page.has_more is True+ assert len(first_page.items) == 20+ assert second_page.has_more is False+ assert len(second_page.items) == 5+ assert [page.session_id for page in filtered.items] == ["ses-24"]+ finally:+ store.close()++def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))page_dir = ensure_show_page_dir("ses123")@@ -171,6 +195,29 @@ def test_show_list_cli_json_reports_existing_pages(monkeypatch, tmp_path, capsysassert public_page["active_url"].startswith("https://alex.avibe.bot/p/")+def test_show_list_cli_json_reports_pagination(monkeypatch, tmp_path, capsys):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _save_config()++ store = ShowPageStore()+ try:+ for index in range(25):+ store.ensure(f"ses-page-{index:02d}")+ finally:+ store.close()++ args = cli.build_parser().parse_args(["show", "list", "--json"])+ assert cli.cmd_show_list(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert payload["count"] == 20+ assert payload["pagination"]["has_more"] is True+ assert payload["pagination"]["next_page"] == 2+ assert "vibe show list --json --page 2 --limit 20" == payload["pagination"]["next_command"]+ assert "还有更多记录" in payload["message"]++def test_show_list_cli_filters_visibility(monkeypatch, tmp_path, capsys):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/vibe/cli.py b/vibe/cli.pyindex beb5564a0..d77e2be89 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -11,7 +11,7 @@ import signalimport subprocessimport sysimport time-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom textwrap import dedentfrom typing import NamedTuple, Optional@@ -59,6 +59,8 @@ from vibe.upgrade import (from storage.db import create_sqlite_enginefrom storage.background import normalize_run_statusfrom storage.models import scope_settings+from storage.pagination import DEFAULT_PAGE_LIMIT, PageRequest, make_page_request, pagination_payload+from storage.read_only_query import ReadOnlyQueryError, run_read_only_queryfrom storage.settings_service import make_scope_idlogger = logging.getLogger(__name__)@@ -163,6 +165,73 @@ def _print_cli_payload(kind: str, **fields) -> None:print(json.dumps(_cli_payload(kind, **fields), indent=2))+def _add_pagination_args(parser, *, help_command: str) -> None:+ parser.add_argument("--page", type=int, help="Page number to return. Defaults to 1.")+ parser.add_argument("--limit", type=int, help=f"Rows per page. Defaults to {DEFAULT_PAGE_LIMIT}.")+ parser.add_argument("--all", action="store_true", help="Return all matching rows without pagination.")+ parser.error_help_command = help_command+++def _page_request_from_args(args, *, help_command: str) -> PageRequest | None:+ try:+ return make_page_request(+ page=getattr(args, "page", None),+ limit=getattr(args, "limit", None),+ all_items=bool(getattr(args, "all", False)),+ )+ except ValueError as exc:+ raise TaskCliError(str(exc), code="invalid_pagination", help_command=help_command) from exc+++def _add_optional_arg(parts: list[str], flag: str, value: object) -> None:+ if value is not None and value != "":+ parts.extend([flag, str(value)])+++def _next_command(parts: list[str], page_result, *, include_all: bool = False) -> str | None:+ if include_all or page_result.next_page is None:+ return None+ command = [*parts, "--page", str(page_result.next_page), "--limit", str(page_result.limit)]+ return shlex.join(command)+++def _pagination_message(page_payload: dict) -> str | None:+ if not page_payload.get("has_more"):+ return None+ next_command = page_payload.get("next_command")+ if next_command:+ return f"还有更多记录。继续翻页:{next_command}"+ return "还有更多记录。请加上 --page 参数继续翻页。"+++def _parse_cli_time_filter(value: str | None, *, field_name: str, help_command: str) -> str | None:+ if value is None:+ return None+ raw = str(value).strip()+ if not raw:+ return None+ suffix = raw[-1].lower()+ amount = raw[:-1]+ units = {+ "s": "seconds",+ "m": "minutes",+ "h": "hours",+ "d": "days",+ }+ if suffix in units and amount.isdigit():+ delta = timedelta(**{units[suffix]: int(amount)})+ return (datetime.now(timezone.utc) - delta).isoformat()+ try:+ datetime.fromisoformat(raw.replace("Z", "+00:00"))+ except ValueError as exc:+ raise TaskCliError(+ f"{field_name} must be an ISO timestamp or a relative value like 30m, 6h, or 7d",+ code="invalid_time_filter",+ help_command=help_command,+ ) from exc+ return raw++def _non_negative_float(value: str) -> float:parsed = float(value)if not math.isfinite(parsed):@@ -2597,9 +2666,56 @@ def _wait_for_run_result(store: TaskExecutionStore, run_id: str, *, wait_timeoutdef cmd_runs_list(args):- runs = _task_request_store().list_runs(status=getattr(args, "status", None))- _print_cli_payload("agent_runs", runs=[_run_payload(run, brief=getattr(args, "brief", False)) for run in runs])- return 0+ try:+ page_request = _page_request_from_args(args, help_command="vibe runs list --help")+ created_after = _parse_cli_time_filter(+ getattr(args, "created_after", None),+ field_name="--created-after",+ help_command="vibe runs list --help",+ )+ created_before = _parse_cli_time_filter(+ getattr(args, "created_before", None),+ field_name="--created-before",+ help_command="vibe runs list --help",+ )+ result = _task_request_store().list_runs_page(+ status=getattr(args, "status", None),+ run_type=getattr(args, "type", None),+ agent_name=getattr(args, "agent", None),+ agent_backend=getattr(args, "backend", None),+ session_id=getattr(args, "session_id", None),+ definition_id=getattr(args, "definition_id", None),+ created_after=created_after,+ created_before=created_before,+ query=getattr(args, "query", None),+ page_request=page_request,+ newest_first=True,+ )+ command = ["vibe", "runs", "list"]+ _add_optional_arg(command, "--status", getattr(args, "status", None))+ _add_optional_arg(command, "--type", getattr(args, "type", None))+ _add_optional_arg(command, "--agent", getattr(args, "agent", None))+ _add_optional_arg(command, "--backend", getattr(args, "backend", None))+ _add_optional_arg(command, "--session-id", getattr(args, "session_id", None))+ _add_optional_arg(command, "--definition-id", getattr(args, "definition_id", None))+ _add_optional_arg(command, "--created-after", getattr(args, "created_after", None))+ _add_optional_arg(command, "--created-before", getattr(args, "created_before", None))+ _add_optional_arg(command, "--q", getattr(args, "query", None))+ if getattr(args, "brief", False):+ command.append("--brief")+ page_payload = pagination_payload(result, next_command=_next_command(command, result, include_all=bool(getattr(args, "all", False))))+ message = _pagination_message(page_payload)+ payload = {+ "runs": [_run_payload(run, brief=getattr(args, "brief", False)) for run in result.items],+ "pagination": page_payload,+ }+ if message:+ payload["message"] = message+ _print_cli_payload("agent_runs", **payload)+ return 0+ except Exception as exc:+ _print_task_error(exc, help_command="vibe runs list --help")+ return 1def cmd_runs_show(args):@@ -2621,6 +2737,38 @@ def cmd_runs_cancel(args):return 0+def cmd_data_query(args):+ try:+ sql = getattr(args, "sql", None)+ sql_file = getattr(args, "sql_file", None)+ if sql_file:+ sql = sys.stdin.read() if sql_file == "-" else Path(sql_file).read_text(encoding="utf-8")+ page_request = _page_request_from_args(args, help_command="vibe data query --help")+ result = run_read_only_query(sql or "", page_request=page_request)+ command = ["vibe", "data", "query"]+ if getattr(args, "sql", None):+ _add_optional_arg(command, "--sql", getattr(args, "sql", None))+ elif sql_file:+ _add_optional_arg(command, "--sql-file", sql_file)+ page_payload = pagination_payload(result.pagination, next_command=_next_command(command, result.pagination, include_all=bool(getattr(args, "all", False))))+ message = _pagination_message(page_payload)+ payload = {+ "columns": result.columns,+ "rows": result.rows,+ "pagination": page_payload,+ }+ if message:+ payload["message"] = message+ _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"))+ return 1+ except Exception as exc:+ _print_task_error(exc, help_command="vibe data query --help")+ return 1++def cmd_watch_add(args):try:session_policy = _validate_definition_session_policy(@@ -3805,6 +3953,9 @@ def _print_show_page_list(payload: dict) -> None:print(f" URL: {page.get('active_url') or 'none'}")print(f" Visibility: {page.get('visibility')}")print(f" Updated: {page.get('updated_at')}")+ if payload.get("message"):+ print("")+ print(payload["message"])print("")print("Use it:")print(" - Open a page: vibe show status --session-id <session-id>")@@ -3834,14 +3985,45 @@ def cmd_show_list(args):store = _load_show_page_store()try:- pages = store.list(visibility=getattr(args, "visibility", None))+ page_request = _page_request_from_args(args, help_command="vibe show list --help")+ updated_after = _parse_cli_time_filter(+ getattr(args, "updated_after", None),+ field_name="--updated-after",+ help_command="vibe show list --help",+ )+ updated_before = _parse_cli_time_filter(+ getattr(args, "updated_before", None),+ field_name="--updated-before",+ help_command="vibe show list --help",+ )+ result = store.list_page(+ visibility=getattr(args, "visibility", None),+ session_id=getattr(args, "session_id", None),+ updated_after=updated_after,+ updated_before=updated_before,+ query=getattr(args, "query", None),+ page_request=page_request,+ )+ command = ["vibe", "show", "list"]+ _add_optional_arg(command, "--visibility", getattr(args, "visibility", None))+ _add_optional_arg(command, "--session-id", getattr(args, "session_id", None))+ _add_optional_arg(command, "--updated-after", getattr(args, "updated_after", None))+ _add_optional_arg(command, "--updated-before", getattr(args, "updated_before", None))+ _add_optional_arg(command, "--q", getattr(args, "query", None))+ if getattr(args, "json", False):+ command.append("--json")+ page_payload = pagination_payload(result, next_command=_next_command(command, result, include_all=bool(getattr(args, "all", False))))+ message = _pagination_message(page_payload)payload = {"ok": True,- "count": len(pages),+ "count": len(result.items),"visibility": getattr(args, "visibility", None),- "pages": [show_page_payload(page) for page in pages],+ "pages": [show_page_payload(page) for page in result.items],+ "pagination": page_payload,"url_guidance": avibe_cloud_connect_guidance(),}+ if message:+ payload["message"] = messageif getattr(args, "json", False):_print_json(payload)else:@@ -4359,7 +4541,16 @@ def build_parser():runs_subparsers.required = Trueruns_list_parser = runs_subparsers.add_parser("list", help="List Agent runs")runs_list_parser.add_argument("--status", help="Filter by run status")+ runs_list_parser.add_argument("--type", help="Filter by run type")+ runs_list_parser.add_argument("--agent", help="Filter by Vibe Agent name")+ runs_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")+ runs_list_parser.add_argument("--session-id", help="Filter by Agent Session ID")+ runs_list_parser.add_argument("--definition-id", help="Filter by task or watch definition ID")+ runs_list_parser.add_argument("--created-after", help="Filter by created_at >= timestamp, or relative value such as 6h or 7d")+ runs_list_parser.add_argument("--created-before", help="Filter by created_at <= timestamp, or relative value such as 6h or 7d")+ runs_list_parser.add_argument("--q", dest="query", help="Search common run text fields")runs_list_parser.add_argument("--brief", action="store_true", help="Show compact run rows")+ _add_pagination_args(runs_list_parser, help_command="vibe runs list --help")_add_json_noop(runs_list_parser)runs_show_parser = runs_subparsers.add_parser("show", help="Show one Agent run")runs_show_parser.add_argument("run_id")@@ -4396,8 +4587,35 @@ def build_parser():choices=("private", "public", "offline"),help="Filter by Show Page visibility.",)+ show_list_parser.add_argument("--session-id", help="Filter by Agent Session ID prefix.")+ show_list_parser.add_argument("--updated-after", help="Filter by updated_at >= timestamp, or relative value such as 6h or 7d.")+ show_list_parser.add_argument("--updated-before", help="Filter by updated_at <= timestamp, or relative value such as 6h or 7d.")+ show_list_parser.add_argument("--q", dest="query", help="Search session ID, share ID, or visibility.")+ _add_pagination_args(show_list_parser, help_command="vibe show list --help")show_list_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ data_parser = subparsers.add_parser(+ "data",+ help="Run read-only queries against Vibe Remote data",+ description="Inspect local Vibe Remote SQLite state with guarded read-only SQL.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe data --help",+ )+ data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query}")+ data_subparsers.required = True+ data_query_parser = data_subparsers.add_parser(+ "query",+ help="Run one read-only SQL query",+ description="Run one guarded read-only SQL query against the local SQLite state database.",+ 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-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)+show_path_parser = show_subparsers.add_parser("path",help="Create or resolve this session's Show Page directory",@@ -4989,6 +5207,10 @@ def main():if args.runs_command == "cancel":sys.exit(cmd_runs_cancel(args))parser.error("runs command is required")+ if args.command == "data":+ if args.data_command == "query":+ sys.exit(cmd_data_query(args))+ parser.error("data command is required")if args.command == "task":if args.task_command == "add":sys.exit(cmd_task_add(args))