Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

40.0 KB
Raw Blame
"""``society.db`` — the roster, the board, rooms, knowledge staging, approvals.

Same conventions as ``dodaios/missions/event_store.py``: aiosqlite in
autocommit with WAL as the lock manager, ``busy_timeout=5000``, idempotent
schema via ``executescript``, ``pragma_table_info`` migrations.

Persist-before-publish: :meth:`SocietyStore.append_and_publish` INSERTs with
``RETURNING seq`` and only then hands the envelope to the bus. A crash in
between loses the fan-out, never the row; startup replays ``events_since``.

Single writer: only the server process opens this file for writing. The CLI
and every other client go through REST.
"""

from __future__ import annotations

import json
import logging
from collections.abc import Iterable
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import aiosqlite

from .bus import SocietyBus
from .events import MsgType, SocietyEnvelope, now_ms


def day_start_ms(at_ms: int) -> int:
    """Midnight UTC of the day ``at_ms`` falls in.

    The one definition of "today" in the society: the scheduler's daily-budget
    gate and the card's spend-today figure both read it, so a card can never
    show an agent under its cap while the gate is refusing its work.
    """
    day = datetime.fromtimestamp(at_ms / 1000, tz=UTC).replace(
        hour=0, minute=0, second=0, microsecond=0
    )
    return int(day.timestamp() * 1000)


log = logging.getLogger(__name__)

__all__ = ["SocietyStore", "SCHEMA_VERSION"]

_SCHEMA_PATH = Path(__file__).parent / "society_schema.sql"
SCHEMA_VERSION = 1

_KEY_KILL_SWITCH = "kill_switch"
_KEY_SCHEMA_VERSION = "schema_version"

_EVENT_COLUMNS = (
    "seq, event_id, msg_type, from_agent, to_agent, trace_id, parent_event_id, "
    "ts_ms, cost_usd, payload_json"
)


_GROUP_COLUMNS = "group_id, name, members_json, created_ms, updated_ms, lead_agent_id, mission"


def _row_to_group(row: Any) -> dict[str, Any]:
    return {
        "group_id": row[0],
        "name": row[1],
        "members": json.loads(row[2]),
        "created_ms": row[3],
        "updated_ms": row[4],
        "lead_agent_id": row[5] or None,
        "mission": row[6] or "",
    }


def _row_to_envelope(row: Any) -> SocietyEnvelope:
    return SocietyEnvelope(
        seq=int(row[0]),
        event_id=str(row[1]),
        msg_type=MsgType(str(row[2])),
        from_agent=str(row[3]),
        to_agent=row[4],
        trace_id=str(row[5]),
        parent_event_id=row[6],
        ts_ms=int(row[7]),
        cost_usd=float(row[8]),
        payload=json.loads(row[9]) if row[9] else {},
    )


