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.

40.2 KB
Raw Blame
import copy
import json
import logging
import hmac
import secrets
import string
import threading
from dataclasses import asdict, dataclass, field, fields
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple

from config import paths
from modules.agents.catalog import NATIVE_CLI_BACKENDS

logger = logging.getLogger(__name__)

DEFAULT_SHOW_MESSAGE_TYPES: List[str] = ["assistant"]
# "system" is deprecated: system/init messages are never pushed to users, so it
# is no longer a user-facing toggle. Normalizing against this set drops any
# legacy "system" value still stored in show_message_types.
ALLOWED_MESSAGE_TYPES = {"assistant", "toolcall"}
SCHEMA_VERSION = 5
SCOPED_KEY_SEP = "::"
THREAD_SETTINGS_PREFIX = "thread"

# Bind code prefix and length
_BIND_CODE_PREFIX = "vr-"
_BIND_CODE_RANDOM_LENGTH = 10
_BIND_CODE_ALPHABET = string.ascii_letters + string.digits
_MAX_ACTIVE_BIND_CODES = 10
_UNSET_AGENT_BINDING = object()


def normalize_show_message_types(show_message_types: Optional[List[str]]) -> List[str]:
    if show_message_types is None:
        return DEFAULT_SHOW_MESSAGE_TYPES.copy()
    return [msg for msg in show_message_types if msg in ALLOWED_MESSAGE_TYPES]


def _generate_bind_code() -> str:
    """Generate a random bind code like 'vr-a3X9k2LmN'."""
    random_part = "".join(secrets.choice(_BIND_CODE_ALPHABET) for _ in range(_BIND_CODE_RANDOM_LENGTH))
    return f"{_BIND_CODE_PREFIX}{random_part}"


def _now_iso() -> str:
    """Return current UTC time as ISO 8601 string."""
    return datetime.now(timezone.utc).isoformat()


def _parse_bind_code_expiry(bind_code: "BindCode") -> Optional[datetime]:
    if not bind_code.expires_at:
        return None
    try:
        expires = datetime.fromisoformat(bind_code.expires_at)
    except (ValueError, TypeError):
        logger.warning("Bind code has unparseable expires_at: %s", bind_code.expires_at)
        return datetime.min.replace(tzinfo=timezone.utc)
    if expires.hour == 0 and expires.minute == 0 and expires.second == 0 and "T" not in bind_code.expires_at:
        expires = expires.replace(hour=23, minute=59, second=59)
    if expires.tzinfo is None:
        expires = expires.replace(tzinfo=timezone.utc)
    return expires


def _is_bind_code_valid(bind_code: "BindCode", *, now: Optional[datetime] = None) -> bool:
    if not bind_code.is_active:
        return False
    expires = _parse_bind_code_expiry(bind_code)
    if expires is not None and (now or datetime.now(timezone.utc)) > expires:
        return False
    return True


def _make_scoped_key(platform: str, item_id: str) -> str:
    return f"{platform}{SCOPED_KEY_SEP}{item_id}"


def _split_scoped_key(scoped_key: str) -> Tuple[Optional[str], str]:
    if SCOPED_KEY_SEP in scoped_key:
        platform, raw_id = scoped_key.split(SCOPED_KEY_SEP, 1)
        if platform:
            return platform, raw_id
    return None, scoped_key


def make_thread_native_id(channel_id: str, thread_id: str) -> str:
    """Build a platform-native thread key that stays unique across channels."""
    return f"{channel_id}/{thread_id}"


def split_thread_native_id(native_id: str) -> Tuple[str, str]:
    channel_id, separator, thread_id = str(native_id).rpartition("/")
    if not separator or not channel_id or not thread_id:
        raise ValueError("thread native id must be '<channel_id>/<thread_id>'")
    return channel_id, thread_id


def make_thread_settings_key(channel_id: str, thread_id: str) -> str:
    """Build the runtime-only key used to route operations to thread settings."""
    return SCOPED_KEY_SEP.join((THREAD_SETTINGS_PREFIX, str(channel_id), str(thread_id)))


def split_thread_settings_key(settings_key: str) -> Optional[Tuple[str, str]]:
    parts = str(settings_key).split(SCOPED_KEY_SEP)
    if len(parts) == 3 and parts[0] == THREAD_SETTINGS_PREFIX and parts[1] and parts[2]:
        return parts[1], parts[2]
    return None


