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.

fix(storage): backfill scope agent names during migration (#344)

Call White58fe6c5d89e8
diff --git a/storage/alembic/versions/20260529_0007_backfill_scope_agent_names.py b/storage/alembic/versions/20260529_0007_backfill_scope_agent_names.py
new file mode 100644
index 000000000..79108f580
--- /dev/null
+++ b/storage/alembic/versions/20260529_0007_backfill_scope_agent_names.py
@@ -0,0 +1,150 @@
+"""backfill scope Agent names from legacy backend routing
+
+Revision ID: 20260529_0007
+Revises: 20260526_0006
+Create Date: 2026-05-29
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from datetime import datetime, timezone
+
+from alembic import op
+
+revision = "20260529_0007"
+down_revision = "20260526_0006"
+branch_labels = None
+depends_on = None
+
+_BACKENDS = ("opencode", "claude", "codex")
+_BUILTIN_DEFAULT_METADATA = {"builtin": True, "builtin_default": True, "lock_delete": True}
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ tables = _tables(bind)
+ if not {"agents", "scopes", "scope_settings"}.issubset(tables):
+ return
+
+ now = _utc_now_iso()
+ for backend in _BACKENDS:
+ rows = _legacy_scope_rows_for_backend(bind, backend)
+ if not rows:
+ continue
+ default_agent_name: str | None = None
+ for scope_id, settings_json in rows:
+ agent_name = _explicit_agent_name_from_settings_json(settings_json)
+ if not agent_name:
+ if default_agent_name is None:
+ default_agent_name = _ensure_backend_default_agent(bind, backend, now)
+ if not default_agent_name:
+ continue
+ agent_name = default_agent_name
+ _backfill_scope_agent_name(bind, scope_id, settings_json, agent_name, now)
+
+
+def downgrade() -> None:
+ pass
+
+
+def _tables(bind) -> set[str]:
+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}
+
+
+def _legacy_scope_rows_for_backend(bind, backend: str):
+ return bind.exec_driver_sql(
+ """
+ select ss.scope_id, ss.settings_json
+ from scope_settings ss
+ join scopes s on s.id = ss.scope_id
+ where s.scope_type in ('channel', 'user')
+ and ss.agent_backend = ?
+ and (ss.agent_name is null or trim(ss.agent_name) = '')
+ """,
+ (backend,),
+ ).fetchall()
+
+
+def _ensure_backend_default_agent(bind, backend: str, now: str) -> str | None:
+ existing = bind.exec_driver_sql(
+ "select name, backend, enabled from agents where normalized_name = ? limit 1",
+ (backend,),
+ ).fetchone()
+ if existing:
+ name, existing_backend, enabled = existing
+ return str(name) if existing_backend == backend and bool(enabled) else None
+
+ metadata = {**_BUILTIN_DEFAULT_METADATA, "backend": backend, "backend_enabled": True}
+ bind.exec_driver_sql(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (?, ?, ?, ?, ?, null, null, null, 1, 'builtin', null, ?, ?, ?)
+ """,
+ (
+ uuid.uuid4().hex[:12],
+ backend,
+ backend,
+ f"Default {backend} agent.",
+ backend,
+ _json_dumps(metadata),
+ now,
+ now,
+ ),
+ )
+ return backend
+
+
+def _backfill_scope_agent_name(bind, scope_id: str, settings_json: str | None, agent_name: str, now: str) -> None:
+ bind.exec_driver_sql(
+ """
+ update scope_settings
+ set agent_name = ?, settings_json = ?, updated_at = ?
+ where scope_id = ?
+ """,
+ (agent_name, _settings_json_with_agent_name(settings_json, agent_name), now, scope_id),
+ )
+
+
+def _explicit_agent_name_from_settings_json(value: str | None) -> str | None:
+ try:
+ payload = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ routing = payload.get("routing")
+ if not isinstance(routing, dict):
+ return None
+ for key in ("agent_name", "agent"):
+ agent_name = routing.get(key)
+ if isinstance(agent_name, str) and agent_name.strip():
+ return agent_name.strip()
+ return None
+
+
+def _settings_json_with_agent_name(value: str | None, agent_name: str) -> str:
+ try:
+ payload = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return value or "{}"
+ if not isinstance(payload, dict):
+ return value or "{}"
+ routing = payload.get("routing")
+ if not isinstance(routing, dict):
+ routing = {}
+ if not routing.get("agent_name"):
+ routing["agent_name"] = agent_name
+ payload["routing"] = routing
+ return _json_dumps(payload)
+
+
+def _json_dumps(value: object) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
diff --git a/storage/importer.py b/storage/importer.py
index 81b47a344..66e3b573d 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -4,6 +4,7 @@ import json
import logging
import shutil
import tempfile
+import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -102,6 +103,7 @@ def ensure_sqlite_state(
_write_parsed_state(target_db, parsed)
with engine.begin() as conn:
+ _backfill_imported_scope_agent_names(conn)
discovered_count = _import_discovered_chats(conn, parsed.discovered)
background_counts = _import_background_state(conn, target_state_dir)
counts = _current_counts(conn)
@@ -366,6 +368,119 @@ def _migrate_session_state_for_import(state: SessionState, *, primary_platform:
migrate_session_state_mappings(state, default_platform)
+def _backfill_imported_scope_agent_names(conn: Connection) -> None:
+ now = _utc_now_iso()
+ for backend in ("opencode", "claude", "codex"):
+ rows = _legacy_scope_rows_for_backend(conn, backend)
+ if not rows:
+ continue
+ default_agent_name: str | None = None
+ for scope_id, settings_json in rows:
+ agent_name = _explicit_agent_name_from_settings_json(settings_json)
+ if not agent_name:
+ if default_agent_name is None:
+ default_agent_name = _ensure_backend_default_agent(conn, backend, now)
+ if not default_agent_name:
+ continue
+ agent_name = default_agent_name
+ _backfill_scope_agent_name(conn, scope_id, settings_json, agent_name, now)
+
+
+def _legacy_scope_rows_for_backend(conn: Connection, backend: str):
+ return conn.exec_driver_sql(
+ """
+ select ss.scope_id, ss.settings_json
+ from scope_settings ss
+ join scopes s on s.id = ss.scope_id
+ where s.scope_type in ('channel', 'user')
+ and ss.agent_backend = ?
+ and (ss.agent_name is null or trim(ss.agent_name) = '')
+ """,
+ (backend,),
+ ).fetchall()
+
+
+def _ensure_backend_default_agent(conn: Connection, backend: str, now: str) -> str | None:
+ existing = conn.exec_driver_sql(
+ "select name, backend, enabled from agents where normalized_name = ? limit 1",
+ (backend,),
+ ).fetchone()
+ if existing:
+ name, existing_backend, enabled = existing
+ return str(name) if existing_backend == backend and bool(enabled) else None
+
+ metadata = {
+ "builtin": True,
+ "builtin_default": True,
+ "lock_delete": True,
+ "backend": backend,
+ "backend_enabled": True,
+ }
+ conn.exec_driver_sql(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (?, ?, ?, ?, ?, null, null, null, 1, 'builtin', null, ?, ?, ?)
+ """,
+ (
+ uuid.uuid4().hex[:12],
+ backend,
+ backend,
+ f"Default {backend} agent.",
+ backend,
+ _json_dumps(metadata),
+ now,
+ now,
+ ),
+ )
+ return backend
+
+
+def _backfill_scope_agent_name(conn: Connection, scope_id: str, settings_json: str | None, agent_name: str, now: str) -> None:
+ conn.exec_driver_sql(
+ """
+ update scope_settings
+ set agent_name = ?, settings_json = ?, updated_at = ?
+ where scope_id = ?
+ """,
+ (agent_name, _settings_json_with_agent_name(settings_json, agent_name), now, scope_id),
+ )
+
+
+def _explicit_agent_name_from_settings_json(value: str | None) -> str | None:
+ try:
+ payload = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ routing = payload.get("routing")
+ if not isinstance(routing, dict):
+ return None
+ for key in ("agent_name", "agent"):
+ agent_name = routing.get(key)
+ if isinstance(agent_name, str) and agent_name.strip():
+ return agent_name.strip()
+ return None
+
+
+def _settings_json_with_agent_name(value: str | None, agent_name: str) -> str:
+ try:
+ payload = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return value or "{}"
+ if not isinstance(payload, dict):
+ return value or "{}"
+ routing = payload.get("routing")
+ if not isinstance(routing, dict):
+ routing = {}
+ if not routing.get("agent_name"):
+ routing["agent_name"] = agent_name
+ payload["routing"] = routing
+ return _json_dumps(payload)
+
+
def _clear_imported_state(conn: Connection) -> None:
for table in imported_state_tables:
conn.execute(table.delete())
diff --git a/storage/migrations.py b/storage/migrations.py
index 569244dbe..bba521920 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -10,6 +10,7 @@ from config import paths
from storage.db import sqlite_url
INITIAL_REVISION = "20260501_0001"
+LATEST_SCHEMA_REVISION = "20260526_0006"
INITIAL_TABLES = {
"state_meta",
"agents",
@@ -198,7 +199,7 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
if not _head_schema_ready(conn, tables):
missing = _missing_head_schema_description(conn, tables)
raise RuntimeError(f"existing SQLite head schema is incomplete; missing: {missing}")
- command.stamp(cfg, "head")
+ command.stamp(cfg, LATEST_SCHEMA_REVISION)
return
command.stamp(cfg, INITIAL_REVISION)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index e3bb09583..3fa1b011c 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -14,6 +14,9 @@ from storage.migrations import background_tables_ready, run_migrations
from storage.models import metadata
+HEAD_REVISION = "20260529_0007"
+
+
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
@@ -42,7 +45,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
}
assert "deleted_at" in background_columns
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260523_0004",)
+ assert version == (HEAD_REVISION,)
def test_initial_migration_is_schema_snapshot() -> None:
@@ -80,7 +83,7 @@ def test_run_migrations_stamps_existing_initial_schema(tmp_path: Path) -> None:
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260523_0004",)
+ assert version == (HEAD_REVISION,)
def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(tmp_path: Path) -> None:
@@ -100,7 +103,47 @@ def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260523_0004",)
+ assert version == (HEAD_REVISION,)
+
+
+def test_run_migrations_runs_data_migration_when_stamping_existing_head_schema(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into scopes (
+ id, platform, scope_type, native_id, parent_scope_id, display_name, native_type,
+ is_private, supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values (
+ 'slack::channel::C1', 'slack', 'channel', 'C1', null, null, null, 0, 1, '{}', 'now', 'now', 'now'
+ );
+ insert into scope_settings (
+ scope_id, enabled, role, workdir, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, require_mention, settings_version, settings_json, created_at, updated_at
+ ) values (
+ 'slack::channel::C1', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_backend":"codex"}}', 'now', 'now'
+ );
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ agent_name = conn.execute("select agent_name from scope_settings").fetchone()[0]
+ codex_agent = conn.execute("select backend from agents where name = 'codex'").fetchone()
+
+ assert version == (HEAD_REVISION,)
+ assert agent_name == "codex"
+ assert codex_agent == ("codex",)
def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path) -> None:
@@ -140,7 +183,7 @@ def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
background_columns = {row[1] for row in conn.execute("pragma table_info(run_definitions)")}
- assert version == ("20260523_0004",)
+ assert version == (HEAD_REVISION,)
assert "deleted_at" in background_columns
assert background_tables_ready(db_path) is True
@@ -166,7 +209,7 @@ def test_run_migrations_repairs_head_stamped_background_schema_drift(tmp_path: P
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
columns = {row[1] for row in conn.execute("pragma table_info(run_definitions)")}
- assert version == ("20260523_0004",)
+ assert version == (HEAD_REVISION,)
assert "definition_type" in columns
assert "task_type" not in columns
assert background_tables_ready(db_path) is True
@@ -208,6 +251,202 @@ def test_run_migrations_backfills_existing_session_policy_only_for_targeted_defi
assert rows["without-target"] is None
+def test_run_migrations_backfills_scope_agent_names_from_legacy_backend(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-claude', 'claude', 'claude', 'Default claude agent.', 'claude', null, null,
+ null, 1, 'builtin', null, '{}', 'now', 'now'
+ );
+ insert into scopes (
+ id, platform, scope_type, native_id, parent_scope_id, display_name, native_type,
+ is_private, supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values
+ ('slack::channel::C1', 'slack', 'channel', 'C1', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::user::U1', 'slack', 'user', 'U1', null, null, null, 1, 0, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C2', 'slack', 'channel', 'C2', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C3', 'slack', 'channel', 'C3', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C4', 'slack', 'channel', 'C4', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C5', 'slack', 'channel', 'C5', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C6', 'slack', 'channel', 'C6', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('discord::guild::G1', 'discord', 'guild', 'G1', null, null, null, 0, 0, '{}', 'now', 'now', 'now');
+ insert into scope_settings (
+ scope_id, enabled, role, workdir, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, require_mention, settings_version, settings_json, created_at, updated_at
+ ) values
+ ('slack::channel::C1', 1, null, '/repo', null, 'codex', null, 'gpt-5.5', 'high', 0, 1,
+ '{"show_message_types":["assistant"],"routing":{"agent_backend":"codex","codex_model":"gpt-5.5"}}', 'now', 'now'),
+ ('slack::user::U1', 1, 'admin', '/repo', null, 'claude', null, null, null, null, 1,
+ '{"routing":{"agent_backend":"claude"}}', 'now', 'now'),
+ ('slack::channel::C2', 1, null, '/repo', 'reviewer', 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_name":"reviewer","agent_backend":"codex"}}', 'now', 'now'),
+ ('slack::channel::C3', 1, null, '/repo', null, null, null, null, null, null, 1,
+ '{"routing":{}}', 'now', 'now'),
+ ('slack::channel::C4', 1, null, '/repo', null, 'claude', null, null, null, null, 1,
+ 'not-json', 'now', 'now'),
+ ('slack::channel::C5', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_name":"reviewer","agent_backend":"codex"}}', 'now', 'now'),
+ ('slack::channel::C6', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent":"legacy-reviewer","agent_backend":"codex"}}', 'now', 'now'),
+ ('discord::guild::G1', 1, null, null, null, 'opencode', null, null, null, null, 1,
+ '{"routing":{"agent_backend":"opencode"}}', 'now', 'now');
+ create table alembic_version (version_num varchar(32) not null);
+ insert into alembic_version values ('20260526_0006');
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ rows = dict(conn.execute("select scope_id, agent_name from scope_settings"))
+ codex_agent = conn.execute(
+ "select backend, source, enabled, metadata_json from agents where name = 'codex'"
+ ).fetchone()
+ claude_agent_count = conn.execute("select count(*) from agents where name = 'claude'").fetchone()[0]
+ payload = json.loads(
+ conn.execute(
+ "select settings_json from scope_settings where scope_id = 'slack::channel::C1'"
+ ).fetchone()[0]
+ )
+ malformed_json = conn.execute(
+ "select settings_json from scope_settings where scope_id = 'slack::channel::C4'"
+ ).fetchone()[0]
+ legacy_payload = json.loads(
+ conn.execute(
+ "select settings_json from scope_settings where scope_id = 'slack::channel::C6'"
+ ).fetchone()[0]
+ )
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert version == (HEAD_REVISION,)
+ assert rows["slack::channel::C1"] == "codex"
+ assert rows["slack::user::U1"] == "claude"
+ assert rows["slack::channel::C2"] == "reviewer"
+ assert rows["slack::channel::C3"] is None
+ assert rows["slack::channel::C4"] == "claude"
+ assert rows["slack::channel::C5"] == "reviewer"
+ assert rows["slack::channel::C6"] == "legacy-reviewer"
+ assert rows["discord::guild::G1"] is None
+ assert codex_agent[0:3] == ("codex", "builtin", 1)
+ assert json.loads(codex_agent[3])["builtin_default"] is True
+ assert claude_agent_count == 1
+ assert payload["routing"]["agent_name"] == "codex"
+ assert payload["routing"]["codex_model"] == "gpt-5.5"
+ assert legacy_payload["routing"]["agent_name"] == "legacy-reviewer"
+ assert legacy_payload["routing"]["agent"] == "legacy-reviewer"
+ assert malformed_json == "not-json"
+
+
+def test_run_migrations_skips_agent_name_backfill_on_backend_name_conflict(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-codex-conflict', 'codex', 'codex', 'User codex alias.', 'opencode', null, null,
+ null, 1, 'user', null, '{}', 'now', 'now'
+ );
+ insert into scopes (
+ id, platform, scope_type, native_id, parent_scope_id, display_name, native_type,
+ is_private, supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values
+ ('slack::channel::C1', 'slack', 'channel', 'C1', null, null, null, 0, 1, '{}', 'now', 'now', 'now'),
+ ('slack::channel::C2', 'slack', 'channel', 'C2', null, null, null, 0, 1, '{}', 'now', 'now', 'now');
+ insert into scope_settings (
+ scope_id, enabled, role, workdir, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, require_mention, settings_version, settings_json, created_at, updated_at
+ ) values
+ ('slack::channel::C1', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_backend":"codex"}}', 'now', 'now'),
+ ('slack::channel::C2', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_name":"reviewer","agent_backend":"codex"}}', 'now', 'now');
+ create table alembic_version (version_num varchar(32) not null);
+ insert into alembic_version values ('20260526_0006');
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ rows = dict(conn.execute("select scope_id, agent_name from scope_settings"))
+ codex_rows = conn.execute("select count(*) from agents where normalized_name = 'codex'").fetchone()[0]
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert version == (HEAD_REVISION,)
+ assert rows["slack::channel::C1"] is None
+ assert rows["slack::channel::C2"] == "reviewer"
+ assert codex_rows == 1
+
+
+def test_run_migrations_skips_disabled_backend_agent_name_match(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-codex-disabled', 'codex', 'codex', 'Disabled codex agent.', 'codex', null, null,
+ null, 0, 'user', null, '{}', 'now', 'now'
+ );
+ insert into scopes (
+ id, platform, scope_type, native_id, parent_scope_id, display_name, native_type,
+ is_private, supports_threads, metadata_json, first_seen_at, last_seen_at, updated_at
+ ) values (
+ 'slack::channel::C1', 'slack', 'channel', 'C1', null, null, null, 0, 1, '{}', 'now', 'now', 'now'
+ );
+ insert into scope_settings (
+ scope_id, enabled, role, workdir, agent_name, agent_backend, agent_variant,
+ model, reasoning_effort, require_mention, settings_version, settings_json, created_at, updated_at
+ ) values (
+ 'slack::channel::C1', 1, null, '/repo', null, 'codex', null, null, null, null, 1,
+ '{"routing":{"agent_backend":"codex"}}', 'now', 'now'
+ );
+ create table alembic_version (version_num varchar(32) not null);
+ insert into alembic_version values ('20260526_0006');
+ """
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ agent_name = conn.execute("select agent_name from scope_settings").fetchone()[0]
+ codex_rows = conn.execute("select count(*) from agents where normalized_name = 'codex'").fetchone()[0]
+
+ assert agent_name is None
+ assert codex_rows == 1
+
+
def test_run_migrations_does_not_stamp_partial_schema_missing_scopes(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
with sqlite3.connect(db_path) as conn:
@@ -311,7 +550,7 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
).fetchone()
channel_settings = conn.execute(
"""
- select s.native_id, ss.workdir, ss.agent_backend, ss.model, ss.reasoning_effort
+ select s.native_id, ss.workdir, ss.agent_name, 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'
@@ -319,7 +558,7 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
).fetchone()
user_settings = conn.execute(
"""
- select ss.role, ss.agent_backend
+ select ss.role, ss.agent_name, 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'
@@ -349,8 +588,8 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
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 channel_settings == ("C123", "/repo", "codex", "codex", "gpt-5.4", None)
+ assert user_settings == ("admin", "opencode", "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"
@@ -375,6 +614,52 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
}
+def test_ensure_sqlite_state_import_skips_agent_name_conflict(tmp_path: Path) -> None:
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ _write_current_settings(state_dir / "settings.json")
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-codex-conflict', 'codex', 'codex', 'User codex alias.', 'opencode', null, null,
+ null, 1, 'user', null, '{}', 'now', 'now'
+ )
+ """
+ )
+ conn.commit()
+
+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+
+ with sqlite3.connect(db_path) as conn:
+ channel_agent_name = conn.execute(
+ """
+ select ss.agent_name
+ from scopes s
+ join scope_settings ss on ss.scope_id = s.id
+ where s.scope_type = 'channel' and s.native_id = 'C123'
+ """
+ ).fetchone()[0]
+ user_agent_name = conn.execute(
+ """
+ select ss.agent_name
+ from scopes s
+ join scope_settings ss on ss.scope_id = s.id
+ where s.scope_type = 'user' and s.native_id = 'U123'
+ """
+ ).fetchone()[0]
+ codex_rows = conn.execute("select count(*) from agents where normalized_name = 'codex'").fetchone()[0]
+
+ assert channel_agent_name is None
+ assert user_agent_name == "opencode"
+ assert codex_rows == 1
+
+
def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
state_dir.mkdir()