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): approvals queue and per-agent routines (M2 backend)
rubenluetke10-beep64eb4aa95694
diff --git a/jarvis/society/approvals.py b/jarvis/society/approvals.pynew file mode 100644index 0000000000..20f658ac5a--- /dev/null+++ b/jarvis/society/approvals.py@@ -0,0 +1,246 @@+"""The unattended ask-queue (MASTERPLAN §2.9, agent-definition §3.4).++An action an agent may not run on its own — above its permission ceiling,+or matched by one of its ``require_approval`` rules — lands here as data.+The chat card, the world's gate, the Jarvis bar badge and voice are+projections of this table. Expiry NEVER drops work: an expired item flips+to ``blocked`` and re-surfaces on the next app focus or voice turn until a+person decides.++Rule evaluation (``decide``), in order: global blacklist (not here — the+ToolExecutor raises before anything), the agent's ``require_approval``+patterns (queue), its ``always_allow`` patterns (run when the tool's own+tier is at most ``monitor``), then the tool's risk tier against the ceiling.+Patterns are capability ids (``plugin:gmail``), ``capability:verb``+(``plugin:gmail:send``) or ``capability:*``.+"""++from __future__ import annotations++import json+import logging+from dataclasses import dataclass+from enum import StrEnum+from typing import Any, Final++from jarvis.missions.ids import uuid7_str++from .events import ApprovalState, MsgType, PermissionCeiling, SocietyEnvelope, now_ms+from .roster import AgentRecord+from .store import SocietyStore++log = logging.getLogger(__name__)++__all__ = ["Approval", "Approvals", "Verdict", "decide", "matches"]++DEFAULT_TTL_MS: Final[int] = 24 * 60 * 60 * 1000+_TIER_RANK: Final[dict[str, int]] = {"safe": 0, "monitor": 1, "ask": 2, "block": 3}+++class Verdict(StrEnum):+ RUN = "run"+ QUEUE = "queue"+ BLOCK = "block"+++def matches(pattern: str, capability_id: str, verb: str = "") -> bool:+ """``plugin:gmail`` matches the capability; ``plugin:gmail:send`` one verb;+ ``plugin:gmail:*`` every verb; ``plugin:*`` every plugin."""+ pattern = pattern.strip()+ if not pattern:+ return False+ if pattern == capability_id:+ return True+ if pattern.endswith(":*"):+ prefix = pattern[:-2]+ return capability_id == prefix or capability_id.startswith(prefix + ":")+ if verb and pattern == f"{capability_id}:{verb}":+ return True+ return False+++def decide(agent: AgentRecord, capability_id: str, tool_tier: str, *, verb: str = "") -> Verdict:+ """What happens to one intended action of ``agent`` (see module doc)."""+ if tool_tier == "block":+ return Verdict.BLOCK+ rules = agent.approval_rules+ if any(matches(p, capability_id, verb) for p in rules.get("require_approval", [])):+ return Verdict.QUEUE+ if any(matches(p, capability_id, verb) for p in rules.get("always_allow", [])):+ return Verdict.RUN if _TIER_RANK.get(tool_tier, 1) <= 1 else Verdict.QUEUE+ ceiling = _TIER_RANK[str(agent.permission_ceiling)]+ tier = _TIER_RANK.get(tool_tier, 1)+ if tier <= ceiling and tool_tier != str(PermissionCeiling.ASK):+ return Verdict.RUN+ return Verdict.QUEUE+++@dataclass(slots=True)+class Approval:+ id: str+ agent_id: str+ trace_id: str+ capability: str+ action: dict[str, Any]+ summary: str+ state: ApprovalState+ created_ms: int+ expires_ms: int+ resolved_ms: int | None+ note: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "agent_id": self.agent_id,+ "trace_id": self.trace_id,+ "capability": self.capability,+ "action": self.action,+ "summary": self.summary,+ "state": str(self.state),+ "created_ms": self.created_ms,+ "expires_ms": self.expires_ms,+ "resolved_ms": self.resolved_ms,+ "note": self.note,+ }++ @classmethod+ def from_row(cls, row: dict[str, Any]) -> Approval:+ try:+ action = json.loads(row.get("action_json") or "{}")+ except ValueError:+ action = {}+ return cls(+ id=str(row["id"]),+ agent_id=str(row["agent_id"]),+ trace_id=str(row.get("trace_id") or ""),+ capability=str(row.get("capability") or ""),+ action=action if isinstance(action, dict) else {},+ summary=str(row.get("summary") or ""),+ state=ApprovalState(str(row.get("state") or "pending")),+ created_ms=int(row.get("created_ms") or 0),+ expires_ms=int(row.get("expires_ms") or 0),+ resolved_ms=row.get("resolved_ms"),+ note=str(row.get("note") or ""),+ )+++class Approvals:+ def __init__(self, store: SocietyStore, *, ttl_ms: int = DEFAULT_TTL_MS) -> None:+ self._store = store+ self._ttl = ttl_ms++ async def enqueue(+ self,+ *,+ agent_id: str,+ trace_id: str,+ capability: str,+ action: dict[str, Any],+ summary: str,+ ) -> Approval:+ now = now_ms()+ approval_id = uuid7_str()+ await self._store.insert_approval(+ {+ "id": approval_id,+ "agent_id": agent_id,+ "trace_id": trace_id,+ "capability": capability,+ "action_json": json.dumps(action, ensure_ascii=False),+ "summary": summary[:500],+ "state": str(ApprovalState.PENDING),+ "created_ms": now,+ "expires_ms": now + self._ttl,+ "resolved_ms": None,+ "note": "",+ }+ )+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.HOLD,+ from_agent=agent_id,+ to_agent="user",+ trace_id=trace_id,+ payload={+ "approval_id": approval_id,+ "capability": capability,+ "text": summary[:500],+ },+ )+ )+ got = await self.get(approval_id)+ assert got is not None+ return got++ async def get(self, approval_id: str) -> Approval | None:+ row = await self._store.get_approval_row(approval_id)+ return Approval.from_row(row) if row else None++ async def items(+ self, *, state: ApprovalState | None = None, agent_id: str | None = None+ ) -> list[Approval]:+ rows = await self._store.list_approval_rows(+ state=str(state) if state else None, agent_id=agent_id+ )+ return [Approval.from_row(r) for r in rows]++ async def pending(self) -> list[Approval]:+ """Everything a person still has to decide — pending AND blocked."""+ pending = await self.items(state=ApprovalState.PENDING)+ blocked = await self.items(state=ApprovalState.BLOCKED)+ return sorted(pending + blocked, key=lambda a: a.created_ms)++ async def resolve(self, approval_id: str, *, approve: bool, note: str = "") -> Approval:+ current = await self.get(approval_id)+ if current is None:+ raise KeyError(approval_id)+ if current.state in (ApprovalState.APPROVED, ApprovalState.DENIED):+ return current+ state = ApprovalState.APPROVED if approve else ApprovalState.DENIED+ await self._store.update_approval(+ approval_id,+ {"state": str(state), "resolved_ms": now_ms(), "note": note[:500]},+ )+ await self._store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.RELEASE if approve else MsgType.VETO,+ from_agent="user",+ to_agent=current.agent_id,+ trace_id=current.trace_id,+ payload={+ "approval_id": approval_id,+ "capability": current.capability,+ "approved": approve,+ "text": note or ("approved" if approve else "denied"),+ **({"reason": "blocked_by_policy"} if not approve else {}),+ },+ )+ )+ got = await self.get(approval_id)+ assert got is not None+ return got++ async def expire_due(self, *, now: int | None = None) -> int:+ """Pending items past their expiry become ``blocked`` — parked, never+ dropped. Returns how many flipped."""+ now = now if now is not None else now_ms()+ flipped = 0+ for item in await self.items(state=ApprovalState.PENDING):+ if item.expires_ms <= now:+ await self._store.update_approval(item.id, {"state": str(ApprovalState.BLOCKED)})+ flipped += 1+ return flipped++ async def resurface(self) -> list[Approval]:+ """On app focus / a voice turn: blocked items become pending again with+ a fresh expiry, so the person is asked once more."""+ revived: list[Approval] = []+ for item in await self.items(state=ApprovalState.BLOCKED):+ await self._store.update_approval(+ item.id, {"state": str(ApprovalState.PENDING), "expires_ms": now_ms() + self._ttl}+ )+ got = await self.get(item.id)+ if got is not None:+ revived.append(got)+ return reviveddiff --git a/jarvis/society/routines.py b/jarvis/society/routines.pynew file mode 100644index 0000000000..945ccb1b77--- /dev/null+++ b/jarvis/society/routines.py@@ -0,0 +1,156 @@+"""Per-agent routines = tagged tasks in the existing Automations scheduler.++No second scheduler (agent-definition §2, build plan wave 9): a routine is a+``TaskSpec`` with ``created_by="society"``, the tags ``society`` and+``agent:<agent_id>``, and a title prefixed ``[agent:<name>]``. It therefore+appears in the Automations section automatically (finish-it-everywhere)+and on the agent's model card through :func:`list_routines`. The task's+prompt carries the agent's identity the same way a dispatched mission+does, and its plugin grants are the unattended pre-authorization the task+runner already understands.+"""++from __future__ import annotations++import json+from typing import Any, Final++from jarvis.tasks.schema import (+ AgentAction,+ PluginGrant,+ TaskSpec,+ TriggerAfterDelay,+ TriggerAtTime,+ TriggerEvery,+ TriggerOnEvent,+)++from .roster import AgentRecord++__all__ = [+ "ROUTINE_TAG",+ "agent_tag",+ "build_task_spec",+ "create_routine",+ "is_agent_routine",+ "list_routines",+]++ROUTINE_TAG: Final[str] = "society"+_MAX_ROUTINES: Final[int] = 50+++def agent_tag(agent_id: str) -> str:+ return f"agent:{agent_id}"+++def _trigger(schedule: dict[str, Any]) -> Any:+ kind = str(schedule.get("kind") or schedule.get("type") or "every")+ if kind == "every":+ return TriggerEvery(+ interval_seconds=float(schedule.get("interval_seconds") or 86_400),+ start_at=schedule.get("start_at"),+ )+ if kind == "at_time":+ return TriggerAtTime(iso_timestamp=str(schedule["iso_timestamp"]))+ if kind == "after_delay":+ return TriggerAfterDelay(delay_seconds=float(schedule["delay_seconds"]))+ if kind == "on_event":+ return TriggerOnEvent(+ event_name=str(schedule["event_name"]),+ filter_expr=schedule.get("filter_expr"),+ max_firings=schedule.get("max_firings"),+ )+ raise ValueError(f"unknown schedule kind {kind!r}")+++def _routine_prompt(agent: AgentRecord, prompt: str) -> str:+ lines = [+ f"You are {agent.name}" + (f", {agent.title}" if agent.title else "") + ",",+ "an agent in the user's agent society led by Jarvis, running a scheduled routine.",+ ]+ if agent.description.strip():+ lines += ["", "Standing instructions:", agent.description.strip()]+ if agent.focus:+ lines += ["", "Reach for these capabilities first: " + ", ".join(agent.focus)]+ lines += ["", "Routine:", prompt.strip()]+ return "\n".join(lines)+++def build_task_spec(+ agent: AgentRecord,+ *,+ title: str,+ prompt: str,+ schedule: dict[str, Any],+ plugin_grants: list[dict[str, str]] | None = None,+ announce_on_success: str | None = None,+) -> TaskSpec:+ grants = tuple(+ PluginGrant(plugin_id=str(g["plugin_id"]), scope=g.get("scope", "read")) # type: ignore[arg-type]+ for g in (plugin_grants or [])+ if g.get("plugin_id")+ )+ clean_title = " ".join(title.split())[:200] or "routine"+ return TaskSpec(+ title=f"[agent:{agent.name}] {clean_title}",+ trigger=_trigger(schedule),+ action=AgentAction(prompt=_routine_prompt(agent, prompt), plugin_grants=grants),+ created_by="society",+ tags=(ROUTINE_TAG, agent_tag(agent.agent_id)),+ announce_on_success=announce_on_success,+ )+++def _tags_of(row: dict[str, Any]) -> tuple[str, ...]:+ raw = row.get("spec_json")+ if not raw:+ return ()+ try:+ spec = json.loads(raw) if isinstance(raw, str) else raw+ except ValueError:+ return ()+ tags = spec.get("tags") if isinstance(spec, dict) else None+ return tuple(str(t) for t in tags) if isinstance(tags, list | tuple) else ()+++def is_agent_routine(row: dict[str, Any], agent_id: str) -> bool:+ return agent_tag(agent_id) in _tags_of(row)+++def _summary(row: dict[str, Any]) -> dict[str, Any]:+ raw = row.get("spec_json")+ spec: dict[str, Any] = {}+ if raw:+ try:+ spec = json.loads(raw) if isinstance(raw, str) else dict(raw)+ except ValueError:+ spec = {}+ return {+ "id": row.get("id"),+ "title": row.get("title") or spec.get("title"),+ "state": row.get("state"),+ "trigger": spec.get("trigger"),+ "due_at_ns": row.get("due_at_ns"),+ "last_run_ns": row.get("last_run_ns"),+ "tags": list(_tags_of(row)),+ }+++async def list_routines(task_store: Any, agent_id: str) -> list[dict[str, Any]]:+ rows = await task_store.list(limit=1000)+ return [_summary(r) for r in rows if is_agent_routine(r, agent_id)]+++async def create_routine(task_store: Any, scheduler: Any | None, spec: TaskSpec) -> str:+ """Schedule through the live scheduler when there is one, else insert."""+ if scheduler is not None:+ return str(await scheduler.schedule(spec))+ return str(await task_store.insert(spec))+++async def count_routines(task_store: Any, agent_id: str) -> int:+ return len(await list_routines(task_store, agent_id))+++MAX_ROUTINES_PER_AGENT: Final[int] = _MAX_ROUTINESdiff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 2322154f2f..f7ee6368b2 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -22,6 +22,7 @@ from collections.abc import Callable, Iterable, Mappingfrom pathlib import Pathfrom typing import Any+from .approvals import Approvalsfrom .bridge import MissionBridgefrom .capabilities import CapabilityRow, build_catalogfrom .events import MsgType, RoomState, SocietyEnvelope, Tier@@ -86,6 +87,7 @@ class SocietyRuntime:self.store = SocietyStore(self._data_dir / _DB_NAME)self.roster = Roster(self.store)self.rooms = Rooms(self.store)+ self.approvals = Approvals(self.store)self.scheduler = SocietyScheduler(self.store,self.roster,diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.pyindex d966e2b44e..44012970e9 100644--- a/jarvis/society/scheduler.py+++ b/jarvis/society/scheduler.py@@ -34,6 +34,7 @@ from datetime import UTC, datetimefrom typing import Any, Finalfrom .events import SCHEDULER_ACTOR as _SCHEDULER+from .events import USER_ACTOR as _USERfrom .events import MsgType, SocietyEnvelope, Tierfrom .failure_reasons import FailureReason, classify_error, retry_actionfrom .roster import AgentRecord, AgentState, Roster@@ -141,7 +142,9 @@ class SocietyScheduler:await self._on_assign(env)elif env.msg_type is MsgType.RESULT:await self._on_result(env)- elif env.msg_type in _DELIVERED and env.to_agent:+ elif env.msg_type in _DELIVERED and env.to_agent and env.to_agent != _USER:+ # Envelopes for the person (HOLD/RELEASE on approvals) are read by+ # the UI, the bar and voice — never delivered to a roster row.await self._on_deliver(env)async def _veto(self, env: SocietyEnvelope, reason: FailureReason, detail: str) -> None:diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex a8a26c4d7d..f15222e6d3 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -387,6 +387,135 @@ async def room_settle(room_id: str, request: Request) -> dict[str, Any]:return {"room": room.to_dict()}+# ----------------------------------------------------------------- routines+++class RoutineBody(BaseModel):+ title: str = Field(min_length=1, max_length=200)+ prompt: str = Field(min_length=1, max_length=16_000)+ schedule: dict[str, Any] = Field(default_factory=lambda: {"kind": "every"})+ plugin_grants: list[dict[str, str]] = Field(default_factory=list)+ announce_on_success: str | None = None+++def _task_store(request: Request) -> Any:+ store = getattr(request.app.state, "task_store", None)+ if store is None:+ raise HTTPException(503, "task store not available")+ return store++[email protected]("/agents/{agent_id}/routines")+async def list_agent_routines(agent_id: str, request: Request) -> dict[str, Any]:+ from jarvis.society.routines import list_routines++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ rows = await list_routines(_task_store(request), agent.agent_id)+ return {"routines": rows, "total": len(rows)}++[email protected]("/agents/{agent_id}/routines", openapi_extra={"x-jarvis-dangerous": True})+async def create_agent_routine(+ agent_id: str, body: RoutineBody, request: Request+) -> dict[str, Any]:+ """A routine is a task in the Automations scheduler tagged with the agent."""+ from jarvis.society.routines import (+ MAX_ROUTINES_PER_AGENT,+ build_task_spec,+ count_routines,+ create_routine,+ )++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ store = _task_store(request)+ if await count_routines(store, agent.agent_id) >= MAX_ROUTINES_PER_AGENT:+ raise HTTPException(409, {"reason": str(FailureReason.BLOCKED_BY_POLICY)})+ try:+ spec = build_task_spec(+ agent,+ title=body.title,+ prompt=body.prompt,+ schedule=body.schedule,+ plugin_grants=body.plugin_grants,+ announce_on_success=body.announce_on_success,+ )+ except (ValueError, KeyError) as exc:+ raise HTTPException(422, f"invalid routine: {exc}") from exc+ task_id = await create_routine(store, getattr(request.app.state, "task_scheduler", None), spec)+ return {"id": task_id, "title": spec.title, "tags": list(spec.tags)}+++# ---------------------------------------------------------------- approvals+++class ResolveApprovalBody(BaseModel):+ approve: bool+ note: str = ""+++class EnqueueApprovalBody(BaseModel):+ agent_id: str+ capability: str+ trace_id: str = ""+ action: dict[str, Any] = Field(default_factory=dict)+ summary: str = ""++[email protected]("/approvals")+async def enqueue_approval(body: EnqueueApprovalBody, request: Request) -> dict[str, Any]:+ """Park an action for the person to decide. Executes nothing by itself —+ the approved action is run by whoever asked (executor, routine, CLI)."""+ rt = await _runtime(request)+ agent = await rt.roster.resolve(body.agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ item = await rt.approvals.enqueue(+ agent_id=agent.agent_id,+ trace_id=body.trace_id or f"approval:{agent.agent_id}",+ capability=body.capability,+ action=body.action,+ summary=body.summary or body.capability,+ )+ return {"approval": item.to_dict()}++[email protected]("/approvals")+async def list_approvals(request: Request, agent_id: str | None = None) -> dict[str, Any]:+ """Everything a person still has to decide (pending and parked), oldest first."""+ rt = await _runtime(request)+ await rt.approvals.expire_due()+ items = await rt.approvals.pending()+ if agent_id:+ items = [a for a in items if a.agent_id == agent_id]+ return {"approvals": [a.to_dict() for a in items], "total": len(items)}++[email protected]("/approvals/{approval_id}/resolve", openapi_extra={"x-jarvis-dangerous": True})+async def resolve_approval(+ approval_id: str, body: ResolveApprovalBody, request: Request+) -> dict[str, Any]:+ rt = await _runtime(request)+ try:+ item = await rt.approvals.resolve(approval_id, approve=body.approve, note=body.note)+ except KeyError as exc:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc+ return {"approval": item.to_dict()}++[email protected]("/approvals/resurface")+async def resurface_approvals(request: Request) -> dict[str, Any]:+ """App focus / voice turn: parked items are asked again."""+ rt = await _runtime(request)+ revived = await rt.approvals.resurface()+ return {"approvals": [a.to_dict() for a in revived], "total": len(revived)}++# ----------------------------------------------------------------- controlsdiff --git a/tests/unit/society/test_approvals.py b/tests/unit/society/test_approvals.pynew file mode 100644index 0000000000..69f3fb67c6--- /dev/null+++ b/tests/unit/society/test_approvals.py@@ -0,0 +1,109 @@+"""Approvals: rule matching, the verdict order, queue → resolve, expiry parks."""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.society.approvals import Approvals, Verdict, decide, matches+from jarvis.society.events import ApprovalState, MsgType+from jarvis.society.roster import Roster+from jarvis.society.store import SocietyStore+++async def world(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ roster = Roster(store)+ try:+ yield store, roster, Approvals(store, ttl_ms=1000)+ finally:+ await store.close()+++def test_pattern_matching():+ assert matches("plugin:gmail", "plugin:gmail")+ assert matches("plugin:gmail:send", "plugin:gmail", "send")+ assert not matches("plugin:gmail:send", "plugin:gmail", "read")+ assert matches("plugin:gmail:*", "plugin:gmail", "anything")+ assert matches("plugin:*", "plugin:gmail")+ assert not matches("plugin:*", "cli:gh")+ assert not matches("", "plugin:gmail")+++async def test_verdict_order(world):+ _, roster, _ = world+ agent, _ = await roster.create(+ name="Mailbox",+ permission_ceiling="monitor",+ approval_rules={"require_approval": ["plugin:gmail:send"], "always_allow": ["cli:gh"]},+ )+ assert decide(agent, "plugin:gmail", "monitor", verb="read") is Verdict.RUN+ assert decide(agent, "plugin:gmail", "monitor", verb="send") is Verdict.QUEUE+ assert decide(agent, "cli:gh", "monitor") is Verdict.RUN+ assert decide(agent, "cli:gh", "ask") is Verdict.QUEUE # always_allow never lifts ask+ assert decide(agent, "core:search-web", "safe") is Verdict.RUN+ assert decide(agent, "core:run-shell", "ask") is Verdict.QUEUE+ assert decide(agent, "plugin:spotify", "block") is Verdict.BLOCK++ strict, _ = await roster.create(name="Reader", permission_ceiling="safe")+ assert decide(strict, "core:search-web", "safe") is Verdict.RUN+ assert decide(strict, "plugin:gmail", "monitor") is Verdict.QUEUE++ trusting, _ = await roster.create(name="Doer", permission_ceiling="ask")+ assert decide(trusting, "plugin:gmail", "monitor") is Verdict.RUN+ assert decide(trusting, "plugin:gmail", "ask") is Verdict.QUEUE # ask still asks a human+++async def test_enqueue_resolve_and_board_projection(world):+ store, roster, approvals = world+ await roster.create(name="Mailbox")+ item = await approvals.enqueue(+ agent_id="mailbox",+ trace_id="t",+ capability="plugin:gmail",+ action={"verb": "send", "to": "[email protected]"},+ summary="Send the weekly report",+ )+ assert item.state is ApprovalState.PENDING+ assert [a.id for a in await approvals.pending()] == [item.id]+ board = await store.events_for_trace("t")+ assert [e.msg_type for e in board] == [MsgType.HOLD]+ assert board[0].payload["approval_id"] == item.id++ done = await approvals.resolve(item.id, approve=True, note="ok")+ assert done.state is ApprovalState.APPROVED and done.note == "ok"+ board = await store.events_for_trace("t")+ assert [e.msg_type for e in board] == [MsgType.HOLD, MsgType.RELEASE]+ assert await approvals.pending() == []+ # Resolving twice is a no-op.+ assert (await approvals.resolve(item.id, approve=False)).state is ApprovalState.APPROVED++ denied = await approvals.enqueue(+ agent_id="mailbox", trace_id="u", capability="plugin:gmail", action={}, summary="x"+ )+ out = await approvals.resolve(denied.id, approve=False)+ assert out.state is ApprovalState.DENIED+ veto = (await store.events_for_trace("u"))[-1]+ assert veto.msg_type is MsgType.VETO and veto.payload["reason"] == "blocked_by_policy"+ with pytest.raises(KeyError):+ await approvals.resolve("nope", approve=True)+++async def test_expiry_parks_and_resurfaces(world):+ _, roster, approvals = world+ await roster.create(name="Mailbox")+ item = await approvals.enqueue(+ agent_id="mailbox", trace_id="t", capability="plugin:gmail", action={}, summary="x"+ )+ assert await approvals.expire_due(now=item.expires_ms - 1) == 0+ assert await approvals.expire_due(now=item.expires_ms) == 1+ parked = await approvals.get(item.id)+ assert parked is not None and parked.state is ApprovalState.BLOCKED+ # Still on the person's list — never dropped.+ assert [a.id for a in await approvals.pending()] == [item.id]+ revived = await approvals.resurface()+ assert [a.state for a in revived] == [ApprovalState.PENDING]+ assert revived[0].expires_ms > item.expires_msdiff --git a/tests/unit/society/test_routines.py b/tests/unit/society/test_routines.pynew file mode 100644index 0000000000..139cc6cae6--- /dev/null+++ b/tests/unit/society/test_routines.py@@ -0,0 +1,136 @@+"""Routines are tagged Automations tasks that carry the agent's identity."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from jarvis.society.roster import Roster+from jarvis.society.routines import (+ agent_tag,+ build_task_spec,+ create_routine,+ is_agent_routine,+ list_routines,+)+from jarvis.society.store import SocietyStore+++class FakeTaskStore:+ def __init__(self) -> None:+ self.rows: list[dict] = []++ async def insert(self, spec, *, trace_id=None) -> str:+ task_id = f"task-{len(self.rows) + 1}"+ self.rows.append(+ {+ "id": task_id,+ "title": spec.title,+ "state": "scheduled",+ "spec_json": spec.model_dump_json(),+ "due_at_ns": 1,+ }+ )+ return task_id++ async def list(self, state_filter=None, *, limit: int = 100) -> list[dict]:+ return list(self.rows)+++class FakeScheduler:+ def __init__(self, store: FakeTaskStore) -> None:+ self.store = store+ self.scheduled: list[str] = []++ async def schedule(self, spec) -> str:+ task_id = await self.store.insert(spec)+ self.scheduled.append(task_id)+ return task_id+++async def agent(tmp_path: Path):+ store = SocietyStore(tmp_path / "society.db")+ await store.open()+ rec, _ = await Roster(store).create(+ name="Mailbox",+ title="Gmail agent",+ description="Handle my mail.",+ focus=["plugin:gmail"],+ )+ try:+ yield rec+ finally:+ await store.close()+++async def test_spec_carries_identity_tags_and_grants(agent):+ spec = build_task_spec(+ agent,+ title=" Morning inbox brief ",+ prompt="Summarize new mail.",+ schedule={"kind": "every", "interval_seconds": 3600, "start_at": "2026-09-02T07:00:00"},+ plugin_grants=[{"plugin_id": "gmail", "scope": "read"}, {"plugin_id": ""}],+ )+ assert spec.title == "[agent:Mailbox] Morning inbox brief"+ assert spec.created_by == "society"+ assert spec.tags == ("society", agent_tag("mailbox"))+ assert spec.trigger.type == "every" and spec.trigger.interval_seconds == 3600+ assert spec.action.kind == "agent"+ assert spec.action.prompt.startswith("You are Mailbox, Gmail agent,")+ assert "Handle my mail." in spec.action.prompt and "Summarize new mail." in spec.action.prompt+ assert "plugin:gmail" in spec.action.prompt+ assert [(g.plugin_id, g.scope) for g in spec.action.plugin_grants] == [("gmail", "read")]+++async def test_every_schedule_kind(agent):+ at = build_task_spec(+ agent,+ title="t",+ prompt="p",+ schedule={"kind": "at_time", "iso_timestamp": "2026-09-02T07:00:00"},+ )+ assert at.trigger.type == "at_time"+ ev = build_task_spec(+ agent, title="t", prompt="p", schedule={"kind": "on_event", "event_name": "MessageSent"}+ )+ assert ev.trigger.type == "on_event"+ delay = build_task_spec(+ agent, title="t", prompt="p", schedule={"kind": "after_delay", "delay_seconds": 5}+ )+ assert delay.trigger.type == "after_delay"+ with pytest.raises(ValueError):+ build_task_spec(agent, title="t", prompt="p", schedule={"kind": "cron"})+++async def test_list_filters_by_agent_tag(agent):+ store = FakeTaskStore()+ spec = build_task_spec(agent, title="brief", prompt="p", schedule={"kind": "every"})+ await create_routine(store, None, spec)+ store.rows.append(+ {+ "id": "other",+ "title": "x",+ "state": "scheduled",+ "spec_json": json.dumps({"tags": ["agent:quill"]}),+ }+ )+ store.rows.append(+ {"id": "broken", "title": "y", "state": "scheduled", "spec_json": "{not json"}+ )+ assert is_agent_routine(store.rows[0], "mailbox")+ assert not is_agent_routine(store.rows[1], "mailbox")+ rows = await list_routines(store, "mailbox")+ assert [r["id"] for r in rows] == ["task-1"]+ assert rows[0]["title"] == "[agent:Mailbox] brief"+ assert rows[0]["trigger"]["type"] == "every"+++async def test_scheduler_is_preferred(agent):+ store = FakeTaskStore()+ scheduler = FakeScheduler(store)+ spec = build_task_spec(agent, title="brief", prompt="p", schedule={"kind": "every"})+ task_id = await create_routine(store, scheduler, spec)+ assert scheduler.scheduled == [task_id]diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.pyindex 8f9207143e..36db9c6feb 100644--- a/tests/unit/ui/web/test_society_routes.py+++ b/tests/unit/ui/web/test_society_routes.py@@ -207,3 +207,63 @@ def test_missing_factory_is_503():app.include_router(router)with TestClient(app) as c:assert c.get("/api/society/status").status_code == 503+++def test_approvals_over_rest(client):+ c, _ = client+ c.post("/api/society/agents", json={"name": "Mailbox"})+ created = c.post(+ "/api/society/approvals",+ json={+ "agent_id": "mailbox",+ "trace_id": "t",+ "capability": "plugin:gmail",+ "action": {"verb": "send"},+ "summary": "Send the report",+ },+ )+ assert created.status_code == 200, created.text+ item = created.json()["approval"]+ assert item["state"] == "pending"+ listed = c.get("/api/society/approvals").json()+ assert [a["id"] for a in listed["approvals"]] == [item["id"]]+ assert c.get("/api/society/approvals", params={"agent_id": "nobody"}).json()["total"] == 0+ board = c.get("/api/society/events", params={"trace_id": "t"}).json()["events"]+ assert [e["msg_type"] for e in board] == ["HOLD"]+ res = c.post(+ f"/api/society/approvals/{item['id']}/resolve", json={"approve": True, "note": "ok"}+ )+ assert res.json()["approval"]["state"] == "approved"+ assert c.get("/api/society/approvals").json()["total"] == 0+ assert c.post("/api/society/approvals/nope/resolve", json={"approve": False}).status_code == 404+ assert c.post("/api/society/approvals/resurface").json()["total"] == 0+ assert (+ c.post("/api/society/approvals", json={"agent_id": "ghost", "capability": "x"}).status_code+ == 404+ )+++def test_routines_over_rest(client):+ from tests.unit.society.test_routines import FakeScheduler, FakeTaskStore++ c, _ = client+ c.post("/api/society/agents", json={"name": "Mailbox", "title": "Gmail agent"})+ assert c.get("/api/society/agents/mailbox/routines").status_code == 503+ store = FakeTaskStore()+ c.app.state.task_store = store+ c.app.state.task_scheduler = FakeScheduler(store)+ res = c.post(+ "/api/society/agents/mailbox/routines",+ json={"title": "Morning brief", "prompt": "Summarize mail.", "schedule": {"kind": "every"}},+ )+ assert res.status_code == 200, res.text+ assert res.json()["title"] == "[agent:Mailbox] Morning brief"+ assert res.json()["tags"] == ["society", "agent:mailbox"]+ listed = c.get("/api/society/agents/mailbox/routines").json()+ assert listed["total"] == 1 and listed["routines"][0]["state"] == "scheduled"+ bad = c.post(+ "/api/society/agents/mailbox/routines",+ json={"title": "x", "prompt": "p", "schedule": {"kind": "cron"}},+ )+ assert bad.status_code == 422+ assert c.get("/api/society/agents/ghost/routines").status_code == 404