class SocietyStore:
    """SQLite WAL store with append-and-publish atomicity."""

    def __init__(self, db_path: Path, bus: SocietyBus | None = None) -> None:
        self._db_path = db_path
        self._bus = bus or SocietyBus()
        self._conn: aiosqlite.Connection | None = None

    @property
    def bus(self) -> SocietyBus:
        return self._bus

    @property
    def path(self) -> Path:
        return self._db_path

    # ------------------------------------------------------------ lifecycle

    async def open(self) -> None:
        if self._conn is not None:
            return
        self._db_path.parent.mkdir(parents=True, exist_ok=True)
        conn = await aiosqlite.connect(self._db_path, isolation_level=None)
        try:
            await conn.execute("PRAGMA journal_mode=WAL")
            await conn.execute("PRAGMA synchronous=NORMAL")
            await conn.execute("PRAGMA busy_timeout=5000")
            await conn.execute("PRAGMA foreign_keys=ON")
            await conn.executescript(_SCHEMA_PATH.read_text(encoding="utf-8"))
            self._conn = conn
            await self._apply_migrations()
            await self._ensure_fts()
            await self.set_meta(_KEY_SCHEMA_VERSION, str(SCHEMA_VERSION))
        except BaseException:
            # Includes cancellation of first-turn initialization on shutdown.
            # The provisional connection is owned here until open completes.
            self._conn = None
            await conn.close()
            raise

    async def _apply_migrations(self) -> None:
        """Idempotent column migrations for databases created by older builds."""
        cur = await self.conn.execute("PRAGMA table_info(society_agents)")
        rows = await cur.fetchall()
        await cur.close()
        existing = {str(r[1]) for r in rows}
        if not existing:  # pragma: no cover — schema always creates the table
            raise RuntimeError("society_agents table missing after schema load")
        if "account_id" not in existing:
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN account_id TEXT NOT NULL DEFAULT ''"
            )
            log.info("society store: migration applied — added account_id")
        if "browser_mode" not in existing:
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN browser_mode TEXT NOT NULL "
                "DEFAULT 'own' CHECK (browser_mode IN ('own', 'attach'))"
            )
            log.info("society store: migration applied — added browser_mode")
        if "browser_allowed_domains_json" not in existing:
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN browser_allowed_domains_json "
                "TEXT NOT NULL DEFAULT '[]'"
            )
            log.info("society store: migration applied — added browser_allowed_domains")
        if "approval_mode" not in existing:
            # NULL preserves legacy sessions until the person chooses a mode.
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN approval_mode TEXT DEFAULT NULL "
                "CHECK (approval_mode IN ('bypass', 'ask', 'always_ask'))"
            )
            log.info("society store: migration applied — added approval_mode")
        if "computer_id" not in existing:
            # NULL = this computer; every existing agent keeps running here.
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN computer_id TEXT DEFAULT NULL"
            )
            log.info("society store: migration applied — added computer_id")
        if "runtime" not in existing:
            # Every existing agent keeps running on Jarvis' own runtime.
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN runtime TEXT NOT NULL DEFAULT 'jarvis' "
                "CHECK (runtime IN ('jarvis', 'hermes', 'openclaw'))"
            )
            log.info("society store: migration applied — added runtime")
        if "execution_environment" not in existing:
            await self.conn.execute(
                "ALTER TABLE society_agents ADD COLUMN execution_environment "
                "TEXT NOT NULL DEFAULT 'local' "
                "CHECK (execution_environment IN ('local', 'sandbox'))"
            )
            log.info("society store: added execution_environment")
        await self._migrate_chat_groups()
        await self._migrate_checkpoint_vocabulary()

    async def _migrate_chat_groups(self) -> None:
        """Team leads (2026-10): a group may name its lead and carry a mission."""
        cur = await self.conn.execute("PRAGMA table_info(society_chat_groups)")
        existing = {str(r[1]) for r in await cur.fetchall()}
        await cur.close()
        if "lead_agent_id" not in existing:
            # NULL = no lead; every existing team keeps working as before.
            await self.conn.execute(
                "ALTER TABLE society_chat_groups ADD COLUMN lead_agent_id TEXT DEFAULT NULL"
            )
            log.info("society store: migration applied — added chat group lead_agent_id")
        if "mission" not in existing:
            await self.conn.execute(
                "ALTER TABLE society_chat_groups ADD COLUMN mission TEXT NOT NULL DEFAULT ''"
            )
            log.info("society store: migration applied — added chat group mission")

    async def _migrate_checkpoint_vocabulary(self) -> None:
        """Widen the ``checkpoint`` CHECK to today's vocabulary (the hub shops, 2026-09).

        SQLite cannot alter a CHECK constraint in place, so a database created
        by an older build gets the standard rebuild: create the table from the
        current schema under a scratch name, copy every column both versions
        share, drop the old table, rename. Idempotent — a table whose CHECK
        already lists every ``Checkpoint`` value is left alone.
        """
        from .events import Checkpoint

        cur = await self.conn.execute(
            "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'society_agents'"
        )
        row = await cur.fetchone()
        await cur.close()
        ddl = str(row[0]) if row and row[0] else ""
        if all(f"'{value}'" in ddl for value in Checkpoint):
            return
        schema = _SCHEMA_PATH.read_text(encoding="utf-8")
        start = schema.index("CREATE TABLE IF NOT EXISTS society_agents")
        end = schema.index(");", start) + 2
        fresh_ddl = schema[start:end].replace(
            "CREATE TABLE IF NOT EXISTS society_agents", "CREATE TABLE society_agents__new", 1
        )
        cur = await self.conn.execute("PRAGMA table_info(society_agents)")
        old_cols = [str(r[1]) for r in await cur.fetchall()]
        await cur.close()
        await self.conn.execute("PRAGMA foreign_keys=OFF")
        try:
            await self.conn.execute("BEGIN")
            await self.conn.execute(fresh_ddl)
            cur = await self.conn.execute("PRAGMA table_info(society_agents__new)")
            new_cols = {str(r[1]) for r in await cur.fetchall()}
            await cur.close()
            shared = ", ".join(c for c in old_cols if c in new_cols)
            # Column names come from PRAGMA table_info, never from input.
            copy_sql = (
                f"INSERT INTO society_agents__new ({shared}) SELECT {shared} FROM society_agents"  # noqa: S608, E501
            )
            await self.conn.execute(copy_sql)
            await self.conn.execute("DROP TABLE society_agents")
            await self.conn.execute("ALTER TABLE society_agents__new RENAME TO society_agents")
            await self.conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_society_agents_state ON society_agents(state)"
            )
            await self.conn.execute("COMMIT")
        except Exception:
            await self.conn.execute("ROLLBACK")
            raise
        finally:
            await self.conn.execute("PRAGMA foreign_keys=ON")
        log.info("society store: migration applied — checkpoint vocabulary widened")

    async def _ensure_fts(self) -> None:
        """FTS5 over knowledge summaries; optional — a sqlite without FTS5 still
        runs the society, search then falls back to LIKE in the read path."""
        try:
            await self.conn.execute(
                "CREATE VIRTUAL TABLE IF NOT EXISTS knowledge_fts USING fts5("
                "summary, wiki_path, content='knowledge', content_rowid='id')"
            )
        except Exception as exc:  # noqa: BLE001 — FTS5 is a build option of sqlite
            log.info("society store: FTS5 unavailable, knowledge search degrades (%s)", exc)

    async def close(self) -> None:
        if self._conn is not None:
            await self._conn.close()
            self._conn = None

    @property
    def conn(self) -> aiosqlite.Connection:
        if self._conn is None:
            raise RuntimeError("SocietyStore: call open() before use")
        return self._conn

    # ---------------------------------------------------------------- meta

    async def get_meta(self, key: str, default: str = "") -> str:
        cur = await self.conn.execute("SELECT value FROM society_meta WHERE key = ?", (key,))
        row = await cur.fetchone()
        await cur.close()
        return str(row[0]) if row else default

    async def set_meta(self, key: str, value: str) -> None:
        await self.conn.execute(
            "INSERT INTO society_meta (key, value) VALUES (?, ?) "
            "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            (key, value),
        )

    async def meta_prefix(self, prefix: str) -> dict[str, str]:
        """Read durable subsystem records without exposing unrelated metadata."""
        cur = await self.conn.execute(
            "SELECT key, value FROM society_meta WHERE substr(key, 1, ?) = ?",
            (len(prefix), prefix),
        )
        rows = await cur.fetchall()
        await cur.close()
        return {str(row[0]): str(row[1]) for row in rows}

    async def kill_switch(self) -> bool:
        return (await self.get_meta(_KEY_KILL_SWITCH, "0")) == "1"

    async def set_kill_switch(self, engaged: bool) -> None:
        await self.set_meta(_KEY_KILL_SWITCH, "1" if engaged else "0")

    # -------------------------------------------------------------- events

    async def append_and_publish(self, envelope: SocietyEnvelope) -> SocietyEnvelope:
        """Persist, then publish. Returns the envelope with its ``seq``."""
        if envelope.seq is not None:
            raise ValueError("append_and_publish: envelope.seq must be None (server-assigned)")
        cur = await self.conn.execute(
            """
            INSERT INTO society_events
                (event_id, msg_type, from_agent, to_agent, trace_id, parent_event_id,
                 ts_ms, cost_usd, payload_json)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            RETURNING seq
            """,
            (
                envelope.event_id,
                str(envelope.msg_type),
                envelope.from_agent,
                envelope.to_agent,
                envelope.trace_id,
                envelope.parent_event_id,
                envelope.ts_ms,
                float(envelope.cost_usd),
                json.dumps(envelope.payload, ensure_ascii=False, separators=(",", ":")),
            ),
        )
        row = await cur.fetchone()
        await cur.close()
        if row is None:  # pragma: no cover — sqlite always returns the seq
            raise RuntimeError("INSERT ... RETURNING seq returned no value")
        stored = envelope.model_copy(update={"seq": int(row[0])})
        await self._bus.publish(stored)
        return stored

    async def delivery_status(self, event_id: str) -> str:
        async with self.conn.execute(
            "SELECT status FROM society_deliveries WHERE event_id = ?", (event_id,)
        ) as cur:
            row = await cur.fetchone()
        return str(row[0]) if row else "queued"

    async def mark_delivery(self, event_id: str, status: str, error: str = "") -> None:
        await self.conn.execute(
            "UPDATE society_deliveries SET status = ?, error = ? WHERE event_id = ?",
            (status, error, event_id),
        )

    async def pending_deliveries(self) -> list[SocietyEnvelope]:
        async with self.conn.execute(
            "SELECT e.seq, e.event_id, e.msg_type, e.from_agent, e.to_agent, e.trace_id, "
            "e.parent_event_id, e.ts_ms, e.cost_usd, e.payload_json "
            "FROM society_events e JOIN society_deliveries d ON d.event_id = e.event_id "
            "WHERE d.status = 'queued' ORDER BY e.seq"
        ) as cur:
            rows = await cur.fetchall()
        return [_row_to_envelope(row) for row in rows]

    async def events_since(self, after_seq: int = 0, *, limit: int = 1000) -> list[SocietyEnvelope]:
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE seq > ? "  # noqa: S608 — identifiers from a fixed allowlist, values bound
            "ORDER BY seq ASC LIMIT ?",
            (int(after_seq), int(limit)),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [_row_to_envelope(r) for r in rows]

    async def get_event(self, event_id: str) -> SocietyEnvelope | None:
        """Read a durable event by its exact id, independently of recent-history limits."""
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE event_id = ?",  # noqa: S608 — fixed identifiers, bound values
            (event_id,),
        )
        row = await cur.fetchone()
        await cur.close()
        return _row_to_envelope(row) if row is not None else None

    async def latest_assignment_for_agent(
        self, agent_id: str, *, from_agent: str
    ) -> SocietyEnvelope | None:
        """Newest assignment from one sender to one agent, across the complete board."""
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events "  # noqa: S608 — fixed identifiers, bound values
            "WHERE msg_type = 'ASSIGN' AND to_agent = ? AND from_agent = ? "
            "ORDER BY seq DESC LIMIT 1",
            (agent_id, from_agent),
        )
        row = await cur.fetchone()
        await cur.close()
        return _row_to_envelope(row) if row is not None else None

    async def events_for_trace(self, trace_id: str) -> list[SocietyEnvelope]:
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE trace_id = ? ORDER BY seq ASC",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (trace_id,),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [_row_to_envelope(r) for r in rows]

    async def events_for_agent(
        self, agent_id: str, *, after_seq: int = 0, limit: int = 200
    ) -> list[SocietyEnvelope]:
        """Everything sent by or to ``agent_id`` (broadcasts included)."""
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events "  # noqa: S608 — identifiers from a fixed allowlist, values bound
            "WHERE seq > ? AND (from_agent = ? OR to_agent = ? OR to_agent IS NULL) "
            "ORDER BY seq DESC LIMIT ?",
            (int(after_seq), agent_id, agent_id, int(limit)),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [_row_to_envelope(r) for r in reversed(list(rows))]

    async def inbox_for(
        self, agent_id: str, *, after_seq: int = 0, limit: int = 200
    ) -> list[SocietyEnvelope]:
        """Envelopes addressed to ``agent_id`` (direct only), oldest first."""
        cur = await self.conn.execute(
            f"SELECT {_EVENT_COLUMNS} FROM society_events WHERE to_agent = ? AND seq > ? "  # noqa: S608 — identifiers from a fixed allowlist, values bound
            "ORDER BY seq ASC LIMIT ?",
            (agent_id, int(after_seq), int(limit)),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [_row_to_envelope(r) for r in rows]

    # ------------------------------------------------------- persistent groups

    async def list_chat_groups(self) -> list[dict[str, Any]]:
        async with self.conn.execute(
            f"SELECT {_GROUP_COLUMNS} FROM society_chat_groups ORDER BY created_ms ASC"  # noqa: S608 — fixed column list
        ) as cur:
            rows = await cur.fetchall()
        return [_row_to_group(row) for row in rows]

    async def get_chat_group(self, group_id: str) -> dict[str, Any] | None:
        async with self.conn.execute(
            f"SELECT {_GROUP_COLUMNS} FROM society_chat_groups WHERE group_id = ?",  # noqa: S608 — fixed column list
            (group_id,),
        ) as cur:
            row = await cur.fetchone()
        return _row_to_group(row) if row is not None else None

    async def create_chat_group(
        self, group_id: str, name: str, members: list[str]
    ) -> dict[str, Any]:
        stamp = now_ms()
        await self.conn.execute(
            "INSERT INTO society_chat_groups "
            "(group_id, name, members_json, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?)",
            (group_id, name, json.dumps(members), stamp, stamp),
        )
        return (await self.get_chat_group(group_id)) or {}

    async def update_chat_group(
        self, group_id: str, name: str, members: list[str]
    ) -> dict[str, Any]:
        await self.conn.execute(
            "UPDATE society_chat_groups SET name = ?, members_json = ?, updated_ms = ? "
            "WHERE group_id = ?",
            (name, json.dumps(members), now_ms(), group_id),
        )
        return (await self.get_chat_group(group_id)) or {}

    async def set_chat_group_lead(
        self, group_id: str, lead_agent_id: str | None
    ) -> dict[str, Any]:
        await self.conn.execute(
            "UPDATE society_chat_groups SET lead_agent_id = ?, updated_ms = ? WHERE group_id = ?",
            (lead_agent_id, now_ms(), group_id),
        )
        return (await self.get_chat_group(group_id)) or {}

    async def set_chat_group_mission(self, group_id: str, mission: str) -> dict[str, Any]:
        await self.conn.execute(
            "UPDATE society_chat_groups SET mission = ?, updated_ms = ? WHERE group_id = ?",
            (mission, now_ms(), group_id),
        )
        return (await self.get_chat_group(group_id)) or {}

    async def delete_chat_group(self, group_id: str) -> None:
        await self.conn.execute("DELETE FROM society_chat_groups WHERE group_id = ?", (group_id,))

    # ---------------------------------------------------- team goals and tasks

    async def _insert(self, table: str, row: dict[str, Any]) -> None:
        cols = ", ".join(row)
        marks = ", ".join("?" for _ in row)
        await self.conn.execute(
            f"INSERT INTO {table} ({cols}) VALUES ({marks})",  # noqa: S608 — identifiers from the caller's fixed dict, values bound
            tuple(row.values()),
        )

    async def _update(self, table: str, key: str, key_value: str, fields: dict[str, Any]) -> bool:
        if not fields:
            return False
        sets = ", ".join(f"{k} = ?" for k in fields)
        cur = await self.conn.execute(
            f"UPDATE {table} SET {sets} WHERE {key} = ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*fields.values(), key_value),
        )
        await cur.close()
        return bool(cur.rowcount)

    async def _select(self, sql: str, args: tuple[Any, ...] = ()) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute(sql, args)
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    async def insert_team_goal(self, row: dict[str, Any]) -> None:
        await self._insert("society_team_goals", row)

    async def update_team_goal(self, goal_id: str, fields: dict[str, Any]) -> bool:
        return await self._update("society_team_goals", "goal_id", goal_id, fields)

    async def transition_team_goal(
        self, goal_id: str, from_states: Iterable[str], fields: dict[str, Any]
    ) -> bool:
        """Update a goal only while it is in one of ``from_states``.

        The compare-and-swap every state change goes through: two callers
        that read the same state cannot both move the goal (a stop that
        lands between a resume's read and its write must win).
        """
        states = tuple(from_states)
        sets = ", ".join(f"{k} = ?" for k in fields)
        marks = ", ".join("?" for _ in states)
        cur = await self.conn.execute(
            f"UPDATE society_team_goals SET {sets} "  # noqa: S608 — identifiers from a fixed allowlist, values bound
            f"WHERE goal_id = ? AND state IN ({marks})",
            (*fields.values(), goal_id, *states),
        )
        await cur.close()
        return bool(cur.rowcount)

    async def get_team_goal_row(self, goal_id: str) -> dict[str, Any] | None:
        rows = await self._select("SELECT * FROM society_team_goals WHERE goal_id = ?", (goal_id,))
        return rows[0] if rows else None

    async def list_team_goal_rows(
        self, *, group_id: str | None = None, limit: int = 200
    ) -> list[dict[str, Any]]:
        """Newest first; every group's goals when ``group_id`` is ``None``."""
        if group_id is None:
            return await self._select(
                "SELECT * FROM society_team_goals ORDER BY created_ms DESC, goal_id DESC LIMIT ?",
                (int(limit),),
            )
        return await self._select(
            "SELECT * FROM society_team_goals WHERE group_id = ? "
            "ORDER BY created_ms DESC, goal_id DESC LIMIT ?",
            (group_id, int(limit)),
        )

    async def delete_team_goals(self, group_id: str) -> None:
        await self.conn.execute(
            "DELETE FROM society_team_tasks WHERE goal_id IN "
            "(SELECT goal_id FROM society_team_goals WHERE group_id = ?)",
            (group_id,),
        )
        await self.conn.execute("DELETE FROM society_team_goals WHERE group_id = ?", (group_id,))

    async def insert_team_task(self, row: dict[str, Any]) -> None:
        await self._insert("society_team_tasks", row)

    async def update_team_task(self, task_id: str, fields: dict[str, Any]) -> bool:
        return await self._update("society_team_tasks", "task_id", task_id, fields)

    async def get_team_task_row(self, task_id: str) -> dict[str, Any] | None:
        rows = await self._select("SELECT * FROM society_team_tasks WHERE task_id = ?", (task_id,))
        return rows[0] if rows else None

    async def get_team_task_row_by_trace(self, trace_id: str) -> dict[str, Any] | None:
        rows = await self._select(
            "SELECT * FROM society_team_tasks WHERE trace_id = ?", (trace_id,)
        )
        return rows[0] if rows else None

    async def list_team_task_rows(self, goal_id: str) -> list[dict[str, Any]]:
        """A goal's tasks, oldest first."""
        return await self._select(
            "SELECT * FROM society_team_tasks WHERE goal_id = ? "
            "ORDER BY created_ms ASC, task_id ASC",
            (goal_id,),
        )

    async def last_seq(self) -> int:
        cur = await self.conn.execute("SELECT COALESCE(MAX(seq), 0) FROM society_events")
        row = await cur.fetchone()
        await cur.close()
        return int(row[0]) if row else 0

    async def count_in_trace(self, trace_id: str) -> int:
        cur = await self.conn.execute(
            "SELECT COUNT(*) FROM society_events WHERE trace_id = ?", (trace_id,)
        )
        row = await cur.fetchone()
        await cur.close()
        return int(row[0]) if row else 0

    async def cost_since(self, agent_id: str, since_ms: int) -> float:
        cur = await self.conn.execute(
            "SELECT COALESCE(SUM(cost_usd), 0) FROM society_events "
            "WHERE from_agent = ? AND ts_ms >= ?",
            (agent_id, int(since_ms)),
        )
        row = await cur.fetchone()
        await cur.close()
        return float(row[0]) if row else 0.0

    async def record_chat_turns(self, turns: list[tuple[str, str, str, int, str]]) -> int:
        """Remember finished chat turns ``(turn_id, agent_id, session_id, ts_ms, status)``.

        Idempotent by turn id: a replayed or backfilled turn is kept once.
        Returns how many were new.
        """
        if not turns:
            return 0
        before = self.conn.total_changes
        await self.conn.executemany(
            "INSERT OR IGNORE INTO society_agent_turns "
            "(turn_id, agent_id, session_id, ts_ms, status) VALUES (?, ?, ?, ?, ?)",
            [(str(t), str(a), str(s), int(ms), str(st)) for t, a, s, ms, st in turns],
        )
        return self.conn.total_changes - before

    async def agent_stats(self, agent_id: str) -> dict[str, Any]:
        """Derived numbers: runs, lifetime cost, last activity.

        A run is a RESULT the agent sent (board work, missions, team goals)
        or a finished chat turn of its own (society_agent_turns: its chat,
        conversations and routine runs, on any runtime). A board dispatch is
        both a chat turn and a RESULT with run_id ``turn:<turn_id>``; it
        counts once.

        ``spent_today_usd`` rides along because the daily budget is a real
        gate — the scheduler refuses a dispatch once an agent has spent its
        ``daily_budget_usd`` since the start of the UTC day — and a budget
        shown without today's spend beside it looks like a decoration rather
        than the limit it is. Same ``day_start_ms`` both places, so the card
        and the gate can never disagree.
        """
        cur = await self.conn.execute(
            "SELECT "
            "  SUM(CASE WHEN msg_type = 'RESULT' THEN 1 ELSE 0 END), "
            "  COALESCE(SUM(cost_usd), 0), MAX(ts_ms) "
            "FROM society_events WHERE from_agent = ?",
            (agent_id,),
        )
        row = await cur.fetchone()
        await cur.close()
        runs, cost, last = row or (0, 0.0, None)
        cur = await self.conn.execute(
            # The agent's RESULT run ids are read once (not per turn); a turn
            # that has one is already counted among the RESULTs above.
            "SELECT SUM(CASE WHEN 'turn:' || t.turn_id IN ("
            "  SELECT json_extract(e.payload_json, '$.run_id') FROM society_events e "
            "  WHERE e.from_agent = ? AND e.msg_type = 'RESULT'"
            ") THEN 0 ELSE 1 END), MAX(t.ts_ms) "
            "FROM society_agent_turns t WHERE t.agent_id = ?",
            (agent_id, agent_id),
        )
        turn_row = await cur.fetchone()
        await cur.close()
        chat_runs, chat_last = turn_row or (0, None)
        if chat_last is not None and (last is None or int(chat_last) > int(last)):
            last = chat_last
        today = await self.cost_since(agent_id, day_start_ms(now_ms()))
        return {
            "runs": int(runs or 0) + int(chat_runs or 0),
            "total_cost_usd": float(cost or 0.0),
            "spent_today_usd": today,
            "last_active_ms": int(last) if last is not None else None,
        }

    # -------------------------------------------------------------- agents
    # Raw row access. Validation and the record type live in roster.py.

    async def insert_agent(self, row: dict[str, Any]) -> None:
        cols = ", ".join(row.keys())
        marks = ", ".join("?" for _ in row)
        await self.conn.execute(
            f"INSERT INTO society_agents ({cols}) VALUES ({marks})",  # noqa: S608 — identifiers from a fixed allowlist
            tuple(row.values()),
        )

    async def update_agent(self, agent_id: str, fields: dict[str, Any]) -> bool:
        if not fields:
            return False
        fields = dict(fields)
        fields["updated_ms"] = now_ms()
        assignments = ", ".join(f"{k} = ?" for k in fields)
        cur = await self.conn.execute(
            f"UPDATE society_agents SET {assignments} WHERE agent_id = ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*fields.values(), agent_id),
        )
        changed = cur.rowcount > 0
        await cur.close()
        return changed

    async def get_agent_row(self, agent_id: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute(
            "SELECT * FROM society_agents WHERE agent_id = ?", (agent_id,)
        )
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def get_agent_row_by_name(self, name: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute(
            "SELECT * FROM society_agents WHERE lower(name) = lower(?)", (name,)
        )
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def list_agent_rows(self, *, include_archived: bool = False) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        sql = "SELECT * FROM society_agents"
        if not include_archived:
            sql += " WHERE state != 'archived'"
        sql += " ORDER BY CASE tier WHEN 'lead' THEN 0 WHEN 'orchestrator' THEN 1 ELSE 2 END, name"
        cur = await self.conn.execute(sql)
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    # --------------------------------------------------------------- rooms

    async def insert_room(self, row: dict[str, Any]) -> None:
        cols = ", ".join(row.keys())
        marks = ", ".join("?" for _ in row)
        await self.conn.execute(
            f"INSERT INTO society_rooms ({cols}) VALUES ({marks})",  # noqa: S608 — identifiers from a fixed allowlist
            tuple(row.values()),
        )

    async def update_room(self, room_id: str, fields: dict[str, Any]) -> None:
        fields = dict(fields)
        fields["updated_ms"] = now_ms()
        assignments = ", ".join(f"{k} = ?" for k in fields)
        await self.conn.execute(
            f"UPDATE society_rooms SET {assignments} WHERE room_id = ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*fields.values(), room_id),
        )

    async def get_room_row(self, room_id: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute("SELECT * FROM society_rooms WHERE room_id = ?", (room_id,))
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def list_room_rows(self, *, state: str | None = None,
                             prefix: str | None = None, limit: int = 20) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        if prefix is not None:
            cur = await self.conn.execute(
                "SELECT * FROM society_rooms WHERE substr(room_id, 1, ?) = ? "
                "ORDER BY created_ms DESC, rowid DESC LIMIT ?",
                (len(prefix), prefix, max(1, min(limit, 100))),
            )
        elif state is None:
            cur = await self.conn.execute("SELECT * FROM society_rooms ORDER BY created_ms DESC")
        else:
            cur = await self.conn.execute(
                "SELECT * FROM society_rooms WHERE state = ? ORDER BY created_ms DESC", (state,)
            )
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    # ----------------------------------------------------------- approvals

    async def insert_approval(self, row: dict[str, Any]) -> None:
        cols = ", ".join(row.keys())
        marks = ", ".join("?" for _ in row)
        await self.conn.execute(
            f"INSERT INTO approvals ({cols}) VALUES ({marks})",  # noqa: S608 — identifiers from a fixed allowlist
            tuple(row.values()),
        )

    async def update_approval(self, approval_id: str, fields: dict[str, Any]) -> bool:
        if not fields:
            return False
        assignments = ", ".join(f"{k} = ?" for k in fields)
        cur = await self.conn.execute(
            f"UPDATE approvals SET {assignments} WHERE id = ?",  # noqa: S608 — identifiers from a fixed allowlist
            (*fields.values(), approval_id),
        )
        changed = cur.rowcount > 0
        await cur.close()
        return changed

    async def get_approval_row(self, approval_id: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute("SELECT * FROM approvals WHERE id = ?", (approval_id,))
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def list_approval_rows(
        self, *, state: str | None = None, agent_id: str | None = None, limit: int = 200
    ) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        clauses: list[str] = []
        params: list[Any] = []
        if state is not None:
            clauses.append("state = ?")
            params.append(state)
        if agent_id is not None:
            clauses.append("agent_id = ?")
            params.append(agent_id)
        where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
        cur = await self.conn.execute(
            f"SELECT * FROM approvals{where} ORDER BY created_ms DESC LIMIT ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*params, int(limit)),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    # ----------------------------------------------------------- knowledge

    # -------------------------------------------------------------- quests

    async def insert_quest(self, row: dict[str, Any]) -> None:
        cols = ", ".join(row)
        marks = ", ".join("?" for _ in row)
        await self.conn.execute(
            f"INSERT INTO society_quests ({cols}) VALUES ({marks})",  # noqa: S608 — identifiers from the caller's fixed dict, values bound
            tuple(row.values()),
        )

    async def update_quest(self, quest_id: str, fields: dict[str, Any]) -> bool:
        if not fields:
            return False
        sets = ", ".join(f"{k} = ?" for k in fields)
        cur = await self.conn.execute(
            f"UPDATE society_quests SET {sets} WHERE quest_id = ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*fields.values(), quest_id),
        )
        await cur.close()
        return bool(cur.rowcount)

    async def get_quest_row(self, quest_id: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute(
            "SELECT * FROM society_quests WHERE quest_id = ?", (quest_id,)
        )
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def get_quest_row_by_trace(self, trace_id: str) -> dict[str, Any] | None:
        self.conn.row_factory = aiosqlite.Row
        cur = await self.conn.execute(
            "SELECT * FROM society_quests WHERE trace_id = ?", (trace_id,)
        )
        row = await cur.fetchone()
        await cur.close()
        return dict(row) if row else None

    async def list_quest_rows(
        self, *, state: str | None = None, limit: int = 200
    ) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        if state is not None:
            cur = await self.conn.execute(
                "SELECT * FROM society_quests WHERE state = ? ORDER BY created_ms DESC LIMIT ?",
                (state, int(limit)),
            )
        else:
            cur = await self.conn.execute(
                "SELECT * FROM society_quests ORDER BY created_ms DESC LIMIT ?", (int(limit),)
            )
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    async def insert_knowledge(self, row: dict[str, Any]) -> int:
        cols = ", ".join(row.keys())
        marks = ", ".join("?" for _ in row)
        cur = await self.conn.execute(
            f"INSERT INTO knowledge ({cols}) VALUES ({marks}) RETURNING id",  # noqa: S608 — identifiers from a fixed allowlist
            tuple(row.values()),
        )
        got = await cur.fetchone()
        await cur.close()
        new_id = int(got[0]) if got else 0
        try:
            await self.conn.execute(
                "INSERT INTO knowledge_fts (rowid, summary, wiki_path) VALUES (?, ?, ?)",
                (new_id, row.get("summary", ""), row.get("wiki_path", "")),
            )
        except Exception:  # noqa: BLE001 — FTS5 optional (see _ensure_fts)
            log.debug("society store: knowledge_fts insert skipped (no FTS5)")
        return new_id

    async def list_knowledge_rows(
        self, *, agent_id: str | None = None, reviewed: bool | None = None, limit: int = 200
    ) -> list[dict[str, Any]]:
        self.conn.row_factory = aiosqlite.Row
        clauses: list[str] = []
        params: list[Any] = []
        if agent_id is not None:
            clauses.append("agent_id = ?")
            params.append(agent_id)
        if reviewed is not None:
            clauses.append("reviewed = ?")
            params.append(1 if reviewed else 0)
        where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
        cur = await self.conn.execute(
            f"SELECT * FROM knowledge{where} ORDER BY created_ms DESC LIMIT ?",  # noqa: S608 — identifiers from a fixed allowlist, values bound
            (*params, int(limit)),
        )
        rows = await cur.fetchall()
        await cur.close()
        return [dict(r) for r in rows]

    async def mark_knowledge_reviewed(self, knowledge_id: int) -> bool:
        cur = await self.conn.execute(
            "UPDATE knowledge SET reviewed = 1 WHERE id = ?", (int(knowledge_id),)
        )
        changed = cur.rowcount > 0
        await cur.close()
        return changed