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(society): substrate — typed envelopes, society.db store, roster (M1 waves 1-2)
rubenluetke10-beep98544ff01855
diff --git a/jarvis/society/__init__.py b/jarvis/society/__init__.pynew file mode 100644index 0000000000..5d72cd0ede--- /dev/null+++ b/jarvis/society/__init__.py@@ -0,0 +1,28 @@+"""Agent Society — durable named agents that message each other under Jarvis.++The package is the substrate described in ``docs/agent-society/MASTERPLAN.md``+(§3) and ``docs/agent-society/agent-definition.md``:++* ``events`` the typed envelope and every enum that crosses layers+* ``failure_reasons`` the typed vocabulary every refusal and error speaks+* ``store`` ``society.db`` — roster, append-only event log, rooms,+ knowledge staging, approvals, meta (persist-before-publish)+* ``bus`` in-process fan-out of stored envelopes+* ``roster`` agent records with validation (adopt-before-mint by name)+* ``capabilities`` ONE catalog over plugins, CLIs, MCP servers, skills, core+* ``focus`` deterministic "what this agent reaches for first"+* ``rooms`` bounded group discussions (2–6 members, ≤3 rounds, ≤10 msgs)+* ``scheduler`` trusted Python: tier wall, depth, budget, caps, kill switch+* ``bridge`` mission envelopes → society events (one world feed)+* ``runtime`` lazy singleton wiring the above; nothing runs at boot++Nothing in this package is imported on the boot critical path (AP-26): the+runtime is built on the first REST call or chat binding. Only+``ToolExecutor.execute()`` ever turns an agent's intent into an action (AP-3),+and no spawn-capable tool exists in any society tool set (AP-5/AP-14) — dispatch+is the scheduler's privilege.+"""++from __future__ import annotations++__all__: list[str] = []diff --git a/jarvis/society/bus.py b/jarvis/society/bus.pynew file mode 100644index 0000000000..0b01e5fbde--- /dev/null+++ b/jarvis/society/bus.py@@ -0,0 +1,72 @@+"""In-process fan-out of stored society envelopes.++The store publishes AFTER the row is on disk (persist-before-publish); the bus+only delivers. Subscribers are observers — a wedged one is abandoned after a+hard timeout and can never block an append (the AP-18 rule of the core bus),+and an exception inside a subscriber is logged, never propagated.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable+from typing import Final++from .events import SocietyEnvelope++log = logging.getLogger(__name__)++__all__ = ["SocietyBus", "SocietyHandler"]++SocietyHandler = Callable[[SocietyEnvelope], Awaitable[None]]++_HANDLER_TIMEOUT_S: Final[float] = 5.0+++class SocietyBus:+ def __init__(self) -> None:+ self._handlers: list[SocietyHandler] = []++ def subscribe_all(self, handler: SocietyHandler) -> Callable[[], None]:+ """Register ``handler`` for every envelope; returns its unsubscribe."""+ self._handlers.append(handler)++ def _unsubscribe() -> None:+ if handler in self._handlers:+ self._handlers.remove(handler)++ return _unsubscribe++ @property+ def active_subs(self) -> int:+ return len(self._handlers)++ async def publish(self, envelope: SocietyEnvelope) -> None:+ handlers = list(self._handlers)+ if not handlers:+ return+ await asyncio.gather(+ *(self._safe_dispatch(h, envelope) for h in handlers), return_exceptions=True+ )++ @staticmethod+ async def _safe_dispatch(handler: SocietyHandler, envelope: SocietyEnvelope) -> None:+ try:+ await asyncio.wait_for(handler(envelope), timeout=_HANDLER_TIMEOUT_S)+ except TimeoutError:+ log.warning(+ "society bus: subscriber %s timed out (>%ss) on %s seq=%s and was abandoned",+ getattr(handler, "__qualname__", repr(handler)),+ _HANDLER_TIMEOUT_S,+ envelope.msg_type,+ envelope.seq,+ )+ except Exception: # noqa: BLE001 — an observer must never break the append path+ log.warning(+ "society bus: subscriber %s failed on %s seq=%s",+ getattr(handler, "__qualname__", repr(handler)),+ envelope.msg_type,+ envelope.seq,+ exc_info=True,+ )diff --git a/jarvis/society/events.py b/jarvis/society/events.pynew file mode 100644index 0000000000..7e615da853--- /dev/null+++ b/jarvis/society/events.py@@ -0,0 +1,166 @@+"""The society's typed envelope and every enum that crosses layers.++These names cross Python → SQLite CHECK constraints → Pydantic → TypeScript+(``src/lib/societyApi.ts``) → UI, so they are pinned against each other by+``tests/unit/society/test_society_enum_parity.py`` (AP-4). Change a member+here, then follow the parity test to the other three spellings.++The message protocol (MASTERPLAN §2.1/§2.2): a compact typed event whose+payload MAY carry human-readable ``text``. Chat surfaces render the text; the+scheduler and the world act on the type.+"""++from __future__ import annotations++import time+from enum import StrEnum+from typing import Any, Final++from pydantic import BaseModel, ConfigDict, Field++from jarvis.missions.ids import uuid7_str++__all__ = [+ "AgentState",+ "ApprovalState",+ "Checkpoint",+ "GrantMode",+ "KnowledgeOrigin",+ "KnowledgeScope",+ "MsgType",+ "PermissionCeiling",+ "RoomState",+ "RunState",+ "SocietyEnvelope",+ "Tier",+ "now_ms",+]+++def now_ms() -> int:+ return int(time.time() * 1000)+++class MsgType(StrEnum):+ """The eleven coordination types plus the two room brackets."""++ ASSIGN = "ASSIGN"+ CLAIM = "CLAIM"+ RESULT = "RESULT"+ QUERY = "QUERY"+ ANSWER = "ANSWER"+ HOLD = "HOLD"+ RELEASE = "RELEASE"+ PROPOSE = "PROPOSE"+ VETO = "VETO"+ DIGEST = "DIGEST"+ SAY = "SAY"+ ROOM_OPEN = "ROOM_OPEN"+ ROOM_SETTLE = "ROOM_SETTLE"+++class Tier(StrEnum):+ LEAD = "lead"+ ORCHESTRATOR = "orchestrator"+ SPECIALIST = "specialist"+++class AgentState(StrEnum):+ """Persisted lifecycle state of a roster row."""++ ACTIVE = "active"+ PAUSED = "paused"+ ARCHIVED = "archived"+++class RunState(StrEnum):+ """Derived from the event log for rows and badges; never stored."""++ IDLE = "idle"+ WORKING = "working"+ WAITING = "waiting"+ PAUSED = "paused"+++class Checkpoint(StrEnum):+ """The semantic place in the world; the client owns the pixels (§2.7)."""++ DESK = "desk"+ MEETING = "meeting"+ ARCHIVE = "archive"+ GATE = "gate"+ IDLE = "idle"+++class PermissionCeiling(StrEnum):+ """The unattended ceiling; ``block`` never appears — block is block."""++ SAFE = "safe"+ MONITOR = "monitor"+ ASK = "ask"+++class GrantMode(StrEnum):+ ALL = "all"+ ALLOWLIST = "allowlist"+++class KnowledgeScope(StrEnum):+ SHARED = "shared"+ OWN = "own"+++class KnowledgeOrigin(StrEnum):+ USER = "user"+ TOOL = "tool"+ WEB = "web"+ AGENT = "agent"+++class RoomState(StrEnum):+ QUEUED = "queued"+ RUNNING = "running"+ SETTLED = "settled"+ FAILED = "failed"+++class ApprovalState(StrEnum):+ PENDING = "pending"+ APPROVED = "approved"+ DENIED = "denied"+ EXPIRED = "expired"+ BLOCKED = "blocked"+++#: Sender id of envelopes the trusted scheduler writes on its own behalf.+SCHEDULER_ACTOR: Final[str] = "scheduler"+#: Sender id of envelopes the person writes (typed ``@name`` in a chat, REST).+USER_ACTOR: Final[str] = "user"+++class SocietyEnvelope(BaseModel):+ """One row of the append-only board.++ ``seq`` is server-assigned by the store (``None`` until persisted).+ ``to_agent`` ``None`` means broadcast. ``payload`` is compact JSON; for+ ``RESULT`` the scheduler validates the handoff record (agent-definition+ §4.3) before it accepts the event.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ event_id: str = Field(default_factory=uuid7_str)+ seq: int | None = None+ msg_type: MsgType+ from_agent: str+ to_agent: str | None = None+ trace_id: str+ parent_event_id: str | None = None+ ts_ms: int = Field(default_factory=now_ms)+ cost_usd: float = 0.0+ payload: dict[str, Any] = Field(default_factory=dict)++ @property+ def text(self) -> str:+ value = self.payload.get("text")+ return value if isinstance(value, str) else ""diff --git a/jarvis/society/failure_reasons.py b/jarvis/society/failure_reasons.pynew file mode 100644index 0000000000..951012cad9--- /dev/null+++ b/jarvis/society/failure_reasons.py@@ -0,0 +1,166 @@+"""The typed vocabulary every society refusal, error and retry hint speaks.++A caller — the scheduler, a chat binding, the REST layer, the voice ACK path —+branches on the *code*, never on an error string. Each code carries one retry+action so a UI can say "try again later" versus "fix the key" versus "pick a+different teammate" without parsing anything.++``classify_error`` folds a provider exception (or its message) onto a code.+Precedence is deliberate: an authentication failure wins over a quota message+that mentions billing, because the fix is different ("add a key" versus "wait+or top up") and a wrong hint sends the person to the wrong screen.+"""++from __future__ import annotations++import re+from enum import StrEnum+from typing import Final++__all__ = [+ "FailureReason",+ "RetryAction",+ "classify_error",+ "retry_action",+]+++class FailureReason(StrEnum):+ """Why an action, message or dispatch did not happen."""++ # Provider / model side+ AUTH_FAILED = "auth_failed"+ PROVIDER_QUOTA_LIMIT = "provider_quota_limit"+ RATE_LIMITED = "rate_limited"+ CONTEXT_OVERFLOW = "context_overflow"+ PROVIDER_ERROR = "provider_error"+ # Target resolution (relay)+ TARGET_UNKNOWN = "target_unknown"+ TARGET_AMBIGUOUS = "target_ambiguous"+ TARGET_BUSY = "target_busy"+ TARGET_OFFLINE = "target_offline"+ TARGET_PAUSED = "target_paused"+ # Society rules (scheduler)+ TIER_NOT_ALLOWED = "tier_not_allowed"+ DEPTH_EXCEEDED = "depth_exceeded"+ BUDGET_EXHAUSTED = "budget_exhausted"+ CONCURRENCY_CAP = "concurrency_cap"+ MESSAGE_CAP = "message_cap"+ KILL_SWITCH = "kill_switch"+ BLOCKED_BY_POLICY = "blocked_by_policy"+ INVALID_RESULT = "invalid_result"+ # Everything else+ INTERNAL_ERROR = "internal_error"+++class RetryAction(StrEnum):+ """What a caller should do about a :class:`FailureReason`."""++ RETRY_LATER = "retry_later"+ FIX_CONFIG = "fix_config"+ CHOOSE_TARGET = "choose_target"+ COMPACT = "compact"+ NEVER = "never"+++_RETRY: Final[dict[FailureReason, RetryAction]] = {+ FailureReason.AUTH_FAILED: RetryAction.FIX_CONFIG,+ FailureReason.PROVIDER_QUOTA_LIMIT: RetryAction.RETRY_LATER,+ FailureReason.RATE_LIMITED: RetryAction.RETRY_LATER,+ FailureReason.CONTEXT_OVERFLOW: RetryAction.COMPACT,+ FailureReason.PROVIDER_ERROR: RetryAction.RETRY_LATER,+ FailureReason.TARGET_UNKNOWN: RetryAction.CHOOSE_TARGET,+ FailureReason.TARGET_AMBIGUOUS: RetryAction.CHOOSE_TARGET,+ FailureReason.TARGET_BUSY: RetryAction.RETRY_LATER,+ FailureReason.TARGET_OFFLINE: RetryAction.RETRY_LATER,+ FailureReason.TARGET_PAUSED: RetryAction.CHOOSE_TARGET,+ FailureReason.TIER_NOT_ALLOWED: RetryAction.NEVER,+ FailureReason.DEPTH_EXCEEDED: RetryAction.NEVER,+ FailureReason.BUDGET_EXHAUSTED: RetryAction.FIX_CONFIG,+ FailureReason.CONCURRENCY_CAP: RetryAction.RETRY_LATER,+ FailureReason.MESSAGE_CAP: RetryAction.NEVER,+ FailureReason.KILL_SWITCH: RetryAction.NEVER,+ FailureReason.BLOCKED_BY_POLICY: RetryAction.NEVER,+ FailureReason.INVALID_RESULT: RetryAction.NEVER,+ FailureReason.INTERNAL_ERROR: RetryAction.RETRY_LATER,+}+++def retry_action(reason: FailureReason | str) -> RetryAction:+ """The retry hint for ``reason``; unknown strings read as internal errors."""+ try:+ code = FailureReason(reason)+ except ValueError:+ code = FailureReason.INTERNAL_ERROR+ return _RETRY[code]+++# Ordered: the first matching group wins. Auth sits above quota on purpose —+# "invalid api key ... check your billing" is an auth problem.+_PATTERNS: Final[tuple[tuple[FailureReason, re.Pattern[str]], ...]] = (+ (+ FailureReason.AUTH_FAILED,+ re.compile(+ r"(unauthori[sz]ed|invalid[ _-]?api[ _-]?key|authentication|"+ r"forbidden|\b401\b|\b403\b|no api key|api key (is )?missing)",+ re.I,+ ),+ ),+ (+ FailureReason.PROVIDER_QUOTA_LIMIT,+ re.compile(+ r"(quota|insufficient[_ ]quota|billing|credit balance|exceeded your current|"+ r"usage limit|out of credits|payment required|\b402\b)",+ re.I,+ ),+ ),+ (+ FailureReason.RATE_LIMITED,+ re.compile(r"(rate[ _-]?limit|too many requests|\b429\b|overloaded|\b529\b)", re.I),+ ),+ (+ FailureReason.CONTEXT_OVERFLOW,+ re.compile(+ r"(context[ _-]?(window|length)|maximum context|too many tokens|"+ r"prompt is too long|input is too long|max_tokens|token limit)",+ re.I,+ ),+ ),+ (+ FailureReason.TARGET_OFFLINE,+ re.compile(r"(connection refused|not reachable|unreachable|offline|econnrefused)", re.I),+ ),+ (+ FailureReason.PROVIDER_ERROR,+ re.compile(+ r"(\b5\d\d\b|internal server error|bad gateway|service unavailable|timeout)", re.I+ ),+ ),+)+++def classify_error(error: BaseException | str | None) -> FailureReason:+ """Fold an exception or message onto a :class:`FailureReason`.++ Looks at the exception's class name and message (and its cause chain), so+ a provider SDK's ``AuthenticationError`` classifies even with an empty+ message. Anything unrecognized is :attr:`FailureReason.INTERNAL_ERROR`.+ """+ if error is None:+ return FailureReason.INTERNAL_ERROR+ parts: list[str] = []+ if isinstance(error, BaseException):+ seen: set[int] = set()+ cur: BaseException | None = error+ while cur is not None and id(cur) not in seen:+ seen.add(id(cur))+ parts.append(type(cur).__name__)+ parts.append(str(cur))+ cur = cur.__cause__ or cur.__context__+ else:+ parts.append(str(error))+ text = " ".join(parts)+ for reason, pattern in _PATTERNS:+ if pattern.search(text):+ return reason+ return FailureReason.INTERNAL_ERRORdiff --git a/jarvis/society/roster.py b/jarvis/society/roster.pynew file mode 100644index 0000000000..4d671a2129--- /dev/null+++ b/jarvis/society/roster.py@@ -0,0 +1,430 @@+"""The roster: agent records with validation on top of the store's raw rows.++Identity rules (agent-definition §2, §6):++* ``name`` is unique, case-insensitive; creating an agent with an existing+ name ADOPTS the row instead of minting a second one (adopt-before-mint) —+ the one invariant that keeps "one agent, one chat" true forever.+* ``agent_id`` is a slug derived from the name once and never changes; the+ canonical chat id is ``society:<agent_id>`` (a pure function, no column).+* Exactly one ``lead`` exists and it is Jarvis; creating another lead is+ refused with a typed reason.+"""++from __future__ import annotations++import json+import re+import unicodedata+from dataclasses import dataclass, field+from typing import Any, Final++from .events import (+ AgentState,+ Checkpoint,+ GrantMode,+ KnowledgeScope,+ PermissionCeiling,+ Tier,+ now_ms,+)+from .failure_reasons import FailureReason+from .store import SocietyStore++__all__ = [+ "AgentRecord",+ "LEAD_AGENT_ID",+ "Roster",+ "RosterError",+ "canonical_session_id",+ "slugify",+]++LEAD_AGENT_ID: Final[str] = "jarvis"++_NAME_RE: Final[re.Pattern[str]] = re.compile(r"^[^/\\:@#<>\"'`]{1,40}$")+_MAX_TITLE: Final[int] = 120+_MAX_DESCRIPTION: Final[int] = 20_000+++class RosterError(ValueError):+ """A roster rule was violated; ``reason`` is the typed code."""++ def __init__(self, reason: FailureReason, message: str) -> None:+ super().__init__(message)+ self.reason = reason+++def slugify(name: str) -> str:+ """``"Mail Bot"`` → ``"mail-bot"``; diacritics folded, never empty."""+ # Fold the sharp s before NFKD drops it (it has no decomposition).+ folded = name.replace("ß", "ss") # i18n-allow: unicode folding, not prose+ text = unicodedata.normalize("NFKD", folded).encode("ascii", "ignore").decode("ascii")+ text = re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower()+ return text or "agent"+++def canonical_session_id(agent_id: str) -> str:+ """The agent's one forever-chat on the agent_chat store."""+ return f"society:{agent_id}"+++def _loads(value: Any, default: Any) -> Any:+ if value is None:+ return default+ if isinstance(value, (list, dict)):+ return value+ try:+ return json.loads(value)+ except (TypeError, ValueError):+ return default+++@dataclass(slots=True)+class AgentRecord:+ agent_id: str+ name: str+ title: str+ description: str+ tier: Tier+ parent_agent_id: str | None+ state: AgentState+ avatar: dict[str, Any]+ checkpoint: Checkpoint+ provider: str+ model: str+ effort: str+ grant_mode: GrantMode+ grants: list[str]+ focus: list[str]+ denies: list[str]+ skills: list[str] | None+ workspace_dir: str+ wiki_namespace: str+ knowledge_scope: KnowledgeScope+ permission_ceiling: PermissionCeiling+ approval_rules: dict[str, list[str]]+ daily_budget_usd: float+ max_concurrent_runs: int+ created_ms: int+ updated_ms: int+ stats: dict[str, Any] = field(default_factory=dict)++ @property+ def session_id(self) -> str:+ return canonical_session_id(self.agent_id)++ @property+ def may_assign(self) -> bool:+ return self.tier in (Tier.LEAD, Tier.ORCHESTRATOR)++ def to_dict(self) -> dict[str, Any]:+ return {+ "agent_id": self.agent_id,+ "name": self.name,+ "title": self.title,+ "description": self.description,+ "tier": str(self.tier),+ "parent_agent_id": self.parent_agent_id,+ "state": str(self.state),+ "avatar": self.avatar,+ "checkpoint": str(self.checkpoint),+ "provider": self.provider,+ "model": self.model,+ "effort": self.effort,+ "grant_mode": str(self.grant_mode),+ "grants": list(self.grants),+ "focus": list(self.focus),+ "denies": list(self.denies),+ "skills": list(self.skills) if self.skills is not None else None,+ "workspace_dir": self.workspace_dir,+ "wiki_namespace": self.wiki_namespace,+ "knowledge_scope": str(self.knowledge_scope),+ "permission_ceiling": str(self.permission_ceiling),+ "approval_rules": {+ "require_approval": list(self.approval_rules.get("require_approval", [])),+ "always_allow": list(self.approval_rules.get("always_allow", [])),+ },+ "daily_budget_usd": self.daily_budget_usd,+ "max_concurrent_runs": self.max_concurrent_runs,+ "session_id": self.session_id,+ "created_ms": self.created_ms,+ "updated_ms": self.updated_ms,+ "stats": dict(self.stats),+ }++ @classmethod+ def from_row(cls, row: dict[str, Any]) -> AgentRecord:+ rules = _loads(row.get("approval_rules_json"), {})+ if not isinstance(rules, dict):+ rules = {}+ skills_raw = row.get("skills_json")+ skills = None if skills_raw is None else list(_loads(skills_raw, []))+ return cls(+ agent_id=str(row["agent_id"]),+ name=str(row["name"]),+ title=str(row.get("title") or ""),+ description=str(row.get("description") or ""),+ tier=Tier(str(row["tier"])),+ parent_agent_id=row.get("parent_agent_id"),+ state=AgentState(str(row.get("state") or "active")),+ avatar=dict(_loads(row.get("avatar_json"), {})),+ checkpoint=Checkpoint(str(row.get("checkpoint") or "idle")),+ provider=str(row.get("provider") or ""),+ model=str(row.get("model") or ""),+ effort=str(row.get("effort") or ""),+ grant_mode=GrantMode(str(row.get("grant_mode") or "all")),+ grants=list(_loads(row.get("grants_json"), [])),+ focus=list(_loads(row.get("focus_json"), [])),+ denies=list(_loads(row.get("denies_json"), [])),+ skills=skills,+ workspace_dir=str(row.get("workspace_dir") or ""),+ wiki_namespace=str(row.get("wiki_namespace") or ""),+ knowledge_scope=KnowledgeScope(str(row.get("knowledge_scope") or "shared")),+ permission_ceiling=PermissionCeiling(str(row.get("permission_ceiling") or "monitor")),+ approval_rules={+ "require_approval": [str(x) for x in rules.get("require_approval", [])],+ "always_allow": [str(x) for x in rules.get("always_allow", [])],+ },+ daily_budget_usd=float(row.get("daily_budget_usd") or 0.0),+ max_concurrent_runs=int(row.get("max_concurrent_runs") or 1),+ created_ms=int(row.get("created_ms") or 0),+ updated_ms=int(row.get("updated_ms") or 0),+ )+++_EDITABLE: Final[frozenset[str]] = frozenset(+ {+ "title",+ "description",+ "tier",+ "parent_agent_id",+ "state",+ "avatar",+ "checkpoint",+ "provider",+ "model",+ "effort",+ "grant_mode",+ "grants",+ "focus",+ "denies",+ "skills",+ "workspace_dir",+ "wiki_namespace",+ "knowledge_scope",+ "permission_ceiling",+ "approval_rules",+ "daily_budget_usd",+ "max_concurrent_runs",+ }+)++_JSON_FIELDS: Final[dict[str, str]] = {+ "avatar": "avatar_json",+ "grants": "grants_json",+ "focus": "focus_json",+ "denies": "denies_json",+ "skills": "skills_json",+ "approval_rules": "approval_rules_json",+}+++def _validate_name(name: str) -> str:+ cleaned = " ".join(str(name or "").split())+ if not _NAME_RE.match(cleaned):+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY,+ "agent name must be 1-40 characters without whitespace-only, slashes, @, #, quotes",+ )+ return cleaned+++def _validate_rules(rules: Any) -> dict[str, list[str]]:+ if rules is None:+ return {"require_approval": [], "always_allow": []}+ if not isinstance(rules, dict):+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, "approval_rules must be an object")+ out: dict[str, list[str]] = {"require_approval": [], "always_allow": []}+ for key in out:+ raw = rules.get(key, [])+ if not isinstance(raw, list) or not all(isinstance(x, str) for x in raw):+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY, f"approval_rules.{key} must be a list of strings"+ )+ out[key] = [x.strip() for x in raw if x.strip()]+ return out+++def _enum(kind: Any, value: Any, field_name: str) -> str:+ try:+ return str(kind(str(value)))+ except ValueError as exc:+ allowed = ", ".join(str(m) for m in kind)+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY, f"{field_name} must be one of: {allowed}"+ ) from exc+++def _coerce(field_name: str, value: Any) -> Any:+ """Validate one editable field and return its column value."""+ if field_name == "title":+ return str(value or "")[:_MAX_TITLE]+ if field_name == "description":+ return str(value or "")[:_MAX_DESCRIPTION]+ if field_name == "tier":+ return _enum(Tier, value, field_name)+ if field_name == "state":+ return _enum(AgentState, value, field_name)+ if field_name == "checkpoint":+ return _enum(Checkpoint, value, field_name)+ if field_name == "grant_mode":+ return _enum(GrantMode, value, field_name)+ if field_name == "knowledge_scope":+ return _enum(KnowledgeScope, value, field_name)+ if field_name == "permission_ceiling":+ return _enum(PermissionCeiling, value, field_name)+ if field_name in ("grants", "focus", "denies"):+ if not isinstance(value, list) or not all(isinstance(x, str) for x in value):+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY, f"{field_name} must be a list of capability ids"+ )+ return json.dumps(sorted({x.strip() for x in value if x.strip()}))+ if field_name == "skills":+ if value is None:+ return None+ if not isinstance(value, list) or not all(isinstance(x, str) for x in value):+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, "skills must be a list or null")+ return json.dumps(sorted({x.strip() for x in value if x.strip()}))+ if field_name == "avatar":+ if not isinstance(value, dict):+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, "avatar must be an object")+ return json.dumps(value, ensure_ascii=False)+ if field_name == "approval_rules":+ return json.dumps(_validate_rules(value))+ if field_name == "daily_budget_usd":+ amount = float(value)+ if amount < 0:+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, "daily_budget_usd must be >= 0")+ return amount+ if field_name == "max_concurrent_runs":+ runs = int(value)+ if runs < 1 or runs > 10:+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, "max_concurrent_runs must be 1-10")+ return runs+ if field_name in ("provider", "model", "effort", "workspace_dir", "wiki_namespace"):+ return str(value or "")+ if field_name == "parent_agent_id":+ return str(value) if value else None+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"unknown field {field_name}")+++class Roster:+ def __init__(self, store: SocietyStore) -> None:+ self._store = store++ async def create(+ self,+ *,+ name: str,+ title: str = "",+ description: str = "",+ tier: Tier | str = Tier.SPECIALIST,+ **fields: Any,+ ) -> tuple[AgentRecord, bool]:+ """Create an agent; returns ``(record, created)``.++ An existing name adopts the row (``created=False``) and leaves it+ untouched — the caller decides whether to PATCH.+ """+ clean_name = _validate_name(name)+ existing = await self._store.get_agent_row_by_name(clean_name)+ if existing is not None:+ return await self._hydrate(existing), False+ tier_value = Tier(_enum(Tier, tier, "tier"))+ agent_id = slugify(clean_name)+ if tier_value is Tier.LEAD and agent_id != LEAD_AGENT_ID:+ raise RosterError(+ FailureReason.TIER_NOT_ALLOWED, "exactly one lead exists and it is Jarvis"+ )+ same_slug = await self._store.get_agent_row(agent_id)+ if same_slug is not None:+ # Same slug, different spelling ("Mail Bot" vs "mail-bot"): adopt.+ return await self._hydrate(same_slug), False+ parent = fields.get("parent_agent_id")+ if parent and await self._store.get_agent_row(str(parent)) is None:+ raise RosterError(FailureReason.TARGET_UNKNOWN, f"parent agent {parent!r} not found")+ now = now_ms()+ row: dict[str, Any] = {+ "agent_id": agent_id,+ "name": clean_name,+ "title": _coerce("title", title),+ "description": _coerce("description", description),+ "tier": str(tier_value),+ "created_ms": now,+ "updated_ms": now,+ "workspace_dir": f"society/{agent_id}/workspace",+ "wiki_namespace": f"society/{agent_id}/",+ }+ if tier_value is Tier.ORCHESTRATOR:+ row["max_concurrent_runs"] = 3+ for key, value in fields.items():+ if key not in _EDITABLE or key in ("title", "description", "tier"):+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"unknown field {key}")+ row[_JSON_FIELDS.get(key, key)] = _coerce(key, value)+ await self._store.insert_agent(row)+ created = await self._store.get_agent_row(agent_id)+ assert created is not None+ return await self._hydrate(created), True++ async def get(self, agent_id: str) -> AgentRecord | None:+ row = await self._store.get_agent_row(agent_id)+ return await self._hydrate(row) if row else None++ async def resolve(self, target: str) -> AgentRecord | None:+ """By id, then by name (case-insensitive); ``None`` when unknown."""+ row = await self._store.get_agent_row(target)+ if row is None:+ row = await self._store.get_agent_row_by_name(target)+ if row is None:+ row = await self._store.get_agent_row(slugify(target))+ return await self._hydrate(row) if row else None++ async def list(self, *, include_archived: bool = False) -> list[AgentRecord]:+ rows = await self._store.list_agent_rows(include_archived=include_archived)+ return [await self._hydrate(r) for r in rows]++ async def update(self, agent_id: str, fields: dict[str, Any]) -> AgentRecord:+ current = await self._store.get_agent_row(agent_id)+ if current is None:+ raise RosterError(FailureReason.TARGET_UNKNOWN, f"agent {agent_id!r} not found")+ columns: dict[str, Any] = {}+ for key, value in fields.items():+ if key not in _EDITABLE:+ raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"field {key!r} is not editable")+ if key == "tier" and agent_id == LEAD_AGENT_ID and str(value) != str(Tier.LEAD):+ raise RosterError(FailureReason.TIER_NOT_ALLOWED, "Jarvis stays the lead")+ if key == "tier" and str(value) == str(Tier.LEAD) and agent_id != LEAD_AGENT_ID:+ raise RosterError(FailureReason.TIER_NOT_ALLOWED, "only Jarvis is the lead")+ if key == "parent_agent_id" and value:+ if str(value) == agent_id:+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY, "an agent cannot parent itself"+ )+ if await self._store.get_agent_row(str(value)) is None:+ raise RosterError(FailureReason.TARGET_UNKNOWN, f"parent {value!r} not found")+ columns[_JSON_FIELDS.get(key, key)] = _coerce(key, value)+ await self._store.update_agent(agent_id, columns)+ row = await self._store.get_agent_row(agent_id)+ assert row is not None+ return await self._hydrate(row)++ async def archive(self, agent_id: str) -> AgentRecord:+ if agent_id == LEAD_AGENT_ID:+ raise RosterError(FailureReason.TIER_NOT_ALLOWED, "the lead cannot be archived")+ return await self.update(agent_id, {"state": AgentState.ARCHIVED})++ async def _hydrate(self, row: dict[str, Any]) -> AgentRecord:+ record = AgentRecord.from_row(row)+ record.stats = await self._store.agent_stats(record.agent_id)+ return recorddiff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sqlnew file mode 100644index 0000000000..e410cacc0e--- /dev/null+++ b/jarvis/society/society_schema.sql@@ -0,0 +1,125 @@+-- Agent Society store. Idempotent (CREATE IF NOT EXISTS). Lives under+-- data/society.db with its own lifecycle, mirroring missions_schema.sql.+-- Every CHECK list below is pinned to the Python enums in jarvis/society/events.py+-- and the TypeScript consts in src/lib/societyApi.ts by+-- tests/unit/society/test_society_enum_parity.py (AP-4).++-- The roster: one row per agent = the model card. Deliberately NO chat-session+-- column: the canonical chat id is a pure function of agent_id (society:<id>),+-- so identity can never drift from its conversation.+CREATE TABLE IF NOT EXISTS society_agents (+ agent_id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ title TEXT NOT NULL DEFAULT '',+ description TEXT NOT NULL DEFAULT '',+ tier TEXT NOT NULL CHECK (tier IN ('lead', 'orchestrator', 'specialist')),+ parent_agent_id TEXT,+ state TEXT NOT NULL DEFAULT 'active'+ CHECK (state IN ('active', 'paused', 'archived')),+ avatar_json TEXT NOT NULL DEFAULT '{}',+ checkpoint TEXT NOT NULL DEFAULT 'idle'+ CHECK (checkpoint IN ('desk', 'meeting', 'archive', 'gate', 'idle')),+ provider TEXT NOT NULL DEFAULT '',+ model TEXT NOT NULL DEFAULT '',+ effort TEXT NOT NULL DEFAULT '',+ grant_mode TEXT NOT NULL DEFAULT 'all'+ CHECK (grant_mode IN ('all', 'allowlist')),+ grants_json TEXT NOT NULL DEFAULT '[]',+ focus_json TEXT NOT NULL DEFAULT '[]',+ denies_json TEXT NOT NULL DEFAULT '[]',+ skills_json TEXT, -- NULL = every active skill+ workspace_dir TEXT NOT NULL DEFAULT '',+ wiki_namespace TEXT NOT NULL DEFAULT '',+ knowledge_scope TEXT NOT NULL DEFAULT 'shared'+ CHECK (knowledge_scope IN ('shared', 'own')),+ permission_ceiling TEXT NOT NULL DEFAULT 'monitor'+ CHECK (permission_ceiling IN ('safe', 'monitor', 'ask')),+ approval_rules_json TEXT NOT NULL DEFAULT '{}',+ daily_budget_usd REAL NOT NULL DEFAULT 2.0,+ max_concurrent_runs INTEGER NOT NULL DEFAULT 1,+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_society_agents_state ON society_agents(state);++-- The board: append-only, typed, one stream for chat, world, ledger and cost.+CREATE TABLE IF NOT EXISTS society_events (+ seq INTEGER PRIMARY KEY AUTOINCREMENT,+ event_id TEXT NOT NULL UNIQUE,+ msg_type TEXT NOT NULL CHECK (msg_type IN (+ 'ASSIGN', 'CLAIM', 'RESULT', 'QUERY', 'ANSWER', 'HOLD',+ 'RELEASE', 'PROPOSE', 'VETO', 'DIGEST', 'SAY',+ 'ROOM_OPEN', 'ROOM_SETTLE')),+ from_agent TEXT NOT NULL,+ to_agent TEXT, -- NULL = broadcast+ trace_id TEXT NOT NULL,+ parent_event_id TEXT,+ ts_ms INTEGER NOT NULL,+ cost_usd REAL NOT NULL DEFAULT 0.0,+ payload_json TEXT NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_society_events_inbox ON society_events(to_agent, seq);+CREATE INDEX IF NOT EXISTS idx_society_events_trace ON society_events(trace_id, seq);+CREATE INDEX IF NOT EXISTS idx_society_events_from ON society_events(from_agent, seq);++-- Bounded group discussions: state lives here, history in society_events+-- (msg_type ROOM_OPEN / SAY / ROOM_SETTLE sharing the room's trace_id).+CREATE TABLE IF NOT EXISTS society_rooms (+ room_id TEXT PRIMARY KEY,+ trace_id TEXT NOT NULL UNIQUE,+ opened_by TEXT NOT NULL,+ topic TEXT NOT NULL DEFAULT '',+ members_json TEXT NOT NULL,+ round INTEGER NOT NULL DEFAULT 0,+ message_count INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL DEFAULT 'queued'+ CHECK (state IN ('queued', 'running', 'settled', 'failed')),+ settle_reason TEXT NOT NULL DEFAULT '',+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL+);++-- Knowledge staging: provenance and review state for pages agents wrote into+-- the vault. The vault holds the knowledge; this table only knows its taint.+CREATE TABLE IF NOT EXISTS knowledge (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ agent_id TEXT NOT NULL,+ wiki_path TEXT NOT NULL,+ origin TEXT NOT NULL CHECK (origin IN ('user', 'tool', 'web', 'agent')),+ source_event TEXT,+ trace_id TEXT,+ reviewed INTEGER NOT NULL DEFAULT 0,+ summary TEXT NOT NULL DEFAULT '',+ created_ms INTEGER NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_knowledge_agent ON knowledge(agent_id, created_ms);+CREATE INDEX IF NOT EXISTS idx_knowledge_reviewed ON knowledge(reviewed);++-- The unattended ask-queue (MASTERPLAN §2.9). Expiry parks work as blocked,+-- never drops it.+CREATE TABLE IF NOT EXISTS approvals (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ trace_id TEXT NOT NULL,+ capability TEXT NOT NULL,+ action_json TEXT NOT NULL,+ summary TEXT NOT NULL DEFAULT '',+ state TEXT NOT NULL DEFAULT 'pending'+ CHECK (state IN ('pending', 'approved', 'denied', 'expired', 'blocked')),+ created_ms INTEGER NOT NULL,+ expires_ms INTEGER NOT NULL,+ resolved_ms INTEGER,+ note TEXT NOT NULL DEFAULT ''+);++CREATE INDEX IF NOT EXISTS idx_approvals_state ON approvals(state, created_ms);+CREATE INDEX IF NOT EXISTS idx_approvals_agent ON approvals(agent_id, state);++-- Kill switch, schema version and other single values.+CREATE TABLE IF NOT EXISTS society_meta (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+);diff --git a/jarvis/society/store.py b/jarvis/society/store.pynew file mode 100644index 0000000000..0a1d4b6a20--- /dev/null+++ b/jarvis/society/store.py@@ -0,0 +1,457 @@+"""``society.db`` — the roster, the board, rooms, knowledge staging, approvals.++Same conventions as ``jarvis/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 pathlib import Path+from typing import Any++import aiosqlite++from .bus import SocietyBus+from .events import MsgType, SocietyEnvelope, now_ms++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"+)+++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)+ 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))++ 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}+ # No migrations yet — the hook exists so the first one is a two-line+ # change, exactly like the missions store.+ if not existing: # pragma: no cover — schema always creates the table+ raise RuntimeError("society_agents table missing after schema load")++ 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 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 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 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]++ 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 agent_stats(self, agent_id: str) -> dict[str, Any]:+ """Derived lifetime numbers: runs (RESULTs sent), cost, last activity."""+ 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)+ return {+ "runs": int(runs or 0),+ "total_cost_usd": float(cost or 0.0),+ "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) -> list[dict[str, Any]]:+ self.conn.row_factory = aiosqlite.Row+ if 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++ 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 changeddiff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.tsnew file mode 100644index 0000000000..771a313ff1--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts@@ -0,0 +1,106 @@+/**+ * TypeScript twins of the society enums (jarvis/society/events.py) and, later,+ * the typed client for /api/society. The const arrays are pinned to the Python+ * enums and the SQL CHECK lists by tests/unit/society/test_society_enum_parity.py+ * (AP-4): add a member in Python first, then here, or the parity test fails.+ */++export const MSG_TYPES = [+ "ASSIGN",+ "CLAIM",+ "RESULT",+ "QUERY",+ "ANSWER",+ "HOLD",+ "RELEASE",+ "PROPOSE",+ "VETO",+ "DIGEST",+ "SAY",+ "ROOM_OPEN",+ "ROOM_SETTLE",+] as const;+export type MsgType = (typeof MSG_TYPES)[number];++export const TIERS = ["lead", "orchestrator", "specialist"] as const;+export type Tier = (typeof TIERS)[number];++export const AGENT_STATES = ["active", "paused", "archived"] as const;+export type AgentState = (typeof AGENT_STATES)[number];++export const RUN_STATES = ["idle", "working", "waiting", "paused"] as const;+export type RunState = (typeof RUN_STATES)[number];++export const CHECKPOINTS = ["desk", "meeting", "archive", "gate", "idle"] as const;+export type Checkpoint = (typeof CHECKPOINTS)[number];++export const PERMISSION_CEILINGS = ["safe", "monitor", "ask"] as const;+export type PermissionCeiling = (typeof PERMISSION_CEILINGS)[number];++export const GRANT_MODES = ["all", "allowlist"] as const;+export type GrantMode = (typeof GRANT_MODES)[number];++export const KNOWLEDGE_SCOPES = ["shared", "own"] as const;+export type KnowledgeScope = (typeof KNOWLEDGE_SCOPES)[number];++export const KNOWLEDGE_ORIGINS = ["user", "tool", "web", "agent"] as const;+export type KnowledgeOrigin = (typeof KNOWLEDGE_ORIGINS)[number];++export const ROOM_STATES = ["queued", "running", "settled", "failed"] as const;+export type RoomState = (typeof ROOM_STATES)[number];++export const APPROVAL_STATES = ["pending", "approved", "denied", "expired", "blocked"] as const;+export type ApprovalState = (typeof APPROVAL_STATES)[number];++/** One row of the board, as GET /api/society/events returns it. */+export interface SocietyEnvelope {+ seq: number;+ event_id: string;+ msg_type: MsgType;+ from_agent: string;+ to_agent: string | null;+ trace_id: string;+ parent_event_id: string | null;+ ts_ms: number;+ cost_usd: number;+ payload: Record<string, unknown>;+}++/** Approval rules — Grok-style, require wins (agent-definition §3.4). */+export interface ApprovalRules {+ require_approval: string[];+ always_allow: string[];+}++/** One roster row as GET /api/society/agents returns it (agent-definition §2). */+export interface SocietyAgentRow {+ agent_id: string;+ name: string;+ title: string;+ description: string;+ tier: Tier;+ parent_agent_id: string | null;+ state: AgentState;+ avatar: Record<string, unknown>;+ checkpoint: Checkpoint;+ provider: string;+ model: string;+ effort: string;+ grant_mode: GrantMode;+ grants: string[];+ focus: string[];+ denies: string[];+ skills: string[] | null;+ workspace_dir: string;+ wiki_namespace: string;+ knowledge_scope: KnowledgeScope;+ permission_ceiling: PermissionCeiling;+ approval_rules: ApprovalRules;+ daily_budget_usd: number;+ max_concurrent_runs: number;+ session_id: string;+ created_ms: number;+ updated_ms: number;+ stats: { runs: number; total_cost_usd: number; last_active_ms: number | null };+ run_state?: RunState;+}diff --git a/tests/unit/society/__init__.py b/tests/unit/society/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/society/test_failure_reasons.py b/tests/unit/society/test_failure_reasons.pynew file mode 100644index 0000000000..747b1d8af4--- /dev/null+++ b/tests/unit/society/test_failure_reasons.py@@ -0,0 +1,60 @@+"""The typed failure vocabulary: every code has a retry hint, auth beats quota."""++from __future__ import annotations++import pytest++from jarvis.society.failure_reasons import (+ FailureReason,+ RetryAction,+ classify_error,+ retry_action,+)+++def test_every_reason_has_a_retry_action():+ for reason in FailureReason:+ assert isinstance(retry_action(reason), RetryAction)+++def test_unknown_string_reads_as_internal_error():+ assert retry_action("no-such-code") == retry_action(FailureReason.INTERNAL_ERROR)+++ ("message", "expected"),+ [+ ("HTTP 401 Unauthorized", FailureReason.AUTH_FAILED),+ ("invalid_api_key: check your billing settings", FailureReason.AUTH_FAILED),+ ("insufficient_quota: exceeded your current quota", FailureReason.PROVIDER_QUOTA_LIMIT),+ ("429 Too Many Requests", FailureReason.RATE_LIMITED),+ ("prompt is too long: 210000 > maximum context", FailureReason.CONTEXT_OVERFLOW),+ ("ECONNREFUSED 127.0.0.1:11434", FailureReason.TARGET_OFFLINE),+ ("502 Bad Gateway", FailureReason.PROVIDER_ERROR),+ ("something odd", FailureReason.INTERNAL_ERROR),+ ("", FailureReason.INTERNAL_ERROR),+ ],+)+def test_classify_error_by_message(message: str, expected: FailureReason):+ assert classify_error(message) == expected+++def test_classify_error_reads_the_exception_class_name():+ class AuthenticationError(Exception):+ pass++ assert classify_error(AuthenticationError("")) == FailureReason.AUTH_FAILED+++def test_classify_error_walks_the_cause_chain():+ try:+ try:+ raise RuntimeError("rate limit exceeded")+ except RuntimeError as inner:+ raise ValueError("wrapped") from inner+ except ValueError as outer:+ assert classify_error(outer) == FailureReason.RATE_LIMITED+++def test_none_is_internal_error():+ assert classify_error(None) == FailureReason.INTERNAL_ERRORdiff --git a/tests/unit/society/test_roster.py b/tests/unit/society/test_roster.pynew file mode 100644index 0000000000..9d432de1eb--- /dev/null+++ b/tests/unit/society/test_roster.py@@ -0,0 +1,174 @@+"""The roster: adopt-before-mint, one lead, validation, no session column."""++from __future__ import annotations++import sqlite3+from pathlib import Path++import pytest++from jarvis.society.events import AgentState, GrantMode, PermissionCeiling, Tier+from jarvis.society.failure_reasons import FailureReason+from jarvis.society.roster import Roster, RosterError, canonical_session_id, slugify+from jarvis.society.store import SocietyStore+++async def roster(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ try:+ yield Roster(store)+ finally:+ await store.close()+++def test_slugify_folds_and_never_empties():+ assert slugify("Mail Bot") == "mail-bot"+ assert slugify("Süßer Bär!") == "susser-bar" # i18n-allow: umlaut folding sample+ assert slugify("!!!") == "agent"+++def test_canonical_session_is_a_pure_function():+ assert canonical_session_id("scout") == "society:scout"+++async def test_create_then_adopt_by_name(roster: Roster):+ scout, created = await roster.create(name="Scout", title="Research scout")+ assert created is True+ assert scout.agent_id == "scout"+ assert scout.tier is Tier.SPECIALIST+ assert scout.state is AgentState.ACTIVE+ assert scout.grant_mode is GrantMode.ALL+ assert scout.permission_ceiling is PermissionCeiling.MONITOR+ assert scout.wiki_namespace == "society/scout/"+ assert scout.session_id == "society:scout"++ again, created_again = await roster.create(name="scout", title="ignored")+ assert created_again is False+ assert again.agent_id == "scout"+ assert again.title == "Research scout"+ assert len(await roster.list()) == 1+++async def test_only_jarvis_can_be_the_lead(roster: Roster):+ with pytest.raises(RosterError) as exc:+ await roster.create(name="Boss", tier=Tier.LEAD)+ assert exc.value.reason is FailureReason.TIER_NOT_ALLOWED++ jarvis, _ = await roster.create(name="Jarvis", tier=Tier.LEAD, title="Lead")+ assert jarvis.agent_id == "jarvis"+ assert jarvis.may_assign++ with pytest.raises(RosterError):+ await roster.update("jarvis", {"tier": "specialist"})+ scout, _ = await roster.create(name="Scout")+ with pytest.raises(RosterError):+ await roster.update(scout.agent_id, {"tier": "lead"})+ with pytest.raises(RosterError):+ await roster.archive("jarvis")+++async def test_orchestrator_defaults_and_parent_validation(roster: Roster):+ orch, _ = await roster.create(name="Planner", tier="orchestrator")+ assert orch.max_concurrent_runs == 3+ assert orch.may_assign+ with pytest.raises(RosterError) as exc:+ await roster.create(name="Kid", parent_agent_id="nobody")+ assert exc.value.reason is FailureReason.TARGET_UNKNOWN+ kid, _ = await roster.create(name="Kid", parent_agent_id="planner")+ assert kid.parent_agent_id == "planner"+ with pytest.raises(RosterError):+ await roster.update("kid", {"parent_agent_id": "kid"})+++async def test_update_validates_and_sorts_grants(roster: Roster):+ scout, _ = await roster.create(name="Scout")+ updated = await roster.update(+ scout.agent_id,+ {+ "grant_mode": "allowlist",+ "grants": ["plugin:gmail", "core:search-web", "plugin:gmail"],+ "focus": ["plugin:gmail"],+ "approval_rules": {"require_approval": ["plugin:gmail:send"]},+ "daily_budget_usd": 1.5,+ "permission_ceiling": "ask",+ "skills": None,+ },+ )+ assert updated.grant_mode is GrantMode.ALLOWLIST+ assert updated.grants == ["core:search-web", "plugin:gmail"]+ assert updated.approval_rules == {+ "require_approval": ["plugin:gmail:send"],+ "always_allow": [],+ }+ assert updated.daily_budget_usd == 1.5+ assert updated.skills is None++ with pytest.raises(RosterError):+ await roster.update(scout.agent_id, {"grants": "plugin:gmail"})+ with pytest.raises(RosterError):+ await roster.update(scout.agent_id, {"permission_ceiling": "block"})+ with pytest.raises(RosterError):+ await roster.update(scout.agent_id, {"max_concurrent_runs": 0})+ with pytest.raises(RosterError):+ await roster.update(scout.agent_id, {"agent_id": "other"})+ with pytest.raises(RosterError) as exc:+ await roster.update("ghost", {"title": "x"})+ assert exc.value.reason is FailureReason.TARGET_UNKNOWN+++async def test_archive_hides_from_default_list(roster: Roster):+ scout, _ = await roster.create(name="Scout")+ await roster.archive(scout.agent_id)+ assert await roster.list() == []+ archived = await roster.list(include_archived=True)+ assert [a.state for a in archived] == [AgentState.ARCHIVED]+++async def test_resolve_by_id_name_or_slug(roster: Roster):+ await roster.create(name="Mail Bot")+ assert (await roster.resolve("mail-bot")) is not None+ assert (await roster.resolve("MAIL BOT")) is not None+ assert (await roster.resolve("Mail bot")) is not None+ assert (await roster.resolve("nobody")) is None+++async def test_name_rules(roster: Roster):+ with pytest.raises(RosterError):+ await roster.create(name="")+ with pytest.raises(RosterError):+ await roster.create(name="a/b")+ with pytest.raises(RosterError):+ await roster.create(name="@scout")+++def test_roster_has_no_session_pointer_column(tmp_path: Path):+ """The canonical chat is a pure function of agent_id; a pointer column is+ the drift bug this design refuses to ship."""+ schema = (Path("jarvis/society/society_schema.sql")).read_text(encoding="utf-8")+ conn = sqlite3.connect(tmp_path / "probe.db")+ conn.executescript(schema)+ cols = {row[1] for row in conn.execute("PRAGMA table_info(society_agents)")}+ conn.close()+ assert not any("session" in c or "chat" in c for c in cols), cols+++def test_record_to_dict_is_json_shaped(tmp_path: Path):+ from jarvis.society.roster import AgentRecord++ rec = AgentRecord.from_row(+ {+ "agent_id": "x",+ "name": "X",+ "tier": "specialist",+ "created_ms": 1,+ "updated_ms": 1,+ "approval_rules_json": "not json",+ "skills_json": '["a"]',+ }+ )+ d = rec.to_dict()+ assert d["approval_rules"] == {"require_approval": [], "always_allow": []}+ assert d["skills"] == ["a"]+ assert d["session_id"] == "society:x"diff --git a/tests/unit/society/test_society_enum_parity.py b/tests/unit/society/test_society_enum_parity.pynew file mode 100644index 0000000000..b1b415a258--- /dev/null+++ b/tests/unit/society/test_society_enum_parity.py@@ -0,0 +1,86 @@+"""AP-4: every society enum is spelled identically in Python, SQL and TypeScript.++The values cross Python → SQLite CHECK → Pydantic → TS → UI. Instead of+trusting four hand-kept lists, this test reads the SQL and TS files as text+and pins them to the Python enums.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from jarvis.society import events++_ROOT = Path(__file__).resolve().parents[3]+_SQL = _ROOT / "jarvis" / "society" / "society_schema.sql"+_TS = _ROOT / "jarvis" / "ui" / "web" / "frontend" / "src" / "lib" / "societyApi.ts"++# (python enum, SQL column whose CHECK lists it, TS const name). ``state`` is+# pinned in the society_agents block only — rooms and approvals have their own.+_PINS = [+ (events.MsgType, "msg_type", "MSG_TYPES"),+ (events.Tier, "tier", "TIERS"),+ (events.AgentState, "society_agents.state", "AGENT_STATES"),+ (events.Checkpoint, "checkpoint", "CHECKPOINTS"),+ (events.PermissionCeiling, "permission_ceiling", "PERMISSION_CEILINGS"),+ (events.GrantMode, "grant_mode", "GRANT_MODES"),+ (events.KnowledgeScope, "knowledge_scope", "KNOWLEDGE_SCOPES"),+ (events.KnowledgeOrigin, "origin", "KNOWLEDGE_ORIGINS"),+ (events.RoomState, None, "ROOM_STATES"),+ (events.ApprovalState, None, "APPROVAL_STATES"),+ (events.RunState, None, "RUN_STATES"),+]+++def _sql_checks(column: str) -> list[set[str]]:+ text = _SQL.read_text(encoding="utf-8")+ if "." in column:+ table, column = column.split(".", 1)+ block = re.search(rf"CREATE TABLE IF NOT EXISTS {table}\s*\((.*?)\);", text, re.S)+ assert block, f"table {table} not in schema"+ text = block.group(1)+ pattern = re.compile(rf"CHECK\s*\(\s*{column}\s+IN\s*\(([^)]*)\)", re.S)+ return [set(re.findall(r"'([^']+)'", m)) for m in pattern.findall(text)]+++def _ts_const(name: str) -> set[str]:+ text = _TS.read_text(encoding="utf-8")+ match = re.search(rf"export const {name}\s*=\s*\[([^\]]*)\]\s*as const;", text, re.S)+ assert match, f"societyApi.ts must export {name}"+ return set(re.findall(r'"([^"]+)"', match.group(1)))++[email protected](("enum", "column", "ts_name"), _PINS, ids=[p[2] for p in _PINS])+def test_python_sql_and_typescript_agree(enum, column, ts_name):+ py = {str(m) for m in enum}+ assert _ts_const(ts_name) == py, f"{ts_name} drifted from {enum.__name__}"+ if column is not None:+ checks = _sql_checks(column)+ assert checks, f"no CHECK for column {column}"+ for check in checks:+ assert check == py, f"SQL CHECK on {column} drifted from {enum.__name__}"+++def test_room_and_approval_states_are_checked_in_sql():+ """These two columns are both called ``state`` in their tables, so they are+ pinned by table rather than by column name."""+ text = _SQL.read_text(encoding="utf-8")+ rooms = re.search(r"society_rooms\s*\((.*?)\);", text, re.S)+ approvals = re.search(r"approvals\s*\((.*?)\);", text, re.S)+ assert rooms and approvals+ state_list = re.compile(r"state.*?IN\s*\(([^)]*)\)", re.S)+ room_match = state_list.search(rooms.group(1))+ approval_match = state_list.search(approvals.group(1))+ assert room_match and approval_match+ room_states = set(re.findall(r"'([a-z]+)'", room_match.group(1)))+ approval_states = set(re.findall(r"'([a-z]+)'", approval_match.group(1)))+ assert room_states == {str(m) for m in events.RoomState}+ assert approval_states == {str(m) for m in events.ApprovalState}+++def test_pydantic_envelope_uses_the_enum():+ field = events.SocietyEnvelope.model_fields["msg_type"]+ assert field.annotation is events.MsgTypediff --git a/tests/unit/society/test_store.py b/tests/unit/society/test_store.pynew file mode 100644index 0000000000..b6856ac53b--- /dev/null+++ b/tests/unit/society/test_store.py@@ -0,0 +1,122 @@+"""society.db: append → seq → publish, replay, inbox, trace, cost and stats."""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.society.events import MsgType, SocietyEnvelope+from jarvis.society.store import SocietyStore+++async def store(tmp_path: Path):+ s = SocietyStore(tmp_path / "society.db")+ await s.open()+ try:+ yield s+ finally:+ await s.close()+++def _say(frm: str, to: str | None, trace: str, text: str = "hi", cost: float = 0.0):+ return SocietyEnvelope(+ msg_type=MsgType.SAY,+ from_agent=frm,+ to_agent=to,+ trace_id=trace,+ cost_usd=cost,+ payload={"text": text},+ )+++async def test_append_assigns_seq_and_publishes_after_persist(store: SocietyStore):+ seen: list[SocietyEnvelope] = []++ async def _observer(env: SocietyEnvelope) -> None:+ # The row is already on disk when the observer runs.+ assert await store.last_seq() == env.seq+ seen.append(env)++ store.bus.subscribe_all(_observer)+ stored = await store.append_and_publish(_say("scout", "archivist", "t1"))+ assert stored.seq == 1+ assert [e.seq for e in seen] == [1]+++async def test_seq_must_be_server_assigned(store: SocietyStore):+ with pytest.raises(ValueError):+ await store.append_and_publish(_say("a", "b", "t").model_copy(update={"seq": 7}))+++async def test_replay_and_reads(store: SocietyStore):+ await store.append_and_publish(_say("scout", "archivist", "t1", "one"))+ await store.append_and_publish(_say("archivist", "scout", "t1", "two"))+ await store.append_and_publish(_say("quill", None, "t2", "all"))++ assert [e.text for e in await store.events_since(0)] == ["one", "two", "all"]+ assert [e.text for e in await store.events_since(1)] == ["two", "all"]+ assert [e.text for e in await store.events_for_trace("t1")] == ["one", "two"]+ assert [e.text for e in await store.inbox_for("scout")] == ["two"]+ # The agent view includes what it sent, what it got, and broadcasts.+ assert [e.text for e in await store.events_for_agent("scout")] == ["one", "two", "all"]+ assert await store.count_in_trace("t1") == 2+++async def test_payload_roundtrips_unicode(store: SocietyStore):+ env = _say("scout", "quill", "t", "Grüße — ünïcode ✓") # i18n-allow: unicode sample+ await store.append_and_publish(env)+ back = (await store.events_since(0))[0]+ assert back.text == "Grüße — ünïcode ✓" # i18n-allow: unicode sample+ assert back.event_id == env.event_id+++async def test_cost_and_stats_are_derived(store: SocietyStore):+ await store.append_and_publish(_say("scout", "quill", "t", cost=0.25))+ await store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.RESULT,+ from_agent="scout",+ to_agent="jarvis",+ trace_id="t",+ cost_usd=0.5,+ payload={"done": "x", "output": ["file:a"]},+ )+ )+ stats = await store.agent_stats("scout")+ assert stats["runs"] == 1+ assert stats["total_cost_usd"] == pytest.approx(0.75)+ assert stats["last_active_ms"] is not None+ assert await store.cost_since("scout", 0) == pytest.approx(0.75)+++async def test_kill_switch_persists(store: SocietyStore, tmp_path: Path):+ assert await store.kill_switch() is False+ await store.set_kill_switch(True)+ await store.close()+ again = SocietyStore(tmp_path / "society.db")+ await again.open()+ try:+ assert await again.kill_switch() is True+ finally:+ await again.close()+++async def test_survives_a_crash_between_persist_and_publish(store: SocietyStore, tmp_path: Path):+ async def _boom(env: SocietyEnvelope) -> None:+ raise RuntimeError("observer died")++ store.bus.subscribe_all(_boom)+ stored = await store.append_and_publish(_say("a", "b", "t"))+ assert stored.seq == 1+ # A failing observer never loses the row.+ assert len(await store.events_since(0)) == 1+++async def test_open_is_idempotent(tmp_path: Path):+ s = SocietyStore(tmp_path / "society.db")+ await s.open()+ await s.open()+ await s.close()+ await s.close()