def _infer_channel_platform(channel_id: str) -> str:
    cid = str(channel_id)
    if cid.startswith("oc_"):
        return "lark"
    if cid and cid[0] in {"C", "G", "D"}:
        return "slack"
    if cid.isdigit() and len(cid) >= 15:
        return "discord"
    return "unknown"


def _infer_user_platform(user_id: str) -> str:
    uid = str(user_id)
    if uid.startswith("ou_"):
        return "lark"
    if uid and uid[0] in {"U", "W"}:
        return "slack"
    if uid.isdigit() and len(uid) >= 15:
        return "discord"
    return "unknown"


@dataclass
class RoutingSettings:
    agent_name: Optional[str] = None
    # Scope-level overrides applied on top of the selected Vibe Agent.
    model: Optional[str] = None
    reasoning_effort: Optional[str] = None
    # The native agent each CLI backend runs for this scope.
    opencode_agent: Optional[str] = None
    claude_agent: Optional[str] = None
    codex_agent: Optional[str] = None


# Retired per-backend spellings of a scope's model and effort (``claude_model``,
# ``codex_reasoning_effort``, ...). Older releases stored them, and API callers may
# still send them; they are read only to fill ``model`` / ``reasoning_effort`` for a
# route on that built-in backend's Agent, and are never stored or returned.
LEGACY_ROUTING_ALIASES = frozenset(
    f"{backend}_{kind}" for backend in NATIVE_CLI_BACKENDS for kind in ("model", "reasoning_effort")
)


def _legacy_routing_alias(payload: dict, agent_name: Optional[str], kind: str) -> Optional[str]:
    if agent_name not in NATIVE_CLI_BACKENDS:
        return None
    return payload.get(f"{agent_name}_{kind}")


def _payload_value(payload: dict, key: str, fallback_key: str) -> Optional[str]:
    if key in payload:
        return payload.get(key)
    return payload.get(fallback_key)


def normalize_routing_settings(routing: Optional[RoutingSettings]) -> RoutingSettings:
    """A copy of a scope route, or the empty route."""
    if routing is None:
        return RoutingSettings()
    return RoutingSettings(**{item.name: getattr(routing, item.name, None) for item in fields(RoutingSettings)})


def routing_from_stored_payload(payload: Optional[dict]) -> RoutingSettings:
    """A route as stored in a scope's settings, from this or an older release.

    An empty canonical value falls back to its retired per-backend alias, as the
    rows older releases wrote can carry only that.
    """
    payload = payload if isinstance(payload, dict) else {}
    agent_name = payload.get("agent_name") or payload.get("agent")
    return RoutingSettings(
        agent_name=agent_name,
        model=payload.get("model")
        or payload.get("model_override")
        or _legacy_routing_alias(payload, agent_name, "model"),
        reasoning_effort=payload.get("reasoning_effort")
        or payload.get("reasoning_effort_override")
        or _legacy_routing_alias(payload, agent_name, "reasoning_effort"),
        opencode_agent=payload.get("opencode_agent"),
        claude_agent=payload.get("claude_agent"),
        codex_agent=payload.get("codex_agent"),
    )


def routing_model_for_backend(routing: Optional[RoutingSettings], backend: Optional[str]) -> Optional[str]:
    normalized = normalize_routing_settings(routing)
    if not _routing_backend_matches(normalized, backend):
        return None
    return normalized.model


def routing_reasoning_effort_for_backend(
    routing: Optional[RoutingSettings],
    backend: Optional[str],
) -> Optional[str]:
    normalized = normalize_routing_settings(routing)
    if not _routing_backend_matches(normalized, backend):
        return None
    return normalized.reasoning_effort


def _routing_backend_matches(routing: RoutingSettings, backend: Optional[str]) -> bool:
    agent_name = getattr(routing, "agent_name", None)
    if agent_name in NATIVE_CLI_BACKENDS:
        return agent_name == backend
    return True


@dataclass
class ChannelSettings:
    enabled: bool = False
    show_message_types: List[str] = field(default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy())
    custom_cwd: Optional[str] = None
    routing: RoutingSettings = field(default_factory=RoutingSettings)
    # Per-channel require_mention override: None=use global default, True=require, False=don't require
    require_mention: Optional[bool] = None
    # Per-channel require_bind gate: None/False=off (any channel member), True=only
    # process messages from bound users; unbound senders are silently ignored.
    require_bind: Optional[bool] = None
    # Internal optimistic-concurrency token. The API mirrors it as
    # ``expected_agent_name`` while persisted settings JSON omits it.
    _agent_name_at_load: object = field(default=_UNSET_AGENT_BINDING, repr=False, compare=False)


