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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(progression): add the Jarvis Verse level system backend
rubenluetke10-beep83f1e99843e5
diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex ce6d83a478..30f84c9448 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -2380,6 +2380,48 @@ class SocietyMessageSent(Event):truncated: bool = False+@dataclass(frozen=True, slots=True)+class SocietyResultPosted(Event):+ """An agent finished (or gave up on) a piece of work: a RESULT on the board.++ Published by :class:`jarvis.society.world_feed.WorldFeed` after the+ envelope is stored. Carries no text — the result itself stays behind+ ``GET /api/society/events``. The level system pays the agent for it+ (``jarvis/progression``); the Verse may celebrate it.+ """++ #: The board envelope's uuid7, stable for dedupe.+ event_id: str = ""+ agent_id: str = ""+ #: ``done`` or ``blocked`` (the RESULT payload's own status).+ status: str = ""+ society_trace: str = ""+++@dataclass(frozen=True, slots=True)+class ProgressionAwarded(Event):+ """A subject of the Jarvis Verse level system earned XP.++ Published by :class:`jarvis.progression.service.ProgressionService`+ after the award is stored. ``level > previous_level`` is a level-up;+ ``unlocked`` names the cosmetics that level-up opened+ (``jarvis/progression/rules.py`` REWARDS). The Verse animates it.+ """++ seq: int = 0+ #: ``person``, ``agent:<agent_id>`` or ``pet:<pet_id>``.+ subject_id: str = ""+ subject_kind: str = ""+ #: The rule that paid (``RULES`` source id).+ xp_source: str = ""+ xp: int = 0+ total_xp: int = 0+ level: int = 1+ previous_level: int = 1+ title: str = ""+ unlocked: tuple[str, ...] = ()++@dataclass(frozen=True, slots=True)class SocietyRoomChanged(Event):"""A bounded group discussion opened or settled (``jarvis/society/rooms.py``).diff --git a/jarvis/progression/__init__.py b/jarvis/progression/__init__.pynew file mode 100644index 0000000000..6ff55879d7--- /dev/null+++ b/jarvis/progression/__init__.py@@ -0,0 +1,11 @@+"""The Jarvis Verse level system: XP, levels, titles and cosmetic rewards.++``rules`` is the pure rulebook, ``store`` the SQLite ledger and ``service``+the bus listener that pays XP for real achievements. Contract:+``docs/agent-society/level-system.md``.+"""++from .rules import MAX_LEVEL, REWARDS, RULES, TITLES+from .service import ProgressionService, UnknownAction++__all__ = ["MAX_LEVEL", "REWARDS", "RULES", "TITLES", "ProgressionService", "UnknownAction"]diff --git a/jarvis/progression/rules.py b/jarvis/progression/rules.pynew file mode 100644index 0000000000..cebf1f07f5--- /dev/null+++ b/jarvis/progression/rules.py@@ -0,0 +1,245 @@+"""The Jarvis Verse level system's rulebook: pure tables, no I/O.++Three kinds of subject level up:++* ``person`` — the person at the keyboard (one subject, id ``person``);+* ``agent`` — every Jarvis agent on the society roster (``agent:<agent_id>``);+* ``pet`` — the person's pet from My Pets, which IS Jarvis in the Verse+ (``pet:<pet_id>``; each pet keeps its own level, the active one earns).++XP only ever comes from a rule in :data:`RULES`. A rule names its source, the+subject kind it pays, a fixed amount, an optional cooldown and an optional+daily cap. Server rules are read off real bus events (a finished turn, a+finished task); world rules are small actions inside the Verse that the client+reports and the server still meters. Nothing here calls a model — the+system works with any single key and costs no tokens (AP-21).++The level curve is front-loaded the way long-running progression usually is:+level 2 arrives within the first few actions, level 10 after about a week of+ordinary use, level 50 after several months. Every level pays a cosmetic,+a frame or a new title band at a fixed milestone (:data:`REWARDS`,+:data:`TITLES`). ``docs/agent-society/level-system.md`` is the readable+version of this file; the parity test pins the frontend's copy of the ids.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Final, Literal++SubjectKind = Literal["person", "agent", "pet"]+SUBJECT_KINDS: Final[tuple[SubjectKind, ...]] = ("person", "agent", "pet")++#: The id of the one person subject.+PERSON_ID: Final[str] = "person"++MAX_LEVEL: Final[int] = 50++#: Society roster id of the lead. The lead is drawn as the person's pet, so its+#: work pays the pet, never an ``agent:jarvis`` subject.+LEAD_AGENT_ID: Final[str] = "jarvis"+++def xp_to_next(level: int) -> int:+ """XP needed to climb from ``level`` to ``level + 1`` (0 at the cap).++ 40 XP for the first step, then a gently super-linear rise, rounded to 5+ so the numbers read cleanly in the HUD.+ """+ if level >= MAX_LEVEL:+ return 0+ if level < 1:+ level = 1+ raw = 40 + 25 * (level - 1) ** 1.1+ return int(round(raw / 5.0) * 5)+++def total_xp_for_level(level: int) -> int:+ """Total XP at which ``level`` is reached (level 1 = 0 XP)."""+ level = max(1, min(MAX_LEVEL, level))+ return sum(xp_to_next(step) for step in range(1, level))+++def level_for_xp(total_xp: int) -> int:+ level = 1+ remaining = max(0, int(total_xp))+ while level < MAX_LEVEL:+ need = xp_to_next(level)+ if remaining < need:+ break+ remaining -= need+ level += 1+ return level+++@dataclass(frozen=True, slots=True)+class LevelProgress:+ level: int+ xp: int+ #: XP gathered since the current level started.+ into_level: int+ #: XP the current level needs in total (0 at the cap).+ for_next: int+++def progress_for_xp(total_xp: int) -> LevelProgress:+ total = max(0, int(total_xp))+ level = level_for_xp(total)+ into = total - total_xp_for_level(level)+ return LevelProgress(level=level, xp=total, into_level=into, for_next=xp_to_next(level))+++# ------------------------------------------------------------------ XP rules++Trigger = Literal["server", "world"]+++@dataclass(frozen=True, slots=True)+class XpRule:+ source: str+ kind: SubjectKind+ xp: int+ trigger: Trigger+ #: Minimum seconds between two awards of this rule to one subject.+ cooldown_s: int = 0+ #: Most XP one subject can earn from this rule per local day (0 = no cap).+ daily_cap: int = 0+ #: True: at most one award per ``ref`` ever (a floor is discovered once).+ once_per_ref: bool = False+++RULES: Final[tuple[XpRule, ...]] = (+ # The person: talking to Jarvis, giving the team work, growing the team.+ XpRule("chat_turn", "person", 5, "server", daily_cap=100),+ XpRule("voice_turn", "person", 5, "server", daily_cap=100),+ XpRule("quest_posted", "person", 15, "server", daily_cap=75),+ XpRule("quest_completed", "person", 20, "server"),+ XpRule("agent_hired", "person", 50, "server"),+ XpRule("mission_completed", "person", 30, "server", daily_cap=150),+ # The person, inside the Verse.+ XpRule("daily_visit", "person", 25, "world", once_per_ref=True),+ XpRule("floor_discovered", "person", 20, "world", once_per_ref=True),+ XpRule("dog_petted", "person", 3, "world", cooldown_s=60, daily_cap=30),+ XpRule("dog_treat", "person", 10, "world", cooldown_s=300, daily_cap=30),+ XpRule("arcade_round", "person", 8, "world", cooldown_s=45, daily_cap=80),+ XpRule("arcade_record", "person", 15, "world", cooldown_s=45, daily_cap=60),+ XpRule("team_meeting", "person", 10, "world", cooldown_s=600, daily_cap=40),+ # Agents: finished work is what counts.+ XpRule("task_done", "agent", 40, "server"),+ XpRule("task_blocked", "agent", 8, "server", daily_cap=40),+ XpRule("quest_done", "agent", 60, "server"),+ XpRule("answered_teammate", "agent", 5, "server", daily_cap=50),+ # The pet is Jarvis: every answer and every hand-off it makes, and the+ # walks it takes beside the person.+ XpRule("jarvis_answered", "pet", 4, "server", daily_cap=120),+ XpRule("delegated", "pet", 10, "server", daily_cap=100),+ XpRule("walk_together", "pet", 3, "world", cooldown_s=20, daily_cap=60),+)++RULES_BY_SOURCE: Final[dict[str, XpRule]] = {rule.source: rule for rule in RULES}++#: Sources the client may report through ``POST /api/progression/actions``.+WORLD_ACTIONS: Final[frozenset[str]] = frozenset(r.source for r in RULES if r.trigger == "world")+++# ------------------------------------------------------------------ rewards++Slot = Literal["frame", "trail", "aura", "gadget"]+SLOTS: Final[tuple[Slot, ...]] = ("frame", "trail", "aura", "gadget")+++@dataclass(frozen=True, slots=True)+class Reward:+ reward_id: str+ slot: Slot+ #: The level each subject kind unlocks it at; ``None`` = not for that kind.+ person: int | None+ agent: int | None+ pet: int | None++ def level_for(self, kind: SubjectKind) -> int | None:+ return {"person": self.person, "agent": self.agent, "pet": self.pet}[kind]+++REWARDS: Final[tuple[Reward, ...]] = (+ Reward("frame_bronze", "frame", person=3, agent=3, pet=3),+ Reward("frame_silver", "frame", person=10, agent=10, pet=10),+ Reward("frame_gold", "frame", person=20, agent=20, pet=20),+ Reward("frame_diamond", "frame", person=50, agent=40, pet=40),+ Reward("trail_footprints", "trail", person=2, agent=None, pet=None),+ Reward("trail_sparkle", "trail", person=5, agent=5, pet=2),+ Reward("trail_comet", "trail", person=12, agent=15, pet=12),+ Reward("trail_neon", "trail", person=20, agent=25, pet=None),+ Reward("trail_rainbow", "trail", person=30, agent=35, pet=25),+ Reward("trail_stardust", "trail", person=45, agent=None, pet=35),+ Reward("aura_glow", "aura", person=7, agent=8, pet=5),+ Reward("aura_runes", "aura", person=15, agent=18, pet=15),+ Reward("aura_storm", "aura", person=35, agent=30, pet=None),+ Reward("aura_legend", "aura", person=50, agent=50, pet=50),+ Reward("gadget_drone", "gadget", person=10, agent=12, pet=None),+ Reward("gadget_halo", "gadget", person=18, agent=20, pet=8),+ Reward("gadget_crown", "gadget", person=25, agent=None, pet=20),+ Reward("gadget_wings", "gadget", person=40, agent=45, pet=None),+)+++def unlocked_rewards(kind: SubjectKind, level: int) -> list[Reward]:+ return [r for r in REWARDS if (at := r.level_for(kind)) is not None and level >= at]+++def rewards_between(kind: SubjectKind, before: int, after: int) -> list[Reward]:+ """Rewards newly unlocked when a subject climbs from ``before`` to ``after``."""+ return [+ r for r in REWARDS+ if (at := r.level_for(kind)) is not None and before < at <= after+ ]+++# ------------------------------------------------------------------ titles++#: Title bands per kind: (first level of the band, title id). The frontend+#: translates ``society.level.title.<id>``.+TITLES: Final[dict[SubjectKind, tuple[tuple[int, str], ...]]] = {+ "person": (+ (1, "newcomer"), (5, "apprentice"), (10, "operator"), (15, "specialist"),+ (20, "strategist"), (25, "architect"), (30, "commander"), (40, "visionary"),+ (50, "legend"),+ ),+ "agent": (+ (1, "rookie"), (5, "trainee"), (10, "associate"), (15, "professional"),+ (20, "expert"), (30, "veteran"), (40, "elite"), (50, "grandmaster"),+ ),+ "pet": (+ (1, "hatchling"), (5, "buddy"), (10, "sidekick"), (20, "partner"),+ (30, "guardian"), (40, "champion"), (50, "mythic"),+ ),+}+++def title_for(kind: SubjectKind, level: int) -> str:+ title = TITLES[kind][0][1]+ for start, name in TITLES[kind]:+ if level >= start:+ title = name+ return title+++def subject_kind(subject_id: str) -> SubjectKind | None:+ if subject_id == PERSON_ID:+ return "person"+ prefix, sep, rest = subject_id.partition(":")+ if not sep or not rest:+ return None+ if prefix == "agent":+ return "agent"+ if prefix == "pet":+ return "pet"+ return None+++def agent_subject(agent_id: str) -> str:+ return f"agent:{agent_id}"+++def pet_subject(pet_id: str) -> str:+ return f"pet:{pet_id}"diff --git a/jarvis/progression/service.py b/jarvis/progression/service.pynew file mode 100644index 0000000000..5ef54a5bcb--- /dev/null+++ b/jarvis/progression/service.py@@ -0,0 +1,265 @@+"""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 Jarvis turn, a finished agent task,+a completed quest) and maps each to one or two rules of+:mod:`jarvis.progression.rules`. The Verse reports its own small world+actions (petting the dog, an arcade round) through+:meth:`ProgressionService.report_action`; the server still applies every+cooldown and cap, so a client can never award itself XP.++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 logging+from collections.abc import Callable+from datetime import datetime+from pathlib import Path+from typing import Any++from .rules import (+ LEAD_AGENT_ID,+ PERSON_ID,+ RULES_BY_SOURCE,+ WORLD_ACTIONS,+ agent_subject,+ pet_subject,+ progress_for_xp,+ rewards_between,+ subject_kind,+ title_for,+)+from .store import Award, ProgressionStore++log = logging.getLogger(__name__)++#: The floors of the Verse a ``floor_discovered`` report may name.+VERSE_FLOORS = frozenset({"agents", "coding", "arcade"})+++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.store = ProgressionStore(db_path, clock=clock)+ 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 jarvis.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.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 jarvis.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)+ )+ 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,+ )+ )+ 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 inside the Verse, reported by the client."""+ if action not in WORLD_ACTIONS:+ raise UnknownAction(action)+ rule = RULES_BY_SOURCE[action]+ if action == "daily_visit":+ # The server's own calendar day, whatever the client sent.+ ref = datetime.now().astimezone().date().isoformat()+ elif action == "floor_discovered":+ if ref not in VERSE_FLOORS:+ raise UnknownAction(f"floor_discovered:{ref}")+ 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}"))++ # ------------------------------------------------------------ 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+ source = "task_done" if getattr(event, "status", "") == "done" else "task_blocked"+ self._later((agent_subject(agent_id), source, str(getattr(event, "event_id", ""))))++ 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 "")+ 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 rowsdiff --git a/jarvis/progression/store.py b/jarvis/progression/store.pynew file mode 100644index 0000000000..c66aa62a9f--- /dev/null+++ b/jarvis/progression/store.py@@ -0,0 +1,247 @@+"""SQLite ledger of every XP award and the running total per subject.++One small database (``<data_dir>/progression.db``) opened on first use, never+on the boot path (AP-26). Every award is one transaction that checks the+rule's limits against the ledger itself — duplicate reference, cooldown,+daily cap — so a replayed bus event or a client that reports twice can never+pay twice. All calls are synchronous; the service runs them off the event+loop.+"""++from __future__ import annotations++import sqlite3+import threading+import time+from collections.abc import Callable+from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+from typing import Any++from .rules import SUBJECT_KINDS, XpRule, level_for_xp, subject_kind++_SCHEMA = f"""+CREATE TABLE IF NOT EXISTS progression_subjects (+ subject_id TEXT PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ({", ".join(repr(k) for k in SUBJECT_KINDS)})),+ xp INTEGER NOT NULL DEFAULT 0,+ level INTEGER NOT NULL DEFAULT 1,+ updated_ms INTEGER NOT NULL+);+CREATE TABLE IF NOT EXISTS progression_awards (+ seq INTEGER PRIMARY KEY AUTOINCREMENT,+ subject_id TEXT NOT NULL,+ source TEXT NOT NULL,+ xp INTEGER NOT NULL,+ level_before INTEGER NOT NULL,+ level_after INTEGER NOT NULL,+ ref TEXT NOT NULL DEFAULT '',+ ts_ms INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_progression_awards_subject+ ON progression_awards (subject_id, source, ts_ms);+CREATE UNIQUE INDEX IF NOT EXISTS uq_progression_awards_ref+ ON progression_awards (subject_id, source, ref) WHERE ref <> '';+"""+++@dataclass(frozen=True, slots=True)+class Award:+ seq: int+ subject_id: str+ kind: str+ source: str+ xp: int+ total_xp: int+ level_before: int+ level_after: int+ ref: str+ ts_ms: int++ @property+ def leveled_up(self) -> bool:+ return self.level_after > self.level_before++ def to_dict(self) -> dict[str, Any]:+ return {+ "seq": self.seq,+ "subject_id": self.subject_id,+ "kind": self.kind,+ "source": self.source,+ "xp": self.xp,+ "total_xp": self.total_xp,+ "level_before": self.level_before,+ "level_after": self.level_after,+ "ref": self.ref,+ "ts_ms": self.ts_ms,+ }+++def _local_day_start_ms(now_ms: int) -> int:+ """Midnight of the machine's local day containing ``now_ms``."""+ local = datetime.fromtimestamp(now_ms / 1000).astimezone()+ midnight = local.replace(hour=0, minute=0, second=0, microsecond=0)+ return int(midnight.timestamp() * 1000)+++class ProgressionStore:+ def __init__(self, path: Path, *, clock: Callable[[], int] | None = None) -> None:+ self._path = Path(path)+ self._clock = clock or (lambda: int(time.time() * 1000))+ self._conn: sqlite3.Connection | None = None+ self._lock = threading.Lock()++ @property+ def path(self) -> Path:+ return self._path++ def _connection(self) -> sqlite3.Connection:+ if self._conn is None:+ self._path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(+ self._path, isolation_level=None, check_same_thread=False, timeout=5.0+ )+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA journal_mode=WAL")+ conn.executescript(_SCHEMA)+ self._conn = conn+ return self._conn++ def close(self) -> None:+ with self._lock:+ if self._conn is not None:+ self._conn.close()+ self._conn = None++ # ------------------------------------------------------------ writes++ def award(self, subject_id: str, rule: XpRule, *, ref: str = "") -> Award | None:+ """Pay ``rule`` to ``subject_id`` unless one of its limits says no.++ Returns the stored award, or ``None`` when the reference was already+ paid, the cooldown is still running or the day's cap is spent. A cap+ that has a little room left pays only that remainder.+ """+ kind = subject_kind(subject_id)+ if kind is None or kind != rule.kind:+ raise ValueError(f"rule {rule.source!r} does not pay subject {subject_id!r}")+ ref = (ref or "")[:200]+ now = self._clock()+ with self._lock:+ conn = self._connection()+ conn.execute("BEGIN IMMEDIATE")+ try:+ result = self._award_locked(conn, subject_id, kind, rule, ref, now)+ except Exception:+ conn.execute("ROLLBACK")+ raise+ conn.execute("COMMIT")+ return result++ def _award_locked(+ self,+ conn: sqlite3.Connection,+ subject_id: str,+ kind: str,+ rule: XpRule,+ ref: str,+ now: int,+ ) -> Award | None:+ if ref:+ # once_per_ref rules key their reference alone; others repeat it at most once too.+ dup = conn.execute(+ "SELECT 1 FROM progression_awards WHERE subject_id = ? AND source = ? AND ref = ?",+ (subject_id, rule.source, ref),+ ).fetchone()+ if dup is not None:+ return None+ if rule.cooldown_s > 0:+ row = conn.execute(+ "SELECT MAX(ts_ms) FROM progression_awards WHERE subject_id = ? AND source = ?",+ (subject_id, rule.source),+ ).fetchone()+ last = row[0] if row is not None else None+ if last is not None and now - int(last) < rule.cooldown_s * 1000:+ return None+ xp = rule.xp+ if rule.daily_cap > 0:+ row = conn.execute(+ "SELECT COALESCE(SUM(xp), 0) FROM progression_awards"+ " WHERE subject_id = ? AND source = ? AND ts_ms >= ?",+ (subject_id, rule.source, _local_day_start_ms(now)),+ ).fetchone()+ xp = min(xp, rule.daily_cap - int(row[0] if row else 0))+ if xp <= 0:+ return None+ current = conn.execute(+ "SELECT xp, level FROM progression_subjects WHERE subject_id = ?", (subject_id,)+ ).fetchone()+ before_xp = int(current["xp"]) if current else 0+ level_before = int(current["level"]) if current else 1+ total = before_xp + xp+ level_after = level_for_xp(total)+ conn.execute(+ """+ INSERT INTO progression_subjects (subject_id, kind, xp, level, updated_ms)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(subject_id) DO UPDATE SET+ xp = excluded.xp, level = excluded.level, updated_ms = excluded.updated_ms+ """,+ (subject_id, kind, total, level_after, now),+ )+ cur = conn.execute(+ """+ INSERT INTO progression_awards+ (subject_id, source, xp, level_before, level_after, ref, ts_ms)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (subject_id, rule.source, xp, level_before, level_after, ref, now),+ )+ return Award(+ seq=int(cur.lastrowid or 0),+ subject_id=subject_id,+ kind=kind,+ source=rule.source,+ xp=xp,+ total_xp=total,+ level_before=level_before,+ level_after=level_after,+ ref=ref,+ ts_ms=now,+ )++ # ------------------------------------------------------------ reads++ def subjects(self) -> list[dict[str, Any]]:+ with self._lock:+ rows = self._connection().execute(+ "SELECT subject_id, kind, xp, level, updated_ms FROM progression_subjects"+ " ORDER BY kind, subject_id"+ ).fetchall()+ return [dict(row) for row in rows]++ def recent(self, *, after_seq: int = 0, limit: int = 50) -> list[dict[str, Any]]:+ """Awards newer than ``after_seq``, oldest first (the last ``limit`` of them)."""+ limit = max(1, min(200, int(limit)))+ with self._lock:+ rows = self._connection().execute(+ """+ SELECT a.seq, a.subject_id, s.kind, a.source, a.xp, a.level_before,+ a.level_after, a.ref, a.ts_ms+ FROM progression_awards a+ JOIN progression_subjects s ON s.subject_id = a.subject_id+ WHERE a.seq > ?+ ORDER BY a.seq DESC+ LIMIT ?+ """,+ (int(after_seq), limit),+ ).fetchall()+ return [dict(row) for row in reversed(rows)]++ def latest_seq(self) -> int:+ with self._lock:+ row = self._connection().execute(+ "SELECT COALESCE(MAX(seq), 0) FROM progression_awards"+ ).fetchone()+ return int(row[0]) if row else 0diff --git a/jarvis/society/world_feed.py b/jarvis/society/world_feed.pyindex d49bd9ff5e..0802fc116d 100644--- a/jarvis/society/world_feed.py+++ b/jarvis/society/world_feed.py@@ -96,6 +96,21 @@ class WorldFeed:await self._announce(self._message_event(env))elif env.msg_type in ROOM_TYPES:await self._announce(self._room_event(env))+ elif env.msg_type is MsgType.RESULT:+ await self._announce(self._result_event(env))++ @staticmethod+ def _result_event(env: SocietyEnvelope) -> Any:+ from jarvis.core.events import SocietyResultPosted++ status = env.payload.get("status")+ return SocietyResultPosted(+ source_layer="society",+ event_id=env.event_id,+ agent_id=env.from_agent,+ status=status if isinstance(status, str) else "",+ society_trace=env.trace_id,+ )@staticmethoddef _room_of(env: SocietyEnvelope) -> str:diff --git a/jarvis/ui/web/progression_routes.py b/jarvis/ui/web/progression_routes.pynew file mode 100644index 0000000000..69073340d8--- /dev/null+++ b/jarvis/ui/web/progression_routes.py@@ -0,0 +1,101 @@+"""REST API of the Jarvis Verse level system (``jarvis/progression``).++- ``GET /api/progression`` → every subject's level, the rulebook and recent awards+- ``POST /api/progression/actions`` → report a world action from the Verse (metered server-side)++Live awards travel as ``ProgressionAwarded`` over the WebSocket; this API is+the first read and the catch-up after a reconnect.+"""++from __future__ import annotations++import asyncio+from typing import Any++from fastapi import APIRouter, HTTPException, Query, Request+from pydantic import BaseModel, Field++from jarvis.progression.rules import (+ MAX_LEVEL,+ REWARDS,+ RULES,+ TITLES,+ total_xp_for_level,+)+from jarvis.progression.service import ProgressionService, UnknownAction++router = APIRouter(prefix="/api/progression", tags=["progression"])+++def _service(request: Request) -> ProgressionService:+ service = getattr(request.app.state, "progression", None)+ if service is None:+ raise HTTPException(status_code=503, detail="Level system not available")+ return service+++def _rulebook() -> dict[str, Any]:+ return {+ "max_level": MAX_LEVEL,+ "level_xp": [total_xp_for_level(level) for level in range(1, MAX_LEVEL + 1)],+ "rules": [+ {+ "source": r.source,+ "kind": r.kind,+ "xp": r.xp,+ "trigger": r.trigger,+ "cooldown_s": r.cooldown_s,+ "daily_cap": r.daily_cap,+ }+ for r in RULES+ ],+ "rewards": [+ {+ "reward_id": r.reward_id,+ "slot": r.slot,+ "levels": {"person": r.person, "agent": r.agent, "pet": r.pet},+ }+ for r in REWARDS+ ],+ "titles": {+ kind: [{"level": lvl, "title": t} for lvl, t in bands]+ for kind, bands in TITLES.items()+ },+ }++[email protected]("", summary="Levels of the person, the pet and every agent")+async def get_progression(+ request: Request,+ after_seq: int = Query(0, ge=0, description="Only awards newer than this sequence number"),+) -> dict[str, Any]:+ service = _service(request)+ subjects, recent, latest = await asyncio.gather(+ asyncio.to_thread(service.snapshot),+ asyncio.to_thread(service.store.recent, after_seq=after_seq, limit=50),+ asyncio.to_thread(service.store.latest_seq),+ )+ return {+ "subjects": subjects,+ "pet_id": service.current_pet(),+ "recent": recent,+ "latest_seq": latest,+ **_rulebook(),+ }+++class WorldAction(BaseModel):+ action: str = Field(..., max_length=40, description="A world-action source from the rulebook")+ ref: str = Field(+ "", max_length=40, description="The action's subject, e.g. the floor discovered"+ )++[email protected]("/actions", summary="Report a small action inside the Jarvis Verse")+async def post_action(body: WorldAction, request: Request) -> dict[str, Any]:+ service = _service(request)+ try:+ award = await service.report_action(body.action, ref=body.ref)+ except UnknownAction as exc:+ raise HTTPException(status_code=422, detail=f"unknown action: {exc}") from exc+ return {"awarded": award.to_dict() if award is not None else None}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex ce6d3e15ef..fe4ee678af 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -739,6 +739,23 @@ class WebServer:app.include_router(browser_profile_router)app.include_router(society_figure_router)app.include_router(drop_router)+ # The Jarvis Verse level system (jarvis/progression): a bus listener+ # that pays XP for real achievements. Constructing it opens nothing;+ # start() subscribes it and the ledger opens on the first award.+ from jarvis.progression import ProgressionService++ from .progression_routes import router as progression_router++ progression_data_dir = Path(+ getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data"+ )+ self._progression = ProgressionService(+ progression_data_dir / "progression.db",+ bus=self.bus,+ pet_id=lambda: str(getattr(getattr(self.cfg, "ui", None), "pet_id", "") or ""),+ )+ app.state.progression = self._progression+ app.include_router(progression_router)# Default: no recorder wired up — _init_session_stack() in start()# sets this once it succeeds.app.state.session_store = None@@ -2929,6 +2946,14 @@ class WebServer:except Exception as exc: # noqa: BLE001logger.opt(exception=exc).warning("AchievementEvaluator.attach() failed")+ # Level system on the bus: pays XP for finished turns, tasks and quests.+ progression = getattr(self, "_progression", None)+ if progression is not None:+ try:+ progression.attach()+ except Exception as exc: # noqa: BLE001 - levels are optional, the app is not+ logger.opt(exception=exc).warning("ProgressionService.attach() failed")+# Bio scheduler — subscribes to achievement unlocks only. It starts no# task and generates nothing here; the brain is resolved per# generation, when a board event actually asks for one.@@ -4058,6 +4083,12 @@ class WebServer:await self._bio_scheduler.stop()except Exception as exc: # noqa: BLE001logger.opt(exception=exc).debug("BioScheduler.stop(): {}", exc)+ progression = getattr(self, "_progression", None)+ if progression is not None:+ try:+ progression.close()+ except Exception as exc: # noqa: BLE001+ logger.opt(exception=exc).debug("ProgressionService.close(): {}", exc)if self._board_evaluator is not None:try:self._board_evaluator.close()diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 349d67949f..89b9490a7c 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -307,6 +307,10 @@ async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Any)except RosterError as exc:raise _typed_error(exc) from exc+ progression = getattr(request.app.state, "progression", None)+ if created and progression is not None:+ # Growing the team levels the person up (jarvis/progression).+ await progression.note_agent_hired(agent.agent_id)return {"agent": agent.to_dict(),"created": created,diff --git a/tests/unit/progression/__init__.py b/tests/unit/progression/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/progression/test_routes.py b/tests/unit/progression/test_routes.pynew file mode 100644index 0000000000..563c4311fb--- /dev/null+++ b/tests/unit/progression/test_routes.py@@ -0,0 +1,64 @@+"""``/api/progression``: one read for the Verse, one metered write for world actions."""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.progression.rules import MAX_LEVEL, REWARDS, RULES+from jarvis.progression.service import ProgressionService+from jarvis.ui.web.progression_routes import router+++def client(tmp_path: Path):+ app = FastAPI()+ app.include_router(router)+ service = ProgressionService(tmp_path / "progression.db", pet_id=lambda: "miso")+ app.state.progression = service+ with TestClient(app) as test_client:+ yield test_client+ service.close()+++def test_the_first_read_carries_the_whole_rulebook(client: TestClient):+ body = client.get("/api/progression").json()+ assert body["subjects"] == []+ assert body["pet_id"] == "miso"+ assert body["max_level"] == MAX_LEVEL+ assert len(body["level_xp"]) == MAX_LEVEL and body["level_xp"][0] == 0+ assert {r["source"] for r in body["rules"]} == {r.source for r in RULES}+ assert {r["reward_id"] for r in body["rewards"]} == {r.reward_id for r in REWARDS}+ assert body["titles"]["person"][0] == {"level": 1, "title": "newcomer"}+++def test_a_world_action_pays_and_shows_up_in_the_next_read(client: TestClient):+ action = {"action": "floor_discovered", "ref": "arcade"}+ paid = client.post("/api/progression/actions", json=action)+ assert paid.status_code == 200+ award = paid.json()["awarded"]+ assert (award["subject_id"], award["xp"]) == ("person", 20)+ again = client.post("/api/progression/actions", json=action)+ assert again.json() == {"awarded": None}++ body = client.get("/api/progression").json()+ assert body["subjects"][0]["subject_id"] == "person"+ assert body["subjects"][0]["xp_into_level"] == 20+ assert body["subjects"][0]["xp_for_next"] == 40+ assert body["latest_seq"] == award["seq"]+ assert client.get(f"/api/progression?after_seq={award['seq']}").json()["recent"] == []+++def test_server_only_and_unknown_actions_are_refused(client: TestClient):+ for action in ("chat_turn", "level_up_now"):+ assert client.post("/api/progression/actions", json={"action": action}).status_code == 422+++def test_without_the_service_the_api_says_unavailable():+ app = FastAPI()+ app.include_router(router)+ with TestClient(app) as test_client:+ assert test_client.get("/api/progression").status_code == 503diff --git a/tests/unit/progression/test_rules.py b/tests/unit/progression/test_rules.pynew file mode 100644index 0000000000..2883b35acf--- /dev/null+++ b/tests/unit/progression/test_rules.py@@ -0,0 +1,105 @@+"""The rulebook of the Jarvis Verse level system is consistent and well paced."""++from __future__ import annotations++from jarvis.progression.rules import (+ MAX_LEVEL,+ REWARDS,+ RULES,+ SLOTS,+ SUBJECT_KINDS,+ TITLES,+ WORLD_ACTIONS,+ level_for_xp,+ progress_for_xp,+ rewards_between,+ subject_kind,+ title_for,+ total_xp_for_level,+ unlocked_rewards,+ xp_to_next,+)+++def test_the_first_level_comes_after_a_handful_of_actions():+ assert xp_to_next(1) == 40+ assert level_for_xp(0) == 1+ assert level_for_xp(39) == 1+ assert level_for_xp(40) == 2+++def test_every_step_costs_more_than_the_one_before_and_reads_in_fives():+ steps = [xp_to_next(level) for level in range(1, MAX_LEVEL)]+ assert all(step % 5 == 0 for step in steps)+ assert all(later > earlier for earlier, later in zip(steps, steps[1:], strict=False))+ assert xp_to_next(MAX_LEVEL) == 0+++def test_pacing_matches_the_design_targets():+ # ~200 XP on an ordinary day: level 10 inside two weeks, the cap after months.+ assert total_xp_for_level(10) < 200 * 14+ assert 200 * 120 < total_xp_for_level(MAX_LEVEL) < 200 * 365+++def test_level_and_progress_round_trip_at_every_boundary():+ for level in range(1, MAX_LEVEL + 1):+ start = total_xp_for_level(level)+ assert level_for_xp(start) == level+ progress = progress_for_xp(start)+ assert (progress.level, progress.into_level) == (level, 0)+ if level > 1:+ assert level_for_xp(start - 1) == level - 1+ capped = progress_for_xp(total_xp_for_level(MAX_LEVEL) + 10_000)+ assert capped.level == MAX_LEVEL and capped.for_next == 0+++def test_rules_have_unique_sources_and_pay_a_known_kind():+ sources = [rule.source for rule in RULES]+ assert len(sources) == len(set(sources))+ for rule in RULES:+ assert rule.kind in SUBJECT_KINDS+ assert rule.xp > 0+ assert rule.trigger in ("server", "world")+ # A world action is reported by the client: it must be metered.+ if rule.trigger == "world":+ assert rule.cooldown_s > 0 or rule.once_per_ref, rule.source+ assert "daily_visit" in WORLD_ACTIONS and "chat_turn" not in WORLD_ACTIONS+++def test_rewards_are_unique_and_every_kind_gets_one_per_slot_family():+ ids = [reward.reward_id for reward in REWARDS]+ assert len(ids) == len(set(ids))+ for reward in REWARDS:+ assert reward.slot in SLOTS+ assert reward.reward_id.startswith(reward.slot + "_")+ for kind in SUBJECT_KINDS:+ level = reward.level_for(kind)+ assert level is None or 2 <= level <= MAX_LEVEL+ for kind in SUBJECT_KINDS:+ slots = {r.slot for r in unlocked_rewards(kind, MAX_LEVEL)}+ assert {"frame", "trail", "aura"} <= slots+++def test_rewards_between_names_only_what_the_climb_crossed():+ assert [r.reward_id for r in rewards_between("person", 1, 2)] == ["trail_footprints"]+ at_ten = {r.reward_id for r in rewards_between("person", 9, 10)}+ assert at_ten == {"frame_silver", "gadget_drone"}+ assert rewards_between("person", 10, 10) == []+++def test_titles_start_at_level_one_and_climb():+ for kind in SUBJECT_KINDS:+ bands = TITLES[kind]+ assert bands[0][0] == 1+ assert [lvl for lvl, _ in bands] == sorted(lvl for lvl, _ in bands)+ assert title_for("person", 1) == "newcomer"+ assert title_for("person", 12) == "operator"+ assert title_for("pet", MAX_LEVEL) == "mythic"+++def test_subject_ids_name_their_kind():+ assert subject_kind("person") == "person"+ assert subject_kind("agent:scout") == "agent"+ assert subject_kind("pet:ember") == "pet"+ assert subject_kind("pet:") is None+ assert subject_kind("robot:x") is Nonediff --git a/tests/unit/progression/test_service.py b/tests/unit/progression/test_service.pynew file mode 100644index 0000000000..3d3f17a4d7--- /dev/null+++ b/tests/unit/progression/test_service.py@@ -0,0 +1,221 @@+"""Real app events pay XP exactly once, within every limit, and announce it."""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import (+ JarvisChatTurnFinished,+ MissionCompleted,+ ProgressionAwarded,+ SocietyMessageSent,+ SocietyQuestChanged,+ SocietyResultPosted,+ VoiceTurnCompleted,+)+from jarvis.progression.rules import RULES_BY_SOURCE+from jarvis.progression.service import ProgressionService, UnknownAction+from jarvis.progression.store import ProgressionStore+++class Clock:+ """A settable millisecond clock, so cooldowns and days are deterministic."""++ def __init__(self, start_ms: int = 1_790_000_000_000) -> None:+ self.now = start_ms++ def __call__(self) -> int:+ return self.now+++def clock() -> Clock:+ return Clock()+++async def setup(tmp_path: Path, clock: Clock):+ bus = EventBus()+ seen: list[ProgressionAwarded] = []++ async def record(event: ProgressionAwarded) -> None:+ seen.append(event)++ bus.subscribe(ProgressionAwarded, record)+ pet = {"id": "ember"}+ service = ProgressionService(+ tmp_path / "progression.db", bus=bus, pet_id=lambda: pet["id"], clock=clock+ )+ service.attach()+ try:+ yield service, bus, seen, pet+ finally:+ service.close()+++def _levels(service: ProgressionService) -> dict[str, tuple[int, int]]:+ return {row["subject_id"]: (row["xp"], row["level"]) for row in service.snapshot()}+++async def test_a_finished_jarvis_chat_turn_pays_the_person_and_the_pet(setup):+ service, bus, seen, _ = setup+ await bus.publish(JarvisChatTurnFinished(session_id="s1", turn_id="t1", status="done"))+ await service.drain()+ assert _levels(service) == {"person": (5, 1), "pet:ember": (4, 1)}+ assert {(e.subject_id, e.xp_source, e.xp) for e in seen} == {+ ("person", "chat_turn", 5),+ ("pet:ember", "jarvis_answered", 4),+ }+++async def test_the_same_turn_twice_pays_once_and_an_error_turn_never(setup):+ service, bus, _, _ = setup+ for _ in range(2):+ await bus.publish(JarvisChatTurnFinished(session_id="s1", turn_id="t1"))+ await bus.publish(JarvisChatTurnFinished(session_id="s1", turn_id="t2", status="error"))+ await service.drain()+ assert _levels(service)["person"] == (5, 1)+++async def test_voice_turns_pay_too(setup):+ service, bus, _, _ = setup+ await bus.publish(VoiceTurnCompleted(session_id="v", turn_id="1"))+ await bus.publish(VoiceTurnCompleted(session_id="v", turn_id="2"))+ await service.drain()+ assert _levels(service)["person"] == (10, 1)+++async def test_the_daily_cap_stops_paying_and_a_new_day_pays_again(setup, clock):+ service, bus, _, _ = setup+ cap = RULES_BY_SOURCE["chat_turn"].daily_cap+ for turn in range(cap // 5 + 5):+ await bus.publish(JarvisChatTurnFinished(session_id="s", turn_id=str(turn)))+ await service.drain()+ assert _levels(service)["person"][0] == cap+ clock.now += 24 * 3600 * 1000+ await bus.publish(JarvisChatTurnFinished(session_id="s", turn_id="tomorrow"))+ await service.drain()+ assert _levels(service)["person"][0] == cap + 5+++async def test_agents_level_from_finished_work_and_quests(setup):+ service, bus, seen, _ = setup+ await bus.publish(SocietyResultPosted(event_id="e1", agent_id="scout", status="done"))+ await bus.publish(SocietyResultPosted(event_id="e2", agent_id="scout", status="blocked"))+ await bus.publish(SocietyQuestChanged(quest_id="q1", state="open", previous=""))+ await bus.publish(+ SocietyQuestChanged(quest_id="q1", state="done", previous="running", agent_id="scout")+ )+ await service.drain()+ levels = _levels(service)+ assert levels["agent:scout"] == (40 + 8 + 60, 3)+ assert levels["person"] == (15 + 20, 1)+ up = [e for e in seen if e.subject_id == "agent:scout" and e.level > e.previous_level]+ assert up and up[-1].level == 3+ assert "frame_bronze" in up[-1].unlocked+++async def test_the_lead_is_the_pet_never_an_agent(setup):+ service, bus, _, _ = setup+ await bus.publish(SocietyResultPosted(event_id="e1", agent_id="jarvis", status="done"))+ await bus.publish(+ SocietyMessageSent(event_id="m1", msg_type="ASSIGN", from_agent="jarvis", to_agent="scout")+ )+ await bus.publish(+ SocietyMessageSent(event_id="m2", msg_type="ANSWER", from_agent="scout", to_agent="jarvis")+ )+ await service.drain()+ levels = _levels(service)+ assert "agent:jarvis" not in levels+ assert levels["pet:ember"] == (10, 1)+ assert levels["agent:scout"] == (5, 1)+++async def test_the_active_pet_earns_and_each_pet_keeps_its_own_level(setup):+ service, bus, _, pet = setup+ await bus.publish(JarvisChatTurnFinished(session_id="s", turn_id="a"))+ pet["id"] = "miso"+ await bus.publish(JarvisChatTurnFinished(session_id="s", turn_id="b"))+ pet["id"] = "none"+ await bus.publish(JarvisChatTurnFinished(session_id="s", turn_id="c"))+ await service.drain()+ levels = _levels(service)+ assert levels["pet:ember"] == (4, 1)+ assert levels["pet:miso"] == (4, 1)+ assert levels["pet:gigi"] == (4, 1)+++async def test_only_approved_missions_pay(setup):+ service, bus, _, _ = setup+ await bus.publish(MissionCompleted(mission_id="m1", status="failed"))+ await bus.publish(MissionCompleted(mission_id="m2", status="approved"))+ await service.drain()+ assert _levels(service)["person"] == (30, 1)+++async def test_a_hired_agent_pays_the_person_once(setup):+ service, _, _, _ = setup+ await service.note_agent_hired("scout")+ await service.note_agent_hired("scout")+ await service.note_agent_hired("jarvis")+ await service.drain()+ assert _levels(service)["person"] == (50, 2)+++async def test_world_actions_are_metered_on_the_server(setup, clock):+ service, _, _, _ = setup+ assert await service.report_action("dog_petted") is not None+ assert await service.report_action("dog_petted") is None # cooldown+ clock.now += 61_000+ assert await service.report_action("dog_petted") is not None+ assert await service.report_action("daily_visit", ref="anything") is not None+ assert await service.report_action("daily_visit") is None # once per day+ assert await service.report_action("floor_discovered", ref="arcade") is not None+ assert await service.report_action("floor_discovered", ref="arcade") is None+ walked = await service.report_action("walk_together")+ assert walked is not None and walked.subject_id == "pet:ember"+++async def test_unknown_or_server_only_actions_are_refused(setup):+ service, _, _, _ = setup+ for action, ref in (("chat_turn", ""), ("cheat", ""), ("floor_discovered", "roof")):+ with pytest.raises(UnknownAction):+ await service.report_action(action, ref=ref)+++def test_the_store_refuses_a_rule_for_the_wrong_kind(tmp_path: Path):+ store = ProgressionStore(tmp_path / "p.db")+ with pytest.raises(ValueError):+ store.award("agent:scout", RULES_BY_SOURCE["chat_turn"])+ store.close()+++def test_recent_awards_come_oldest_first_after_a_sequence(tmp_path: Path):+ store = ProgressionStore(tmp_path / "p.db")+ rule = RULES_BY_SOURCE["task_done"]+ first = store.award("agent:a", rule, ref="1")+ store.award("agent:a", rule, ref="2")+ assert first is not None+ rows = store.recent(after_seq=first.seq)+ assert [row["ref"] for row in rows] == ["2"]+ assert rows[0]["kind"] == "agent"+ assert store.latest_seq() == first.seq + 1+ store.close()+++async def test_a_broken_bus_never_loses_the_award(tmp_path: Path, clock: Clock):+ class BrokenBus:+ def subscribe(self, *_: Any) -> None:+ return None++ async def publish(self, _: Any) -> None:+ raise RuntimeError("bus down")++ service = ProgressionService(tmp_path / "p.db", bus=BrokenBus(), clock=clock)+ award = await service.award("person", "agent_hired", ref="x")+ assert award is not None and award.xp == 50+ service.close()diff --git a/tests/unit/society/test_world_feed.py b/tests/unit/society/test_world_feed.pyindex 0a81d79842..cf71fc75db 100644--- a/tests/unit/society/test_world_feed.py+++ b/tests/unit/society/test_world_feed.py@@ -218,3 +218,16 @@ def test_the_typescript_half_lists_the_same_types():def test_the_relay_is_wired_into_the_runtime(tmp_path: Path):runtime = SocietyRuntime(tmp_path, seed_starter_team=False)assert isinstance(runtime.world_feed, WorldFeed)+++async def test_a_result_reaches_the_app_bus_without_its_text(rt):+ from jarvis.core.events import SocietyResultPosted++ runtime, pushed = rt+ await runtime.say(+ from_agent="scout", to_agent="archivist", text="secret body", msg_type=MsgType.RESULT+ )+ results = [e for e in pushed if isinstance(e, SocietyResultPosted)]+ assert len(results) == 1+ assert results[0].agent_id == "scout"+ assert "secret" not in repr(results[0])