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
feat(data): session digests: recall a Session by its latest checkpoint memory (#3069)
Call White9ce221d65eee
diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 3f646fc0b..0f1a017d9 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -1343,6 +1343,11 @@ def _memo_lines(items: Sequence[MemoItem]) -> list[str]:return lines if items else [MEMO_HEADING, MIND_EMPTY]+def memo_text(items: Sequence[MemoItem]) -> str:+ """The memo under its heading, as the checkpoint shows it: what the Session's digest keeps of it (section 7)."""+ return "\n".join(_memo_lines(items))++# --- skills carried back (context.md section 7) ----------------------------------------diff --git a/core/prompts/preferences-context.md b/core/prompts/preferences-context.mdindex dab8eb142..8bb698b25 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; 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.+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 `digests` view to recognize a Session by what it is about and where it stands, then read its `transcript` or `turns`. 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/docs/CLI.md b/docs/CLI.mdindex eb047d5da..b680b9e43 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -356,6 +356,7 @@ Results return 20 rows per page by default and at most 100. It is how an Agentrecalls earlier work in this Session or any other.```bash+vibe data query --sql "select session_id, title, excerpt(text, 'tax') from digests where text like '%tax%' order by last_active_at desc" --format textvibe data query --sql "select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc" --format textvibe data query --sql "select started_at, input, reply from turns where session_id = 'sesk8m4q2p7x' order by started_at" --format textvibe data query --sql "select session_id, title from sessions where parent_session_id = 'sesk8m4q2p7x'"@@ -366,11 +367,13 @@ vibe data query --sql "select id, status, created_at from agent_runs order by crvibe data query --sql-file query.sql --limit 50```-Three views give every query a stable way into conversation history; the raw-tables stay queryable:+Four views give every query a stable way into conversation history; the raw+tables stay queryable. Start from `digests` to recognize a Session, then read+its details in `transcript` or `turns`:| View | Columns | Meaning || --- | --- | --- |+| `digests` | `session_id`, `title`, `agent_name`, `last_active_at`, `parent_session_id`, `digest_at`, `mind`, `memo`, `now`, `text` | One row per Session that has something to say: what it is about and where it stands. For a Vibey Session that has written a checkpoint, the latest checkpoint's memory, written at `digest_at`: `mind` (for whom and why, goals, key decisions, lessons), `memo` (the user's own words it keeps), and `now` (progress and next steps); `text` holds all three. Otherwise `text` is the Session's first input and latest reply. || `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`. |diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex a108de12f..761cea523 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -259,6 +259,7 @@ SQLite 数据库的 `agent_events` 与 `skill_usage_daily` 中,没有统计面Agent 用它回忆当前 Session 或其他 Session 里之前做过的事。```bash+vibe data query --sql "select session_id, title, excerpt(text, '报税') from digests where text like '%报税%' order by last_active_at desc" --format textvibe data query --sql "select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc" --format textvibe data query --sql "select started_at, input, reply from turns where session_id = 'sesk8m4q2p7x' order by started_at" --format textvibe data query --sql "select session_id, title from sessions where parent_session_id = 'sesk8m4q2p7x'"@@ -269,10 +270,12 @@ vibe data query --sql "select id, status, created_at from agent_runs order by crvibe data query --sql-file query.sql --limit 50```-三个视图为每次查询提供读取对话历史的稳定入口;原始表照样可以直接查询:+四个视图为每次查询提供读取对话历史的稳定入口;原始表照样可以直接查询。先用 `digests`+认出 Session,再到 `transcript` 或 `turns` 里读细节:| 视图 | 列 | 含义 || --- | --- | --- |+| `digests` | `session_id`、`title`、`agent_name`、`last_active_at`、`parent_session_id`、`digest_at`、`mind`、`memo`、`now`、`text` | 每个有内容的 Session 一行:它在做什么、进展到哪里。写过压缩摘要的 Vibey Session 给出最新一份摘要里的记忆,写于 `digest_at`:`mind`(心智:为谁、为什么,目标,关键决定,经验)、`memo`(备忘:保留的用户原话)、`now`(现场:进度与下一步),`text` 是三者合在一起。其他 Session 的 `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` 里。 |diff --git a/docs/plans/agent-core-contracts/context.md b/docs/plans/agent-core-contracts/context.mdindex 35b1ca085..4501e72d6 100644--- a/docs/plans/agent-core-contracts/context.md+++ b/docs/plans/agent-core-contracts/context.md@@ -483,6 +483,13 @@ Iterative checkpoints start from what the latest one kept: its mind is `mind.md`skills candidates again, and its message is part of the forked prefix. The mind is revised, never rewritten whole, sowhat the model leaves alone stays word for word across any number of checkpoints (§11).+The latest checkpoint's memory is also how other Sessions recall this one. The transaction that appends a+`Compaction` holding any of the mind, the memo, and the now writes them to the Session's one `session_digests` row,+the memo as the checkpoint shows it (`# 5. The user's words`, its entries, their cut notes); `vibe data query` reads+it through its `digests` view. A row holding none of them (a drop that left them out, §8 c) leaves the previous+digest, still the latest memory the Session wrote. Only the latest is kept: the Session itself reads its earlier+detail in its earlier record, and every checkpoint stays in its own row.+## 8. Overflow ladderBounded per model request. Each step makes the next request smaller; the ladder takes at least one step and stopsdiff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.mdindex 5070b2744..9bec74d9b 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, uDiscover 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 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.+To recall earlier work in this Session or another, start from four views. `digests` (`session_id`, `title`, `last_active_at`, `digest_at`, `mind`, `memo`, `now`, `text`) says what each Session is about and where it stands: for a Vibey Session that has written a checkpoint, its latest checkpoint memory as `mind`, `memo`, and `now`, all three in `text`; otherwise `text` is the Session's first input and latest reply. Search its `text` to recognize a Session, then read the details in `transcript` (`session_id`, `at`, `role` = `user`/`agent`/`harness`, `kind`, `text`, `turn_id`) or `turns` (`session_id`, `input`, `reply`, `outcome`, `started_at`); `sessions` (`session_id`, `title`, `agent_name`, `parent_session_id`, `last_active_at`) lists every Session. `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/agent_transcript.py b/storage/agent_transcript.pyindex 1bb2c6ba9..4d0c80f97 100644--- a/storage/agent_transcript.py+++ b/storage/agent_transcript.py@@ -19,6 +19,8 @@ context exactly when its ``context_seq`` is non-null:Every entry carries its row's ``created_at`` as epoch seconds, as written andas loaded (C-9 reads a response's to tell a cold provider cache after arestart). ``append_payloads`` commits several payload rows in one transaction.+A checkpoint row rewrites its Session's ``session_digests`` row in the same one:+the mind, memo, and now that other Sessions recall it by.Allocation. Every write takes SQLite's writer lock before its first read(``reserve_write_lock``) and runs under a per-Session lock, so@@ -69,6 +71,7 @@ from datetime import datetime, timezonefrom typing import Any, Callable, Literal, Mapping, Optional, Sequence, TypeVarfrom sqlalchemy import and_, bindparam, func, or_, select, text+from sqlalchemy.dialects.sqlite import insert as sqlite_insertfrom sqlalchemy.engine import Connection, Enginefrom core.agent_core.harness.fork import fork_point, latest_cut@@ -90,7 +93,16 @@ from core.agent_core.messages import (from storage import agent_events_service, media_service, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.message_deliveries import TURN_OWNER_STATES-from storage.models import MESSAGE_TURN_ID_SQL, agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns+from storage.models import (+ MESSAGE_TURN_ID_SQL,+ agent_events,+ agent_sessions,+ message_deliveries,+ messages,+ scopes,+ session_digests,+ session_turns,+)from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATEINPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")@@ -434,6 +446,8 @@ class SQLiteTranscriptStore:)if message is not None:_register_images(conn, origin.scope_id, session_id, message)+ if kind == "compaction":+ _record_digest(conn, session_id, row["id"], row["created_at"], payload)return ContextEntry(session_id, seq, kind, row["id"], message=message, payload=payload, created_at=_epoch(row["created_at"]))@@ -1004,6 +1018,35 @@ def _event_entry(session_id: str, row: Mapping[str, Any]) -> ContextEntry:)+def _record_digest(+ conn: Connection, session_id: str, compaction_id: str, written_at: str, payload: Mapping[str, Any]+) -> None:+ """Keep the checkpoint's mind, memo, and now as the Session's digest, the memory other Sessions recall.++ A checkpoint that holds none of them (a drop that left them out, context.md section 8 c) leaves the previous+ digest: it is still the latest memory the Session wrote.+ """+ # Only a Vibey runtime appends a checkpoint, and it has the harness loaded; this module's other importers+ # (core.session_turns, restart resume) never write one and need not load it.+ from core.agent_core.harness.context import MemoItem, memo_text++ mind = _block(payload.get("mind"))+ memo = memo_text([MemoItem(**item) for item in payload["memo"]]) if payload.get("memo") else None+ now = _block(payload.get("checkpoint"))+ if not (mind or memo or now):+ return+ values = {"compaction_id": compaction_id, "updated_at": written_at, "mind": mind, "memo": memo, "now": now}+ conn.execute(+ sqlite_insert(session_digests)+ .values(session_id=session_id, **values)+ .on_conflict_do_update(index_elements=[session_digests.c.session_id], set_=values)+ )+++def _block(value: Any) -> Optional[str]:+ return value if isinstance(value, str) and value.strip() else None++def _message(value: Any, expected: type, row_id: str) -> Any:try:message = message_from_dict(value)diff --git a/storage/alembic/versions/20261030_0072_session_digests.py b/storage/alembic/versions/20261030_0072_session_digests.pynew file mode 100644index 000000000..81457bb06--- /dev/null+++ b/storage/alembic/versions/20261030_0072_session_digests.py@@ -0,0 +1,121 @@+"""keep each Vibey Session's latest memory in session_digests++Other Sessions recall a Session by its latest checkpoint's mind, memo, and now+(``docs/plans/agent-core-contracts/context.md`` section 7). The transcript store+rewrites a Session's one row in the transaction that appends a+``context_compaction`` row; ``vibe data query`` reads it through its ``digests``+view, so a search does not parse every checkpoint's JSON, skills included.++The backfill gives every Session its latest checkpoint that holds any of the+three, read through ``ix_agent_events_session_type_created_id`` one Session at a+time. A ``checkpoint-v4`` row has no mind or memo: its whole text is the now. The+memo is rendered here as the harness showed it when this revision was written, so+the revision does what it did whatever the harness later becomes. Additive and+derived: released versions never read the table, and downgrade drops it.++Revision ID: 20261030_0072+Revises: 20261020_0071+Create Date: 2026-10-30+"""++from __future__ import annotations++import json+from typing import Any, Optional++import sqlalchemy as sa+from alembic import op++revision = "20261030_0072"+down_revision = "20261020_0071"+branch_labels = None+depends_on = None+MIGRATION_SAFETY = "backfill"++_TABLE = "session_digests"+_MEMO_HEADING = "# 5. The user's words"+_MEMO_CUT = "[cut short; the whole message is #{seq} in the earlier record]"+++def _tables(bind) -> set[str]:+ return {+ str(row[0])+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")+ }+++def _text(value: Any) -> Optional[str]:+ return value if isinstance(value, str) and value.strip() else None+++def _memo(value: Any) -> Optional[str]:+ if not isinstance(value, list):+ return None+ lines = [_MEMO_HEADING]+ for item in value:+ if not isinstance(item, dict) or not isinstance(item.get("text"), str):+ continue+ seq = item.get("seq")+ first, *rest = item["text"].replace("\r\n", "\n").replace("\r", "\n").split("\n")+ lines.append(f"- (#{seq}) {first}")+ lines.extend(f" {line}" for line in rest)+ if item.get("truncated") is True:+ lines.append(f" {_MEMO_CUT.format(seq=seq)}")+ return "\n".join(lines) if len(lines) > 1 else None+++def _digest(raw: Any) -> Optional[tuple[Optional[str], Optional[str], Optional[str]]]:+ try:+ payload = json.loads(raw or "")+ except (TypeError, ValueError):+ return None+ if not isinstance(payload, dict):+ return None+ blocks = (_text(payload.get("mind")), _memo(payload.get("memo")), _text(payload.get("checkpoint")))+ return blocks if any(blocks) else None+++def _backfill(bind) -> None:+ sessions = [row[0] for row in bind.exec_driver_sql("select id from agent_sessions")]+ for session_id in sessions:+ rows = bind.exec_driver_sql(+ "select id, created_at, content_json from agent_events "+ "where session_id = ? and event_type = 'context_compaction' and visibility = 'context' "+ "order by created_at desc, id desc",+ (session_id,),+ ).fetchall()+ for compaction_id, created_at, raw in rows:+ blocks = _digest(raw)+ if blocks is None:+ continue+ bind.exec_driver_sql(+ f"insert into {_TABLE} (session_id, compaction_id, updated_at, mind, memo, now) "+ "values (?, ?, ?, ?, ?, ?)",+ (session_id, compaction_id, created_at, *blocks),+ )+ break+++def upgrade() -> None:+ bind = op.get_bind()+ tables = _tables(bind)+ if "agent_sessions" not in tables or _TABLE in tables:+ return+ op.create_table(+ _TABLE,+ sa.Column("session_id", sa.String(), nullable=False),+ sa.Column("compaction_id", sa.String(), nullable=False),+ sa.Column("updated_at", sa.String(), nullable=False),+ sa.Column("mind", sa.Text(), nullable=True),+ sa.Column("memo", sa.Text(), nullable=True),+ sa.Column("now", sa.Text(), nullable=True),+ sa.PrimaryKeyConstraint("session_id"),+ sa.ForeignKeyConstraint(["session_id"], ["agent_sessions.id"], ondelete="CASCADE"),+ )+ if "agent_events" in tables:+ _backfill(bind)+++def downgrade() -> None:+ if _TABLE in _tables(op.get_bind()):+ op.drop_table(_TABLE)diff --git a/storage/migrations.py b/storage/migrations.pyindex 24e281cf4..3cfdedd53 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -66,6 +66,7 @@ HEAD_TABLES = INITIAL_TABLES | {"session_turns","session_turn_replies","agent_events",+ "session_digests","skill_usage_daily","show_session_events","media_objects",diff --git a/storage/models.py b/storage/models.pyindex c74c2a532..d49985bb4 100644--- a/storage/models.py+++ b/storage/models.py@@ -550,6 +550,21 @@ agent_events = Table(),)+# A Vibey Session's latest memory, for other Sessions to recall: the mind, the memo, and+# the now of its latest checkpoint that holds any of them (context.md section 7). One row+# per Session, rewritten by primary key in the transaction that appends the+# ``context_compaction`` row; ``vibe data query`` reads it through its ``digests`` view.+session_digests = Table(+ "session_digests",+ metadata,+ Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="CASCADE"), primary_key=True),+ Column("compaction_id", String, nullable=False),+ Column("updated_at", String, nullable=False),+ Column("mind", Text, nullable=True),+ Column("memo", Text, nullable=True),+ Column("now", Text, nullable=True),+)+skill_usage_daily = Table("skill_usage_daily",metadata,diff --git a/storage/read_only_query.py b/storage/read_only_query.pyindex 804f7d69d..5fde72257 100644--- a/storage/read_only_query.py+++ b/storage/read_only_query.py@@ -59,6 +59,14 @@ _COLUMNS_HINT = "Read a table's columns with PRAGMA table_info(<table>)."# ``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``.+#+# ``digests`` says what each Session is about and where it stands, for an Agent to+# recognize a Session before it reads the transcript: a Vibey Session's latest+# checkpoint memory (``session_digests``: its mind, memo, and now, together in+# ``text``), otherwise the Session's first input and latest reply. Every+# lookup is by Session id through an index, so a search over all of them stays a+# pass over one row per Session.+_GAP = "char(10) || char(10)"RECALL_VIEWS = {"sessions": ("SELECT s.id AS session_id, s.title, s.agent_name, s.agent_backend AS backend, s.model, "@@ -80,6 +88,22 @@ RECALL_VIEWS = {"ORDER BY coalesce(delivered_at, created_at) DESC, id DESC LIMIT 1) AS reply ""FROM session_turns t"),+ "digests": (+ "SELECT * FROM (SELECT s.session_id, s.title, s.agent_name, s.last_active_at, s.parent_session_id, "+ "d.updated_at AS digest_at, d.mind, d.memo, d.now, "+ "CASE WHEN d.session_id IS NOT NULL THEN ltrim("+ f"coalesce({_GAP} || d.mind, '') || coalesce({_GAP} || d.memo, '') || coalesce({_GAP} || d.now, ''), "+ "char(10)) ELSE nullif(ltrim("+ f"coalesce({_GAP} || '# First input' || char(10) || (SELECT m.content_text FROM messages m "+ "WHERE m.session_id = s.session_id AND m.type IN ('user', 'harness', 'agent_initiated') "+ "AND m.content_text != '' ORDER BY m.created_at, m.id LIMIT 1), '') "+ f"|| coalesce({_GAP} || '# Latest reply' || char(10) || (SELECT m.content_text FROM messages m "+ "WHERE m.session_id = s.session_id AND m.type = 'result' AND m.content_text != '' "+ "ORDER BY m.created_at DESC, m.id DESC LIMIT 1), ''), "+ "char(10)), '') END AS text "+ "FROM sessions s LEFT JOIN session_digests d ON d.session_id = s.session_id) "+ "WHERE text IS NOT NULL"+ ),}EXCERPT_DEFAULT_WIDTH = 300diff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.pyindex 8f2979156..15ab5cff5 100644--- a/tests/test_agent_context_seq_migration.py+++ b/tests/test_agent_context_seq_migration.py@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261020_0071",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261030_0072",)assert_released_rows_unchanged(conn)assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not Nonefor table, (first, same_session, other_session) in _IDS.items():diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.pyindex d9a845077..dbdb39c99 100644--- a/tests/test_agent_transcript.py+++ b/tests/test_agent_transcript.py@@ -34,7 +34,7 @@ from storage import message_deliveries, messages_servicefrom storage.agent_transcript import SQLiteTranscriptStore, TranscriptError, resolve_fork_pointfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_events, messages+from storage.models import agent_events, messages, session_digestsfrom storage.models import message_deliveries as delivery_rowsfrom storage.settings_service import upsert_scope@@ -491,6 +491,59 @@ async def test_turn_context_load_ignores_long_fork_history(engine) -> None:assert all(entry.session_id == "ses_long_child" for entry in turn)+async def test_a_checkpoint_keeps_the_sessions_latest_memory_as_its_digest(engine) -> None:+ """Other Sessions recall this one by its latest checkpoint's mind, memo, and now, kept in its one+ ``session_digests`` row with the checkpoint row; a checkpoint that holds none of them (a drop that left+ them out) leaves the previous one."""+ with engine.begin() as conn:+ home = _scope(conn, "C-home")+ _session(conn, "ses_main", home)+ consumed = _row(conn, "ses_main", home, "报税材料齐了吗?\n先看清单")+ store = SQLiteTranscriptStore(engine)+ await store.consume_input("ses_main", consumed, _user("报税材料齐了吗?\n先看清单"))+ checkpoint = {+ **COMPACTION,+ "mind": "# 1. Where I stand\n## For whom and why\n用户要按时报税。",+ "mind_truncated": False,+ "memo": [{"seq": 1, "text": "报税材料齐了吗?\n先看清单", "truncated": True}],+ "checkpoint": "# 6. Now\n## Current step\n- 核对清单",+ }+ written = await store.append_payload("ses_main", "compaction", checkpoint)+ left_out = {**COMPACTION, "mode": "dropped", "reason": "overflow", "checkpoint": "", "mind": "", "memo": []}+ await store.append_payload("ses_main", "compaction", left_out)++ def digests() -> list[dict]:+ with engine.connect() as conn:+ return [dict(row) for row in conn.execute(select(session_digests)).mappings()]++ with engine.connect() as conn:+ written_at = conn.execute(+ select(agent_events.c.created_at).where(agent_events.c.id == written.row_id)+ ).scalar_one()+ assert digests() == [+ {+ "session_id": "ses_main",+ "compaction_id": written.row_id,+ "updated_at": written_at,+ "mind": "# 1. Where I stand\n## For whom and why\n用户要按时报税。",+ "memo": "# 5. The user's words\n- (#1) 报税材料齐了吗?\n 先看清单\n"+ " [cut short; the whole message is #1 in the earlier record]",+ "now": "# 6. Now\n## Current step\n- 核对清单",+ }+ ]++ later = await store.append_payload(+ "ses_main", "compaction", {**checkpoint, "memo": [], "checkpoint": "# 6. Now\n## Current step\n- 已提交"}+ )+ [digest] = digests()+ assert (digest["compaction_id"], digest["mind"], digest["memo"], digest["now"]) == (+ later.row_id,+ "# 1. Where I stand\n## For whom and why\n用户要按时报税。",+ None,+ "# 6. Now\n## Current step\n- 已提交",+ )++async def test_a_cancelled_write_raises_only_after_its_commit_settled(engine) -> None:with engine.begin() as conn:home = _scope(conn, "C-home")diff --git a/tests/test_prompt_render_export.py b/tests/test_prompt_render_export.pyindex 94cea951d..41ae3ce9d 100644--- a/tests/test_prompt_render_export.py+++ b/tests/test_prompt_render_export.py@@ -39,7 +39,8 @@ _PREVIOUS_HISTORY_GUIDANCE = ()_HISTORY_AS_MEMORY_GUIDANCE = ("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. "+ "start from its `digests` view to recognize a Session by what it is about and where it stands, "+ "then read its `transcript` or `turns`. ""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.pyindex 45eb3dd2a..4bbce7a90 100644--- a/tests/test_read_only_query_recall.py+++ b/tests/test_read_only_query_recall.py@@ -118,6 +118,42 @@ def test_history_views_answer_in_the_shape_agents_ask_for(state_db: Path) -> Non}+def test_digests_say_what_each_session_is_about(state_db: Path) -> None:+ """A Vibey Session's checkpoint memory, else the first input and latest reply; one row per Session that+ has either, so one ``text like`` finds a Session before its transcript is read."""+ _seed_history(state_db)+ with sqlite3.connect(state_db) as conn:+ _session(conn, "ses-taxes", "Taxes", "2026-10-02T00:00:00Z")+ _session(conn, "ses-v4", "Older checkpoint", "2026-10-02T00:00:00Z")+ conn.executemany(+ "insert into session_digests (session_id, compaction_id, updated_at, mind, memo, now)"+ " values (?, ?, '2026-10-02T01:00:00Z', ?, ?, ?)",+ [+ ("ses-taxes", "evt-1", "# 1. Where I stand\n用户要按时报税。", "# 5. The user's words\n- (#1) 材料齐了吗?",+ "# 6. Now\n- 核对清单"),+ ("ses-v4", "evt-2", None, None, "# 1. Self and method\n- 只读核验"),+ ],+ )+ conn.commit()++ digests = {+ row["session_id"]: row+ for row in _rows("select session_id, title, parent_session_id, digest_at, text from digests", state_db)+ }++ # OTHER has nothing to say.+ assert set(digests) == {PARENT, CHILD, "ses-taxes", "ses-v4"}+ assert digests["ses-taxes"]["text"] == (+ "# 1. Where I stand\n用户要按时报税。\n\n# 5. The user's words\n- (#1) 材料齐了吗?\n\n# 6. Now\n- 核对清单"+ )+ assert digests["ses-taxes"]["digest_at"] == "2026-10-02T01:00:00Z"+ assert digests["ses-v4"]["text"] == "# 1. Self and method\n- 只读核验"+ assert digests[CHILD]["text"] == "# First input\nSlim the watch list rows\n\n# Latest reply\nPR #2971 is open"+ assert (digests[CHILD]["parent_session_id"], digests[CHILD]["digest_at"]) == (PARENT, None)+ assert digests[PARENT]["text"] == "# First input\nShip it"+ assert _rows("select session_id from digests where text like '%报税%'", state_db) == [{"session_id": "ses-taxes"}]++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.@@ -135,6 +171,11 @@ def test_history_views_read_through_indexes(state_db: Path) -> None:assert any(step.startswith("SEARCH") and "ix_messages_turn_id" in step for step in turns), turnsassert not any(step.startswith("SCAN") and "messages" in step for step in turns), turns+ # A search over every digest is one pass over the Sessions; each Session's own rows are looked up.+ digests = plan("select session_id from digests where text like '%x%'")+ assert all("agent_sessions" in step for step in digests if step.startswith("SCAN")), digests+ assert any(step.startswith("SEARCH d ") for step in digests), digests+def test_history_views_never_hide_a_real_table(state_db: Path) -> None:with sqlite3.connect(state_db) as conn:diff --git a/tests/test_session_digests_migration.py b/tests/test_session_digests_migration.pynew file mode 100644index 000000000..f915f4e79--- /dev/null+++ b/tests/test_session_digests_migration.py@@ -0,0 +1,93 @@+"""20261030_0072: ``session_digests`` backfilled from the checkpoints a database already holds.++A database a released version wrote has every Vibey Session's checkpoints and no+digest. After the upgrade, each Session that has a checkpoint holding any of the+mind, memo, and now is recallable by its latest such checkpoint; downgrade drops+the table and the next upgrade rebuilds it from the same rows.+"""++import json+import sqlite3++import pytest+from alembic import command++from storage import migrations++pytestmark = pytest.mark.no_sqlite_template++REVISION = "20261030_0072"+PREVIOUS_REVISION = "20261020_0071"+V5 = {+ "version": 1,+ "mode": "normal",+ "checkpoint": "# 6. Now\n## Current step\n- 核对清单",+ "mind": "# 1. Where I stand\n## For whom and why\n用户要按时报税。",+ "memo": [+ {"seq": 3, "text": "材料齐了吗?", "truncated": False},+ {"seq": 9, "text": "先看清单\n再交", "truncated": True},+ ],+}+# A drop that left the checkpoint out: it holds nothing to recall.+LEFT_OUT = {"version": 1, "mode": "dropped", "checkpoint": "", "mind": "", "memo": []}+# A checkpoint-v4 row has no mind or memo: its whole text is the now.+V4 = {"version": 1, "mode": "normal", "checkpoint": "# 1. Self and method\n- 只读核验"}+++def _session(conn, session_id: 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) values (?, 'vibey', 'vibey', ?, '', 'active', '{}', ?, ?)",+ (session_id, session_id, "2026-10-20T00:00:00Z", "2026-10-20T00:00:00Z"),+ )+++def _checkpoint(conn, event_id: str, session_id: str, at: str, content) -> None:+ conn.execute(+ "insert into agent_events (id, session_id, platform, event_type, visibility, context_seq, content_json,"+ " metadata_json, created_at, updated_at) values (?, ?, 'avibe', 'context_compaction', 'context', ?, ?, '{}',"+ " ?, ?)",+ (event_id, session_id, int(event_id[-1]), content if isinstance(content, str) else json.dumps(content), at, at),+ )+++def _digests(path) -> dict:+ with sqlite3.connect(path) as conn:+ rows = conn.execute("select session_id, compaction_id, updated_at, mind, memo, now from session_digests")+ return {row[0]: row[1:] for row in rows}+++def test_upgrade_gives_each_session_its_latest_checkpoint_memory(tmp_path):+ path = tmp_path / "state.sqlite"+ migrations.run_migrations(path, revision=PREVIOUS_REVISION)+ with sqlite3.connect(path) as conn:+ for session_id in ("ses_taxes", "ses_v4", "ses_broken", "ses_plain"):+ _session(conn, session_id)+ _checkpoint(conn, "evt_1", "ses_taxes", "2026-10-21T00:00:00Z", {**V5, "checkpoint": "# 6. Now\n- 旧的"})+ _checkpoint(conn, "evt_2", "ses_taxes", "2026-10-22T00:00:00Z", V5)+ _checkpoint(conn, "evt_3", "ses_taxes", "2026-10-23T00:00:00Z", LEFT_OUT)+ _checkpoint(conn, "evt_4", "ses_v4", "2026-10-21T00:00:00Z", V4)+ _checkpoint(conn, "evt_5", "ses_broken", "2026-10-21T00:00:00Z", "{not json")++ migrations.run_migrations(path)++ expected = {+ "ses_taxes": (+ "evt_2",+ "2026-10-22T00:00:00Z",+ "# 1. Where I stand\n## For whom and why\n用户要按时报税。",+ "# 5. The user's words\n- (#3) 材料齐了吗?\n- (#9) 先看清单\n 再交\n"+ " [cut short; the whole message is #9 in the earlier record]",+ "# 6. Now\n## Current step\n- 核对清单",+ ),+ "ses_v4": ("evt_4", "2026-10-21T00:00:00Z", None, None, "# 1. Self and method\n- 只读核验"),+ }+ with sqlite3.connect(path) as conn:+ assert conn.execute("select version_num from alembic_version").fetchone() == (REVISION,)+ assert _digests(path) == expected++ command.downgrade(migrations.alembic_config(path), PREVIOUS_REVISION)+ with sqlite3.connect(path) as conn:+ assert "session_digests" not in {row[0] for row in conn.execute("select name from sqlite_master")}+ migrations.run_migrations(path)+ assert _digests(path) == expecteddiff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.pyindex a050b5ab4..1c327b6aa 100644--- a/tests/test_skill_observability_migration.py+++ b/tests/test_skill_observability_migration.py@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261020_0071",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261030_0072",)assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {"scopes",diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 0b98d6310..c62fb668f 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -44,7 +44,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20261020_0071"+HEAD_REVISION = "20261030_0072"PREVIOUS_HEAD_REVISION = "20261016_0068"_SCOPE_ID_DRIFT_TABLES = ("messages", "agent_events", "media_objects")# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed anddiff --git a/tests/test_turn_last_reply_store.py b/tests/test_turn_last_reply_store.pyindex a39395a57..eb7c72993 100644--- a/tests/test_turn_last_reply_store.py+++ b/tests/test_turn_last_reply_store.py@@ -13,6 +13,7 @@ import sqlite3import pytestfrom alembic import command+from alembic.script import ScriptDirectoryfrom sqlalchemy import event, selectfrom config import paths@@ -26,8 +27,8 @@ from storage.settings_service import upsert_scopeNOW = "2026-10-20T00:00:00.000000Z"SESSION = "ses_last_reply"TURN = "trn_last_reply"-REVISION = "20261020_0071"PREVIOUS_REVISION = "20261018_0070"+HEAD = ScriptDirectory.from_config(migrations.alembic_config()).get_current_head()def _seed(conn) -> dict:@@ -220,7 +221,7 @@ async def test_a_released_database_upgrades_and_its_running_turn_ends_without_a_dispose_cached_sqlite_engines()with sqlite3.connect(path) as conn:- assert conn.execute("select version_num from alembic_version").fetchone() == (REVISION,)+ assert conn.execute("select version_num from alembic_version").fetchone() == (HEAD,)command.downgrade(migrations.alembic_config(path), PREVIOUS_REVISION)with sqlite3.connect(path) as conn:tables = {row[0] for row in conn.execute("select name from sqlite_master where type = 'table'")}diff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.pyindex ffdb67fce..7e4557f19 100644--- a/tests/test_web_push_provider_invalidation_migration.py+++ b/tests/test_web_push_provider_invalidation_migration.py@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)with sqlite3.connect(path) as conn:assert conn.execute("select version_num from alembic_version").fetchone() == (- "20261020_0071",+ "20261030_0072",)command.downgrade(migrations.alembic_config(path), "20260907_0061")diff --git a/vibe/cli.py b/vibe/cli.pyindex d90293f88..0f1beafa9 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -18061,11 +18061,15 @@ 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"+ "Recall earlier work through four views (the raw tables stay queryable):\n"+ " digests(session_id, title, agent_name, last_active_at, parent_session_id, digest_at, mind, memo, now, text)\n"+ " what each Session is about and where it stands: a Vibey Session's latest checkpoint memory\n"+ " (mind, memo, now; text holds all three), else its first input and latest reply\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, title, excerpt(text, 'tax') from digests where text like '%tax%' order by last_active_at desc\" --format text\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"