@dataclass
class GuildSettings:
    enabled: bool = True


@dataclass
class UserSettings:
    """Settings for a bound DM user."""

    display_name: str = ""
    is_admin: bool = False
    bound_at: str = ""  # ISO 8601 timestamp
    enabled: bool = True
    show_message_types: List[str] = field(default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy())
    custom_cwd: Optional[str] = None
    routing: RoutingSettings = field(default_factory=RoutingSettings)
    dm_chat_id: str = ""
    pending_bind_menu_hint: bool = False
    _agent_name_at_load: object = field(default=_UNSET_AGENT_BINDING, repr=False, compare=False)


@dataclass
class BindCode:
    """A bind code for authorizing DM access."""

    code: str
    type: str  # "one_time" or "expiring"
    created_at: str  # ISO 8601
    expires_at: Optional[str] = None  # ISO 8601, only for "expiring" type
    is_active: bool = True
    used_by: List[str] = field(default_factory=list)  # user_ids that used this code


@dataclass
class SettingsState:
    channels: Dict[str, ChannelSettings] = field(default_factory=dict)
    threads: Dict[str, ChannelSettings] = field(default_factory=dict)
    guilds: Dict[str, GuildSettings] = field(default_factory=dict)
    guild_scope_platforms: set[str] = field(default_factory=set)
    guild_default_enabled: Dict[str, bool] = field(default_factory=dict)
    users: Dict[str, UserSettings] = field(default_factory=dict)
    bind_codes: List[BindCode] = field(default_factory=list)


def lift_legacy_routing_aliases(payload: dict, agent_name: Optional[str]) -> dict:
    """``payload`` with its retired per-backend aliases folded into the canonical keys.

    An alias fills only a canonical key the payload does not state, and only
    for a route on that built-in backend's own Agent; every alias is dropped.
    """
    lifted = {key: value for key, value in payload.items() if key not in LEGACY_ROUTING_ALIASES}
    for kind in ("model", "reasoning_effort"):
        alias = _legacy_routing_alias(payload, agent_name, kind)
        if alias is not None and kind not in lifted and f"{kind}_override" not in lifted:
            lifted[kind] = alias
    return lifted


def _parse_routing(payload: dict) -> RoutingSettings:
    """A route as an API caller or settings file states it.

    A canonical key that is present wins, even as an explicit clear; only an
    absent one is filled from its retired per-backend alias.
    """
    if not isinstance(payload, dict):
        payload = {}
    agent_name = payload.get("agent_name") or payload.get("agent")
    payload = lift_legacy_routing_aliases(payload, agent_name)
    return RoutingSettings(
        agent_name=agent_name,
        model=_payload_value(payload, "model", "model_override"),
        reasoning_effort=_payload_value(payload, "reasoning_effort", "reasoning_effort_override"),
        opencode_agent=payload.get("opencode_agent"),
        claude_agent=payload.get("claude_agent"),
        codex_agent=payload.get("codex_agent"),
    )


