Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

refactor(state): collapse sqlite schema

cyh0ce387b77471
diff --git a/docs/plans/sqlite-state-migration.md b/docs/plans/sqlite-state-migration.md
index 60d5b13f4..82e17ab2e 100644
--- a/docs/plans/sqlite-state-migration.md
+++ b/docs/plans/sqlite-state-migration.md
@@ -1,832 +1,325 @@
-# SQLite State Migration Plan
+# SQLite State Migration Design
## Status
- Branch: `feature/sqlite-state-migration-plan`
-- Status: Planning
-- Scope: Settings, sessions, and future session message storage
-
-## Background
-
-Vibe Remote currently stores product state in JSON files under
-`~/.vibe_remote/`. This has worked well while the state model was small:
-
-- `config/config.json`: global runtime, platform, backend, and UI config
-- `state/settings.json`: channel/user/guild settings, routing, bind codes
-- `state/sessions.json`: agent session mappings, active polls, active
- threads, and processed-message deduplication
-- `state/scheduled_tasks.json`, `state/watches.json`, and
- `state/task_requests/`: task/watch orchestration
-- `state/discovered_chats.json`: discovered IM chat metadata
-- `runtime/*.json`: pid/status/doctor/watch runtime files
-
-The next product direction changes the pressure on persistence:
-
-- Web UI Chat will need session listing, pagination, message replay, and
- eventually search.
-- Sub-agent support will add richer session/message relationships and more
- routing metadata.
-- Session state is no longer only a small recovery blob; it is becoming a
- product data model.
-- Project-level user-editable configuration should remain file-based, similar
- to Claude Code and Codex, rather than becoming opaque database rows.
-
-The migration should therefore separate **configuration** from **data**:
-
-- User-editable project configuration remains file-based.
-- Operational/product state that benefits from indexing, querying, and
- recovery moves to SQLite.
-
-## Goals
-
-1. Migrate existing users automatically and safely on upgrade.
-2. Make SQLite the source of truth for settings, sessions, and future message
- history.
-3. Preserve current public Python APIs during the first implementation pass so
- platform adapters and agent backends do not all change at once.
-4. Keep hot reload behavior simple and robust across the UI process and service
- process.
-5. Add real migration management with Alembic rather than ad hoc schema setup.
-6. Keep project-level user configuration readable and editable on disk.
-7. Avoid long-lived ORM sessions or ORM-object caching in runtime code.
-
-## Non-Goals
-
-- Do not move `config/config.json` into SQLite in the first migration. It
- contains user-facing global configuration and secrets, already has atomic
- writes, and is edited through a mature API path.
-- Do not migrate task/watch persistence in the first pass. The current volume is
- low and file-based claim/recovery semantics are already well-scoped.
-- Do not move pid/status/doctor runtime files into SQLite. They are process
- liveness artifacts, not durable product data.
-- Do not add a revision table in the first pass. Use SQLite's built-in
- `PRAGMA data_version` for coarse cache invalidation.
-- Do not make project-level agent/skill config database-backed. Keep those files
- under the user's project so they can be reviewed, edited, and versioned.
-
-## Proposed Storage Boundary
-
-### Remain File-Based
-
-| Data | Reason |
-| --- | --- |
-| `config/config.json` | User-visible global config and secrets; existing API already validates and atomically writes it. |
-| Project-level `.vibe/*` config | Should be reachable and versionable by users in project repos. |
-| `scheduled_tasks.json` | Low volume; not urgent; can migrate later if task querying grows. |
-| `watches.json` | Low volume; operational control rather than chat/session product data. |
-| `task_requests/` | Directory queue semantics are already clear; defer DB queue until needed. |
-| `runtime/*.json` | Process state, pid files, status snapshots; DB adds little value. |
-| `user_preferences.md` | Human-readable durable notes, not structured app state. |
-
-### Move to SQLite
-
-| Data | Reason |
-| --- | --- |
-| Settings | Needs scoped lookup, future filtering, admin/user management, and UI views. |
-| Sessions | Needs robust session identity, session listing, restore behavior, and agent binding queries. |
-| Session messages/events | Needed for Web UI Chat, replay, pagination, search, and sub-agent activity. |
-| Discovered chats | Useful for searchable UI selection; small but naturally relational. |
-
-## Dependency Choice
-
-Use:
-
-- SQLAlchemy 2.x for database access.
-- Alembic for schema migrations.
-
-Rationale:
-
-- Alembic is the mature migration path for SQLAlchemy and avoids inventing a
- local migration runner.
-- SQLAlchemy lets the implementation use ORM where it improves clarity and Core
- where explicit SQL is better.
-- The app already uses Python dataclasses heavily; service methods can return
- plain dataclasses instead of leaking ORM objects across layers.
-
-Avoid:
-
-- Peewee as the primary ORM: lighter, but migration management is weaker for
- this product's upgrade-safety requirement.
-- SQLModel as the first choice: it adds Pydantic coupling without solving
- migrations better than SQLAlchemy plus Alembic.
-- Long-lived SQLAlchemy `Session` objects as application caches.
-
-## Database Layout
+- Scope: migrate Settings and Sessions from JSON files to SQLite.
+- Source compatibility: keep existing `SettingsStore` and `SessionsStore`
+ Python APIs during the first pass.
+- Release assumption: the previous 14-table draft has not shipped, so the
+ initial Alembic revision is rewritten to the final six-table model instead of
+ adding a migration from an unreleased schema.
-Default path:
+## Product Intent
-```text
-~/.vibe_remote/state/vibe.sqlite
-```
+This migration is not a mechanical JSON-to-table conversion. The goal is to
+separate durable product state from user-editable files and establish a small
+data model that can support Web UI Chat, sub-agents, session recovery, and
+future querying without inheriting the accidental shape of the old JSON files.
-Migration and backup paths:
+The durable model recognizes six concepts:
-```text
-~/.vibe_remote/state/vibe.sqlite
-~/.vibe_remote/state/vibe.sqlite-shm
-~/.vibe_remote/state/vibe.sqlite-wal
-~/.vibe_remote/state/migration.lock
-~/.vibe_remote/state/backups/<timestamp>/
-```
+- `scopes`: external IM objects that Vibe Remote can configure or observe.
+- `scope_settings`: current default configuration for a scope.
+- `agent_sessions`: Vibe Remote-owned agent session handles.
+- `runtime_records`: typed restart/dedup/recovery records.
+- `auth_codes`: user binding code lifecycle.
+- `state_meta`: database-level migration and compatibility markers.
-Connection setup:
+## Storage Boundary
-```sql
-PRAGMA journal_mode = WAL;
-PRAGMA foreign_keys = ON;
-PRAGMA busy_timeout = 5000;
-```
+SQLite becomes the source of truth for:
-Notes:
+- channel, guild, platform policy, and user settings;
+- bound user roles;
+- bind codes;
+- agent session mappings;
+- active poll/thread recovery state;
+- processed-message dedup records;
+- discovered chat identity metadata.
-- WAL allows the UI process and service process to read concurrently while a
- writer commits changes.
-- `busy_timeout` avoids brittle immediate failures when the two processes race.
-- `foreign_keys` should be enabled on every connection because SQLite does not
- enforce it globally.
+These remain file-based for now:
-## Layering
+- `config/config.json`, because it contains global runtime/platform/backend
+ config and secrets;
+- project-level agent/skill config, because users should be able to inspect and
+ version it in their repository;
+- task/watch persistence, because volume is low and the current queue semantics
+ are already clear;
+- process runtime artifacts such as pid/status files.
-The new persistence stack should have four layers:
+## Database File
-```text
-Business code
- -> SettingsService / SessionService / MessageStore
- -> repositories
- -> SQLAlchemy engine + short-lived Session
- -> SQLite
-```
+Default path:
-Rules:
-
-- Business code should not import SQLAlchemy models directly.
-- Public service methods return dataclasses, frozen dataclasses, or simple
- dictionaries that match current domain concepts.
-- A SQLAlchemy `Session` is request/operation scoped, not process scoped.
-- ORM objects are not cached and are not passed into platform adapters.
-- Stores keep the old method names where practical during the first migration
- so existing call paths can move gradually.
-
-## Why Not Cache ORM Objects
-
-SQLAlchemy ORM objects are in-process Python objects associated with one
-SQLAlchemy `Session`. They do not represent shared live state across processes.
-
-The UI process and service process can share the SQLite database file, but they
-cannot share the same ORM object or identity map. A long-lived ORM session would
-also risk stale reads after the other process updates the database.
-
-If caching is needed, cache resolved domain values such as:
-
-```python
-EffectiveSettings(
- platform="slack",
- scope_type="channel",
- scope_id="C123",
- enabled=True,
- show_message_types=("assistant", "toolcall"),
- custom_cwd="/repo",
- routing=RoutingSettings(...),
- require_mention=False,
-)
+```text
+~/.vibe_remote/state/vibe.sqlite
```
-This object is independent of the DB session lifecycle and can be discarded
-whenever the underlying DB changes.
-
-## Hot Reload Strategy
-
-First pass:
-
-- SQLite is the source of truth.
-- Each process keeps its own small in-memory cache only where there is a proven
- hot path.
-- Same-process writes clear that process's relevant cache immediately.
-- Cross-process writes are detected through `PRAGMA data_version`.
-- If the data version changes, clear the cache and reload on the next access.
-- Compare `PRAGMA data_version` values on one long-lived probe connection per
- process. Do not compare values from arbitrary pooled connections; SQLite only
- guarantees useful comparisons across repeated calls on the same connection.
-
-Implementation sketch:
-
-```python
-class SqliteInvalidationProbe:
- def __init__(self, engine):
- self.connection = engine.connect()
- self.last_data_version: int | None = None
-
- def has_external_write(self) -> bool:
- version = self.connection.exec_driver_sql("PRAGMA data_version").scalar_one()
- changed = self.last_data_version is not None and version != self.last_data_version
- self.last_data_version = version
- return changed
+Connection setup:
- def close(self) -> None:
- self.connection.close()
+```sql
+PRAGMA journal_mode = WAL;
+PRAGMA foreign_keys = ON;
+PRAGMA busy_timeout = 5000;
```
-Settings resolution:
-
-- At message ingress, resolve effective settings once for the context.
-- Store the resolved value on the message/request context.
-- Downstream routing, handlers, and formatters use that resolved context value.
-- CLI and UI API reads query through the same service layer.
-
-This preserves the current "changes show up shortly after saving" behavior
-without building a custom revision table. If a future Web UI needs more precise
-invalidation, add a `change_log` or domain revision table later.
-
-## Schema Draft
-
-The first schema should be explicit enough to support future querying, but not
-over-normalized. JSON columns are acceptable for stable, nested settings where
-SQL filtering is not valuable yet.
-
-### `schema_meta`
-
-Optional app-level metadata separate from Alembic's own version table:
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `key` | text primary key | Metadata key |
-| `value` | text | Metadata value |
-| `updated_at` | text | ISO timestamp |
+WAL allows the Web UI process and service process to share the same SQLite file
+with concurrent readers. `busy_timeout` keeps short write races from failing
+immediately.
-Use for import markers such as `json_import_completed_at`.
+## Table Design
### `scopes`
-Common identity for channel/user/guild scopes.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | integer primary key | Internal key |
-| `platform` | text not null | `slack`, `discord`, `telegram`, `lark`, `wechat` |
-| `scope_type` | text not null | `channel`, `user`, `guild` |
-| `scope_id` | text not null | Native IM ID |
-| `display_name` | text | Optional user/chat display name |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
+`scopes` represents a long-lived external target in an IM platform. A scope is
+not a thread. Thread and flat-chat differences are represented by
+`agent_sessions.session_anchor`.
+
+Fields:
+
+- `id`: semantic primary key, formatted as
+ `<platform>::<scope_type>::<native_id>`, for example
+ `slack::channel::C123`. This is a readable DB identity, not something runtime
+ code should parse to recover the platform ID.
+- `platform`: `slack`, `telegram`, `discord`, `lark`, `wechat`, or future
+ platform name.
+- `scope_type`: `channel`, `user`, `guild`, or `platform`.
+- `native_id`: the original platform ID used by IM adapters, for example a
+ Slack channel ID or Telegram chat ID.
+- `parent_scope_id`: optional parent scope, such as a Discord channel pointing
+ to its guild scope.
+- `display_name`: UI name such as `#general`, `Core Forum`, or `Alex`.
+- `native_type`: platform-native kind such as Telegram `supergroup`.
+- `is_private`: private channel/chat/DM marker.
+- `supports_threads`: normalized thread/topic capability.
+- `metadata_json`: platform-observed metadata that is not a primary query
+ dimension.
+- `first_seen_at`, `last_seen_at`, `updated_at`: lifecycle timestamps.
Constraints and indexes:
-- Unique: `(platform, scope_type, scope_id)`
-- Index: `(platform, scope_type)`
-
-### `channel_settings`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `scope_id` | integer primary key references `scopes(id)` | Must be `channel` scope |
-| `enabled` | integer not null | Boolean |
-| `show_message_types_json` | text not null | Serialized list |
-| `custom_cwd` | text | Optional |
-| `routing_json` | text not null | Serialized routing settings |
-| `require_mention` | integer | Null means inherit global default |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
-
-### `guild_settings`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `scope_id` | integer primary key references `scopes(id)` | Must be `guild` scope |
-| `enabled` | integer not null | Boolean |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
-
-### `guild_policies`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `platform` | text primary key | Usually `discord`, but keep generic |
-| `default_enabled` | integer not null | Boolean |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
-
-### `user_settings`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `scope_id` | integer primary key references `scopes(id)` | Must be `user` scope |
-| `is_admin` | integer not null | Boolean |
-| `bound_at` | text | ISO timestamp |
-| `enabled` | integer not null | Boolean |
-| `show_message_types_json` | text not null | Serialized list |
-| `custom_cwd` | text | Optional |
-| `routing_json` | text not null | Serialized routing settings |
-| `dm_chat_id` | text | Lark/Feishu DM delivery binding |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
-
-### `bind_codes`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `code` | text primary key | Existing code string |
-| `type` | text not null | `one_time` or `expiring` |
-| `created_at` | text not null | ISO timestamp |
-| `expires_at` | text | ISO timestamp |
-| `is_active` | integer not null | Boolean |
-| `used_by_json` | text not null | Preserve existing list semantics first |
-
-Future refinement: normalize used-by rows only if UI/query requirements need it.
-
-### `agent_session_bindings`
-
-Replaces `session_mappings`.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | integer primary key | Internal key |
-| `scope_key` | text not null | Existing key such as `slack::C123` |
-| `agent_name` | text not null | `opencode`, `claude`, `codex`, or sub-agent name |
-| `thread_id` | text not null | Existing thread/base key |
-| `session_id` | text not null | Backend-native session ID |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
+- Primary key: `id`.
+- Unique: `(platform, scope_type, native_id)`, because one external IM object
+ must map to one scope.
+- Index: `(platform, scope_type)` for platform UI lists.
+- Index: `parent_scope_id` for parent/child navigation.
+
+### `scope_settings`
+
+`scope_settings` stores the current default configuration attached to a scope.
+Channel settings, user settings, guild settings, and platform-level guild policy
+share one table. Stable query dimensions are columns; volatile or nested details
+stay in JSON.
+
+Fields:
+
+- `scope_id`: primary key and foreign key to `scopes.id`.
+- `enabled`: whether the scope is enabled.
+- `role`: user permission role, currently `admin` or `member`; only meaningful
+ for user scopes.
+- `workdir`: default working directory for this scope.
+- `agent_backend`: default backend, such as `codex`, `claude`, or `opencode`.
+- `agent_variant`: default agent/sub-agent name.
+- `model`: default model for this scope.
+- `reasoning_effort`: default reasoning effort when the backend supports it.
+- `require_mention`: channel/platform mention policy override; null means
+ inherit.
+- `settings_version`: version of `settings_json`.
+- `settings_json`: non-primary-query details such as `show_message_types`,
+ bound DM chat ID, and backend-specific temporary settings.
+- `created_at`, `updated_at`: lifecycle timestamps.
Constraints and indexes:
-- Unique: `(scope_key, agent_name, thread_id)`
-- Index: `(session_id)`
-- Index: `(scope_key, agent_name)`
-
-### `active_threads`
-
-Replaces `active_slack_threads`, but keeps the model platform-generic.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | integer primary key | Internal key |
-| `scope_key` | text not null | Existing user/session scope key |
-| `channel_id` | text not null | Native channel/chat ID |
-| `thread_id` | text not null | Native thread/topic ID |
-| `last_active_at` | real not null | Preserve current float timestamp semantics |
-
-Constraints:
+- Primary key: `scope_id`. One scope has one current default settings row.
+- Index: `role` for admin/user listing.
+- Index: `workdir` for project-level grouping and management.
+- Index: `(agent_backend, model)` for Web UI filtering and bulk editing.
+
+### `agent_sessions`
+
+`agent_sessions` stores Vibe Remote-owned agent session instances. The ID is a
+short random handle intended to be injected into prompts, shown in logs, and
+passed back to CLI commands.
+
+Fields:
+
+- `id`: primary key, formatted as `ses` plus 10 lowercase base32-like
+ characters, for example `sesk8m4q2p7x`. It has no symbols, is not purely
+ numeric, and is short enough for agents to copy.
+- `scope_id`: optional foreign key to `scopes.id`.
+- `agent_backend`: backend used to create the native session.
+- `agent_variant`: routing agent or sub-agent name; defaults to `default` for
+ future APIs.
+- `model`: model used when the native session was created.
+- `reasoning_effort`: reasoning effort used when the native session was
+ created.
+- `session_anchor`: conversation anchor. A Slack thread uses thread/message ID;
+ a flat Telegram chat uses the chat itself.
+- `workdir`: working directory used for the session.
+- `native_session_id`: underlying backend session ID, encoded as a string while
+ preserving legacy non-string values.
+- `title`: optional Web UI title.
+- `status`: `active`, `stale`, `archived`, or future state.
+- `metadata_json`: compatibility and backend-specific details.
+- `created_at`, `updated_at`, `last_active_at`: lifecycle timestamps.
-- Unique: `(scope_key, channel_id, thread_id)`
-
-### `active_polls`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `opencode_session_id` | text primary key | Existing key |
-| `base_session_id` | text not null | Existing value |
-| `platform` | text not null | Backfilled during import |
-| `channel_id` | text not null | Existing value |
-| `thread_id` | text not null | Existing value |
-| `settings_key` | text not null | Raw settings key |
-| `working_path` | text not null | Existing value |
-| `started_at` | real not null | Existing value |
-| `baseline_message_ids_json` | text not null | Existing list |
-| `seen_tool_calls_json` | text not null | Existing list |
-| `emitted_assistant_messages_json` | text not null | Existing list |
-| `ack_reaction_message_id` | text | Existing value |
-| `ack_reaction_emoji` | text | Existing value |
-| `typing_indicator_active` | integer not null | Boolean |
-| `context_token` | text not null | Existing value |
-| `processing_indicator_json` | text not null | Existing dict |
-| `user_id` | text not null | Existing value |
-| `updated_at` | text not null | ISO timestamp |
-
-### `processed_messages`
-
-Replaces `processed_message_ts`.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | integer primary key | Internal key |
-| `channel_id` | text not null | Native channel/chat ID |
-| `thread_id` | text not null | Native thread/topic ID |
-| `message_id` | text not null | Native message ID |
-| `processed_at` | text not null | ISO timestamp |
-
-Constraints and cleanup:
-
-- Unique: `(channel_id, thread_id, message_id)`
-- Index: `(channel_id, thread_id, processed_at)`
-- Keep only the latest 200 rows per `(channel_id, thread_id)` to preserve
- current bounded-dedup behavior.
-
-### `chat_sessions`
-
-New product model for Web UI Chat and sub-agent activity.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | text primary key | Stable Vibe Remote session ID |
-| `platform` | text not null | IM platform |
-| `scope_type` | text not null | `channel` or `user` |
-| `scope_id` | text not null | Native channel/user ID |
-| `thread_id` | text | Native thread/topic ID |
-| `agent_backend` | text | Effective backend |
-| `agent_name` | text | Effective agent/sub-agent |
-| `working_path` | text | Effective cwd |
-| `title` | text | Optional display title |
-| `status` | text not null | `active`, `idle`, `archived`, `error` |
-| `created_at` | text not null | ISO timestamp |
-| `updated_at` | text not null | ISO timestamp |
-| `last_message_at` | text | ISO timestamp |
+Constraints and indexes:
-Indexes:
+- Primary key: `id`.
+- No business unique constraint on `scope_id + session_anchor + workdir`. Future
+ Web UI Chat, forks, sub-agents, and parallel agents can create multiple
+ sessions under the same context.
+- Index: `(scope_id, session_anchor, workdir)` to restore/list sessions for a
+ context.
+- Index: `(agent_backend, agent_variant)` for backend/agent filtering.
+- Index: `(status, last_active_at)` for "recent active session" queries.
+- Index: `native_session_id` for reverse lookup and compatibility.
+
+### `runtime_records`
+
+`runtime_records` keeps restartable operational state and idempotency markers
+without splitting every low-level runtime concept into its own table.
+
+Fields:
+
+- `id`: primary key, formatted as `runtime::<record_type>::<record_key>`.
+- `record_type`: `active_poll`, `active_thread`, `processed_message`, or future
+ runtime record type.
+- `record_key`: type-local stable key.
+- `scope_id`: optional foreign key to `scopes.id`.
+- `session_anchor`: optional conversation anchor for cleanup or listing.
+- `workdir`: optional project directory for diagnostics and cleanup.
+- `payload_json`: type-specific recovery payload.
+- `expires_at`: optional cleanup time.
+- `created_at`, `updated_at`: lifecycle timestamps.
-- `(platform, scope_type, scope_id, updated_at)`
-- `(agent_backend, agent_name)`
-- `(working_path)`
+Constraints and indexes:
-### `session_messages`
-
-Append-only message/event stream for Web UI Chat and replay.
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `id` | text primary key | Stable event/message ID |
-| `session_id` | text not null references `chat_sessions(id)` | Vibe session |
-| `parent_message_id` | text | For threaded/sub-agent relationships |
-| `role` | text not null | `user`, `assistant`, `system`, `tool`, `event` |
-| `source` | text not null | `im`, `agent`, `scheduled`, `hook`, `system` |
-| `content_text` | text | Renderable text |
-| `content_json` | text not null | Full structured payload |
-| `agent_backend` | text | Backend that produced it |
-| `agent_name` | text | Agent/sub-agent that produced it |
-| `native_message_id` | text | IM or backend-native ID |
-| `created_at` | text not null | ISO timestamp |
-
-Indexes:
-
-- `(session_id, created_at)`
-- `(native_message_id)`
-- `(agent_backend, agent_name, created_at)`
-
-Future search:
-
-- Add SQLite FTS only after Web UI Chat needs full-text search. Do not include
- FTS in the first migration.
-
-### `discovered_chats`
-
-| Column | Type | Notes |
-| --- | --- | --- |
-| `platform` | text not null | IM platform |
-| `chat_id` | text not null | Native chat/channel ID |
-| `name` | text not null | Display name |
-| `username` | text not null | Optional username |
-| `chat_type` | text not null | Native chat type |
-| `is_private` | integer not null | Boolean |
-| `is_forum` | integer not null | Boolean |
-| `supports_topics` | integer not null | Boolean |
-| `last_seen_at` | text not null | ISO timestamp |
-
-Primary key:
-
-- `(platform, chat_id)`
-
-## JSON Compatibility Mapping
-
-The first implementation should preserve the current dataclass domain models
-and method signatures where possible.
-
-### Settings Import
-
-Current JSON `settings.json` supports both current and legacy schemas:
-
-- Current: `scopes.channel`, `scopes.guild`, `scopes.guild_policy`,
- `scopes.user`, `bind_codes`
-- Legacy: flat `channels` and `users`
-
-Import should reuse the current parser in `config.v2_settings.SettingsStore`
-first, then persist the normalized `SettingsState` into SQLite. This avoids
-duplicating legacy inference rules in the DB importer.
-
-### Sessions Import
-
-Current JSON `sessions.json` includes:
-
-- `session_mappings`
-- `active_slack_threads`
-- `active_polls`
-- `processed_message_ts`
-- `last_activity`
-
-Import should reuse existing migration helpers first:
-
-- `migrate_active_polls(primary_platform)`
-- `migrate_session_mappings(primary_platform)`
-
-Then import the normalized in-memory state into SQLite.
-
-### Message Store Bootstrap
-
-Existing installs do not have historical message content in Vibe Remote state.
-On first migration:
-
-- Create empty `chat_sessions` and `session_messages`.
-- Existing agent session bindings remain available through
- `agent_session_bindings`.
-- Web UI Chat only shows messages captured after the new message store ships.
+- Primary key: `id`.
+- Unique: `(record_type, record_key)`, because `record_key` is defined as the
+ type-local business identity.
+- Index: `(record_type, scope_id, expires_at)` for recovery and cleanup.
+- Index: `(scope_id, session_anchor)` for context-level runtime lookup.
+- Index: `workdir` for project-level cleanup and diagnostics.
-## First-Run Migration Flow
+### `auth_codes`
-Migration must be automatic when a user installs a new version and starts Vibe
-Remote. It must also be idempotent.
+`auth_codes` stores bind-code lifecycle. It is independent from scopes because
+codes can be created before any user scope exists.
-1. Ensure `~/.vibe_remote/state/` exists.
-2. Acquire an exclusive migration lock:
- - Use a `migration.lock` file with OS-level locking.
- - The UI process and service process must share this lock.
- - If another process is migrating, wait with a timeout and then re-check DB
- health.
-3. Open or create `vibe.sqlite`.
-4. Run Alembic migrations to the latest head.
-5. If `schema_meta.json_import_completed_at` exists, skip JSON import.
-6. If JSON import is needed, create a timestamped backup directory:
- - Copy `settings.json` if present.
- - Copy `sessions.json` if present.
- - Copy `discovered_chats.json` if present.
- - Copy a small manifest with source file sizes and mtimes.
-7. Parse current JSON through existing stores:
- - Use current `SettingsStore` parser for settings.
- - Use current `SessionsStore` loader plus current migration helpers for
- sessions.
- - Use current `DiscoveredChatsStore` parser for discovered chats.
-8. Import all parsed rows in one SQLite transaction.
-9. Validate imported data:
- - `PRAGMA integrity_check` returns `ok`.
- - Imported counts match parsed counts for channels, users, guilds, bind
- codes, session mappings, active polls, processed messages, and discovered
- chats.
- - Critical uniqueness checks have no conflicts.
-10. Mark `json_import_completed_at` in `schema_meta` within the same
- transaction.
-11. Leave original JSON files in place as backups. Do not delete or rewrite them
- during the first release.
-12. Release the migration lock.
+Fields:
-Failure behavior:
+- `code`: primary key and user-entered token.
+- `type`: `one_time` or `expiring`.
+- `is_active`: whether the code can still be used.
+- `expires_at`: optional expiration.
+- `used_by_json`: list of user scope keys or legacy user IDs that consumed it.
+- `created_at`, `updated_at`: lifecycle timestamps.
-- If migration fails before `json_import_completed_at`, leave the DB either
- empty or partially written only inside a rolled-back transaction.
-- Keep JSON files untouched.
-- Log the failure and continue with JSON fallback only for the first migration
- release if fallback is explicitly implemented.
-- If fallback is not implemented, fail startup with a clear doctor/actionable
- error rather than running against ambiguous state.
+Constraints:
-Recommended first-release approach:
+- Primary key: `code`.
+- No extra unique constraint.
-- Implement a JSON fallback read path behind a temporary `StorageProvider`
- boundary for one release.
-- Once migration stability is proven, remove fallback writes and keep JSON only
- as recovery backups.
+### `state_meta`
-## Runtime Access Pattern
+`state_meta` stores database-level metadata.
-### Settings
+Fields:
-Introduce `SettingsService` as the canonical runtime API:
+- `key`: primary key.
+- `value_json`: JSON-encoded value.
+- `updated_at`: timestamp.
-- `get_effective_settings(platform, scope_type, scope_id)`
-- `get_channel_settings(platform, channel_id)`
-- `update_channel_settings(platform, channel_id, settings)`
-- `get_user(platform, user_id)`
-- `bind_user_with_code(platform, user_id, display_name, code, dm_chat_id)`
-- `list_channels(platform, filters...)`
-- `list_users(platform, filters...)`
+Current keys:
-The existing `SettingsStore` and `SettingsManager` can become compatibility
-wrappers around this service during migration.
-
-Cache:
+- `json_import_completed_at`
+- `sessions_last_activity`
-- Start without caching except for per-message resolved settings.
-- Add a small effective-settings cache only if profiling shows need.
-- Invalidate by same-process write and `PRAGMA data_version`.
-
-### Sessions
-
-Introduce `SessionService`:
-
-- Agent session binding methods used by `SessionsFacade`.
-- Active-thread methods used by Slack and scheduled delivery.
-- Active-poll restore/update methods used by OpenCode.
-- Processed-message dedup methods.
-- New chat-session/message APIs for Web UI Chat.
-
-The existing `SessionsStore` can become a compatibility wrapper around
-`SessionService`. `SessionsFacade` should keep its public method names during
-the first pass.
-
-### Messages
-
-Add append-only capture from the common message handling path, not from each
-platform adapter. The right long-term integration point is near core handlers
-or dispatcher boundaries, where both IM inbound messages and agent outbound
-events have normalized context.
-
-First pass message capture can be limited to:
-
-- Inbound user message.
-- Final assistant response.
-- Tool-call summaries if already normalized.
-
-Do not block the SQLite migration on perfect event capture coverage.
-
-## Implementation Phases
-
-### Phase 0: Storage Skeleton
-
-- Add dependencies: `sqlalchemy` and `alembic`.
-- Add `storage/` package:
- - engine/session factory
- - SQLite pragmas
- - migration runner
- - migration lock
- - invalidation probe
-- Add Alembic environment and first schema migration.
-- Add path helpers for `vibe.sqlite` and `migration.lock`.
-
-Validation:
+## JSON Payload Policy
-- Unit tests for engine pragmas, migration lock, and idempotent migration
- runner.
-- A test that creates an empty DB and verifies Alembic head.
+SQLite JSON functions exist, but this design does not rely on JSON as the main
+query interface. If a field is expected to be filtered, sorted, joined, or used
+for authorization, it becomes a column.
-### Phase 1: Importer and Read-Only Verification
+Column fields:
-- Implement JSON-to-SQLite importer.
-- Reuse current JSON parsers and compatibility migrations.
-- Add count and integrity validation.
-- Add a CLI/internal doctor command to inspect migration status.
+- `role`
+- `workdir`
+- `agent_backend`
+- `agent_variant`
+- `model`
+- `reasoning_effort`
+- `native_type`
+- `is_private`
+- `supports_threads`
+- `session_anchor`
+- `status`
-Validation:
+JSON fields:
-- Fixtures for current settings schema.
-- Fixtures for legacy flat settings schema.
-- Fixtures for legacy session mappings and active polls.
-- Corrupt JSON handling.
-- Existing JSON remains untouched.
+- `show_message_types`, because current code reads it with settings as a whole;
+- backend-specific temporary routing details;
+- platform raw metadata such as username or flags;
+- active poll internals such as baseline message IDs and seen tool calls.
-### Phase 2: Settings Store Switch
+## Migration Flow
-- Implement `SettingsService` and repositories.
-- Convert `SettingsStore` to SQLite-backed behavior while preserving current
- public methods.
-- Convert `SettingsManager` to resolve from service instead of JSON mtime.
-- Replace `_file_mtime` checks with `data_version` invalidation semantics.
-- Keep dataclass serialization behavior stable at API boundaries.
+1. Resolve target DB and state directory.
+2. Acquire `migration.lock`.
+3. Run Alembic migrations.
+4. If `state_meta.json_import_completed_at` exists, skip JSON import.
+5. Clear previously imported SQLite rows if a previous import failed before
+ writing the marker.
+6. Back up `settings.json`, `sessions.json`, and `discovered_chats.json` to
+ `state/backups/sqlite-state-migration-<timestamp>/`.
+7. Parse JSON from temporary copies so source JSON is never rewritten during
+ import.
+8. Import settings through `SQLiteSettingsService`.
+9. Import sessions through `SQLiteSessionsService`.
+10. Import discovered chats into `scopes`.
+11. Run `PRAGMA integrity_check`.
+12. Write `state_meta.json_import_completed_at`.
-Validation:
+The old JSON files are not deleted and are no longer written after the stores
+switch to SQLite. Later startup decisions rely on the SQLite marker, not on
+whether JSON files still exist.
-- Existing settings, auth, user-scope, Discord guild, update-checker, and UI API
- tests should pass with minimal changes.
-- Add cross-process simulation: one connection writes settings, another process
- detects `data_version` change and reloads.
+## Compatibility Notes
-### Phase 3: Sessions Store Switch
+- Existing `SettingsStore` methods continue returning `ChannelSettings`,
+ `GuildSettings`, `UserSettings`, and `BindCode`.
+- Existing `SessionsStore` methods continue returning `SessionState` and
+ `ActivePollInfo`.
+- Settings writes upsert missing scopes but do not erase observed scope metadata
+ such as private/thread capability flags gathered from discovered chats.
+- Legacy session values that were not strings are stored with a JSON prefix and
+ decoded back to their original shape.
+- Legacy raw session scope keys are preserved in `agent_sessions.metadata_json`
+ so direct `SessionsStore.save()` / reload behavior does not rename keys.
+- Platform backfill for old sessions still requires a primary platform when the
+ platform cannot be inferred.
-- Implement `SessionService`.
-- Convert `SessionsStore` and `SessionsFacade` to SQLite-backed behavior.
-- Preserve active poll restore behavior.
-- Preserve processed-message bounded dedup behavior.
-- Preserve agent session mapping semantics across OpenCode, Claude, and Codex.
+## Validation
-Validation:
+Focused validation for this migration:
-- Existing `test_v2_sessions.py` coverage should pass through the compatibility
- wrapper.
-- Add concurrent write tests for processed-message dedup and active-poll
- updates.
+```text
+uv run pytest \
+ tests/test_sqlite_state_migration.py \
+ tests/test_sqlite_settings_store.py \
+ tests/test_sqlite_sessions_store.py \
+ tests/test_sqlite_state_startup.py
+```
-### Phase 4: Message Store
+The test coverage checks:
-- Add `chat_sessions` and `session_messages` write APIs.
-- Capture normalized inbound and outbound message records.
-- Expose read APIs for future Web UI Chat:
- - list sessions
- - get session
- - list messages with cursor/pagination
-- Do not build Web UI Chat in this migration PR unless explicitly scoped.
-
-Validation:
-
-- Focused tests for append-only ordering, pagination, and session metadata
- updates.
-- Contract tests around message record shape.
-
-### Phase 5: Cleanup and Documentation
-
-- Update CLI docs to mention SQLite-backed settings/sessions.
-- Update operational docs with backup and recovery steps.
-- Keep JSON backups documented.
-- Decide when to remove JSON fallback code after one stable release window.
-
-## Test Plan
-
-Minimum automated tests:
-
-- Empty install creates SQLite DB and reaches Alembic head.
-- Install with no JSON files starts cleanly.
-- Current `settings.json` imports exactly once.
-- Legacy flat `settings.json` imports through current parser.
-- Current `sessions.json` imports exactly once.
-- Legacy session mappings are normalized before DB import.
-- Corrupt JSON causes clear migration failure and leaves JSON untouched.
-- Second startup after import does not duplicate rows.
-- UI process write invalidates service process cache using `PRAGMA data_version`.
-- Same-process write clears local cache immediately.
-- `processed_messages` enforces bounded dedup behavior.
-- Active polls survive restart and preserve platform/settings-key semantics.
-
-Regression checks:
-
-- Focused pytest for settings and sessions.
-- CLI task/watch tests should not need migration changes in the first pass.
-- Docker regression after settings/sessions switch because platform adapters
- rely heavily on settings lookups.
-
-Manual checks:
-
-- Upgrade a real-ish `~/.vibe_remote` copy with Slack, Discord, Telegram, Lark,
- and WeChat settings.
-- Verify Web UI settings edits are visible to the running service without
- restart.
-- Verify `/clear`, resume, and active thread behavior across OpenCode, Claude,
- and Codex.
-
-## Rollout Plan
-
-First release with SQLite:
-
-- Auto-migrate on startup.
-- Keep source JSON files untouched as recovery backups.
-- Keep a clear doctor/status output showing:
- - DB path
- - Alembic revision
- - JSON import completed timestamp
- - backup path
-- Keep temporary JSON fallback only if migration fails before DB becomes source
- of truth.
-
-Second release:
-
-- Keep JSON backup but stop reading JSON fallback in normal startup.
-- Add explicit recovery command if needed.
-
-Future:
-
-- Consider moving task/watch persistence only when there is a real querying or
- queueing requirement.
-- Add FTS for message search only after Web UI Chat needs it.
-
-## Risks and Mitigations
-
-| Risk | Mitigation |
-| --- | --- |
-| UI and service migrate at the same time | Shared migration lock and idempotent import marker. |
-| Partial import corrupts source of truth | Single SQLite transaction plus untouched JSON backups. |
-| Legacy JSON edge cases are reimplemented incorrectly | Reuse current parsers and current session migration helpers. |
-| Stale settings after UI edit | `PRAGMA data_version` invalidation plus local write cache clear. |
-| Invalid cache checks due to pooled connections | Keep one dedicated probe connection per process for `PRAGMA data_version`. |
-| ORM objects leak into business code | Service/repository boundary returns dataclasses/dicts only. |
-| SQLite write contention | WAL, short transactions, `busy_timeout`, and operation-scoped sessions. |
-| Message store scope grows too large | Ship session/message APIs separately from UI Chat UI. |
-| Existing tests depend on file paths | Compatibility wrappers keep method names; tests migrate gradually. |
-
-## Self Review
-
-This plan is intentionally conservative. The main strength is that it avoids a
-big-bang rewrite: current JSON parsers perform compatibility normalization, then
-SQLite becomes the source of truth behind mostly stable public store APIs.
-
-Issues to watch before implementation:
-
-1. **Fallback policy needs a product decision.** Running with JSON fallback after
- a failed migration is friendlier, but it risks extending dual-source
- complexity. Failing startup loudly is simpler and safer once migration has
- good diagnostics.
-2. **`SettingsManager` currently owns runtime caches.** The first code PR should
- reduce that cache surface rather than translating `_file_mtime` directly into
- another long-lived cache.
-3. **`PRAGMA data_version` is subtle.** The implementation must keep a dedicated
- probe connection per process; comparing values from different pooled
- connections would be a false simplification.
-4. **Message capture should not be bolted onto every platform adapter.** It
- belongs in shared core paths, otherwise multi-platform behavior will drift.
-5. **Alembic packaging must be verified.** Migrations need to be included in
- wheels and sdists, and `vibe` must be able to locate them after installation.
-6. **SQLite path and backup policy need doctor visibility.** Users must be able
- to tell whether they are using DB-backed state and where backups live.
-7. **Schema may need one adjustment before coding:** `chat_sessions.id` should be
- defined from the product's future session identity model. If that identity is
- not settled, the first implementation can create the table but delay writes
- until the session identity contract is clear.
-
-Recommended next step:
-
-- Implement Phase 0 and Phase 1 first, behind compatibility wrappers, and stop
- before switching live Settings/Sessions reads. That gives a safe migration
- artifact that can be tested against real state copies before changing runtime
- behavior.
+- Alembic creates and stamps the initial schema;
+- old JSON files are backed up and not rewritten;
+- import marker is only written after successful import;
+- invalid JSON can be fixed and retried;
+- custom state directories do not create default home directories;
+- Settings and Sessions stores reload external SQLite writes;
+- legacy session mappings and non-string session values round-trip.
diff --git a/storage/alembic/versions/20260501_0001_initial_sqlite_state.py b/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
index 2e77e6bc4..bcbfe3ae5 100644
--- a/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
+++ b/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
@@ -18,206 +18,116 @@ depends_on = None
def upgrade() -> None:
op.create_table(
- "schema_meta",
+ "state_meta",
sa.Column("key", sa.String(), primary_key=True),
- sa.Column("value", sa.Text(), nullable=False),
+ sa.Column("value_json", sa.Text(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
)
op.create_table(
"scopes",
- sa.Column("id", sa.Integer(), primary_key=True),
+ sa.Column("id", sa.String(), primary_key=True),
sa.Column("platform", sa.String(), nullable=False),
sa.Column("scope_type", sa.String(), nullable=False),
- sa.Column("scope_id", sa.String(), nullable=False),
+ sa.Column("native_id", sa.String(), nullable=False),
+ sa.Column("parent_scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
sa.Column("display_name", sa.Text(), nullable=True),
- sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("native_type", sa.String(), nullable=True),
+ sa.Column("is_private", sa.Integer(), nullable=False),
+ sa.Column("supports_threads", sa.Integer(), nullable=False),
+ sa.Column("metadata_json", sa.Text(), nullable=False),
+ sa.Column("first_seen_at", sa.String(), nullable=False),
+ sa.Column("last_seen_at", sa.String(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
- sa.UniqueConstraint("platform", "scope_type", "scope_id", name="uq_scopes_platform_type_id"),
+ sa.UniqueConstraint("platform", "scope_type", "native_id", name="uq_scopes_platform_type_native"),
)
op.create_index("ix_scopes_platform_type", "scopes", ["platform", "scope_type"])
+ op.create_index("ix_scopes_parent", "scopes", ["parent_scope_id"])
op.create_table(
- "channel_settings",
- sa.Column("scope_id", sa.Integer(), sa.ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
+ "scope_settings",
+ sa.Column("scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
sa.Column("enabled", sa.Integer(), nullable=False),
- sa.Column("show_message_types_json", sa.Text(), nullable=False),
- sa.Column("custom_cwd", sa.Text(), nullable=True),
- sa.Column("routing_json", sa.Text(), nullable=False),
+ sa.Column("role", sa.String(), nullable=True),
+ sa.Column("workdir", sa.Text(), nullable=True),
+ sa.Column("agent_backend", sa.String(), nullable=True),
+ sa.Column("agent_variant", sa.String(), nullable=True),
+ sa.Column("model", sa.String(), nullable=True),
+ sa.Column("reasoning_effort", sa.String(), nullable=True),
sa.Column("require_mention", sa.Integer(), nullable=True),
+ sa.Column("settings_version", sa.Integer(), nullable=False),
+ sa.Column("settings_json", sa.Text(), nullable=False),
sa.Column("created_at", sa.String(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
)
+ op.create_index("ix_scope_settings_role", "scope_settings", ["role"])
+ op.create_index("ix_scope_settings_workdir", "scope_settings", ["workdir"])
+ op.create_index("ix_scope_settings_backend_model", "scope_settings", ["agent_backend", "model"])
+
op.create_table(
- "guild_settings",
- sa.Column("scope_id", sa.Integer(), sa.ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
- sa.Column("enabled", sa.Integer(), nullable=False),
- sa.Column("created_at", sa.String(), nullable=False),
- sa.Column("updated_at", sa.String(), nullable=False),
- )
- op.create_table(
- "guild_policies",
- sa.Column("platform", sa.String(), primary_key=True),
- sa.Column("default_enabled", sa.Integer(), nullable=False),
- sa.Column("created_at", sa.String(), nullable=False),
- sa.Column("updated_at", sa.String(), nullable=False),
- )
- op.create_table(
- "user_settings",
- sa.Column("scope_id", sa.Integer(), sa.ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
- sa.Column("is_admin", sa.Integer(), nullable=False),
- sa.Column("bound_at", sa.String(), nullable=True),
- sa.Column("enabled", sa.Integer(), nullable=False),
- sa.Column("show_message_types_json", sa.Text(), nullable=False),
- sa.Column("custom_cwd", sa.Text(), nullable=True),
- sa.Column("routing_json", sa.Text(), nullable=False),
- sa.Column("dm_chat_id", sa.Text(), nullable=True),
- sa.Column("created_at", sa.String(), nullable=False),
- sa.Column("updated_at", sa.String(), nullable=False),
- )
- op.create_table(
- "bind_codes",
+ "auth_codes",
sa.Column("code", sa.String(), primary_key=True),
sa.Column("type", sa.String(), nullable=False),
- sa.Column("created_at", sa.String(), nullable=False),
- sa.Column("expires_at", sa.String(), nullable=True),
sa.Column("is_active", sa.Integer(), nullable=False),
+ sa.Column("expires_at", sa.String(), nullable=True),
sa.Column("used_by_json", sa.Text(), nullable=False),
- )
- op.create_table(
- "agent_session_bindings",
- sa.Column("id", sa.Integer(), primary_key=True),
- sa.Column("scope_key", sa.String(), nullable=False),
- sa.Column("agent_name", sa.String(), nullable=False),
- sa.Column("thread_id", sa.String(), nullable=False),
- sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("created_at", sa.String(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
- sa.UniqueConstraint("scope_key", "agent_name", "thread_id", name="uq_agent_session_binding"),
- )
- op.create_index("ix_agent_session_bindings_session_id", "agent_session_bindings", ["session_id"])
- op.create_index(
- "ix_agent_session_bindings_scope_agent",
- "agent_session_bindings",
- ["scope_key", "agent_name"],
- )
-
- op.create_table(
- "active_threads",
- sa.Column("id", sa.Integer(), primary_key=True),
- sa.Column("scope_key", sa.String(), nullable=False),
- sa.Column("channel_id", sa.String(), nullable=False),
- sa.Column("thread_id", sa.String(), nullable=False),
- sa.Column("last_active_at", sa.Float(), nullable=False),
- sa.UniqueConstraint("scope_key", "channel_id", "thread_id", name="uq_active_thread"),
- )
- op.create_table(
- "active_polls",
- sa.Column("opencode_session_id", sa.String(), primary_key=True),
- sa.Column("base_session_id", sa.String(), nullable=False),
- sa.Column("platform", sa.String(), nullable=False),
- sa.Column("channel_id", sa.String(), nullable=False),
- sa.Column("thread_id", sa.String(), nullable=False),
- sa.Column("settings_key", sa.String(), nullable=False),
- sa.Column("working_path", sa.Text(), nullable=False),
- sa.Column("started_at", sa.Float(), nullable=False),
- sa.Column("baseline_message_ids_json", sa.Text(), nullable=False),
- sa.Column("seen_tool_calls_json", sa.Text(), nullable=False),
- sa.Column("emitted_assistant_messages_json", sa.Text(), nullable=False),
- sa.Column("ack_reaction_message_id", sa.Text(), nullable=True),
- sa.Column("ack_reaction_emoji", sa.Text(), nullable=True),
- sa.Column("typing_indicator_active", sa.Integer(), nullable=False),
- sa.Column("context_token", sa.Text(), nullable=False),
- sa.Column("processing_indicator_json", sa.Text(), nullable=False),
- sa.Column("user_id", sa.String(), nullable=False),
- sa.Column("updated_at", sa.String(), nullable=False),
- )
- op.create_table(
- "processed_messages",
- sa.Column("id", sa.Integer(), primary_key=True),
- sa.Column("channel_id", sa.String(), nullable=False),
- sa.Column("thread_id", sa.String(), nullable=False),
- sa.Column("message_id", sa.String(), nullable=False),
- sa.Column("processed_at", sa.String(), nullable=False),
- sa.UniqueConstraint("channel_id", "thread_id", "message_id", name="uq_processed_message"),
- )
- op.create_index(
- "ix_processed_messages_thread_time",
- "processed_messages",
- ["channel_id", "thread_id", "processed_at"],
)
op.create_table(
- "chat_sessions",
+ "agent_sessions",
sa.Column("id", sa.String(), primary_key=True),
- sa.Column("platform", sa.String(), nullable=False),
- sa.Column("scope_type", sa.String(), nullable=False),
- sa.Column("scope_id", sa.String(), nullable=False),
- sa.Column("thread_id", sa.String(), nullable=True),
- sa.Column("agent_backend", sa.String(), nullable=True),
- sa.Column("agent_name", sa.String(), nullable=True),
- sa.Column("working_path", sa.Text(), nullable=True),
+ sa.Column("scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ sa.Column("agent_backend", sa.String(), nullable=False),
+ sa.Column("agent_variant", sa.String(), nullable=False),
+ sa.Column("model", sa.String(), nullable=True),
+ sa.Column("reasoning_effort", sa.String(), nullable=True),
+ sa.Column("session_anchor", sa.String(), nullable=False),
+ sa.Column("workdir", sa.Text(), nullable=True),
+ sa.Column("native_session_id", sa.Text(), nullable=False),
sa.Column("title", sa.Text(), nullable=True),
sa.Column("status", sa.String(), nullable=False),
+ sa.Column("metadata_json", sa.Text(), nullable=False),
sa.Column("created_at", sa.String(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
- sa.Column("last_message_at", sa.String(), nullable=True),
+ sa.Column("last_active_at", sa.String(), nullable=True),
)
op.create_index(
- "ix_chat_sessions_scope_updated",
- "chat_sessions",
- ["platform", "scope_type", "scope_id", "updated_at"],
+ "ix_agent_sessions_scope_anchor_workdir",
+ "agent_sessions",
+ ["scope_id", "session_anchor", "workdir"],
)
- op.create_index("ix_chat_sessions_agent", "chat_sessions", ["agent_backend", "agent_name"])
- op.create_index("ix_chat_sessions_working_path", "chat_sessions", ["working_path"])
+ op.create_index("ix_agent_sessions_backend_variant", "agent_sessions", ["agent_backend", "agent_variant"])
+ op.create_index("ix_agent_sessions_status_activity", "agent_sessions", ["status", "last_active_at"])
+ op.create_index("ix_agent_sessions_native_session", "agent_sessions", ["native_session_id"])
op.create_table(
- "session_messages",
+ "runtime_records",
sa.Column("id", sa.String(), primary_key=True),
- sa.Column("session_id", sa.String(), sa.ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False),
- sa.Column("parent_message_id", sa.String(), nullable=True),
- sa.Column("role", sa.String(), nullable=False),
- sa.Column("source", sa.String(), nullable=False),
- sa.Column("content_text", sa.Text(), nullable=True),
- sa.Column("content_json", sa.Text(), nullable=False),
- sa.Column("agent_backend", sa.String(), nullable=True),
- sa.Column("agent_name", sa.String(), nullable=True),
- sa.Column("native_message_id", sa.String(), nullable=True),
+ sa.Column("record_type", sa.String(), nullable=False),
+ sa.Column("record_key", sa.String(), nullable=False),
+ sa.Column("scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ sa.Column("session_anchor", sa.String(), nullable=True),
+ sa.Column("workdir", sa.Text(), nullable=True),
+ sa.Column("payload_json", sa.Text(), nullable=False),
+ sa.Column("expires_at", sa.String(), nullable=True),
sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("record_type", "record_key", name="uq_runtime_records_type_key"),
)
- op.create_index("ix_session_messages_session_time", "session_messages", ["session_id", "created_at"])
- op.create_index("ix_session_messages_native_message", "session_messages", ["native_message_id"])
op.create_index(
- "ix_session_messages_agent_time",
- "session_messages",
- ["agent_backend", "agent_name", "created_at"],
- )
-
- op.create_table(
- "discovered_chats",
- sa.Column("platform", sa.String(), primary_key=True),
- sa.Column("chat_id", sa.String(), primary_key=True),
- sa.Column("name", sa.Text(), nullable=False),
- sa.Column("username", sa.Text(), nullable=False),
- sa.Column("chat_type", sa.String(), nullable=False),
- sa.Column("is_private", sa.Integer(), nullable=False),
- sa.Column("is_forum", sa.Integer(), nullable=False),
- sa.Column("supports_topics", sa.Integer(), nullable=False),
- sa.Column("last_seen_at", sa.String(), nullable=False),
+ "ix_runtime_records_type_scope_expiry",
+ "runtime_records",
+ ["record_type", "scope_id", "expires_at"],
)
+ op.create_index("ix_runtime_records_scope_anchor", "runtime_records", ["scope_id", "session_anchor"])
+ op.create_index("ix_runtime_records_workdir", "runtime_records", ["workdir"])
def downgrade() -> None:
- op.drop_table("discovered_chats")
- op.drop_table("session_messages")
- op.drop_table("chat_sessions")
- op.drop_table("processed_messages")
- op.drop_table("active_polls")
- op.drop_table("active_threads")
- op.drop_table("agent_session_bindings")
- op.drop_table("bind_codes")
- op.drop_table("user_settings")
- op.drop_table("guild_policies")
- op.drop_table("guild_settings")
- op.drop_table("channel_settings")
+ op.drop_table("runtime_records")
+ op.drop_table("agent_sessions")
+ op.drop_table("auth_codes")
+ op.drop_table("scope_settings")
op.drop_table("scopes")
- op.drop_table("schema_meta")
+ op.drop_table("state_meta")
diff --git a/storage/importer.py b/storage/importer.py
index a07e86a6b..da164b160 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -3,12 +3,12 @@ from __future__ import annotations
import json
import shutil
import tempfile
-from dataclasses import asdict, dataclass, field, is_dataclass
+from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
-from sqlalchemy import Connection, Engine, func, select
+from sqlalchemy import Connection, func, select
from config import paths
from config.discovered_chats import DiscoveredChatsStore
@@ -19,26 +19,13 @@ from config.v2_sessions import (
migrate_session_state_active_polls,
migrate_session_state_mappings,
)
-from config.v2_settings import SettingsState, _split_scoped_key, load_settings_state_from_json
+from config.v2_settings import SettingsState, load_settings_state_from_json
from storage.db import create_sqlite_engine
from storage.lock import MigrationFileLock
from storage.migrations import run_migrations
-from storage.models import (
- active_polls,
- active_threads,
- agent_session_bindings,
- bind_codes,
- channel_settings,
- discovered_chats,
- guild_policies,
- guild_settings,
- imported_state_tables,
- processed_messages,
- schema_meta,
- scopes,
- user_settings,
-)
-from storage.sessions_service import SESSIONS_LAST_ACTIVITY_KEY, encode_session_value
+from storage.models import agent_sessions, auth_codes, imported_state_tables, runtime_records, scope_settings, scopes, state_meta
+from storage.sessions_service import SESSIONS_LAST_ACTIVITY_KEY, SQLiteSessionsService
+from storage.settings_service import SQLiteSettingsService, upsert_scope
JSON_IMPORT_MARKER = "json_import_completed_at"
@@ -80,19 +67,23 @@ def ensure_sqlite_state(
counts=_current_counts(conn),
)
+ _clear_imported_state(conn)
+
backup_path = _backup_json_state(target_state_dir)
parsed = _parse_json_state(target_state_dir, primary_platform=primary_platform)
+ _write_parsed_state(target_db, parsed)
with engine.begin() as conn:
- _clear_imported_state(conn)
- counts = _import_parsed_state(conn, parsed)
+ discovered_count = _import_discovered_chats(conn, parsed.discovered)
+ counts = _current_counts(conn)
+ counts["discovered_scopes"] = discovered_count
_validate_import(conn, counts)
_set_import_marker(conn)
return MigrationImportReport(
db_path=target_db,
imported=True,
backup_path=backup_path,
- counts=counts,
+ counts=_current_counts(conn) | {"discovered_scopes": discovered_count},
)
finally:
engine.dispose()
@@ -153,7 +144,7 @@ def _resolve_primary_platform_from_config_path(config_path: Path) -> str | None:
def _has_import_marker(conn: Connection) -> bool:
return (
- conn.execute(select(schema_meta.c.value).where(schema_meta.c.key == JSON_IMPORT_MARKER)).scalar_one_or_none()
+ conn.execute(select(state_meta.c.value_json).where(state_meta.c.key == JSON_IMPORT_MARKER)).scalar_one_or_none()
is not None
)
@@ -161,9 +152,9 @@ def _has_import_marker(conn: Connection) -> bool:
def _set_import_marker(conn: Connection) -> None:
now = _utc_now_iso()
conn.execute(
- schema_meta.insert().values(
+ state_meta.insert().values(
key=JSON_IMPORT_MARKER,
- value=now,
+ value_json=_json_dumps(now),
updated_at=now,
)
)
@@ -293,273 +284,59 @@ def _migrate_session_state_for_import(state: SessionState, *, primary_platform:
def _clear_imported_state(conn: Connection) -> None:
for table in imported_state_tables:
conn.execute(table.delete())
- conn.execute(schema_meta.delete().where(schema_meta.c.key == JSON_IMPORT_MARKER))
- conn.execute(schema_meta.delete().where(schema_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))
+ conn.execute(state_meta.delete().where(state_meta.c.key == JSON_IMPORT_MARKER))
+ conn.execute(state_meta.delete().where(state_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))
-def _import_parsed_state(conn: Connection, parsed: _ParsedState) -> dict[str, int]:
- now = _utc_now_iso()
- counts = {
- "channel_settings": 0,
- "guild_settings": 0,
- "guild_policies": 0,
- "user_settings": 0,
- "bind_codes": 0,
- "agent_session_bindings": 0,
- "active_threads": 0,
- "active_polls": 0,
- "processed_messages": 0,
- "discovered_chats": 0,
- }
-
- settings_state = parsed.settings
-
- for scoped_key, item in settings_state.channels.items():
- platform, channel_id = _split_scoped_key(scoped_key)
- scope_id = _get_or_create_scope(conn, platform or "unknown", "channel", channel_id, now=now)
- conn.execute(
- channel_settings.insert().values(
- scope_id=scope_id,
- enabled=_bool_int(item.enabled),
- show_message_types_json=_json_dumps(item.show_message_types),
- custom_cwd=item.custom_cwd,
- routing_json=_json_dumps(_asdict(item.routing)),
- require_mention=_nullable_bool_int(item.require_mention),
- created_at=now,
- updated_at=now,
- )
- )
- counts["channel_settings"] += 1
-
- for platform in sorted(settings_state.guild_scope_platforms):
- conn.execute(
- guild_policies.insert().values(
- platform=platform,
- default_enabled=_bool_int(settings_state.guild_default_enabled.get(platform, False)),
- created_at=now,
- updated_at=now,
- )
- )
- counts["guild_policies"] += 1
-
- for scoped_key, item in settings_state.guilds.items():
- platform, guild_id = _split_scoped_key(scoped_key)
- scope_id = _get_or_create_scope(conn, platform or "discord", "guild", guild_id, now=now)
- conn.execute(
- guild_settings.insert().values(
- scope_id=scope_id,
- enabled=_bool_int(item.enabled),
- created_at=now,
- updated_at=now,
- )
- )
- counts["guild_settings"] += 1
-
- for scoped_key, item in settings_state.users.items():
- platform, user_id = _split_scoped_key(scoped_key)
- scope_id = _get_or_create_scope(
- conn,
- platform or "unknown",
- "user",
- user_id,
- display_name=item.display_name,
- now=now,
- )
- conn.execute(
- user_settings.insert().values(
- scope_id=scope_id,
- is_admin=_bool_int(item.is_admin),
- bound_at=item.bound_at or None,
- enabled=_bool_int(item.enabled),
- show_message_types_json=_json_dumps(item.show_message_types),
- custom_cwd=item.custom_cwd,
- routing_json=_json_dumps(_asdict(item.routing)),
- dm_chat_id=item.dm_chat_id or None,
- created_at=now,
- updated_at=now,
- )
- )
- counts["user_settings"] += 1
-
- for item in settings_state.bind_codes:
- conn.execute(
- bind_codes.insert().values(
- code=item.code,
- type=item.type,
- created_at=item.created_at or now,
- expires_at=item.expires_at,
- is_active=_bool_int(item.is_active),
- used_by_json=_json_dumps(item.used_by),
- )
- )
- counts["bind_codes"] += 1
-
- session_state = parsed.sessions
- _import_sessions_last_activity(conn, session_state, now=now)
-
- for scope_key, agent_maps in session_state.session_mappings.items():
- for agent_name, thread_map in agent_maps.items():
- for thread_id, session_id in thread_map.items():
- conn.execute(
- agent_session_bindings.insert().values(
- scope_key=str(scope_key),
- agent_name=str(agent_name),
- thread_id=str(thread_id),
- session_id=encode_session_value(session_id),
- created_at=now,
- updated_at=now,
- )
- )
- counts["agent_session_bindings"] += 1
-
- for scope_key, channel_map in session_state.active_slack_threads.items():
- for channel_id, thread_map in channel_map.items():
- for thread_id, last_active_at in thread_map.items():
- conn.execute(
- active_threads.insert().values(
- scope_key=str(scope_key),
- channel_id=str(channel_id),
- thread_id=str(thread_id),
- last_active_at=float(last_active_at),
- )
- )
- counts["active_threads"] += 1
+def _write_parsed_state(db_path: Path, parsed: _ParsedState) -> None:
+ settings_service = SQLiteSettingsService(db_path)
+ sessions_service = SQLiteSessionsService(db_path)
+ try:
+ settings_service.save_state(parsed.settings)
+ sessions_service.save_state(parsed.sessions)
+ finally:
+ settings_service.close()
+ sessions_service.close()
- for opencode_session_id, item in session_state.active_polls.items():
- if not isinstance(item, dict):
- continue
- conn.execute(
- active_polls.insert().values(
- opencode_session_id=str(opencode_session_id),
- base_session_id=str(item.get("base_session_id") or ""),
- platform=str(item.get("platform") or ""),
- channel_id=str(item.get("channel_id") or ""),
- thread_id=str(item.get("thread_id") or ""),
- settings_key=str(item.get("settings_key") or ""),
- working_path=str(item.get("working_path") or ""),
- started_at=float(item.get("started_at") or 0.0),
- baseline_message_ids_json=_json_dumps(item.get("baseline_message_ids") or []),
- seen_tool_calls_json=_json_dumps(item.get("seen_tool_calls") or []),
- emitted_assistant_messages_json=_json_dumps(item.get("emitted_assistant_messages") or []),
- ack_reaction_message_id=item.get("ack_reaction_message_id"),
- ack_reaction_emoji=item.get("ack_reaction_emoji"),
- typing_indicator_active=_bool_int(item.get("typing_indicator_active", False)),
- context_token=str(item.get("context_token") or ""),
- processing_indicator_json=_json_dumps(item.get("processing_indicator") or {}),
- user_id=str(item.get("user_id") or ""),
- updated_at=now,
- )
- )
- counts["active_polls"] += 1
- for channel_id, thread_map in session_state.processed_message_ts.items():
- if not isinstance(thread_map, dict):
- continue
- for thread_id, value in thread_map.items():
- message_ids = [value] if isinstance(value, str) else list(value or [])
- for message_id in message_ids[-200:]:
- result = conn.execute(
- processed_messages.insert().values(
- channel_id=str(channel_id),
- thread_id=str(thread_id),
- message_id=str(message_id),
- processed_at=now,
- ).prefix_with("OR IGNORE")
- )
- counts["processed_messages"] += int(result.rowcount or 0)
-
- for platform, chats in parsed.discovered.state.chats.items():
+def _import_discovered_chats(conn: Connection, discovered: DiscoveredChatsStore) -> int:
+ now = _utc_now_iso()
+ count = 0
+ for platform, chats in discovered.state.chats.items():
for chat_id, chat in chats.items():
- conn.execute(
- discovered_chats.insert().values(
- platform=str(platform),
- chat_id=str(chat_id),
- name=chat.name,
- username=chat.username,
- chat_type=chat.chat_type,
- is_private=_bool_int(chat.is_private),
- is_forum=_bool_int(chat.is_forum),
- supports_topics=_bool_int(chat.supports_topics),
- last_seen_at=chat.last_seen_at,
- )
+ upsert_scope(
+ conn,
+ str(platform),
+ "channel",
+ str(chat_id),
+ display_name=chat.name,
+ native_type=chat.chat_type,
+ is_private=chat.is_private,
+ supports_threads=chat.supports_topics,
+ metadata={
+ "username": chat.username,
+ "is_forum": chat.is_forum,
+ "last_seen_at": chat.last_seen_at,
+ },
+ now=now,
)
- counts["discovered_chats"] += 1
-
- return counts
-
-
-def _import_sessions_last_activity(conn: Connection, session_state: SessionState, *, now: str) -> None:
- if session_state.last_activity is None:
- return
- conn.execute(
- schema_meta.insert().values(
- key=SESSIONS_LAST_ACTIVITY_KEY,
- value=str(session_state.last_activity),
- updated_at=now,
- )
- )
-
-
-def _get_or_create_scope(
- conn: Connection,
- platform: str,
- scope_type: str,
- scope_id: str,
- *,
- now: str,
- display_name: str | None = None,
-) -> int:
- existing = conn.execute(
- select(scopes.c.id).where(
- scopes.c.platform == platform,
- scopes.c.scope_type == scope_type,
- scopes.c.scope_id == scope_id,
- )
- ).scalar_one_or_none()
- if existing is not None:
- if display_name:
- conn.execute(scopes.update().where(scopes.c.id == existing).values(display_name=display_name, updated_at=now))
- return int(existing)
-
- result = conn.execute(
- scopes.insert().values(
- platform=platform,
- scope_type=scope_type,
- scope_id=scope_id,
- display_name=display_name,
- created_at=now,
- updated_at=now,
- )
- )
- return int(result.inserted_primary_key[0])
+ count += 1
+ return count
-def _validate_import(conn: Connection, counts: dict[str, int]) -> None:
+def _validate_import(conn: Connection, _counts: dict[str, int]) -> None:
integrity = conn.exec_driver_sql("PRAGMA integrity_check").scalar_one()
if integrity != "ok":
raise RuntimeError(f"SQLite integrity check failed: {integrity}")
- current = _current_counts(conn)
- mismatches = {
- key: {"expected": value, "actual": current.get(key)}
- for key, value in counts.items()
- if current.get(key) != value
- }
- if mismatches:
- raise RuntimeError(f"SQLite JSON import count mismatch: {mismatches}")
def _current_counts(conn: Connection) -> dict[str, int]:
tables = {
- "channel_settings": channel_settings,
- "guild_settings": guild_settings,
- "guild_policies": guild_policies,
- "user_settings": user_settings,
- "bind_codes": bind_codes,
- "agent_session_bindings": agent_session_bindings,
- "active_threads": active_threads,
- "active_polls": active_polls,
- "processed_messages": processed_messages,
- "discovered_chats": discovered_chats,
+ "scopes": scopes,
+ "scope_settings": scope_settings,
+ "auth_codes": auth_codes,
+ "agent_sessions": agent_sessions,
+ "runtime_records": runtime_records,
}
return {key: int(conn.execute(select(func.count()).select_from(table)).scalar_one()) for key, table in tables.items()}
@@ -568,23 +345,5 @@ def _json_dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
-def _asdict(value: Any) -> dict[str, Any]:
- if value is None:
- return {}
- if is_dataclass(value):
- return asdict(value)
- if isinstance(value, dict):
- return value
- return dict(value)
-
-
-def _bool_int(value: Any) -> int:
- return 1 if bool(value) else 0
-
-
-def _nullable_bool_int(value: Any) -> int | None:
- return None if value is None else _bool_int(value)
-
-
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
diff --git a/storage/migrations.py b/storage/migrations.py
index 6e9aa20a9..23e686bef 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -11,8 +11,16 @@ from storage.db import sqlite_url
INITIAL_REVISION = "20260501_0001"
INITIAL_TABLES = {
- "schema_meta",
+ "state_meta",
"scopes",
+ "scope_settings",
+ "auth_codes",
+ "agent_sessions",
+ "runtime_records",
+}
+UNRELEASED_OLD_INITIAL_TABLES = [
+ "session_messages",
+ "chat_sessions",
"channel_settings",
"guild_settings",
"guild_policies",
@@ -22,10 +30,11 @@ INITIAL_TABLES = {
"active_threads",
"active_polls",
"processed_messages",
- "chat_sessions",
- "session_messages",
"discovered_chats",
-}
+ "scopes",
+ "schema_meta",
+ "alembic_version",
+]
def alembic_dir() -> Path:
@@ -42,22 +51,42 @@ def alembic_config(db_path: Path | None = None) -> Config:
def run_migrations(db_path: Path | None = None, *, revision: str = "head") -> None:
target_db = db_path or paths.get_sqlite_state_path()
cfg = alembic_config(target_db)
+ _reset_unreleased_initial_schema_drift(target_db)
_stamp_existing_initial_schema(target_db, cfg)
command.upgrade(cfg, revision)
+def _reset_unreleased_initial_schema_drift(db_path: Path) -> None:
+ path = db_path.expanduser().resolve()
+ if not path.exists():
+ return
+
+ with sqlite3.connect(path) as conn:
+ tables = _table_names(conn)
+ if INITIAL_TABLES.issubset(tables):
+ return
+ if "alembic_version" not in tables:
+ return
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ if version != (INITIAL_REVISION,):
+ return
+ if not any(table in tables for table in UNRELEASED_OLD_INITIAL_TABLES):
+ return
+
+ conn.execute("PRAGMA foreign_keys = OFF")
+ for table in UNRELEASED_OLD_INITIAL_TABLES:
+ if table in tables:
+ conn.execute(f'drop table if exists "{table}"')
+ conn.commit()
+
+
def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
path = db_path.expanduser().resolve()
if not path.exists():
return
with sqlite3.connect(path) as conn:
- tables = {
- row[0]
- for row in conn.execute(
- "select name from sqlite_master where type = 'table'",
- )
- }
+ tables = _table_names(conn)
if not tables:
return
if "alembic_version" in tables:
@@ -68,3 +97,12 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
return
command.stamp(cfg, INITIAL_REVISION)
+
+
+def _table_names(conn: sqlite3.Connection) -> set[str]:
+ return {
+ row[0]
+ for row in conn.execute(
+ "select name from sqlite_master where type = 'table'",
+ )
+ }
diff --git a/storage/models.py b/storage/models.py
index c416f6f6e..6a4ad87d3 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -15,212 +15,115 @@ from sqlalchemy import (
metadata = MetaData()
-schema_meta = Table(
- "schema_meta",
+state_meta = Table(
+ "state_meta",
metadata,
Column("key", String, primary_key=True),
- Column("value", Text, nullable=False),
+ Column("value_json", Text, nullable=False),
Column("updated_at", String, nullable=False),
)
scopes = Table(
"scopes",
metadata,
- Column("id", Integer, primary_key=True),
+ Column("id", String, primary_key=True),
Column("platform", String, nullable=False),
Column("scope_type", String, nullable=False),
- Column("scope_id", String, nullable=False),
+ Column("native_id", String, nullable=False),
+ Column("parent_scope_id", String, ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
Column("display_name", Text, nullable=True),
- Column("created_at", String, nullable=False),
+ Column("native_type", String, nullable=True),
+ Column("is_private", Integer, nullable=False),
+ Column("supports_threads", Integer, nullable=False),
+ Column("metadata_json", Text, nullable=False),
+ Column("first_seen_at", String, nullable=False),
+ Column("last_seen_at", String, nullable=False),
Column("updated_at", String, nullable=False),
- UniqueConstraint("platform", "scope_type", "scope_id", name="uq_scopes_platform_type_id"),
+ UniqueConstraint("platform", "scope_type", "native_id", name="uq_scopes_platform_type_native"),
Index("ix_scopes_platform_type", "platform", "scope_type"),
+ Index("ix_scopes_parent", "parent_scope_id"),
)
-channel_settings = Table(
- "channel_settings",
+scope_settings = Table(
+ "scope_settings",
metadata,
- Column("scope_id", Integer, ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
Column("enabled", Integer, nullable=False),
- Column("show_message_types_json", Text, nullable=False),
- Column("custom_cwd", Text, nullable=True),
- Column("routing_json", Text, nullable=False),
+ Column("role", String, nullable=True),
+ Column("workdir", Text, nullable=True),
+ Column("agent_backend", String, nullable=True),
+ Column("agent_variant", String, nullable=True),
+ Column("model", String, nullable=True),
+ Column("reasoning_effort", String, nullable=True),
Column("require_mention", Integer, nullable=True),
+ Column("settings_version", Integer, nullable=False),
+ Column("settings_json", Text, nullable=False),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
+ Index("ix_scope_settings_role", "role"),
+ Index("ix_scope_settings_workdir", "workdir"),
+ Index("ix_scope_settings_backend_model", "agent_backend", "model"),
)
-guild_settings = Table(
- "guild_settings",
- metadata,
- Column("scope_id", Integer, ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
- Column("enabled", Integer, nullable=False),
- Column("created_at", String, nullable=False),
- Column("updated_at", String, nullable=False),
-)
-
-guild_policies = Table(
- "guild_policies",
- metadata,
- Column("platform", String, primary_key=True),
- Column("default_enabled", Integer, nullable=False),
- Column("created_at", String, nullable=False),
- Column("updated_at", String, nullable=False),
-)
-
-user_settings = Table(
- "user_settings",
- metadata,
- Column("scope_id", Integer, ForeignKey("scopes.id", ondelete="CASCADE"), primary_key=True),
- Column("is_admin", Integer, nullable=False),
- Column("bound_at", String, nullable=True),
- Column("enabled", Integer, nullable=False),
- Column("show_message_types_json", Text, nullable=False),
- Column("custom_cwd", Text, nullable=True),
- Column("routing_json", Text, nullable=False),
- Column("dm_chat_id", Text, nullable=True),
- Column("created_at", String, nullable=False),
- Column("updated_at", String, nullable=False),
-)
-
-bind_codes = Table(
- "bind_codes",
+auth_codes = Table(
+ "auth_codes",
metadata,
Column("code", String, primary_key=True),
Column("type", String, nullable=False),
- Column("created_at", String, nullable=False),
- Column("expires_at", String, nullable=True),
Column("is_active", Integer, nullable=False),
+ Column("expires_at", String, nullable=True),
Column("used_by_json", Text, nullable=False),
-)
-
-agent_session_bindings = Table(
- "agent_session_bindings",
- metadata,
- Column("id", Integer, primary_key=True),
- Column("scope_key", String, nullable=False),
- Column("agent_name", String, nullable=False),
- Column("thread_id", String, nullable=False),
- Column("session_id", Text, nullable=False),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
- UniqueConstraint("scope_key", "agent_name", "thread_id", name="uq_agent_session_binding"),
- Index("ix_agent_session_bindings_session_id", "session_id"),
- Index("ix_agent_session_bindings_scope_agent", "scope_key", "agent_name"),
)
-active_threads = Table(
- "active_threads",
- metadata,
- Column("id", Integer, primary_key=True),
- Column("scope_key", String, nullable=False),
- Column("channel_id", String, nullable=False),
- Column("thread_id", String, nullable=False),
- Column("last_active_at", Float, nullable=False),
- UniqueConstraint("scope_key", "channel_id", "thread_id", name="uq_active_thread"),
-)
-
-active_polls = Table(
- "active_polls",
- metadata,
- Column("opencode_session_id", String, primary_key=True),
- Column("base_session_id", String, nullable=False),
- Column("platform", String, nullable=False),
- Column("channel_id", String, nullable=False),
- Column("thread_id", String, nullable=False),
- Column("settings_key", String, nullable=False),
- Column("working_path", Text, nullable=False),
- Column("started_at", Float, nullable=False),
- Column("baseline_message_ids_json", Text, nullable=False),
- Column("seen_tool_calls_json", Text, nullable=False),
- Column("emitted_assistant_messages_json", Text, nullable=False),
- Column("ack_reaction_message_id", Text, nullable=True),
- Column("ack_reaction_emoji", Text, nullable=True),
- Column("typing_indicator_active", Integer, nullable=False),
- Column("context_token", Text, nullable=False),
- Column("processing_indicator_json", Text, nullable=False),
- Column("user_id", String, nullable=False),
- Column("updated_at", String, nullable=False),
-)
-
-processed_messages = Table(
- "processed_messages",
- metadata,
- Column("id", Integer, primary_key=True),
- Column("channel_id", String, nullable=False),
- Column("thread_id", String, nullable=False),
- Column("message_id", String, nullable=False),
- Column("processed_at", String, nullable=False),
- UniqueConstraint("channel_id", "thread_id", "message_id", name="uq_processed_message"),
- Index("ix_processed_messages_thread_time", "channel_id", "thread_id", "processed_at"),
-)
-
-chat_sessions = Table(
- "chat_sessions",
+agent_sessions = Table(
+ "agent_sessions",
metadata,
Column("id", String, primary_key=True),
- Column("platform", String, nullable=False),
- Column("scope_type", String, nullable=False),
- Column("scope_id", String, nullable=False),
- Column("thread_id", String, nullable=True),
- Column("agent_backend", String, nullable=True),
- Column("agent_name", String, nullable=True),
- Column("working_path", Text, nullable=True),
+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ Column("agent_backend", String, nullable=False),
+ Column("agent_variant", String, nullable=False),
+ Column("model", String, nullable=True),
+ Column("reasoning_effort", String, nullable=True),
+ Column("session_anchor", String, nullable=False),
+ Column("workdir", Text, nullable=True),
+ Column("native_session_id", Text, nullable=False),
Column("title", Text, nullable=True),
Column("status", String, nullable=False),
+ Column("metadata_json", Text, nullable=False),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
- Column("last_message_at", String, nullable=True),
- Index("ix_chat_sessions_scope_updated", "platform", "scope_type", "scope_id", "updated_at"),
- Index("ix_chat_sessions_agent", "agent_backend", "agent_name"),
- Index("ix_chat_sessions_working_path", "working_path"),
+ Column("last_active_at", String, nullable=True),
+ Index("ix_agent_sessions_scope_anchor_workdir", "scope_id", "session_anchor", "workdir"),
+ Index("ix_agent_sessions_backend_variant", "agent_backend", "agent_variant"),
+ Index("ix_agent_sessions_status_activity", "status", "last_active_at"),
+ Index("ix_agent_sessions_native_session", "native_session_id"),
)
-session_messages = Table(
- "session_messages",
+runtime_records = Table(
+ "runtime_records",
metadata,
Column("id", String, primary_key=True),
- Column("session_id", String, ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False),
- Column("parent_message_id", String, nullable=True),
- Column("role", String, nullable=False),
- Column("source", String, nullable=False),
- Column("content_text", Text, nullable=True),
- Column("content_json", Text, nullable=False),
- Column("agent_backend", String, nullable=True),
- Column("agent_name", String, nullable=True),
- Column("native_message_id", String, nullable=True),
+ Column("record_type", String, nullable=False),
+ Column("record_key", String, nullable=False),
+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ Column("session_anchor", String, nullable=True),
+ Column("workdir", Text, nullable=True),
+ Column("payload_json", Text, nullable=False),
+ Column("expires_at", String, nullable=True),
Column("created_at", String, nullable=False),
- Index("ix_session_messages_session_time", "session_id", "created_at"),
- Index("ix_session_messages_native_message", "native_message_id"),
- Index("ix_session_messages_agent_time", "agent_backend", "agent_name", "created_at"),
-)
-
-discovered_chats = Table(
- "discovered_chats",
- metadata,
- Column("platform", String, primary_key=True),
- Column("chat_id", String, primary_key=True),
- Column("name", Text, nullable=False),
- Column("username", Text, nullable=False),
- Column("chat_type", String, nullable=False),
- Column("is_private", Integer, nullable=False),
- Column("is_forum", Integer, nullable=False),
- Column("supports_topics", Integer, nullable=False),
- Column("last_seen_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ UniqueConstraint("record_type", "record_key", name="uq_runtime_records_type_key"),
+ Index("ix_runtime_records_type_scope_expiry", "record_type", "scope_id", "expires_at"),
+ Index("ix_runtime_records_scope_anchor", "scope_id", "session_anchor"),
+ Index("ix_runtime_records_workdir", "workdir"),
)
imported_state_tables = [
- session_messages,
- chat_sessions,
- channel_settings,
- guild_settings,
- guild_policies,
- user_settings,
- bind_codes,
- agent_session_bindings,
- active_threads,
- active_polls,
- processed_messages,
- discovered_chats,
+ scope_settings,
+ auth_codes,
+ agent_sessions,
+ runtime_records,
scopes,
]
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 7da7abff1..53d074021 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -8,17 +9,14 @@ from typing import Any
from sqlalchemy import Connection, select
from config.v2_sessions import ActivePollInfo, SessionState
+from config.v2_settings import _split_scoped_key
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
-from storage.models import (
- active_polls,
- active_threads,
- agent_session_bindings,
- processed_messages,
- schema_meta,
-)
+from storage.models import agent_sessions, runtime_records, scopes, state_meta
+from storage.settings_service import make_scope_id, upsert_scope
SESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"
JSON_VALUE_PREFIX = "__json__:"
+SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
class SQLiteSessionsService:
@@ -48,38 +46,65 @@ class SQLiteSessionsService:
with self.engine.begin() as conn:
self._clear(conn)
now = _utc_now_iso()
+ used_session_ids: set[str] = set()
for scope_key, agent_maps in state.session_mappings.items():
if not isinstance(agent_maps, dict):
continue
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
for agent_name, thread_map in agent_maps.items():
if not isinstance(thread_map, dict):
continue
- for thread_id, session_id in thread_map.items():
+ for thread_id, native_session_id in thread_map.items():
+ thread_key = str(thread_id)
conn.execute(
- agent_session_bindings.insert().values(
- scope_key=str(scope_key),
- agent_name=str(agent_name),
- thread_id=str(thread_id),
- session_id=encode_session_value(session_id),
+ agent_sessions.insert().values(
+ id=_new_session_id(used_session_ids),
+ scope_id=scope_id,
+ agent_backend=_agent_backend(str(agent_name)),
+ agent_variant=str(agent_name) or "default",
+ model=None,
+ reasoning_effort=None,
+ session_anchor=thread_key,
+ workdir=_workdir_from_anchor(thread_key),
+ native_session_id=encode_session_value(native_session_id),
+ title=None,
+ status="active",
+ metadata_json=_json_dumps({"legacy_scope_key": str(scope_key)}),
created_at=now,
updated_at=now,
+ last_active_at=now,
)
)
for scope_key, channel_map in state.active_slack_threads.items():
if not isinstance(channel_map, dict):
continue
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
for channel_id, thread_map in channel_map.items():
if not isinstance(thread_map, dict):
continue
for thread_id, last_active_at in thread_map.items():
+ record_key = f"{scope_key}|{channel_id}|{thread_id}"
conn.execute(
- active_threads.insert().values(
- scope_key=str(scope_key),
- channel_id=str(channel_id),
- thread_id=str(thread_id),
- last_active_at=_float(last_active_at),
+ runtime_records.insert().values(
+ id=f"runtime::active_thread::{record_key}",
+ record_type="active_thread",
+ record_key=record_key,
+ scope_id=scope_id,
+ session_anchor=str(thread_id),
+ workdir=None,
+ payload_json=_json_dumps(
+ {
+ "scope_key": str(scope_key),
+ "channel_id": str(channel_id),
+ "thread_id": str(thread_id),
+ "last_active_at": _float(last_active_at),
+ }
+ ),
+ expires_at=None,
+ created_at=now,
+ updated_at=now,
)
)
@@ -87,148 +112,166 @@ class SQLiteSessionsService:
data = item.to_dict() if isinstance(item, ActivePollInfo) else item
if not isinstance(data, dict):
continue
+ record_key = str(opencode_session_id)
+ settings_key = str(data.get("settings_key") or "")
+ platform = str(data.get("platform") or "")
+ scope_id = resolve_scope_from_legacy_key(
+ conn,
+ f"{platform}::{settings_key}" if platform and "::" not in settings_key else settings_key,
+ now=now,
+ )
conn.execute(
- active_polls.insert().values(
- opencode_session_id=str(opencode_session_id),
- base_session_id=str(data.get("base_session_id") or ""),
- platform=str(data.get("platform") or ""),
- channel_id=str(data.get("channel_id") or ""),
- thread_id=str(data.get("thread_id") or ""),
- settings_key=str(data.get("settings_key") or ""),
- working_path=str(data.get("working_path") or ""),
- started_at=_float(data.get("started_at")),
- baseline_message_ids_json=_json_dumps(data.get("baseline_message_ids") or []),
- seen_tool_calls_json=_json_dumps(data.get("seen_tool_calls") or []),
- emitted_assistant_messages_json=_json_dumps(data.get("emitted_assistant_messages") or []),
- ack_reaction_message_id=data.get("ack_reaction_message_id"),
- ack_reaction_emoji=data.get("ack_reaction_emoji"),
- typing_indicator_active=_bool_int(data.get("typing_indicator_active", False)),
- context_token=str(data.get("context_token") or ""),
- processing_indicator_json=_json_dumps(data.get("processing_indicator") or {}),
- user_id=str(data.get("user_id") or ""),
+ runtime_records.insert().values(
+ id=f"runtime::active_poll::{record_key}",
+ record_type="active_poll",
+ record_key=record_key,
+ scope_id=scope_id,
+ session_anchor=str(data.get("base_session_id") or data.get("thread_id") or ""),
+ workdir=str(data.get("working_path") or "") or None,
+ payload_json=_json_dumps(data),
+ expires_at=None,
+ created_at=now,
updated_at=now,
)
)
+ seen_messages: set[tuple[str, str, str]] = set()
for channel_id, thread_map in state.processed_message_ts.items():
if not isinstance(thread_map, dict):
continue
for thread_id, value in thread_map.items():
message_ids = [value] if isinstance(value, str) else list(value or [])
for message_id in message_ids[-200:]:
+ key = (str(channel_id), str(thread_id), str(message_id))
+ if key in seen_messages:
+ continue
+ seen_messages.add(key)
+ record_key = "|".join(key)
conn.execute(
- processed_messages.insert().values(
- channel_id=str(channel_id),
- thread_id=str(thread_id),
- message_id=str(message_id),
- processed_at=now,
- ).prefix_with("OR IGNORE")
+ runtime_records.insert().values(
+ id=f"runtime::processed_message::{record_key}",
+ record_type="processed_message",
+ record_key=record_key,
+ scope_id=None,
+ session_anchor=str(thread_id),
+ workdir=None,
+ payload_json=_json_dumps(
+ {
+ "channel_id": str(channel_id),
+ "thread_id": str(thread_id),
+ "message_id": str(message_id),
+ "processed_at": now,
+ }
+ ),
+ expires_at=None,
+ created_at=now,
+ updated_at=now,
+ )
)
if state.last_activity is not None:
conn.execute(
- schema_meta.insert().values(
+ state_meta.insert().values(
key=SESSIONS_LAST_ACTIVITY_KEY,
- value=str(state.last_activity),
+ value_json=_json_dumps(state.last_activity),
updated_at=now,
)
)
def _clear(self, conn: Connection) -> None:
- conn.execute(agent_session_bindings.delete())
- conn.execute(active_threads.delete())
- conn.execute(active_polls.delete())
- conn.execute(processed_messages.delete())
- conn.execute(schema_meta.delete().where(schema_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))
+ conn.execute(agent_sessions.delete())
+ conn.execute(runtime_records.delete())
+ conn.execute(state_meta.delete().where(state_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))
def _load_session_mappings(self, conn: Connection) -> dict[str, dict[str, dict[str, Any]]]:
rows = conn.execute(
select(
- agent_session_bindings.c.scope_key,
- agent_session_bindings.c.agent_name,
- agent_session_bindings.c.thread_id,
- agent_session_bindings.c.session_id,
- )
- )
+ agent_sessions.c.scope_id,
+ agent_sessions.c.agent_variant,
+ agent_sessions.c.session_anchor,
+ agent_sessions.c.native_session_id,
+ agent_sessions.c.metadata_json,
+ scopes.c.platform,
+ scopes.c.native_id,
+ ).join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)
+ ).mappings()
result: dict[str, dict[str, dict[str, Any]]] = {}
- for scope_key, agent_name, thread_id, session_id in rows:
- result.setdefault(str(scope_key), {}).setdefault(str(agent_name), {})[str(thread_id)] = decode_session_value(
- session_id
+ for row in rows:
+ scope_key = _legacy_scope_key(row)
+ agent_name = str(row["agent_variant"] or "default")
+ result.setdefault(scope_key, {}).setdefault(agent_name, {})[str(row["session_anchor"])] = (
+ decode_session_value(row["native_session_id"])
)
return result
def _load_active_threads(self, conn: Connection) -> dict[str, dict[str, dict[str, float]]]:
rows = conn.execute(
- select(
- active_threads.c.scope_key,
- active_threads.c.channel_id,
- active_threads.c.thread_id,
- active_threads.c.last_active_at,
- )
+ select(runtime_records.c.payload_json).where(runtime_records.c.record_type == "active_thread")
)
result: dict[str, dict[str, dict[str, float]]] = {}
- for scope_key, channel_id, thread_id, last_active_at in rows:
- result.setdefault(str(scope_key), {}).setdefault(str(channel_id), {})[str(thread_id)] = float(last_active_at)
+ for (payload_json,) in rows:
+ payload = _json_loads(payload_json, {})
+ scope_key = str(payload.get("scope_key") or "")
+ channel_id = str(payload.get("channel_id") or "")
+ thread_id = str(payload.get("thread_id") or "")
+ if not scope_key or not channel_id or not thread_id:
+ continue
+ result.setdefault(scope_key, {}).setdefault(channel_id, {})[thread_id] = _float(
+ payload.get("last_active_at")
+ )
return result
def _load_active_polls(self, conn: Connection) -> dict[str, dict[str, Any]]:
- rows = conn.execute(select(active_polls)).mappings()
+ rows = conn.execute(
+ select(runtime_records.c.record_key, runtime_records.c.payload_json).where(
+ runtime_records.c.record_type == "active_poll"
+ )
+ )
result: dict[str, dict[str, Any]] = {}
- for row in rows:
- session_id = str(row["opencode_session_id"])
- result[session_id] = {
- "opencode_session_id": session_id,
- "base_session_id": row["base_session_id"] or "",
- "platform": row["platform"] or "",
- "channel_id": row["channel_id"] or "",
- "thread_id": row["thread_id"] or "",
- "settings_key": row["settings_key"] or "",
- "working_path": row["working_path"] or "",
- "baseline_message_ids": _json_loads(row["baseline_message_ids_json"], []),
- "seen_tool_calls": _json_loads(row["seen_tool_calls_json"], []),
- "emitted_assistant_messages": _json_loads(row["emitted_assistant_messages_json"], []),
- "started_at": float(row["started_at"] or 0.0),
- "ack_reaction_message_id": row["ack_reaction_message_id"],
- "ack_reaction_emoji": row["ack_reaction_emoji"],
- "typing_indicator_active": bool(row["typing_indicator_active"]),
- "context_token": row["context_token"] or "",
- "processing_indicator": _json_loads(row["processing_indicator_json"], {}),
- "user_id": row["user_id"] or "",
- }
+ for record_key, payload_json in rows:
+ payload = _json_loads(payload_json, {})
+ if not isinstance(payload, dict):
+ continue
+ payload.setdefault("opencode_session_id", str(record_key))
+ result[str(record_key)] = payload
return result
def _load_processed_messages(self, conn: Connection) -> dict[str, dict[str, list[str]]]:
rows = conn.execute(
- select(
- processed_messages.c.channel_id,
- processed_messages.c.thread_id,
- processed_messages.c.message_id,
- ).order_by(processed_messages.c.id)
+ select(runtime_records.c.payload_json)
+ .where(runtime_records.c.record_type == "processed_message")
+ .order_by(runtime_records.c.created_at)
)
result: dict[str, dict[str, list[str]]] = {}
- for channel_id, thread_id, message_id in rows:
- thread_map = result.setdefault(str(channel_id), {})
- items = thread_map.setdefault(str(thread_id), [])
- items.append(str(message_id))
+ for (payload_json,) in rows:
+ payload = _json_loads(payload_json, {})
+ channel_id = str(payload.get("channel_id") or "")
+ thread_id = str(payload.get("thread_id") or "")
+ message_id = str(payload.get("message_id") or "")
+ if not channel_id or not thread_id or not message_id:
+ continue
+ result.setdefault(channel_id, {}).setdefault(thread_id, []).append(message_id)
return result
def _load_last_activity(self, conn: Connection) -> str | None:
- return conn.execute(
- select(schema_meta.c.value).where(schema_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY)
+ value = conn.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY)
).scalar_one_or_none()
+ return _json_loads(value, None)
-def _json_dumps(value: Any) -> str:
- return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
-
-
-def _json_loads(value: str | None, default: Any) -> Any:
- if not value:
- return default
- try:
- return json.loads(value)
- except (TypeError, ValueError):
- return default
+def resolve_scope_from_legacy_key(conn: Connection, scope_key: str, *, now: str) -> str | None:
+ platform, native_id = _split_scoped_key(scope_key)
+ if not native_id:
+ return None
+ if platform is None:
+ platform = "unknown"
+ existing = conn.execute(
+ select(scopes.c.id).where(scopes.c.platform == platform, scopes.c.native_id == native_id).limit(1)
+ ).scalar_one_or_none()
+ if existing is not None:
+ return str(existing)
+ return upsert_scope(conn, platform, _infer_scope_type(platform, native_id), native_id, now=now)
def encode_session_value(value: Any) -> str:
@@ -248,8 +291,61 @@ def decode_session_value(value: Any) -> Any:
return value
-def _bool_int(value: Any) -> int:
- return 1 if bool(value) else 0
+def _legacy_scope_key(row: dict[str, Any]) -> str:
+ metadata = _json_loads(row.get("metadata_json"), {})
+ if isinstance(metadata, dict) and metadata.get("legacy_scope_key"):
+ return str(metadata["legacy_scope_key"])
+ platform = row.get("platform")
+ native_id = row.get("native_id")
+ if platform and native_id:
+ return f"{platform}::{native_id}"
+ scope_id = row.get("scope_id")
+ if isinstance(scope_id, str) and scope_id.count("::") >= 2:
+ parts = scope_id.split("::", 2)
+ return f"{parts[0]}::{parts[2]}"
+ return str(scope_id or "")
+
+
+def _infer_scope_type(platform: str, native_id: str) -> str:
+ if platform == "slack" and native_id and native_id[0] in {"U", "W"}:
+ return "user"
+ if platform == "lark" and native_id.startswith("ou_"):
+ return "user"
+ if platform == "wechat" and (native_id.startswith("wxid_") or native_id.startswith("user")):
+ return "user"
+ return "channel"
+
+
+def _agent_backend(agent_name: str) -> str:
+ return agent_name if agent_name in {"codex", "claude", "opencode"} else "unknown"
+
+
+def _new_session_id(used: set[str]) -> str:
+ while True:
+ value = "ses" + "".join(secrets.choice(SESSION_ID_ALPHABET) for _ in range(10))
+ if value not in used:
+ used.add(value)
+ return value
+
+
+def _workdir_from_anchor(anchor: str) -> str | None:
+ if ":" not in anchor:
+ return None
+ suffix = anchor.rsplit(":", 1)[1]
+ return suffix or None
+
+
+def _json_dumps(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _json_loads(value: str | None, default: Any) -> Any:
+ if not value:
+ return default
+ try:
+ return json.loads(value)
+ except (TypeError, ValueError):
+ return default
def _float(value: Any) -> float:
diff --git a/storage/settings_service.py b/storage/settings_service.py
index 66d719e13..f3fa90437 100644
--- a/storage/settings_service.py
+++ b/storage/settings_service.py
@@ -6,7 +6,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any
-from sqlalchemy import Connection, Engine, select
+from sqlalchemy import Connection, select
from config.v2_settings import (
BindCode,
@@ -19,14 +19,10 @@ from config.v2_settings import (
_split_scoped_key,
)
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
-from storage.models import (
- bind_codes,
- channel_settings,
- guild_policies,
- guild_settings,
- scopes,
- user_settings,
-)
+from storage.models import auth_codes, scope_settings, scopes
+
+SETTINGS_VERSION = 1
+GUILD_POLICY_KIND = "guild_policy"
class SQLiteSettingsService:
@@ -55,29 +51,48 @@ class SQLiteSettingsService:
def save_state(self, state: SettingsState) -> None:
with self.engine.begin() as conn:
- self._clear(conn)
+ self._clear_settings(conn)
now = _utc_now_iso()
+
for scoped_key, item in state.channels.items():
platform, channel_id = _split_scoped_key(scoped_key)
- scope_id = self._get_or_create_scope(conn, platform or "unknown", "channel", channel_id, now=now)
+ scope_id = upsert_scope(conn, platform or "unknown", "channel", channel_id, now=now)
+ routing = asdict(item.routing)
conn.execute(
- channel_settings.insert().values(
+ scope_settings.insert().values(
scope_id=scope_id,
enabled=_bool_int(item.enabled),
- show_message_types_json=_json_dumps(item.show_message_types),
- custom_cwd=item.custom_cwd,
- routing_json=_json_dumps(asdict(item.routing)),
+ role=None,
+ workdir=item.custom_cwd,
require_mention=_nullable_bool_int(item.require_mention),
+ settings_json=_json_dumps(
+ {
+ "show_message_types": item.show_message_types,
+ "routing": routing,
+ }
+ ),
created_at=now,
updated_at=now,
+ settings_version=SETTINGS_VERSION,
+ **_routing_columns(item.routing),
)
)
for platform in sorted(state.guild_scope_platforms):
+ scope_id = upsert_scope(conn, platform, "platform", platform, now=now)
conn.execute(
- guild_policies.insert().values(
- platform=platform,
- default_enabled=_bool_int(state.guild_default_enabled.get(platform, False)),
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=_bool_int(state.guild_default_enabled.get(platform, False)),
+ role=None,
+ workdir=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=SETTINGS_VERSION,
+ settings_json=_json_dumps({"kind": GUILD_POLICY_KIND}),
created_at=now,
updated_at=now,
)
@@ -85,11 +100,20 @@ class SQLiteSettingsService:
for scoped_key, item in state.guilds.items():
platform, guild_id = _split_scoped_key(scoped_key)
- scope_id = self._get_or_create_scope(conn, platform or "discord", "guild", guild_id, now=now)
+ scope_id = upsert_scope(conn, platform or "discord", "guild", guild_id, now=now)
conn.execute(
- guild_settings.insert().values(
+ scope_settings.insert().values(
scope_id=scope_id,
enabled=_bool_int(item.enabled),
+ role=None,
+ workdir=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=SETTINGS_VERSION,
+ settings_json=_json_dumps({}),
created_at=now,
updated_at=now,
)
@@ -97,103 +121,110 @@ class SQLiteSettingsService:
for scoped_key, item in state.users.items():
platform, user_id = _split_scoped_key(scoped_key)
- scope_id = self._get_or_create_scope(
+ scope_id = upsert_scope(
conn,
platform or "unknown",
"user",
user_id,
display_name=item.display_name,
+ is_private=True,
now=now,
)
+ routing = asdict(item.routing)
conn.execute(
- user_settings.insert().values(
+ scope_settings.insert().values(
scope_id=scope_id,
- is_admin=_bool_int(item.is_admin),
- bound_at=item.bound_at or None,
enabled=_bool_int(item.enabled),
- show_message_types_json=_json_dumps(item.show_message_types),
- custom_cwd=item.custom_cwd,
- routing_json=_json_dumps(asdict(item.routing)),
- dm_chat_id=item.dm_chat_id or None,
+ role="admin" if item.is_admin else "member",
+ workdir=item.custom_cwd,
+ require_mention=None,
+ settings_version=SETTINGS_VERSION,
+ settings_json=_json_dumps(
+ {
+ "bound_at": item.bound_at or "",
+ "dm_chat_id": item.dm_chat_id or "",
+ "show_message_types": item.show_message_types,
+ "routing": routing,
+ }
+ ),
created_at=now,
updated_at=now,
+ **_routing_columns(item.routing),
)
)
for item in state.bind_codes:
conn.execute(
- bind_codes.insert().values(
+ auth_codes.insert().values(
code=item.code,
type=item.type,
- created_at=item.created_at or now,
- expires_at=item.expires_at,
is_active=_bool_int(item.is_active),
+ expires_at=item.expires_at,
used_by_json=_json_dumps(item.used_by),
+ created_at=item.created_at or now,
+ updated_at=now,
)
)
- def _clear(self, conn: Connection) -> None:
- conn.execute(channel_settings.delete())
- conn.execute(guild_settings.delete())
- conn.execute(guild_policies.delete())
- conn.execute(user_settings.delete())
- conn.execute(bind_codes.delete())
- conn.execute(scopes.delete())
+ def _clear_settings(self, conn: Connection) -> None:
+ conn.execute(scope_settings.delete())
+ conn.execute(auth_codes.delete())
def _load_channels(self, conn: Connection) -> dict[str, ChannelSettings]:
- rows = conn.execute(
- select(scopes, channel_settings).join(channel_settings, channel_settings.c.scope_id == scopes.c.id)
- ).mappings()
+ rows = _settings_rows(conn, "channel")
result: dict[str, ChannelSettings] = {}
for row in rows:
- key = _make_scoped_key(str(row["platform"]), str(row["scope_id"]))
+ payload = _json_loads(row["settings_json"], {})
+ key = _make_scoped_key(str(row["platform"]), str(row["native_id"]))
result[key] = ChannelSettings(
enabled=bool(row["enabled"]),
- show_message_types=_json_loads(row["show_message_types_json"], []),
- custom_cwd=row["custom_cwd"],
- routing=_routing_from_json(row["routing_json"]),
+ show_message_types=_json_list(payload.get("show_message_types")),
+ custom_cwd=row["workdir"],
+ routing=_routing_from_row(row, payload),
require_mention=_nullable_bool(row["require_mention"]),
)
return result
def _load_guilds(self, conn: Connection) -> dict[str, GuildSettings]:
- rows = conn.execute(
- select(scopes, guild_settings).join(guild_settings, guild_settings.c.scope_id == scopes.c.id)
- ).mappings()
+ rows = _settings_rows(conn, "guild")
result: dict[str, GuildSettings] = {}
for row in rows:
- key = _make_scoped_key(str(row["platform"]), str(row["scope_id"]))
+ key = _make_scoped_key(str(row["platform"]), str(row["native_id"]))
result[key] = GuildSettings(enabled=bool(row["enabled"]))
return result
def _load_guild_scope_platforms(self, conn: Connection) -> set[str]:
- return {str(row[0]) for row in conn.execute(select(guild_policies.c.platform))}
+ return set(self._load_guild_policies(conn).keys())
def _load_guild_policies(self, conn: Connection) -> dict[str, bool]:
- rows = conn.execute(select(guild_policies.c.platform, guild_policies.c.default_enabled))
- return {str(platform): bool(default_enabled) for platform, default_enabled in rows}
+ rows = _settings_rows(conn, "platform")
+ result: dict[str, bool] = {}
+ for row in rows:
+ payload = _json_loads(row["settings_json"], {})
+ if payload.get("kind") == GUILD_POLICY_KIND:
+ result[str(row["platform"])] = bool(row["enabled"])
+ return result
def _load_users(self, conn: Connection) -> dict[str, UserSettings]:
- rows = conn.execute(
- select(scopes, user_settings).join(user_settings, user_settings.c.scope_id == scopes.c.id)
- ).mappings()
+ rows = _settings_rows(conn, "user")
result: dict[str, UserSettings] = {}
for row in rows:
- key = _make_scoped_key(str(row["platform"]), str(row["scope_id"]))
+ payload = _json_loads(row["settings_json"], {})
+ key = _make_scoped_key(str(row["platform"]), str(row["native_id"]))
result[key] = UserSettings(
display_name=row["display_name"] or "",
- is_admin=bool(row["is_admin"]),
- bound_at=row["bound_at"] or "",
+ is_admin=str(row["role"] or "").lower() in {"admin", "owner"},
+ bound_at=str(payload.get("bound_at") or ""),
enabled=bool(row["enabled"]),
- show_message_types=_json_loads(row["show_message_types_json"], []),
- custom_cwd=row["custom_cwd"],
- routing=_routing_from_json(row["routing_json"]),
- dm_chat_id=row["dm_chat_id"] or "",
+ show_message_types=_json_list(payload.get("show_message_types")),
+ custom_cwd=row["workdir"],
+ routing=_routing_from_row(row, payload),
+ dm_chat_id=str(payload.get("dm_chat_id") or ""),
)
return result
def _load_bind_codes(self, conn: Connection) -> list[BindCode]:
- rows = conn.execute(select(bind_codes)).mappings()
+ rows = conn.execute(select(auth_codes)).mappings()
return [
BindCode(
code=row["code"],
@@ -206,52 +237,139 @@ class SQLiteSettingsService:
for row in rows
]
- def _get_or_create_scope(
- self,
- conn: Connection,
- platform: str,
- scope_type: str,
- scope_id: str,
- *,
- now: str,
- display_name: str | None = None,
- ) -> int:
- existing = conn.execute(
- select(scopes.c.id).where(
- scopes.c.platform == platform,
- scopes.c.scope_type == scope_type,
- scopes.c.scope_id == scope_id,
- )
- ).scalar_one_or_none()
- if existing is not None:
- return int(existing)
- result = conn.execute(
- scopes.insert().values(
- platform=platform,
- scope_type=scope_type,
- scope_id=scope_id,
- display_name=display_name,
- created_at=now,
- updated_at=now,
- )
+
+def upsert_scope(
+ conn: Connection,
+ platform: str,
+ scope_type: str,
+ native_id: str,
+ *,
+ now: str,
+ parent_scope_id: str | None = None,
+ display_name: str | None = None,
+ native_type: str | None = None,
+ is_private: bool | None = None,
+ supports_threads: bool | None = None,
+ metadata: dict[str, Any] | None = None,
+) -> str:
+ scope_id = make_scope_id(platform, scope_type, native_id)
+ existing = conn.execute(select(scopes.c.id).where(scopes.c.id == scope_id)).scalar_one_or_none()
+ values = {
+ "parent_scope_id": parent_scope_id,
+ "display_name": display_name,
+ "native_type": native_type,
+ "last_seen_at": now,
+ "updated_at": now,
+ }
+ if is_private is not None:
+ values["is_private"] = _bool_int(is_private)
+ if supports_threads is not None:
+ values["supports_threads"] = _bool_int(supports_threads)
+ if metadata is not None:
+ values["metadata_json"] = _json_dumps(metadata)
+ if existing is not None:
+ clean_values = {key: value for key, value in values.items() if value not in (None, "", _json_dumps({}))}
+ if clean_values:
+ conn.execute(scopes.update().where(scopes.c.id == scope_id).values(**clean_values))
+ return scope_id
+
+ insert_values = {
+ "id": scope_id,
+ "platform": platform,
+ "scope_type": scope_type,
+ "native_id": native_id,
+ "is_private": _bool_int(is_private),
+ "supports_threads": _bool_int(supports_threads),
+ "metadata_json": _json_dumps(metadata or {}),
+ "first_seen_at": now,
+ **values,
+ }
+ conn.execute(scopes.insert().values(**insert_values))
+ return scope_id
+
+
+def make_scope_id(platform: str, scope_type: str, native_id: str) -> str:
+ return f"{platform}::{scope_type}::{native_id}"
+
+
+def _settings_rows(conn: Connection, scope_type: str):
+ return conn.execute(
+ select(
+ scopes.c.id.label("scope_id"),
+ scopes.c.platform,
+ scopes.c.scope_type,
+ scopes.c.native_id,
+ scopes.c.display_name,
+ scope_settings,
+ )
+ .join(scope_settings, scope_settings.c.scope_id == scopes.c.id)
+ .where(scopes.c.scope_type == scope_type)
+ ).mappings()
+
+
+def _routing_columns(routing: RoutingSettings) -> dict[str, str | None]:
+ backend = routing.agent_backend
+ if backend == "codex":
+ variant = routing.codex_agent
+ model = routing.codex_model
+ effort = routing.codex_reasoning_effort
+ elif backend == "claude":
+ variant = routing.claude_agent
+ model = routing.claude_model
+ effort = routing.claude_reasoning_effort
+ elif backend == "opencode":
+ variant = routing.opencode_agent
+ model = routing.opencode_model
+ effort = routing.opencode_reasoning_effort
+ else:
+ variant = routing.codex_agent or routing.claude_agent or routing.opencode_agent
+ model = routing.codex_model or routing.claude_model or routing.opencode_model
+ effort = (
+ routing.codex_reasoning_effort
+ or routing.claude_reasoning_effort
+ or routing.opencode_reasoning_effort
)
- return int(result.inserted_primary_key[0])
-
-
-def _routing_from_json(value: str) -> RoutingSettings:
- payload = _json_loads(value, {})
- return RoutingSettings(
- agent_backend=payload.get("agent_backend"),
- opencode_agent=payload.get("opencode_agent"),
- opencode_model=payload.get("opencode_model"),
- opencode_reasoning_effort=payload.get("opencode_reasoning_effort"),
- claude_agent=payload.get("claude_agent"),
- claude_model=payload.get("claude_model"),
- claude_reasoning_effort=payload.get("claude_reasoning_effort"),
- codex_agent=payload.get("codex_agent"),
- codex_model=payload.get("codex_model"),
- codex_reasoning_effort=payload.get("codex_reasoning_effort"),
+ return {
+ "agent_backend": backend,
+ "agent_variant": variant,
+ "model": model,
+ "reasoning_effort": effort,
+ }
+
+
+def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSettings:
+ routing_payload = payload.get("routing") or {}
+ routing = RoutingSettings(
+ agent_backend=routing_payload.get("agent_backend"),
+ opencode_agent=routing_payload.get("opencode_agent"),
+ opencode_model=routing_payload.get("opencode_model"),
+ opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),
+ claude_agent=routing_payload.get("claude_agent"),
+ claude_model=routing_payload.get("claude_model"),
+ claude_reasoning_effort=routing_payload.get("claude_reasoning_effort"),
+ codex_agent=routing_payload.get("codex_agent"),
+ codex_model=routing_payload.get("codex_model"),
+ codex_reasoning_effort=routing_payload.get("codex_reasoning_effort"),
)
+ backend = row.get("agent_backend")
+ if backend:
+ routing.agent_backend = str(backend)
+ variant = row.get("agent_variant")
+ model = row.get("model")
+ effort = row.get("reasoning_effort")
+ if routing.agent_backend == "codex":
+ routing.codex_agent = routing.codex_agent or variant
+ routing.codex_model = routing.codex_model or model
+ routing.codex_reasoning_effort = routing.codex_reasoning_effort or effort
+ elif routing.agent_backend == "claude":
+ routing.claude_agent = routing.claude_agent or variant
+ routing.claude_model = routing.claude_model or model
+ routing.claude_reasoning_effort = routing.claude_reasoning_effort or effort
+ elif routing.agent_backend == "opencode":
+ routing.opencode_agent = routing.opencode_agent or variant
+ routing.opencode_model = routing.opencode_model or model
+ routing.opencode_reasoning_effort = routing.opencode_reasoning_effort or effort
+ return routing
def _json_dumps(value: Any) -> str:
@@ -267,6 +385,10 @@ def _json_loads(value: str | None, default: Any) -> Any:
return default
+def _json_list(value: Any) -> list[str]:
+ return [str(item) for item in value] if isinstance(value, list) else []
+
+
def _bool_int(value: Any) -> int:
return 1 if bool(value) else 0
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index 9989e81c3..2d7fe2baf 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -5,8 +5,11 @@ from pathlib import Path
from config import paths
from config.v2_settings import ChannelSettings, SettingsState, SettingsStore, UserSettings
+from storage.db import create_sqlite_engine
+from storage.migrations import run_migrations
+from storage.models import scopes
from storage.sessions_service import SQLiteSessionsService
-from storage.settings_service import SQLiteSettingsService
+from storage.settings_service import SQLiteSettingsService, upsert_scope
def test_settings_store_uses_sqlite_without_rewriting_legacy_json(tmp_path: Path) -> None:
@@ -63,6 +66,54 @@ def test_settings_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:
store.close()
+def test_settings_save_preserves_observed_scope_metadata(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ upsert_scope(
+ conn,
+ "telegram",
+ "channel",
+ "123",
+ display_name="General",
+ native_type="supergroup",
+ is_private=True,
+ supports_threads=True,
+ metadata={"username": "general"},
+ now="2026-05-01T00:00:00+00:00",
+ )
+ finally:
+ engine.dispose()
+
+ service = SQLiteSettingsService(db_path)
+ try:
+ service.save_state(
+ SettingsState(
+ channels={
+ "telegram::123": ChannelSettings(enabled=True),
+ }
+ )
+ )
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.connect() as conn:
+ row = conn.execute(
+ scopes.select().where(scopes.c.id == "telegram::channel::123"),
+ ).mappings().one()
+ finally:
+ engine.dispose()
+
+ assert row["native_type"] == "supergroup"
+ assert row["is_private"] == 1
+ assert row["supports_threads"] == 1
+ assert json.loads(row["metadata_json"]) == {"username": "general"}
+
+
def test_settings_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
paths.ensure_data_dirs()
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 3e57c50b8..d99f0f121 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import re
import sqlite3
from pathlib import Path
@@ -27,9 +28,9 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
)
}
assert "alembic_version" in tables
- assert "channel_settings" in tables
- assert "agent_session_bindings" in tables
- assert "session_messages" in tables
+ assert "scope_settings" in tables
+ assert "agent_sessions" in tables
+ assert "runtime_records" in tables
version = conn.execute("select version_num from alembic_version").fetchone()
assert version == ("20260501_0001",)
@@ -106,24 +107,68 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
assert first.imported is True
assert first.backup_path is not None
assert (first.backup_path / "settings.json").exists()
- assert first.counts["channel_settings"] == 1
- assert first.counts["user_settings"] == 1
- assert first.counts["guild_settings"] == 1
- assert first.counts["bind_codes"] == 1
- assert first.counts["agent_session_bindings"] == 1
- assert first.counts["active_threads"] == 1
- assert first.counts["active_polls"] == 1
- assert first.counts["processed_messages"] == 2
- assert first.counts["discovered_chats"] == 1
+ assert first.counts["scopes"] == 5
+ assert first.counts["scope_settings"] == 4
+ assert first.counts["auth_codes"] == 1
+ assert first.counts["agent_sessions"] == 1
+ assert first.counts["runtime_records"] == 4
+ assert first.counts["discovered_scopes"] == 1
with sqlite3.connect(db_path) as conn:
last_activity = conn.execute(
- "select value from schema_meta where key = 'sessions_last_activity'",
+ "select value_json from state_meta where key = 'sessions_last_activity'",
).fetchone()
- assert last_activity == ("2026-05-01T00:00:00+00:00",)
+ channel_settings = conn.execute(
+ """
+ select s.native_id, ss.workdir, ss.agent_backend, ss.model, ss.reasoning_effort
+ from scopes s
+ join scope_settings ss on ss.scope_id = s.id
+ where s.platform = 'slack' and s.scope_type = 'channel' and s.native_id = 'C123'
+ """,
+ ).fetchone()
+ user_settings = conn.execute(
+ """
+ select ss.role, ss.agent_backend
+ from scopes s
+ join scope_settings ss on ss.scope_id = s.id
+ where s.platform = 'slack' and s.scope_type = 'user' and s.native_id = 'U123'
+ """,
+ ).fetchone()
+ agent_session = conn.execute(
+ """
+ select id, scope_id, session_anchor, workdir, native_session_id
+ from agent_sessions
+ """,
+ ).fetchone()
+ duplicate_insert_ok = True
+ try:
+ conn.execute(
+ """
+ insert into agent_sessions (
+ id, scope_id, agent_backend, agent_variant, model, reasoning_effort,
+ session_anchor, workdir, native_session_id, title, status,
+ metadata_json, created_at, updated_at, last_active_at
+ ) values (
+ 'sesabc234def', ?, 'codex', 'codex', 'gpt-5.4', 'high',
+ ?, ?, 'native-2', null, 'active', '{}', 'now', 'now', 'now'
+ )
+ """,
+ (agent_session[1], agent_session[2], agent_session[3]),
+ )
+ except sqlite3.IntegrityError:
+ duplicate_insert_ok = False
+ assert last_activity == ('"2026-05-01T00:00:00+00:00"',)
+ assert channel_settings == ("C123", "/repo", "codex", "gpt-5.4", None)
+ assert user_settings == ("admin", "opencode")
+ assert re.fullmatch(r"ses[23456789abcdefghjkmnpqrstuvwxyz]{10}", agent_session[0])
+ assert agent_session[1] == "slack::channel::C123"
+ assert agent_session[2] == "slack_1774074591.762089:/repo"
+ assert agent_session[3] == "/repo"
+ assert agent_session[4] == "codex-session-1"
+ assert duplicate_insert_ok is True
assert second.imported is False
assert second.backup_path is None
- assert second.counts == first.counts
+ assert second.counts == {key: value for key, value in first.counts.items() if key != "discovered_scopes"}
def test_custom_state_paths_do_not_bootstrap_default_home(tmp_path: Path, monkeypatch) -> None:
@@ -174,7 +219,7 @@ def test_legacy_sessions_import_requires_platform_when_not_inferable(tmp_path: P
with sqlite3.connect(db_path) as conn:
marker = conn.execute(
- "select value from schema_meta where key = 'json_import_completed_at'",
+ "select value_json from state_meta where key = 'json_import_completed_at'",
).fetchone()
assert marker is None
@@ -200,7 +245,7 @@ def test_legacy_settings_import_does_not_rewrite_source_json(tmp_path: Path) ->
report = ensure_sqlite_state(db_path=state_dir / "vibe.sqlite", state_dir=state_dir, primary_platform="slack")
assert report.imported is True
- assert report.counts["channel_settings"] == 1
+ assert report.counts["scope_settings"] == 1
assert settings_path.read_text(encoding="utf-8") == original
@@ -215,7 +260,7 @@ def test_failed_json_import_does_not_mark_complete_and_can_retry(tmp_path: Path)
with sqlite3.connect(db_path) as conn:
marker = conn.execute(
- "select value from schema_meta where key = 'json_import_completed_at'",
+ "select value_json from state_meta where key = 'json_import_completed_at'",
).fetchone()
assert marker is None
@@ -223,7 +268,7 @@ def test_failed_json_import_does_not_mark_complete_and_can_retry(tmp_path: Path)
report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
assert report.imported is True
- assert report.counts["channel_settings"] == 1
+ assert report.counts["scope_settings"] == 4
def test_invalid_discovered_chats_import_does_not_mark_complete_and_can_retry(tmp_path: Path) -> None:
@@ -239,7 +284,7 @@ def test_invalid_discovered_chats_import_does_not_mark_complete_and_can_retry(tm
with sqlite3.connect(db_path) as conn:
marker = conn.execute(
- "select value from schema_meta where key = 'json_import_completed_at'",
+ "select value_json from state_meta where key = 'json_import_completed_at'",
).fetchone()
assert marker is None
@@ -247,7 +292,7 @@ def test_invalid_discovered_chats_import_does_not_mark_complete_and_can_retry(tm
report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
assert report.imported is True
- assert report.counts["discovered_chats"] == 1
+ assert report.counts["discovered_scopes"] == 1
def test_malformed_discovered_chats_structure_does_not_mark_complete(tmp_path: Path) -> None:
@@ -266,7 +311,7 @@ def test_malformed_discovered_chats_structure_does_not_mark_complete(tmp_path: P
with sqlite3.connect(db_path) as conn:
marker = conn.execute(
- "select value from schema_meta where key = 'json_import_completed_at'",
+ "select value_json from state_meta where key = 'json_import_completed_at'",
).fetchone()
assert marker is None
@@ -274,7 +319,7 @@ def test_malformed_discovered_chats_structure_does_not_mark_complete(tmp_path: P
report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
assert report.imported is True
- assert report.counts["discovered_chats"] == 1
+ assert report.counts["discovered_scopes"] == 1
def test_data_version_probe_detects_external_write(tmp_path: Path) -> None:
@@ -286,7 +331,7 @@ def test_data_version_probe_detects_external_write(tmp_path: Path) -> None:
assert probe.has_external_write() is False
with engine.begin() as conn:
conn.exec_driver_sql(
- "insert into schema_meta (key, value, updated_at) values ('probe', '1', 'now')"
+ "insert into state_meta (key, value_json, updated_at) values ('probe', '1', 'now')"
)
assert probe.has_external_write() is True
assert probe.has_external_write() is False