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.

16.4 KB
Raw Blame
"""Turns real app events into XP and announces every award on the bus.

The service listens to the core ``EventBus`` for the handful of events that
mean "something was achieved" (a finished assistant turn, a finished agent
task, a completed quest) and maps each to one or two rules of
:mod:`dodaios.progression.rules`. The ship reports its own small world
actions (a deck discovered, a simulator round, a deck inspected) through
:meth:`ProgressionService.report_action`. Those are the client's word: the
server applies every cooldown and daily cap and checks every reference (a
known deck), so a client can at most collect the few capped XP a day that
playing would have paid.

Every handler is an observer: a failure is logged and swallowed, never
raised into the bus (AP-18), and the database is opened on the first award,
not at boot (AP-26). Writes run off the event loop.
"""

from __future__ import annotations

import asyncio
import dataclasses
import logging
import threading
import time
from collections.abc import Callable, Mapping
from datetime import datetime
from pathlib import Path
from typing import Any

from .duel_stats import DuelResult, DuelResultError, DuelStatsStore, parse_duel_result
from .rules import (
    LEAD_AGENT_ID,
    PERSON_ID,
    RULES_BY_SOURCE,
    VERSE_DECKS,
    WORLD_ACTIONS,
    agent_subject,
    duel_awards,
    looks_between,
    pet_subject,
    progress_for_xp,
    rewards_between,
    subject_kind,
    title_for,
)
from .store import Award, ProgressionStore

log = logging.getLogger(__name__)

__all__ = ["VERSE_DECKS", "DuelResultError", "ProgressionService", "UnknownAction"]


class UnknownAction(ValueError):
    """A world action the rulebook does not know."""