def routing_to_dict(routing: Optional[RoutingSettings]) -> dict:
    """A scope route as the settings API and storage spell it."""
    return asdict(normalize_routing_settings(routing))


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"),
                        require_bind=cp.get("require_bind"),
                    )

        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", ""),
                        pending_bind_menu_hint=bool(up.get("pending_bind_menu_hint", False)),
                    )
    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"),
                require_bind=cp.get("require_bind"),
            )
            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", ""),
                    pending_bind_menu_hint=bool(up.get("pending_bind_menu_hint", False)),
                )

    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.
    # ------------------------------------------------------------------
    _instance: Optional["SettingsStore"] = None
    _instance_lock = threading.Lock()

    @classmethod
    def get_instance(cls, settings_path: Optional[Path] = None) -> "SettingsStore":
        """Return the process-wide singleton, creating it on first call.

        Automatically reloads if the runtime-settings revision has changed.
        """
        with cls._instance_lock:
            target_path = settings_path or paths.get_settings_path()
            if cls._instance is None or cls._instance.settings_path != target_path:
                cls._instance = cls(target_path)
            else:
                cls._instance.maybe_reload()
            return cls._instance

    @classmethod
    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 = 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._reload_lock = threading.RLock()
        self._generation = 0
        self._observed_revision: str | None = None
        self._reload_count = 0
        from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
        from storage.settings_service import SQLiteSettingsService

        ensure_sqlite_state(
            db_path=self.db_path,
            state_dir=self.settings_path.parent,
            primary_platform=resolve_primary_platform_from_config(self.settings_path.parent),
        )
        self._service = SQLiteSettingsService(self.db_path)
        self._load_with_revision()

    def close(self) -> None:
        service = getattr(self, "_service", None)
        if service is not None:
            service.close()

    @property
    def generation(self) -> int:
        return self._generation

    @property
    def reload_count(self) -> int:
        return self._reload_count

    def maybe_reload(self) -> bool:
        """Reload once when another transaction changed runtime settings."""
        with self._reload_lock:
            revision = self._service.current_revision()
            if revision == self._observed_revision:
                return False
            self._load()
            # Record the revision read before the load. If a newer write races
            # with the load, the next check sees it instead of losing it.
            self._observed_revision = revision
            self._reload_count += 1
            return True

    def _load_with_revision(self) -> None:
        revision = self._service.current_revision()
        self._load()
        self._observed_revision = revision

    def _load(self) -> None:
        self.settings = self._service.load_state()
        self._loaded_state = copy.deepcopy(self.settings)
        self._generation += 1

    def save(self, *, user_context=None) -> None:
        with self._reload_lock:
            try:
                revision = self._service.save_state(
                    self.settings, user_context=user_context, baseline=self._loaded_state
                )
            except Exception:
                # Restore the durable snapshot after a refused transaction before
                # this store can be read or saved again.
                self._load_with_revision()
                raise
            # Use the exact revision committed by this transaction. Reading the
            # current value here could absorb a later external write without loading it.
            self._observed_revision = revision
            self._loaded_state = copy.deepcopy(self.settings)
            self._generation += 1

    def apply(self, mutate: Callable[[SettingsState], None], *, user_context=None) -> None:
        """Run ``mutate`` on the authoritative settings inside one write transaction.

        Unlike ``save``, nothing this store loaded earlier is written back, so an
        edit cannot revert what another writer changed in the meantime. The store
        then holds the committed snapshot.
        """
        with self._reload_lock:
            try:
                revision = self._service.save_state(self.settings, user_context=user_context, mutate=mutate)
            except Exception:
                self._load_with_revision()
                raise
            self._observed_revision = revision
            self._loaded_state = copy.deepcopy(self.settings)
            self._generation += 1

    # --- Channel helpers ---

    def _channel_key(self, channel_id: str, platform: Optional[str] = None) -> str:
        return _make_scoped_key(platform, channel_id) if platform else channel_id

    def _thread_key(self, channel_id: str, thread_id: str, platform: Optional[str] = None) -> str:
        native_id = make_thread_native_id(channel_id, thread_id)
        return _make_scoped_key(platform, native_id) if platform else native_id

    def _user_key(self, user_id: str, platform: Optional[str] = None) -> str:
        return _make_scoped_key(platform, user_id) if platform else user_id

    def get_channels_for_platform(self, platform: str) -> Dict[str, ChannelSettings]:
        result: Dict[str, ChannelSettings] = {}
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        for key, settings in self.settings.channels.items():
            if key.startswith(prefix):
                result[key[len(prefix) :]] = settings
        return result

    def set_channels_for_platform(self, platform: str, channels: Dict[str, ChannelSettings]) -> None:
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        previous = self.settings.channels
        self.settings.channels = {k: v for k, v in previous.items() if not k.startswith(prefix)}
        for channel_id, settings in channels.items():
            key = self._channel_key(str(channel_id), platform)
            self._carry_agent_binding_expectation(previous.get(key), settings)
            self.settings.channels[key] = settings

    def get_threads_for_platform(self, platform: str) -> Dict[str, Dict[str, ChannelSettings]]:
        result: Dict[str, Dict[str, ChannelSettings]] = {}
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        for key, settings in self.settings.threads.items():
            if not key.startswith(prefix):
                continue
            try:
                channel_id, thread_id = split_thread_native_id(key[len(prefix) :])
            except ValueError:
                continue
            result.setdefault(channel_id, {})[thread_id] = settings
        return result

    def find_thread(
        self,
        channel_id: str,
        thread_id: str,
        platform: Optional[str] = None,
    ) -> Optional[ChannelSettings]:
        return self.settings.threads.get(self._thread_key(channel_id, thread_id, platform))

    def find_effective_channel(
        self,
        channel_id: str,
        *,
        thread_id: Optional[str] = None,
        platform: Optional[str] = None,
    ) -> Optional[ChannelSettings]:
        if thread_id:
            thread = self.find_thread(channel_id, thread_id, platform=platform)
            if thread is not None:
                return thread
        return self.find_channel(channel_id, platform=platform)

    def update_thread(
        self,
        channel_id: str,
        thread_id: str,
        settings: ChannelSettings,
        platform: Optional[str] = None,
        *,
        user_context=None,
    ) -> None:
        key = self._thread_key(channel_id, thread_id, platform)
        self._carry_agent_binding_expectation(self.settings.threads.get(key), settings)
        self.settings.threads[key] = settings
        self.save(user_context=user_context)

    def delete_thread(
        self,
        channel_id: str,
        thread_id: str,
        platform: Optional[str] = None,
        *,
        user_context=None,
    ) -> bool:
        removed = self.settings.threads.pop(self._thread_key(channel_id, thread_id, platform), None)
        if removed is not None:
            self.save(user_context=user_context)
            return True
        return False

    def get_guilds_for_platform(self, platform: str) -> Dict[str, GuildSettings]:
        result: Dict[str, GuildSettings] = {}
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        for key, settings in self.settings.guilds.items():
            if key.startswith(prefix):
                result[key[len(prefix) :]] = settings
        return result

    def set_guilds_for_platform(
        self,
        platform: str,
        guilds: Dict[str, GuildSettings],
        default_enabled: bool = False,
    ) -> None:
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        self.settings.guilds = {k: v for k, v in self.settings.guilds.items() if not k.startswith(prefix)}
        self.settings.guild_scope_platforms.add(platform)
        self.settings.guild_default_enabled[platform] = bool(default_enabled)
        for guild_id, settings in guilds.items():
            self.settings.guilds[_make_scoped_key(platform, str(guild_id))] = settings

    def has_guild_scope_for_platform(self, platform: str) -> bool:
        return platform in self.settings.guild_scope_platforms

    def get_guild_default_enabled_for_platform(self, platform: str) -> bool:
        return bool(self.settings.guild_default_enabled.get(platform, False))

    def is_guild_enabled(self, platform: str, guild_id: str) -> bool:
        if not self.has_guild_scope_for_platform(platform):
            return True
        settings = self.settings.guilds.get(_make_scoped_key(platform, str(guild_id)))
        if settings is not None:
            return bool(settings.enabled)
        return self.get_guild_default_enabled_for_platform(platform)

    def get_users_for_platform(self, platform: str) -> Dict[str, UserSettings]:
        result: Dict[str, UserSettings] = {}
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        for key, settings in self.settings.users.items():
            if key.startswith(prefix):
                result[key[len(prefix) :]] = settings
        return result

    def set_users_for_platform(self, platform: str, users: Dict[str, UserSettings]) -> None:
        prefix = f"{platform}{SCOPED_KEY_SEP}"
        previous = self.settings.users
        self.settings.users = {k: v for k, v in previous.items() if not k.startswith(prefix)}
        for user_id, settings in users.items():
            key = self._user_key(str(user_id), platform)
            self._carry_agent_binding_expectation(previous.get(key), settings)
            self.settings.users[key] = settings

    def get_channel(self, channel_id: str, platform: Optional[str] = None) -> ChannelSettings:
        key = self._channel_key(channel_id, platform)
        if platform is None and key not in self.settings.channels:
            suffix = f"{SCOPED_KEY_SEP}{channel_id}"
            for scoped_key, settings in self.settings.channels.items():
                if scoped_key.endswith(suffix):
                    return settings
        if key not in self.settings.channels:
            self.settings.channels[key] = ChannelSettings()
        return self.settings.channels[key]

    def find_channel(self, channel_id: str, platform: Optional[str] = None) -> Optional[ChannelSettings]:
        key = self._channel_key(channel_id, platform)
        if key in self.settings.channels:
            return self.settings.channels[key]
        if platform is None:
            suffix = f"{SCOPED_KEY_SEP}{channel_id}"
            for scoped_key, settings in self.settings.channels.items():
                if scoped_key.endswith(suffix):
                    return settings
        return None

    def update_channel(self, channel_id: str, settings: ChannelSettings, platform: Optional[str] = None) -> None:
        key = self._channel_key(channel_id, platform)
        self._carry_agent_binding_expectation(self.settings.channels.get(key), settings)
        self.settings.channels[key] = settings
        self.save()

    # --- User helpers ---

    def get_user(self, user_id: str, platform: Optional[str] = None) -> Optional[UserSettings]:
        """Get user settings, or None if user is not bound."""
        key = self._user_key(user_id, platform)
        user = self.settings.users.get(key)
        if user is not None or platform:
            return user
        suffix = f"{SCOPED_KEY_SEP}{user_id}"
        for scoped_key, value in self.settings.users.items():
            if scoped_key.endswith(suffix):
                return value
        return None

    def is_bound_user(self, user_id: str, platform: Optional[str] = None) -> bool:
        if platform:
            return self._user_key(user_id, platform) in self.settings.users
        if user_id in self.settings.users:
            return True
        suffix = f"{SCOPED_KEY_SEP}{user_id}"
        return any(key.endswith(suffix) for key in self.settings.users.keys())

    def is_enabled_user(self, user_id: str, platform: Optional[str] = None) -> bool:
        user = self.get_user(user_id, platform=platform)
        return user is not None and user.enabled

    def is_admin(self, user_id: str, platform: Optional[str] = None) -> bool:
        if platform:
            user = self.settings.users.get(self._user_key(user_id, platform))
            return user is not None and user.enabled and user.is_admin
        if user_id in self.settings.users:
            user = self.settings.users[user_id]
            return user.enabled and user.is_admin
        suffix = f"{SCOPED_KEY_SEP}{user_id}"
        for key, value in self.settings.users.items():
            if key.endswith(suffix) and value.enabled:
                return value.is_admin
        return False

    def has_any_admin(self, platform: Optional[str] = None) -> bool:
        """Return True if at least one admin record exists."""
        if platform:
            prefix = f"{platform}{SCOPED_KEY_SEP}"
            return any(u.is_admin for key, u in self.settings.users.items() if key.startswith(prefix))
        return any(u.is_admin for u in self.settings.users.values())

    def has_enabled_admin(self, platform: Optional[str] = None) -> bool:
        """Return True if at least one enabled admin exists."""
        if platform:
            prefix = f"{platform}{SCOPED_KEY_SEP}"
            return any(u.enabled and u.is_admin for key, u in self.settings.users.items() if key.startswith(prefix))
        return any(u.enabled and u.is_admin for u in self.settings.users.values())

    def get_admins(self, platform: Optional[str] = None) -> Dict[str, UserSettings]:
        """Return enabled admin users."""
        if platform:
            prefix = f"{platform}{SCOPED_KEY_SEP}"
            return {
                uid: u
                for uid, u in self.settings.users.items()
                if uid.startswith(prefix) and u.enabled and u.is_admin
            }
        return {uid: u for uid, u in self.settings.users.items() if u.enabled and u.is_admin}

    def add_user(
        self, user_id: str, display_name: str, is_admin: bool = False, platform: Optional[str] = None
    ) -> UserSettings:
        """Add a new bound user. Returns the created UserSettings."""
        user = UserSettings(
            display_name=display_name,
            is_admin=is_admin,
            bound_at=_now_iso(),
            enabled=True,
        )
        self.settings.users[self._user_key(user_id, platform)] = user
        self.save()
        return user

    def bind_user_with_code(
        self, user_id: str, display_name: str, code: str, dm_chat_id: str = "", platform: Optional[str] = None
    ) -> Tuple[bool, bool]:
        """Atomically validate code, create user, and consume code.

        Returns (success, is_admin).
        Thread-safe: uses a lock to prevent concurrent bind races.
        """
        with self._bind_lock:
            # Ensure we have the latest data from disk (UI API may have
            # created bind codes via the same singleton after we last read).
            self.maybe_reload()

            # Check already bound
            if self.is_bound_user(user_id, platform=platform):
                return False, False

            # Validate code
            bc = self.validate_bind_code(code)
            if bc is None:
                return False, False

            # Auto-admin for first user
            is_admin = not self.has_enabled_admin(platform=platform)

            # Create user
            user = UserSettings(
                display_name=display_name,
                is_admin=is_admin,
                bound_at=_now_iso(),
                enabled=True,
                dm_chat_id=dm_chat_id,
            )
            scoped_user_id = self._user_key(user_id, platform)
            self.settings.users[scoped_user_id] = user

            # Consume code
            bc.used_by.append(scoped_user_id)
            if bc.type == "one_time":
                bc.is_active = False

            self.save()
            return True, is_admin

    def update_user(self, user_id: str, settings: UserSettings, platform: Optional[str] = None) -> None:
        key = self._user_key(user_id, platform)
        self._carry_agent_binding_expectation(self.settings.users.get(key), settings)
        self.settings.users[key] = settings
        self.save()

    def update_user_fields(self, user_id: str, *, platform: Optional[str] = None, **values) -> bool:
        """Set only these fields of a bound user; False when the user is not bound.

        Runtime bookkeeping (a DM channel id, a one-shot hint) must not write
        back a cached copy of the rest of the row, such as a revoked admin flag.
        """
        key = self._user_key(user_id, platform)
        found = []

        def mutate(state: SettingsState) -> None:
            user = state.users.get(key)
            if user is None:
                return
            for name, value in values.items():
                setattr(user, name, value)
            found.append(True)

        self.apply(mutate)
        return bool(found)

    @staticmethod
    def _carry_agent_binding_expectation(previous: object, current: object) -> None:
        current_expected = getattr(current, "_agent_name_at_load", _UNSET_AGENT_BINDING)
        if current_expected is not _UNSET_AGENT_BINDING:
            return
        if previous is None:
            setattr(current, "_agent_name_at_load", None)
            return
        expected = getattr(previous, "_agent_name_at_load", _UNSET_AGENT_BINDING)
        if expected is _UNSET_AGENT_BINDING:
            expected = getattr(getattr(previous, "routing", None), "agent_name", None)
        setattr(current, "_agent_name_at_load", expected)

    def remove_user(self, user_id: str, platform: Optional[str] = None) -> bool:
        key = self._user_key(user_id, platform)
        if key in self.settings.users:
            del self.settings.users[key]
            self.save()
            return True
        return False

    def set_admin(self, user_id: str, is_admin: bool, platform: Optional[str] = None) -> bool:
        """Set admin flag for a user. Returns False if user not found."""
        key = self._user_key(user_id, platform)
        user = self.settings.users.get(key)
        if user is None:
            return False
        user.is_admin = is_admin
        self.save()
        return True

    # --- Bind code helpers ---

    def create_bind_code(self, code_type: str = "one_time", expires_at: Optional[str] = None) -> BindCode:
        """Create a new bind code."""
        with self._bind_lock:
            self.maybe_reload()
            now = datetime.now(timezone.utc)
            active_count = sum(1 for bc in self.settings.bind_codes if _is_bind_code_valid(bc, now=now))
            if active_count >= _MAX_ACTIVE_BIND_CODES:
                raise ValueError(f"active bind code limit reached ({_MAX_ACTIVE_BIND_CODES})")

            existing_codes = [bc.code for bc in self.settings.bind_codes]
            code = _generate_bind_code()
            while any(hmac.compare_digest(candidate, code) for candidate in existing_codes):
                code = _generate_bind_code()

            bc = BindCode(
                code=code,
                type=code_type,
                created_at=_now_iso(),
                expires_at=expires_at if code_type == "expiring" else None,
                is_active=True,
            )
            self.settings.bind_codes.append(bc)
            self.save()
            return bc

    def validate_bind_code(self, code: str) -> Optional[BindCode]:
        """Validate a bind code. Returns the BindCode if valid, None otherwise."""
        candidate = str(code or "")
        matched: Optional[BindCode] = None
        for bc in self.settings.bind_codes:
            if hmac.compare_digest(str(bc.code or ""), candidate):
                matched = matched or bc
        if matched is None or not _is_bind_code_valid(matched):
            return None
        return matched

    def use_bind_code(self, code: str, user_id: str) -> bool:
        """Mark a bind code as used by a user. Returns True on success."""
        bc = self.validate_bind_code(code)
        if bc is None:
            return False
        bc.used_by.append(user_id)
        if bc.type == "one_time":
            bc.is_active = False
        self.save()
        return True

    def deactivate_bind_code(self, code: str) -> bool:
        """Deactivate a bind code. Returns True if found and deactivated."""
        candidate = str(code or "")
        for bc in self.settings.bind_codes:
            if hmac.compare_digest(str(bc.code or ""), candidate):
                bc.is_active = False
                self.save()
                return True
        return False

    def get_bind_codes(self) -> List[BindCode]:
        """Return all bind codes."""
        return list(self.settings.bind_codes)