Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(settings): back settings store with sqlite

cyhba5fb83c4742
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 24a6bacf0..cd595a71b 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -174,6 +174,149 @@ def _routing_to_dict(routing: RoutingSettings) -> dict:
}
+def parse_settings_payload(payload: dict) -> tuple[SettingsState, bool]:
+ """Parse current or legacy settings JSON into normalized SettingsState."""
+ if not isinstance(payload, dict):
+ raise ValueError("settings payload must be an object")
+
+ channels: Dict[str, ChannelSettings] = {}
+ guilds: Dict[str, GuildSettings] = {}
+ guild_scope_platforms: set[str] = set()
+ guild_default_enabled: Dict[str, bool] = {}
+ users: Dict[str, UserSettings] = {}
+ migrated_legacy_channels = False
+
+ scopes = payload.get("scopes")
+ if isinstance(scopes, dict):
+ raw_channel_scopes = scopes.get("channel") or {}
+ if isinstance(raw_channel_scopes, dict):
+ for platform, items in raw_channel_scopes.items():
+ if not isinstance(items, dict):
+ continue
+ for channel_id, cp in items.items():
+ if not isinstance(cp, dict):
+ continue
+ key = _make_scoped_key(str(platform), str(channel_id))
+ channels[key] = ChannelSettings(
+ enabled=cp.get("enabled", False),
+ show_message_types=normalize_show_message_types(cp.get("show_message_types")),
+ custom_cwd=cp.get("custom_cwd"),
+ routing=_parse_routing(cp.get("routing") or {}),
+ require_mention=cp.get("require_mention"),
+ )
+
+ raw_guild_scopes = scopes.get("guild") or {}
+ if isinstance(raw_guild_scopes, dict):
+ raw_guild_policy = scopes.get("guild_policy") or {}
+ for platform, items in raw_guild_scopes.items():
+ platform_key = str(platform)
+ guild_scope_platforms.add(platform_key)
+ policy = raw_guild_policy.get(platform_key) if isinstance(raw_guild_policy, dict) else None
+ if isinstance(policy, dict):
+ guild_default_enabled[platform_key] = bool(policy.get("default_enabled", False))
+ else:
+ guild_default_enabled[platform_key] = False
+ if not isinstance(items, dict):
+ continue
+ for guild_id, gp in items.items():
+ if not isinstance(gp, dict):
+ continue
+ key = _make_scoped_key(platform_key, str(guild_id))
+ guilds[key] = GuildSettings(enabled=gp.get("enabled", True))
+
+ raw_user_scopes = scopes.get("user") or {}
+ if isinstance(raw_user_scopes, dict):
+ for platform, items in raw_user_scopes.items():
+ if not isinstance(items, dict):
+ continue
+ for user_id, up in items.items():
+ if not isinstance(up, dict):
+ continue
+ key = _make_scoped_key(str(platform), str(user_id))
+ users[key] = UserSettings(
+ display_name=up.get("display_name", ""),
+ is_admin=up.get("is_admin", False),
+ bound_at=up.get("bound_at", ""),
+ enabled=up.get("enabled", True),
+ show_message_types=normalize_show_message_types(up.get("show_message_types")),
+ custom_cwd=up.get("custom_cwd"),
+ routing=_parse_routing(up.get("routing") or {}),
+ dm_chat_id=up.get("dm_chat_id", ""),
+ )
+ else:
+ raw_channels = payload.get("channels") or {}
+ if not isinstance(raw_channels, dict):
+ logger.error("Failed to load settings: channels must be an object")
+ raw_channels = {}
+ for channel_id, cp in raw_channels.items():
+ if not isinstance(cp, dict):
+ continue
+ platform = _infer_channel_platform(str(channel_id))
+ scoped_key = _make_scoped_key(platform, str(channel_id))
+ channels[scoped_key] = ChannelSettings(
+ enabled=cp.get("enabled", False),
+ show_message_types=normalize_show_message_types(cp.get("show_message_types")),
+ custom_cwd=cp.get("custom_cwd"),
+ routing=_parse_routing(cp.get("routing") or {}),
+ require_mention=cp.get("require_mention"),
+ )
+ migrated_legacy_channels = True
+
+ raw_users = payload.get("users") or {}
+ if isinstance(raw_users, dict):
+ for user_id, up in raw_users.items():
+ if not isinstance(up, dict):
+ continue
+ platform = _infer_user_platform(str(user_id))
+ scoped_key = _make_scoped_key(platform, str(user_id))
+ users[scoped_key] = UserSettings(
+ display_name=up.get("display_name", ""),
+ is_admin=up.get("is_admin", False),
+ bound_at=up.get("bound_at", ""),
+ enabled=up.get("enabled", True),
+ show_message_types=normalize_show_message_types(up.get("show_message_types")),
+ custom_cwd=up.get("custom_cwd"),
+ routing=_parse_routing(up.get("routing") or {}),
+ dm_chat_id=up.get("dm_chat_id", ""),
+ )
+
+ raw_codes = payload.get("bind_codes") or []
+ bind_codes: List[BindCode] = []
+ if isinstance(raw_codes, list):
+ for bc in raw_codes:
+ if not isinstance(bc, dict):
+ continue
+ bind_codes.append(
+ BindCode(
+ code=bc.get("code", ""),
+ type=bc.get("type", "one_time"),
+ created_at=bc.get("created_at", ""),
+ expires_at=bc.get("expires_at"),
+ is_active=bc.get("is_active", True),
+ used_by=bc.get("used_by") or [],
+ )
+ )
+
+ return (
+ SettingsState(
+ channels=channels,
+ guilds=guilds,
+ guild_scope_platforms=guild_scope_platforms,
+ guild_default_enabled=guild_default_enabled,
+ users=users,
+ bind_codes=bind_codes,
+ ),
+ migrated_legacy_channels,
+ )
+
+
+def load_settings_state_from_json(settings_path: Path) -> tuple[SettingsState, bool]:
+ if not settings_path.exists():
+ return SettingsState(), False
+ payload = json.loads(settings_path.read_text(encoding="utf-8"))
+ return parse_settings_payload(payload)
+
+
class SettingsStore:
# ------------------------------------------------------------------
# Singleton: one store shared by bot process AND UI API handlers.
@@ -199,248 +342,42 @@ class SettingsStore:
def reset_instance(cls) -> None:
"""Reset singleton (for tests only)."""
with cls._instance_lock:
+ if cls._instance is not None:
+ cls._instance.close()
cls._instance = None
def __init__(self, settings_path: Optional[Path] = None):
- self.settings_path = settings_path or paths.get_settings_path()
+ self.settings_path = Path(settings_path) if settings_path else paths.get_settings_path()
+ self.db_path = self.settings_path.with_name("vibe.sqlite")
self.settings: SettingsState = SettingsState()
self._bind_lock = threading.Lock() # Guards atomic bind operations
self._file_mtime: float = 0
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import SQLiteSettingsService
+
+ ensure_sqlite_state(db_path=self.db_path, state_dir=self.settings_path.parent)
+ self._service = SQLiteSettingsService(self.db_path)
self._load()
+ self._service.has_external_write()
+
+ def close(self) -> None:
+ service = getattr(self, "_service", None)
+ if service is not None:
+ service.close()
def maybe_reload(self) -> None:
- """Reload from disk if the file has been modified since last load."""
- try:
- mtime = self.settings_path.stat().st_mtime
- if mtime > self._file_mtime:
- self._load()
- except FileNotFoundError:
- pass
+ """Reload from SQLite if another connection has committed changes."""
+ if self._service.has_external_write():
+ self._load()
def _load(self) -> None:
- if not self.settings_path.exists():
- return
- try:
- payload = json.loads(self.settings_path.read_text(encoding="utf-8"))
- except Exception as exc:
- logger.error("Failed to load settings: %s", exc)
- return
- if not isinstance(payload, dict):
- logger.error("Failed to load settings: invalid format")
- return
-
- channels: Dict[str, ChannelSettings] = {}
- guilds: Dict[str, GuildSettings] = {}
- guild_scope_platforms: set[str] = set()
- guild_default_enabled: Dict[str, bool] = {}
- users: Dict[str, UserSettings] = {}
- migrated_legacy_channels = False
-
- # --- New schema (v3): payload["scopes"]["channel"|"user"][platform][id] ---
- scopes = payload.get("scopes")
- if isinstance(scopes, dict):
- raw_channel_scopes = scopes.get("channel") or {}
- if isinstance(raw_channel_scopes, dict):
- for platform, items in raw_channel_scopes.items():
- if not isinstance(items, dict):
- continue
- for channel_id, cp in items.items():
- if not isinstance(cp, dict):
- continue
- key = _make_scoped_key(str(platform), str(channel_id))
- channels[key] = ChannelSettings(
- enabled=cp.get("enabled", False),
- show_message_types=normalize_show_message_types(cp.get("show_message_types")),
- custom_cwd=cp.get("custom_cwd"),
- routing=_parse_routing(cp.get("routing") or {}),
- require_mention=cp.get("require_mention"),
- )
-
- raw_guild_scopes = scopes.get("guild") or {}
- if isinstance(raw_guild_scopes, dict):
- raw_guild_policy = scopes.get("guild_policy") or {}
- for platform, items in raw_guild_scopes.items():
- platform_key = str(platform)
- guild_scope_platforms.add(platform_key)
- policy = raw_guild_policy.get(platform_key) if isinstance(raw_guild_policy, dict) else None
- if isinstance(policy, dict):
- guild_default_enabled[platform_key] = bool(policy.get("default_enabled", False))
- else:
- guild_default_enabled[platform_key] = False
- if not isinstance(items, dict):
- continue
- for guild_id, gp in items.items():
- if not isinstance(gp, dict):
- continue
- key = _make_scoped_key(platform_key, str(guild_id))
- guilds[key] = GuildSettings(enabled=gp.get("enabled", True))
-
- raw_user_scopes = scopes.get("user") or {}
- if isinstance(raw_user_scopes, dict):
- for platform, items in raw_user_scopes.items():
- if not isinstance(items, dict):
- continue
- for user_id, up in items.items():
- if not isinstance(up, dict):
- continue
- key = _make_scoped_key(str(platform), str(user_id))
- users[key] = UserSettings(
- display_name=up.get("display_name", ""),
- is_admin=up.get("is_admin", False),
- bound_at=up.get("bound_at", ""),
- enabled=up.get("enabled", True),
- show_message_types=normalize_show_message_types(up.get("show_message_types")),
- custom_cwd=up.get("custom_cwd"),
- routing=_parse_routing(up.get("routing") or {}),
- dm_chat_id=up.get("dm_chat_id", ""),
- )
- else:
- # --- Legacy schema: flat payload["channels"] / payload["users"] ---
- raw_channels = payload.get("channels") or {}
- if not isinstance(raw_channels, dict):
- logger.error("Failed to load settings: channels must be an object")
- raw_channels = {}
- for channel_id, cp in raw_channels.items():
- if not isinstance(cp, dict):
- continue
- platform = _infer_channel_platform(str(channel_id))
- scoped_key = _make_scoped_key(platform, str(channel_id))
- channels[scoped_key] = ChannelSettings(
- enabled=cp.get("enabled", False),
- show_message_types=normalize_show_message_types(cp.get("show_message_types")),
- custom_cwd=cp.get("custom_cwd"),
- routing=_parse_routing(cp.get("routing") or {}),
- require_mention=cp.get("require_mention"),
- )
- migrated_legacy_channels = True
-
- raw_users = payload.get("users") or {}
- if isinstance(raw_users, dict):
- for user_id, up in raw_users.items():
- if not isinstance(up, dict):
- continue
- platform = _infer_user_platform(str(user_id))
- scoped_key = _make_scoped_key(platform, str(user_id))
- users[scoped_key] = UserSettings(
- display_name=up.get("display_name", ""),
- is_admin=up.get("is_admin", False),
- bound_at=up.get("bound_at", ""),
- enabled=up.get("enabled", True),
- show_message_types=normalize_show_message_types(up.get("show_message_types")),
- custom_cwd=up.get("custom_cwd"),
- routing=_parse_routing(up.get("routing") or {}),
- dm_chat_id=up.get("dm_chat_id", ""),
- )
-
- # --- Bind Codes ---
- raw_codes = payload.get("bind_codes") or []
- bind_codes: List[BindCode] = []
- if isinstance(raw_codes, list):
- for bc in raw_codes:
- if not isinstance(bc, dict):
- continue
- bind_codes.append(
- BindCode(
- code=bc.get("code", ""),
- type=bc.get("type", "one_time"),
- created_at=bc.get("created_at", ""),
- expires_at=bc.get("expires_at"),
- is_active=bc.get("is_active", True),
- used_by=bc.get("used_by") or [],
- )
- )
-
- self.settings = SettingsState(
- channels=channels,
- guilds=guilds,
- guild_scope_platforms=guild_scope_platforms,
- guild_default_enabled=guild_default_enabled,
- users=users,
- bind_codes=bind_codes,
- )
-
- if migrated_legacy_channels:
- logger.info("Migrating legacy channel settings to platform-scoped schema")
- self.save()
-
- try:
- self._file_mtime = self.settings_path.stat().st_mtime
- except FileNotFoundError:
- self._file_mtime = 0
+ self.settings = self._service.load_state()
+ self._file_mtime += 1
def save(self) -> None:
- paths.ensure_data_dirs()
- payload: dict = {
- "schema_version": SCHEMA_VERSION,
- "scopes": {"channel": {}, "guild": {}, "guild_policy": {}, "user": {}},
- "bind_codes": [],
- }
-
- # Channels (platform-scoped)
- for scoped_key, s in self.settings.channels.items():
- platform, channel_id = _split_scoped_key(scoped_key)
- if not platform:
- platform = _infer_channel_platform(channel_id)
- payload["scopes"]["channel"].setdefault(platform, {})[channel_id] = {
- "enabled": s.enabled,
- "show_message_types": s.show_message_types,
- "custom_cwd": s.custom_cwd,
- "routing": _routing_to_dict(s.routing),
- "require_mention": s.require_mention,
- }
-
- # Guilds / Discord servers (platform-scoped)
- for platform in sorted(self.settings.guild_scope_platforms):
- payload["scopes"]["guild"].setdefault(platform, {})
- payload["scopes"]["guild_policy"][platform] = {
- "default_enabled": bool(self.settings.guild_default_enabled.get(platform, False)),
- }
- for scoped_key, s in self.settings.guilds.items():
- platform, guild_id = _split_scoped_key(scoped_key)
- if not platform:
- platform = "discord"
- payload["scopes"]["guild"].setdefault(platform, {})[guild_id] = {
- "enabled": s.enabled,
- }
- payload["scopes"]["guild_policy"].setdefault(
- platform,
- {"default_enabled": bool(self.settings.guild_default_enabled.get(platform, False))},
- )
-
- # Users (platform-scoped)
- for scoped_key, u in self.settings.users.items():
- platform, user_id = _split_scoped_key(scoped_key)
- if not platform:
- platform = _infer_user_platform(user_id)
- payload["scopes"]["user"].setdefault(platform, {})[user_id] = {
- "display_name": u.display_name,
- "is_admin": u.is_admin,
- "bound_at": u.bound_at,
- "enabled": u.enabled,
- "show_message_types": u.show_message_types,
- "custom_cwd": u.custom_cwd,
- "routing": _routing_to_dict(u.routing),
- "dm_chat_id": u.dm_chat_id,
- }
-
- # Bind codes
- for bc in self.settings.bind_codes:
- payload["bind_codes"].append(
- {
- "code": bc.code,
- "type": bc.type,
- "created_at": bc.created_at,
- "expires_at": bc.expires_at,
- "is_active": bc.is_active,
- "used_by": bc.used_by,
- }
- )
-
- self.settings_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
- try:
- self._file_mtime = self.settings_path.stat().st_mtime
- except FileNotFoundError:
- self._file_mtime = 0
+ self._service.save_state(self.settings)
+ self._service.has_external_write()
+ self._file_mtime += 1
# --- Channel helpers ---
diff --git a/storage/importer.py b/storage/importer.py
index ab2280d8e..25e85f0c9 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -13,7 +13,7 @@ from sqlalchemy import Connection, Engine, func, select
from config import paths
from config.discovered_chats import DiscoveredChatsStore
from config.v2_sessions import SessionsStore
-from config.v2_settings import SettingsStore, _split_scoped_key
+from config.v2_settings import SettingsState, _split_scoped_key, load_settings_state_from_json
from storage.db import create_sqlite_engine
from storage.lock import MigrationFileLock
from storage.migrations import run_migrations
@@ -137,7 +137,7 @@ def _backup_json_state(state_dir: Path) -> Path:
@dataclass
class _ParsedState:
- settings: SettingsStore
+ settings: SettingsState
sessions: SessionsStore
discovered: DiscoveredChatsStore
@@ -149,12 +149,13 @@ def _parse_json_state(state_dir: Path, *, primary_platform: str) -> _ParsedState
return _ParsedState(settings=settings, sessions=sessions, discovered=discovered)
-def _load_settings_from_copy(source: Path) -> SettingsStore:
+def _load_settings_from_copy(source: Path) -> SettingsState:
with tempfile.TemporaryDirectory() as tmpdir:
target = Path(tmpdir) / "settings.json"
if source.exists():
shutil.copy2(source, target)
- return SettingsStore(target)
+ state, _migrated = load_settings_state_from_json(target)
+ return state
def _load_sessions_from_copy(source: Path, *, primary_platform: str) -> SessionsStore:
@@ -190,7 +191,7 @@ def _import_parsed_state(conn: Connection, parsed: _ParsedState) -> dict[str, in
"discovered_chats": 0,
}
- settings_state = parsed.settings.settings
+ settings_state = parsed.settings
for scoped_key, item in settings_state.channels.items():
platform, channel_id = _split_scoped_key(scoped_key)
diff --git a/storage/settings_service.py b/storage/settings_service.py
new file mode 100644
index 000000000..66d719e13
--- /dev/null
+++ b/storage/settings_service.py
@@ -0,0 +1,283 @@
+from __future__ import annotations
+
+import json
+from dataclasses import asdict
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import Connection, Engine, select
+
+from config.v2_settings import (
+ BindCode,
+ ChannelSettings,
+ GuildSettings,
+ RoutingSettings,
+ SettingsState,
+ UserSettings,
+ _make_scoped_key,
+ _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,
+)
+
+
+class SQLiteSettingsService:
+ def __init__(self, db_path: Path):
+ self.db_path = db_path
+ self.engine = create_sqlite_engine(db_path)
+ self._probe = SqliteInvalidationProbe(self.engine)
+
+ def close(self) -> None:
+ self._probe.close()
+ self.engine.dispose()
+
+ def has_external_write(self) -> bool:
+ return self._probe.has_external_write()
+
+ def load_state(self) -> SettingsState:
+ with self.engine.connect() as conn:
+ return SettingsState(
+ channels=self._load_channels(conn),
+ guilds=self._load_guilds(conn),
+ guild_scope_platforms=self._load_guild_scope_platforms(conn),
+ guild_default_enabled=self._load_guild_policies(conn),
+ users=self._load_users(conn),
+ bind_codes=self._load_bind_codes(conn),
+ )
+
+ def save_state(self, state: SettingsState) -> None:
+ with self.engine.begin() as conn:
+ self._clear(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)
+ 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,
+ )
+ )
+
+ for platform in sorted(state.guild_scope_platforms):
+ conn.execute(
+ guild_policies.insert().values(
+ platform=platform,
+ default_enabled=_bool_int(state.guild_default_enabled.get(platform, False)),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ 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)
+ conn.execute(
+ guild_settings.insert().values(
+ scope_id=scope_id,
+ enabled=_bool_int(item.enabled),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ for scoped_key, item in state.users.items():
+ platform, user_id = _split_scoped_key(scoped_key)
+ scope_id = self._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,
+ )
+ )
+
+ for item in 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),
+ )
+ )
+
+ 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 _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()
+ result: dict[str, ChannelSettings] = {}
+ for row in rows:
+ key = _make_scoped_key(str(row["platform"]), str(row["scope_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"]),
+ 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()
+ result: dict[str, GuildSettings] = {}
+ for row in rows:
+ key = _make_scoped_key(str(row["platform"]), str(row["scope_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))}
+
+ 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}
+
+ 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()
+ result: dict[str, UserSettings] = {}
+ for row in rows:
+ key = _make_scoped_key(str(row["platform"]), str(row["scope_id"]))
+ result[key] = UserSettings(
+ display_name=row["display_name"] or "",
+ is_admin=bool(row["is_admin"]),
+ bound_at=row["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 "",
+ )
+ return result
+
+ def _load_bind_codes(self, conn: Connection) -> list[BindCode]:
+ rows = conn.execute(select(bind_codes)).mappings()
+ return [
+ BindCode(
+ code=row["code"],
+ type=row["type"],
+ created_at=row["created_at"],
+ expires_at=row["expires_at"],
+ is_active=bool(row["is_active"]),
+ used_by=_json_loads(row["used_by_json"], []),
+ )
+ 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,
+ )
+ )
+ 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"),
+ )
+
+
+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 _bool_int(value: Any) -> int:
+ return 1 if bool(value) else 0
+
+
+def _nullable_bool(value: Any) -> bool | None:
+ return None if value is None else bool(value)
+
+
+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/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
new file mode 100644
index 000000000..3e807710f
--- /dev/null
+++ b/tests/test_sqlite_settings_store.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from config.v2_settings import ChannelSettings, SettingsState, SettingsStore, UserSettings
+from storage.settings_service import SQLiteSettingsService
+
+
+def test_settings_store_uses_sqlite_without_rewriting_legacy_json(tmp_path: Path) -> None:
+ settings_path = tmp_path / "settings.json"
+ original = json.dumps(
+ {
+ "channels": {
+ "C123": {
+ "enabled": True,
+ "show_message_types": ["assistant"],
+ }
+ }
+ },
+ indent=2,
+ )
+ settings_path.write_text(original, encoding="utf-8")
+
+ store = SettingsStore(settings_path)
+ store.update_channel("C999", ChannelSettings(enabled=True), platform="slack")
+ store.close()
+
+ reloaded = SettingsStore(settings_path)
+ try:
+ assert reloaded.find_channel("C123", platform="slack") is not None
+ assert reloaded.find_channel("C999", platform="slack") is not None
+ assert settings_path.read_text(encoding="utf-8") == original
+ finally:
+ reloaded.close()
+
+
+def test_settings_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:
+ settings_path = tmp_path / "settings.json"
+ store = SettingsStore(settings_path)
+ external = SQLiteSettingsService(tmp_path / "vibe.sqlite")
+ try:
+ assert store.get_user("U1", platform="slack") is None
+
+ external.save_state(
+ SettingsState(
+ users={
+ "slack::U1": UserSettings(display_name="Alex", is_admin=True),
+ }
+ )
+ )
+
+ store.maybe_reload()
+
+ user = store.get_user("U1", platform="slack")
+ assert user is not None
+ assert user.display_name == "Alex"
+ assert user.is_admin is True
+ finally:
+ external.close()
+ store.close()