class ProgressionService:
    def __init__(
        self,
        db_path: Path,
        *,
        bus: Any | None = None,
        pet_id: Callable[[], str] | None = None,
        clock: Callable[[], int] | None = None,
    ) -> None:
        self._clock = clock or (lambda: int(time.time() * 1000))
        self.store = ProgressionStore(db_path, clock=self._clock)
        self.duels = DuelStatsStore(db_path, clock=self._clock)
        # One duel result at a time: its row, its awards and its mark are one step.
        self._duel_lock = threading.Lock()
        self._ledger_open = False
        self._bus = bus
        self._pet_id = pet_id or (lambda: "gigi")
        self._attached = False
        self._tasks: set[asyncio.Task[None]] = set()

    # ------------------------------------------------------------ wiring

    def attach(self) -> None:
        """Subscribe to the bus. Idempotent; opens nothing."""
        if self._bus is None or self._attached:
            return
        from dodaios.core.events import (
            JarvisChatTurnFinished,
            MissionCompleted,
            SocietyMessageSent,
            SocietyQuestChanged,
            SocietyResultPosted,
            VoiceTurnCompleted,
        )

        self._bus.subscribe(JarvisChatTurnFinished, self._on_chat_turn)
        self._bus.subscribe(VoiceTurnCompleted, self._on_voice_turn)
        self._bus.subscribe(SocietyQuestChanged, self._on_quest)
        self._bus.subscribe(SocietyResultPosted, self._on_result)
        self._bus.subscribe(SocietyMessageSent, self._on_message)
        self._bus.subscribe(MissionCompleted, self._on_mission)
        self._attached = True

    def close(self) -> None:
        for task in list(self._tasks):
            task.cancel()
        self.duels.close()
        self.store.close()

    async def drain(self) -> None:
        """Wait for every award the bus handlers queued (tests, shutdown)."""
        while self._tasks:
            await asyncio.gather(*list(self._tasks), return_exceptions=True)

    def _later(self, *awards: tuple[str, str, str]) -> None:
        """Queue awards off the publisher's path.

        Typed bus handlers are awaited by the publisher (the voice pipeline
        among them), so a handler only schedules its writes and returns.
        """

        async def run() -> None:
            for subject_id, source, ref in awards:
                await self._safe_award(subject_id, source, ref)

        task = asyncio.get_running_loop().create_task(run(), name="progression-award")
        self._tasks.add(task)
        task.add_done_callback(self._tasks.discard)

    def current_pet(self) -> str:
        try:
            pet = str(self._pet_id() or "").strip()
        except Exception:  # noqa: BLE001 - a broken getter falls back to the default pet
            log.debug("progression: pet id unavailable", exc_info=True)
            pet = ""
        return pet if pet and pet != "none" else "gigi"

    # ------------------------------------------------------------ paying

    async def award(self, subject_id: str, source: str, *, ref: str = "") -> Award | None:
        rule = RULES_BY_SOURCE.get(source)
        if rule is None:
            raise UnknownAction(source)
        result = await asyncio.to_thread(self.store.award, subject_id, rule, ref=ref)
        if result is not None:
            await self._announce(result)
        return result

    async def _safe_award(self, subject_id: str, source: str, ref: str = "") -> None:
        try:
            await self.award(subject_id, source, ref=ref)
        except Exception:  # noqa: BLE001 - XP is a garnish; a failed write never breaks a turn
            log.warning("progression: %s for %s not stored", source, subject_id, exc_info=True)

    async def _announce(self, award: Award) -> None:
        if self._bus is None:
            return
        from dodaios.core.events import ProgressionAwarded

        kind = subject_kind(award.subject_id) or "person"
        unlocked = tuple(
            r.reward_id for r in rewards_between(kind, award.level_before, award.level_after)
        )
        looks = (
            tuple(looks_between(award.level_before, award.level_after)) if kind == "agent" else ()
        )
        try:
            await self._bus.publish(
                ProgressionAwarded(
                    source_layer="progression",
                    seq=award.seq,
                    subject_id=award.subject_id,
                    subject_kind=kind,
                    xp_source=award.source,
                    xp=award.xp,
                    total_xp=award.total_xp,
                    level=award.level_after,
                    previous_level=award.level_before,
                    title=title_for(kind, award.level_after),
                    unlocked=unlocked,
                    unlocked_looks=looks,
                )
            )
        except Exception:  # noqa: BLE001 - the award is stored; the Verse catches up on its next read
            log.debug("progression: award %s not pushed", award.seq, exc_info=True)

    # ------------------------------------------------------------ world actions

    async def report_action(self, action: str, *, ref: str = "") -> Award | None:
        """A small action aboard the ship, reported by the client."""
        if action not in WORLD_ACTIONS:
            raise UnknownAction(action)
        rule = RULES_BY_SOURCE[action]
        today = datetime.fromtimestamp(self._clock() / 1000).astimezone().date().isoformat()
        if action == "daily_visit":
            # The server's own calendar day, whatever the client sent.
            ref = today
        elif action == "deck_discovered":
            if ref not in VERSE_DECKS:
                raise UnknownAction(f"deck_discovered:{ref}")
        elif action == "inspection":
            if ref not in VERSE_DECKS:
                raise UnknownAction(f"inspection:{ref}")
            # Each deck's inspection pays once per day.
            ref = f"{ref}:{today}"
        elif action == "team_briefing":
            # Which team gathered is kept for the log; the cooldown and the cap meter it.
            ref = f"{ref[:40]}@{self._clock()}" if ref else ""
        else:
            ref = ""
        subject = PERSON_ID if rule.kind == "person" else pet_subject(self.current_pet())
        return await self.award(subject, action, ref=ref)

    async def note_agent_hired(self, agent_id: str) -> None:
        if agent_id and agent_id != LEAD_AGENT_ID:
            self._later((PERSON_ID, "agent_hired", f"agent:{agent_id}"))

    # ------------------------------------------------------------ duels

    async def record_duel(self, data: Mapping[str, Any]) -> dict[str, Any]:
        """Store one ``duel.result`` (bridge-protocol 10) and pay its XP.

        Idempotent on ``match_id``: a result sent again stores nothing, pays
        nothing and answers with the awards the first one paid. Implausible
        numbers are clamped and logged. Raises :class:`DuelResultError` for a
        payload that is not a result (the bridge answers ``bad_request``).
        """
        result = parse_duel_result(data)
        if result.clamped:
            log.warning(
                "progression: duel %s clamped: %s", result.match_id, "; ".join(result.clamped)
            )
        fresh, awards, paid = await asyncio.to_thread(self._record_duel_locked, result)
        for award in paid:
            await self._announce(award)
        if fresh:
            await self._announce_duel(result)
        totals = await asyncio.to_thread(self.duels.bridge_totals)
        # Exactly the reply result of bridge-protocol 10 (golden schema ``result.duel.result``).
        return {
            "recorded": True,
            "awards": [{"xp_source": a["xp_source"], "xp": a["xp"]} for a in awards],
            "duel_stats": totals,
        }

    def _record_duel_locked(
        self, result: DuelResult
    ) -> tuple[bool, list[dict[str, Any]], list[Award]]:
        """Store the row and pay its rules; returns (fresh, award summaries, new awards)."""
        with self._duel_lock:
            self._ledger_first()
            fresh = self.duels.insert(result)
            row = self.duels.get(result.match_id)
            if row is not None and row["awards_done"]:
                return fresh, list(row["awards"]), []
            # A new row, or one whose awards a crash interrupted: the ledger's
            # per-ref uniqueness keeps a rerun from paying anything twice.
            ref = f"duel:{result.match_id}"
            paid: list[Award] = []
            for source, xp in duel_awards(
                mode=result.mode,
                outcome=result.outcome,
                match_time_s=result.match_time_s,
                tier_key=result.tier_key,
                finishers=result.stats["finishers"],
            ):
                rule = dataclasses.replace(RULES_BY_SOURCE[source], xp=xp)
                award = self.store.award(PERSON_ID, rule, ref=ref)
                if award is not None:
                    paid.append(award)
            # Summaries from the ledger, not only from this run: after a crash
            # between paying and finish() the rerun pays nothing new, yet the
            # set still paid what the ledger holds for its ref.
            summaries = self.duels.paid_awards(PERSON_ID, ref)
            self.duels.finish(result.match_id, summaries)
            return fresh, summaries, paid

    async def _announce_duel(self, result: DuelResult) -> None:
        """Publish ``VerseDuelRecorded`` once the bus has the event (WP17 adds it)."""
        if self._bus is None:
            return
        from dodaios.core import events

        event_type = getattr(events, "VerseDuelRecorded", None)
        if event_type is None:
            log.debug("progression: VerseDuelRecorded not defined yet; %s not announced",
                      result.match_id)
            return
        try:
            await self._bus.publish(
                event_type(
                    source_layer="progression",
                    match_id=result.match_id,
                    outcome=result.outcome,
                    kills=result.stats["kills"],
                    deaths=result.stats["deaths"],
                )
            )
        except Exception:  # noqa: BLE001 - the row is stored; the read path still has it
            log.debug("progression: duel %s not announced", result.match_id, exc_info=True)

    def _ledger_first(self) -> None:
        """Open the XP ledger before the duel tables, so one connection creates the file."""
        if not self._ledger_open:
            self.store.latest_seq()
            self._ledger_open = True

    def duel_stats(self) -> dict[str, Any]:
        """Duel totals for ``GET /api/progression`` and the bridge snapshot."""
        self._ledger_first()
        return self.duels.totals()

    def bridge_duel_stats(self) -> dict[str, Any]:
        """Duel totals in the strict ``duel_stats`` shape of ``progression.snapshot``."""
        self._ledger_first()
        return self.duels.bridge_totals()

    def recent_duels(self, limit: int = 20) -> list[dict[str, Any]]:
        self._ledger_first()
        return self.duels.recent(limit=limit)

    # ------------------------------------------------------------ bus handlers

    async def _on_chat_turn(self, event: Any) -> None:
        if getattr(event, "status", "done") != "done":
            return
        turn = str(getattr(event, "turn_id", "") or getattr(event, "session_id", ""))
        ref = f"chat:{turn}" if turn else ""
        self._later(
            (PERSON_ID, "chat_turn", ref),
            (pet_subject(self.current_pet()), "jarvis_answered", ref),
        )

    async def _on_voice_turn(self, event: Any) -> None:
        turn = str(getattr(event, "turn_id", "") or "")
        ref = f"voice:{getattr(event, 'session_id', '')}:{turn}" if turn else ""
        self._later(
            (PERSON_ID, "voice_turn", ref),
            (pet_subject(self.current_pet()), "jarvis_answered", ref),
        )

    async def _on_quest(self, event: Any) -> None:
        quest_id = str(getattr(event, "quest_id", "") or "")
        if not quest_id:
            return
        state = str(getattr(event, "state", ""))
        previous = str(getattr(event, "previous", ""))
        awards: list[tuple[str, str, str]] = []
        if not previous:
            awards.append((PERSON_ID, "quest_posted", quest_id))
        if state == "done" and previous != "done":
            awards.append((PERSON_ID, "quest_completed", quest_id))
            agent_id = str(getattr(event, "agent_id", "") or "")
            if agent_id and agent_id != LEAD_AGENT_ID:
                awards.append((agent_subject(agent_id), "quest_done", quest_id))
        if awards:
            self._later(*awards)

    async def _on_result(self, event: Any) -> None:
        agent_id = str(getattr(event, "agent_id", "") or "")
        if not agent_id or agent_id == LEAD_AGENT_ID or agent_id in {"user", "scheduler"}:
            return
        ref = str(getattr(event, "event_id", "") or "")
        # Without an id a replayed result could not be told apart, and task_done has no cap.
        if not ref:
            return
        source = "task_done" if getattr(event, "status", "") == "done" else "task_blocked"
        self._later((agent_subject(agent_id), source, ref))

    async def _on_message(self, event: Any) -> None:
        kind = str(getattr(event, "msg_type", ""))
        sender = str(getattr(event, "from_agent", "") or "")
        ref = str(getattr(event, "event_id", "") or "")
        if kind == "ASSIGN" and sender == LEAD_AGENT_ID:
            self._later((pet_subject(self.current_pet()), "delegated", ref))
        elif kind == "ANSWER" and sender and sender not in {LEAD_AGENT_ID, "user", "scheduler"}:
            self._later((agent_subject(sender), "answered_teammate", ref))

    async def _on_mission(self, event: Any) -> None:
        if getattr(event, "status", "") != "approved":
            return
        mission = str(getattr(event, "mission_id", "") or "")
        if not mission:
            return
        self._later((PERSON_ID, "mission_completed", mission))

    # ------------------------------------------------------------ reads

    def snapshot(self) -> list[dict[str, Any]]:
        rows = []
        for row in self.store.subjects():
            kind = row["kind"]
            progress = progress_for_xp(int(row["xp"]))
            rows.append(
                {
                    "subject_id": row["subject_id"],
                    "kind": kind,
                    "xp": progress.xp,
                    "level": progress.level,
                    "xp_into_level": progress.into_level,
                    "xp_for_next": progress.for_next,
                    "title": title_for(kind, progress.level),
                    "updated_ms": int(row["updated_ms"]),
                }
            )
        return rows