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): recall views, excerpt, and bounded values for data query (#3068)

Call White8ca70d7694c8
diff --git a/core/prompts/preferences-context.md b/core/prompts/preferences-context.md
index 621b3f1d3..dab8eb142 100644
--- a/core/prompts/preferences-context.md
+++ b/core/prompts/preferences-context.md
@@ -7,4 +7,4 @@ A shared user context and preferences file is available at `{preferences_path}`.
Use the current platform `{platform}` and the user id from the current message metadata to choose the appropriate user section: `{platform}/<user_id>`.
Only record durable, factual, reusable information there. Keep entries short, deduplicated, and free of secrets unless the user explicitly asks.
-When the missing context is previous Avibe conversation history, make good use of `vibe data query` to search Sessions and Messages by keyword, time, scope, Agent, or run history. Query it freely: it reaches beyond this Session to the whole platform's data across every Session, Agent, and channel, and it is the clearest, most direct, and rawest source of memory. Do not rely on vague impressions or ask the user to repeat themselves.
+When the missing context is previous Avibe conversation history, make good use of `vibe data query` to search Sessions and Messages by keyword, time, scope, Agent, or run history; start from its `transcript`, `turns`, and `sessions` views. Query it freely: it reaches beyond this Session to the whole platform's data across every Session, Agent, and channel, and it is the clearest, most direct, and rawest source of memory. Do not rely on vague impressions or ask the user to repeat themselves.
diff --git a/core/session_handoff.py b/core/session_handoff.py
index 05f561e03..a3fc77795 100644
--- a/core/session_handoff.py
+++ b/core/session_handoff.py
@@ -154,7 +154,7 @@ def render_backend_handoff(
query = _history_query(session_id)
tail = ["[End of Avibe handoff]"]
if query:
- tail.insert(0, f"The full conversation is in Avibe's messages table. For example:\n{query}")
+ tail.insert(0, f"The full conversation is in Avibe's transcript. For example:\n{query}")
remaining = budget - _size(head) - _size(tail)
work_lines = _open_work_lines(open_work)
@@ -182,8 +182,8 @@ def _history_query(session_id: str) -> str | None:
if _PLAIN_ID.fullmatch(session_id) is None:
return None
sql = (
- "SELECT created_at, type, substr(content_text,1,2000) FROM messages"
- f" WHERE session_id='{session_id}' ORDER BY created_at, id LIMIT 50 OFFSET 0"
+ "SELECT at, role, kind, text FROM transcript"
+ f" WHERE session_id='{session_id}' ORDER BY at, message_id LIMIT 50"
)
return f'vibe data query --sql "{sql}" --format text'
diff --git a/docs/CLI.md b/docs/CLI.md
index ad6c1402a..eb047d5da 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -352,17 +352,37 @@ 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.
+Results return 20 rows per page by default and at most 100. It is how an Agent
+recalls earlier work in this Session or any other.
```bash
+vibe data query --sql "select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc" --format text
+vibe data query --sql "select started_at, input, reply from turns where session_id = 'sesk8m4q2p7x' order by started_at" --format text
+vibe data query --sql "select session_id, title from sessions where parent_session_id = 'sesk8m4q2p7x'"
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
-vibe data query --sql "select created_at, author, content_text from messages where session_id = 'sesk8m4q2p7x' order by created_at" --format text
```
+Three views give every query a stable way into conversation history; the raw
+tables stay queryable:
+
+| View | Columns | Meaning |
+| --- | --- | --- |
+| `sessions` | `session_id`, `title`, `agent_name`, `backend`, `model`, `status`, `workdir`, `created_at`, `last_active_at`, `parent_session_id` | One row per Session. `parent_session_id` is the Session whose Agent started it with `vibe agent run`. |
+| `transcript` | `session_id`, `at`, `role`, `kind`, `text`, `turn_id`, `message_id` | Every message with text, in delivery time `at`. `role` is `user`, `agent`, or `harness` (input Avibe delivered: another Agent's brief, a callback, a Watch or Task); `kind` is the message type, such as `result` for an Agent's reply. |
+| `turns` | `session_id`, `turn_id`, `started_at`, `ended_at`, `outcome`, `input`, `reply` | One row per recorded Agent Turn: the text it was given and its final reply. Older history without Turn records is in `transcript`. |
+
+Two functions help with long text. `excerpt(text, 'term')` returns about 300
+characters of `text` around the first case-insensitive match of `term` (pass a
+third argument for another width); without a match it returns the opening.
+`text REGEXP 'pattern'` matches a Python regular expression, such as
+`'(?i)PR ?#?2868'`. Every text value longer than `--max-chars` (default 2000)
+is cut and ends `…[+N chars]`; the response says how many values were cut, and
+`--max-chars 0` keeps values whole.
+
`--format text` prints each row as a record for reading long text such as a
transcript or a message body: a `-[ RECORD n ]` line, then one `column: value`
line per column. Values are printed as stored, with real newlines; a multi-line
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 4b0c77fcd..a108de12f 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -256,16 +256,33 @@ SQLite 数据库的 `agent_events` 与 `skill_usage_daily` 中,没有统计面
### `vibe data query`
对本地 SQLite 状态数据库执行一条受保护的只读 SQL 语句。结果默认每页 20 行,最多 100 行。
+Agent 用它回忆当前 Session 或其他 Session 里之前做过的事。
```bash
+vibe data query --sql "select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc" --format text
+vibe data query --sql "select started_at, input, reply from turns where session_id = 'sesk8m4q2p7x' order by started_at" --format text
+vibe data query --sql "select session_id, title from sessions where parent_session_id = 'sesk8m4q2p7x'"
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
-vibe data query --sql "select created_at, author, content_text from messages where session_id = 'sesk8m4q2p7x' order by created_at" --format text
```
+三个视图为每次查询提供读取对话历史的稳定入口;原始表照样可以直接查询:
+
+| 视图 | 列 | 含义 |
+| --- | --- | --- |
+| `sessions` | `session_id`、`title`、`agent_name`、`backend`、`model`、`status`、`workdir`、`created_at`、`last_active_at`、`parent_session_id` | 每个 Session 一行。`parent_session_id` 是用 `vibe agent run` 启动它的那个 Session。 |
+| `transcript` | `session_id`、`at`、`role`、`kind`、`text`、`turn_id`、`message_id` | 所有有正文的消息,`at` 是送达时间。`role` 为 `user`、`agent` 或 `harness`(Avibe 投递的输入:其他 Agent 的任务说明、回调、Watch 或 Task);`kind` 是消息类型,例如 Agent 的回复是 `result`。 |
+| `turns` | `session_id`、`turn_id`、`started_at`、`ended_at`、`outcome`、`input`、`reply` | 每个有记录的 Agent 回合一行:它收到的原文和最终回复。没有回合记录的更早历史在 `transcript` 里。 |
+
+两个函数用来处理长文本。`excerpt(text, 'term')` 返回 `text` 中第一个匹配 `term`
+(不区分大小写)的位置前后约 300 个字符,第三个参数可以调整宽度;没有匹配时返回开头。
+`text REGEXP 'pattern'` 按 Python 正则表达式匹配,例如 `'(?i)PR ?#?2868'`。超过
+`--max-chars`(默认 2000)的文本值会被截断,以 `…[+N chars]` 结尾;响应会说明截断了
+几个值,`--max-chars 0` 保留完整值。
+
`--format text` 把每一行输出为一条记录,适合阅读对话记录或消息正文这类长文本:先是
一行 `-[ RECORD n ]`,然后每列一行 `column: value`。值按存储原样输出,换行就是真实
换行;多行的值从列名的下一行开始,缩进两个空格;SQL `NULL` 输出为 `(null)`。还有更多
diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.md
index 97120e231..5070b2744 100644
--- a/skills/use-avibe-harness/SKILL.md
+++ b/skills/use-avibe-harness/SKILL.md
@@ -35,7 +35,7 @@ Use `vibe harness status` first for this Session's active Runs, armed Watches, u
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.
-To read long text such as a Session transcript, message bodies, or a run's message and reply, add `--format text`: each row prints as a `-[ RECORD n ]` record with one `column: value` line per column, values as stored with real newlines (a multi-line value is indented under its column), and SQL `NULL` as `(null)`. For example, `vibe data query --sql "select created_at, author, content_text from messages where session_id = '<session-id>' order by created_at" --format text`. Read it directly instead of piping JSON through a script; the last line is `next_command: ...` when more rows exist.
+To recall earlier work in this Session or another, start from three views: `transcript` (`session_id`, `at`, `role` = `user`/`agent`/`harness`, `kind`, `text`, `turn_id`), `turns` (`session_id`, `input`, `reply`, `outcome`, `started_at`), and `sessions` (`session_id`, `title`, `agent_name`, `parent_session_id`, `last_active_at`). `excerpt(text, 'term')` shows the text around a match instead of its opening, and `text REGEXP '(?i)pattern'` matches a Python regular expression. Add `--format text` to read long text as `-[ RECORD n ]` records with real newlines, for example `vibe data query --sql "select at, role, excerpt(text, 'dormant') from transcript where session_id = '<session-id>' and text like '%dormant%' order by at" --format text`. Values over `--max-chars` (default 2000) end `…[+N chars]`; pass `--max-chars 0` when you need them whole. Read the output directly instead of piping JSON through a script; the last line is `next_command: ...` when more rows exist.
`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.
diff --git a/storage/read_only_query.py b/storage/read_only_query.py
index 031d56d5d..804f7d69d 100644
--- a/storage/read_only_query.py
+++ b/storage/read_only_query.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import difflib
+import functools
import re
import sqlite3
from dataclasses import dataclass
@@ -10,6 +11,7 @@ from urllib.parse import quote
from config import paths
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+from storage.models import MESSAGE_TURN_ID_SQL
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
DEFAULT_QUERY_STEP_LIMIT = 250_000
@@ -48,6 +50,91 @@ _SQL_KEYWORDS = frozenset(
)
_COLUMNS_HINT = "Read a table's columns with PRAGMA table_info(<table>)."
+# Views every query can read, for recalling earlier work. Agents kept guessing these
+# names (a ``sessions`` table, a ``role`` column) and missing the shape of the real
+# tables: an Agent's reply is a ``result`` row, not ``type='agent'``, and a Turn's
+# input lives on ``session_turns``. They are TEMP views of this connection only, so
+# they add nothing to the database, and the raw tables stay queryable.
+#
+# ``turns`` compares the indexed turn id with ``+t.id``: a TEXT-affinity column on
+# the right would apply its affinity to the indexed expression and turn every
+# lookup into a scan of ``ix_messages_turn_id``.
+RECALL_VIEWS = {
+ "sessions": (
+ "SELECT s.id AS session_id, s.title, s.agent_name, s.agent_backend AS backend, s.model, "
+ "s.status, s.workdir, s.created_at, s.last_active_at, "
+ "(SELECT r.source_actor FROM agent_runs r WHERE r.session_id = s.id AND r.source_kind = 'agent' "
+ "AND r.session_policy IN ('none', 'create', 'fork') ORDER BY r.created_at, r.id LIMIT 1) "
+ "AS parent_session_id "
+ "FROM agent_sessions s"
+ ),
+ "transcript": (
+ "SELECT session_id, coalesce(delivered_at, created_at) AS at, author AS role, type AS kind, "
+ f"content_text AS text, {MESSAGE_TURN_ID_SQL} AS turn_id, id AS message_id "
+ "FROM messages WHERE content_text IS NOT NULL AND content_text != ''"
+ ),
+ "turns": (
+ "SELECT t.session_id, t.id AS turn_id, t.started_at, t.terminal_at AS ended_at, "
+ "t.terminal_outcome AS outcome, t.dispatch_text AS input, "
+ f"(SELECT content_text FROM messages WHERE {MESSAGE_TURN_ID_SQL} = +t.id AND type = 'result' "
+ "ORDER BY coalesce(delivered_at, created_at) DESC, id DESC LIMIT 1) AS reply "
+ "FROM session_turns t"
+ ),
+}
+
+EXCERPT_DEFAULT_WIDTH = 300
+
+
+def _excerpt(*args: Any) -> str | None:
+ """``excerpt(text, term[, width])``: ``width`` characters of ``text`` around its first ``term``.
+
+ Agents bounded long text with ``substr(text, 1, n)``, which keeps the opening
+ and, for a third to a half of keyword hits, loses the match itself. Matching is
+ case-insensitive like ``LIKE``; text without the term yields its opening.
+ """
+
+ if len(args) not in (2, 3):
+ raise ValueError("excerpt takes (text, term) or (text, term, width)")
+ text, term = args[0], args[1]
+ if text is None:
+ return None
+ text = str(text)
+ try:
+ width = int(args[2]) if len(args) == 3 else EXCERPT_DEFAULT_WIDTH
+ except (TypeError, ValueError) as exc:
+ raise ValueError("excerpt width must be a whole number of characters") from exc
+ if width < 1:
+ raise ValueError("excerpt width must be at least 1")
+ if len(text) <= width:
+ return text
+ match = re.search(re.escape(str(term)), text, re.IGNORECASE) if term not in (None, "") else None
+ start = max(0, (match.start() + match.end()) // 2 - width // 2) if match else 0
+ end = min(len(text), start + width)
+ start = max(0, end - width)
+ return ("…" if start else "") + text[start:end] + ("…" if end < len(text) else "")
+
+
[email protected]_cache(maxsize=64)
+def _compiled_pattern(pattern: str) -> re.Pattern[str]:
+ try:
+ return re.compile(pattern)
+ except re.error as exc:
+ raise ValueError(f"invalid regular expression {pattern!r}: {exc}") from exc
+
+
+def _regexp(pattern: Any, value: Any) -> int | None:
+ """``value REGEXP pattern``, with Python regular expression syntax."""
+
+ if pattern is None or value is None:
+ return None
+ return 1 if _compiled_pattern(str(pattern)).search(str(value)) else 0
+
+
+_FUNCTION_HINTS = {
+ "excerpt": "Call excerpt(text, 'term') or excerpt(text, 'term', width).",
+ "regexp": "REGEXP takes a Python regular expression; add (?i) to ignore case.",
+}
+
class ReadOnlyQueryError(ValueError):
def __init__(self, message: str, *, code: str = "query_failed", hint: str | None = None):
@@ -83,6 +170,19 @@ def run_read_only_query(
conn.row_factory = sqlite3.Row
steps = 0
denials: list[tuple[int, str | None]] = []
+ function_errors: list[tuple[str, str]] = []
+
+ def reporting(name, function):
+ # sqlite3 reports any exception from a Python function as "user-defined
+ # function raised exception"; keep the real reason for the error.
+ def call(*args):
+ try:
+ return function(*args)
+ except Exception as exc:
+ function_errors.append((name, str(exc)))
+ raise
+
+ return call
def progress() -> int:
nonlocal steps
@@ -90,6 +190,12 @@ def run_read_only_query(
return 1 if steps > step_limit else 0
try:
+ conn.create_function("excerpt", -1, reporting("excerpt", _excerpt), deterministic=True)
+ conn.create_function("regexp", 2, reporting("regexp", _regexp), deterministic=True)
+ # TEMP objects live in this connection only, so a read-only database still
+ # takes them; they must exist before query_only and the authorizer forbid it.
+ for name, select in RECALL_VIEWS.items():
+ conn.execute(f"CREATE TEMP VIEW {name} AS {select}")
conn.execute("PRAGMA query_only = ON")
def authorize(action, arg1, arg2, db_name, source):
# SQL has no resource-row filter. Raw Skill observations share
@@ -124,6 +230,9 @@ def run_read_only_query(
message = str(exc)
code = "query_interrupted" if "interrupted" in message.lower() else "query_failed"
conn.set_progress_handler(None, 0)
+ if function_errors:
+ name, reason = function_errors[0]
+ raise ReadOnlyQueryError(f"{name}: {reason}", code=code, hint=_FUNCTION_HINTS[name]) from exc
hint = _error_hint(conn, statement, message, denials)
raise ReadOnlyQueryError(message, code=code, hint=hint) from exc
finally:
@@ -163,9 +272,14 @@ def _error_hint(
def _schema_columns(conn: sqlite3.Connection) -> dict[str, list[str]]:
- """Every queryable table's columns, in declaration order."""
+ """Every queryable view's and table's columns, in declaration order, views first."""
columns: dict[str, list[str]] = {}
+ for view in RECALL_VIEWS:
+ try:
+ columns[view] = [row[1] for row in conn.execute(f"PRAGMA temp.table_info({view})")]
+ except sqlite3.DatabaseError:
+ continue # a database without the tables a view reads has no such view to offer
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"
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 1150baf71..7eee53c2c 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -657,14 +657,47 @@ def test_data_query_text_prints_records_with_values_verbatim_and_pages(monkeypat
assert capsys.readouterr().out.splitlines() == ["-[ RECORD 3 ]", "body: third", "gone: x", "n: 9"]
+def test_data_query_cuts_long_values_and_says_how_to_read_them_whole(monkeypatch, tmp_path, capsys) -> None:
+ """One message body can be hundreds of thousands of characters; a page of them must not fill a context."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ SQLiteBackgroundTaskStore().close()
+ sql = "select 'short' as a, printf('%.3000c', 'x') as b union all select 'two', 'y'"
+
+ args = cli.build_parser().parse_args(["data", "query", "--sql", sql])
+ assert cli.cmd_data_query(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["rows"][0] == {"a": "short", "b": "x" * 2000 + "…[+1000 chars]"}
+ assert payload["rows"][1] == {"a": "two", "b": "y"}
+ assert payload["truncated_values"] == 1
+ assert "--max-chars 0" in payload["truncation"]
+
+ args = cli.build_parser().parse_args(["data", "query", "--sql", sql, "--max-chars", "0"])
+ assert cli.cmd_data_query(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["rows"][0]["b"] == "x" * 3000
+ assert "truncated_values" not in payload
+
+ args = cli.build_parser().parse_args(
+ ["data", "query", "--sql", sql, "--max-chars", "10", "--limit", "1", "--format", "text"]
+ )
+ assert cli.cmd_data_query(args) == 0
+ lines = capsys.readouterr().out.splitlines()
+ assert "b: xxxxxxxxxx…[+2990 chars]" in lines
+ assert lines[-2].startswith("1 value(s) cut at 10 characters")
+ # The next page is read the same way.
+ assert lines[-1].endswith("--format text --max-chars 10 --page 2 --limit 1")
+
+
@pytest.mark.parametrize(
("sql", "fragments"),
[
- ("select * from sessions", ["Did you mean agent_sessions", "Tables: ", "run_definitions"]),
+ ("select * from session", ["Did you mean sessions, 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,"],
+ ["No column 'turn_id' on messages.", "is a column of transcript, turns, agent_events", "messages columns: id,"],
),
(
"select content from agent_events",
diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.py
index 780dc5be8..94cea951d 100644
--- a/tests/test_prompt_render_export.py
+++ b/tests/test_prompt_render_export.py
@@ -38,7 +38,8 @@ _PREVIOUS_HISTORY_GUIDANCE = (
"instead of relying on memory or asking the user to repeat context."
)
_HISTORY_AS_MEMORY_GUIDANCE = (
- "make good use of `vibe data query` to search Sessions and Messages by keyword, time, scope, Agent, or run history. "
+ "make good use of `vibe data query` to search Sessions and Messages by keyword, time, scope, Agent, or run history; "
+ "start from its `transcript`, `turns`, and `sessions` views. "
"Query it freely: it reaches beyond this Session to the whole platform's data across every Session, Agent, "
"and channel, and it is the clearest, most direct, and rawest source of memory. "
"Do not rely on vague impressions or ask the user to repeat themselves."
diff --git a/tests/test_read_only_query_recall.py b/tests/test_read_only_query_recall.py
new file mode 100644
index 000000000..45eb3dd2a
--- /dev/null
+++ b/tests/test_read_only_query_recall.py
@@ -0,0 +1,180 @@
+"""Recall through ``vibe data query``: the history views and the long-text functions.
+
+Agents recall earlier work by querying Avibe's own state. They kept guessing a
+``sessions`` table and a ``role`` column, filtered on a ``type='agent'`` that does
+not exist (an empty answer, not an error), and bounded long text with
+``substr(text, 1, n)``, which keeps the opening and loses the match.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from storage.background import SQLiteBackgroundTaskStore
+from storage.pagination import PageRequest
+from storage.read_only_query import RECALL_VIEWS, ReadOnlyQueryError, run_read_only_query
+
+PARENT = "ses-parent"
+CHILD = "ses-child"
+OTHER = "ses-other"
+TURN = "trn-child-1"
+
+
+def state_db(monkeypatch, tmp_path) -> Path:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ SQLiteBackgroundTaskStore().close() # the migrated schema
+ return paths.get_sqlite_state_path()
+
+
+def _session(conn, session_id: str, title: str, created_at: str) -> None:
+ conn.execute(
+ "insert into agent_sessions (id, agent_backend, agent_variant, session_anchor, native_session_id, status,"
+ " metadata_json, created_at, updated_at, last_active_at, title, agent_name)"
+ " values (?, 'claude', 'default', ?, '', 'active', '{}', ?, ?, ?, ?, 'claude')",
+ (session_id, session_id, created_at, created_at, created_at, title),
+ )
+
+
+def _run(conn, run_id: str, session_id: str, policy: str, source_actor: str, created_at: str) -> None:
+ conn.execute(
+ "insert into agent_runs (id, run_type, status, session_id, session_policy, source_kind, source_actor,"
+ " message, metadata_json, created_at, updated_at)"
+ " values (?, 'agent_run', 'succeeded', ?, ?, 'agent', ?, 'work', '{}', ?, ?)",
+ (run_id, session_id, policy, source_actor, created_at, created_at),
+ )
+
+
+def _message(conn, message_id: str, session_id: str, author: str, kind: str, text: str, at: str, turn: str | None = None):
+ conn.execute(
+ "insert into messages (id, session_id, platform, author, type, content_text, content_json, metadata_json,"
+ " created_at, updated_at) values (?, ?, 'avibe', ?, ?, ?, '{}', ?, ?, ?)",
+ (message_id, session_id, author, kind, text, json.dumps({"turn_id": turn} if turn else {}), at, at),
+ )
+
+
+def _seed_history(db_path: Path) -> None:
+ with sqlite3.connect(db_path) as conn:
+ _session(conn, PARENT, "Release review", "2026-10-01T00:00:00Z")
+ _session(conn, CHILD, "Lane A", "2026-10-01T01:00:00Z")
+ _session(conn, OTHER, "Unrelated", "2026-10-01T02:00:00Z")
+ # The parent's Agent created the child; a later Agent only continued the parent.
+ _run(conn, "run-create", CHILD, "none", PARENT, "2026-10-01T01:00:00Z")
+ _run(conn, "run-continue", PARENT, "existing", OTHER, "2026-10-01T03:00:00Z")
+ conn.execute(
+ "insert into session_turns (id, session_id, initial_delivery_id, state, backend, start_attempt_id,"
+ " start_receipt_outcome, dispatch_text, dispatch_sha256, terminal_outcome, created_at, updated_at,"
+ " started_at, terminal_at) values (?, ?, 'dlv-1', 'terminal', 'claude', 'atm-1', 'accepted',"
+ " 'Slim the watch list rows', 'sha', 'completed', ?, ?, ?, ?)",
+ (TURN, CHILD, "2026-10-01T01:00:00Z", "2026-10-01T01:30:00Z", "2026-10-01T01:00:00Z", "2026-10-01T01:30:00Z"),
+ )
+ _message(conn, "m1", CHILD, "harness", "harness", "Slim the watch list rows", "2026-10-01T01:00:01Z")
+ _message(conn, "m2", CHILD, "agent", "assistant", "", "2026-10-01T01:00:02Z", TURN)
+ _message(conn, "m3", CHILD, "agent", "assistant", "Reading the projection", "2026-10-01T01:00:03Z", TURN)
+ _message(conn, "m4", CHILD, "agent", "result", "First reply", "2026-10-01T01:10:00Z", TURN)
+ _message(conn, "m5", CHILD, "agent", "result", "PR #2971 is open", "2026-10-01T01:29:00Z", TURN)
+ _message(conn, "m6", PARENT, "user", "user", "Ship it", "2026-10-01T00:00:01Z")
+ conn.commit()
+
+
+def _rows(sql: str, db_path: Path) -> list[dict]:
+ return run_read_only_query(sql, db_path=db_path, page_request=PageRequest(page=1, limit=100)).rows
+
+
+def test_history_views_answer_in_the_shape_agents_ask_for(state_db: Path) -> None:
+ _seed_history(state_db)
+
+ sessions = {
+ row["session_id"]: row
+ for row in _rows("select session_id, title, parent_session_id from sessions", state_db)
+ }
+ assert sessions[CHILD]["parent_session_id"] == PARENT
+ # Being continued by another Agent does not make it the parent.
+ assert sessions[PARENT]["parent_session_id"] is None
+
+ transcript = _rows(
+ f"select role, kind, text, turn_id from transcript where session_id = '{CHILD}' order by at", state_db
+ )
+ assert [(row["role"], row["kind"], row["text"]) for row in transcript] == [
+ ("harness", "harness", "Slim the watch list rows"),
+ ("agent", "assistant", "Reading the projection"),
+ ("agent", "result", "First reply"),
+ ("agent", "result", "PR #2971 is open"),
+ ]
+ assert transcript[-1]["turn_id"] == TURN
+
+ (turn,) = _rows(f"select turn_id, outcome, input, reply from turns where session_id = '{CHILD}'", state_db)
+ assert turn == {
+ "turn_id": TURN,
+ "outcome": "completed",
+ "input": "Slim the watch list rows",
+ "reply": "PR #2971 is open",
+ }
+
+
+def test_history_views_read_through_indexes(state_db: Path) -> None:
+ """A Session's transcript and each Turn's reply are index lookups, not scans of every message.
+
+ ``turns`` matches the indexed turn-id expression against ``+t.id``: compared with a
+ TEXT column, the expression would take its affinity and the index would only scan.
+ """
+
+ def plan(sql: str) -> list[str]:
+ return [row["detail"] for row in _rows(f"explain query plan {sql}", state_db)]
+
+ transcript = plan("select * from transcript where session_id = 'x' order by at")
+ assert any("USING INDEX ix_messages_session_transcript_id" in step for step in transcript), transcript
+
+ turns = plan("select reply from turns where session_id = 'x'")
+ assert any(step.startswith("SEARCH") and "ix_messages_turn_id" in step for step in turns), turns
+ assert not any(step.startswith("SCAN") and "messages" in step for step in turns), turns
+
+
+def test_history_views_never_hide_a_real_table(state_db: Path) -> None:
+ with sqlite3.connect(state_db) as conn:
+ tables = {name for (name,) in conn.execute("select name from sqlite_master")}
+ assert not set(RECALL_VIEWS) & tables
+
+
+def test_excerpt_shows_the_match_not_the_opening(state_db: Path) -> None:
+ text = "intro " * 200 + "the Watch List rows were slimmed" + " outro" * 200
+ sql = (
+ f"select excerpt('{text}', 'watch list', 40) as hit, excerpt('{text}', 'absent', 20) as miss,"
+ " excerpt('short', 'x') as short, excerpt(null, 'x') as gone"
+ )
+
+ (row,) = _rows(sql, state_db)
+
+ assert row["hit"].startswith("…") and row["hit"].endswith("…")
+ assert "Watch List" in row["hit"] and len(row["hit"]) == 42
+ assert row["miss"] == "intro intro intro in…"
+ assert row["short"] == "short"
+ assert row["gone"] is None
+
+
+def test_regexp_matches_python_patterns_and_explains_a_bad_one(state_db: Path) -> None:
+ _seed_history(state_db)
+
+ hits = _rows("select message_id from transcript where text regexp '(?i)pr ?#?2971\\b'", state_db)
+ assert [row["message_id"] for row in hits] == ["m5"]
+
+ with pytest.raises(ReadOnlyQueryError) as exc_info:
+ _rows("select 1 from transcript where text regexp 'pr ('", state_db)
+ assert str(exc_info.value).startswith("regexp: invalid regular expression 'pr ('")
+ assert "Python regular expression" in exc_info.value.hint
+
+
+def test_unknown_names_point_at_the_views(state_db: Path) -> None:
+ with pytest.raises(ReadOnlyQueryError) as exc_info:
+ _rows("select * from session", state_db)
+ assert "Did you mean sessions" in exc_info.value.hint
+
+ with pytest.raises(ReadOnlyQueryError) as exc_info:
+ _rows("select role from messages", state_db)
+ assert "'role' is a column of transcript" in exc_info.value.hint
diff --git a/vibe/cli.py b/vibe/cli.py
index 98e2ea7f8..d90293f88 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -7380,7 +7380,40 @@ def cmd_data_skill_usage(args):
return 1
-def _query_records_text(result, page_fields: dict) -> str:
+DATA_QUERY_MAX_CHARS = 2000
+
+
+def _bounded_query_rows(rows: list[dict], max_chars: int) -> tuple[list[dict], int]:
+ """Rows with each text value cut to ``max_chars`` characters, and how many were cut.
+
+ One message body can run to hundreds of thousands of characters; a page of them
+ would fill an Agent's context. A cut value ends ``…[+N chars]``, so the Agent
+ knows what it did not see and can read it with ``--max-chars 0`` or ``excerpt()``.
+ """
+
+ if max_chars <= 0:
+ return rows, 0
+ cut = 0
+ bounded: list[dict] = []
+ for row in rows:
+ values = {}
+ for column, value in row.items():
+ if isinstance(value, str) and len(value) > max_chars:
+ value = f"{value[:max_chars]}…[+{len(value) - max_chars} chars]"
+ cut += 1
+ values[column] = value
+ bounded.append(values)
+ return bounded, cut
+
+
+def _non_negative_int(value: str) -> int:
+ parsed = int(value)
+ if parsed < 0:
+ raise argparse.ArgumentTypeError("must be >= 0")
+ return parsed
+
+
+def _query_records_text(result, page_fields: dict, *, rows: list[dict], cut_note: str | None) -> str:
"""``vibe data query --format text``: each row as an expanded record, values verbatim.
JSON escapes every newline and quote of a transcript or message body, so
@@ -7390,7 +7423,7 @@ def _query_records_text(result, page_fields: dict) -> str:
lines: list[str] = []
offset = (result.pagination.page - 1) * result.pagination.limit
- for number, row in enumerate(result.rows, start=offset + 1):
+ for number, row in enumerate(rows, start=offset + 1):
lines.append(f"-[ RECORD {number} ]")
for column, value in row.items():
text = "(null)" if value is None else str(value)
@@ -7400,8 +7433,10 @@ def _query_records_text(result, page_fields: dict) -> str:
lines.extend(f" {line}" if line else "" for line in value_lines)
else:
lines.append(f"{column}: {text}" if text else f"{column}:")
- if not result.rows:
+ if not rows:
lines.append("(0 rows)")
+ if cut_note:
+ lines.append(cut_note)
pagination = page_fields["pagination"]
if pagination.get("next_command"):
lines.append(f"next_command: {pagination['next_command']}")
@@ -7429,6 +7464,16 @@ def cmd_data_query(args):
text_format = getattr(args, "format", "json") == "text"
if text_format:
command.extend(["--format", "text"])
+ max_chars = getattr(args, "max_chars", DATA_QUERY_MAX_CHARS)
+ if max_chars != DATA_QUERY_MAX_CHARS:
+ command.extend(["--max-chars", str(max_chars)])
+ rows, cut = _bounded_query_rows(result.rows, max_chars)
+ cut_note = (
+ f"{cut} value(s) cut at {max_chars} characters (marked …[+N chars]); "
+ "read them whole with --max-chars 0, or around a term with excerpt(column, 'term')."
+ if cut
+ else None
+ )
omit_next_command = bool(sql_file == "-")
page_fields = _paginated_fields(
result.pagination,
@@ -7436,9 +7481,15 @@ def cmd_data_query(args):
include_next_command=not omit_next_command,
)
if text_format:
- print(_query_records_text(result, page_fields))
+ print(_query_records_text(result, page_fields, rows=rows, cut_note=cut_note))
return 0
- _print_cli_payload("data_query", columns=result.columns, rows=result.rows, **page_fields)
+ _print_cli_payload(
+ "data_query",
+ columns=result.columns,
+ rows=rows,
+ **({"truncated_values": cut, "truncation": cut_note} if cut else {}),
+ **page_fields,
+ )
return 0
except ReadOnlyQueryError as exc:
_print_task_error(
@@ -18010,14 +18061,17 @@ def build_parser():
help="Run one read-only SQL query",
description="Run one guarded read-only SQL query against the local SQLite state database.",
epilog=(
+ "Recall earlier work through three views (the raw tables stay queryable):\n"
+ " sessions(session_id, title, agent_name, backend, model, status, workdir, created_at, last_active_at, parent_session_id)\n"
+ " transcript(session_id, at, role, kind, text, turn_id, message_id) role: user, agent, harness\n"
+ " turns(session_id, turn_id, started_at, ended_at, outcome, input, reply)\n"
+ "excerpt(text, 'term'[, width]) shows the text around a match; REGEXP takes a Python pattern.\n"
+ " vibe data query --sql \"select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc\" --format text\n"
+ " vibe data query --sql \"select started_at, input, reply from turns where session_id = 'ses...' order by started_at\" --format text\n"
"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).\n"
- "Read long text such as a transcript as records with real newlines:\n"
- " vibe data query --sql \"select created_at, author, content_text from messages where session_id = 'ses...' order by created_at\" --format text"
+ f"Only schema PRAGMAs run: {', '.join(sorted(SCHEMA_PRAGMAS))}. "
+ "Tasks and Watches are rows of run_definitions."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe data query --help",
@@ -18031,6 +18085,13 @@ def build_parser():
default="json",
help="json (default) prints the JSON envelope; text prints each row as a record with values verbatim.",
)
+ data_query_parser.add_argument(
+ "--max-chars",
+ type=_non_negative_int,
+ default=DATA_QUERY_MAX_CHARS,
+ metavar="N",
+ help=f"Cut each text value at N characters (default {DATA_QUERY_MAX_CHARS}); 0 keeps values whole.",
+ )
_add_pagination_args(data_query_parser, help_command="vibe data query --help")
_add_json_noop(data_query_parser)
data_retention_parser = data_subparsers.add_parser(