Skip to content

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

feat(society): the Quest Board - a posted job is routed to one agent, forged when nobody fits, and read back off the board

rubenluetke10-beepe63d8ac77cd2
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index 19396b134c..d6b7a80e42 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -2147,6 +2147,23 @@ class SocietyCheckpointChanged(Event):
previous: str = ""
+@dataclass(frozen=True, slots=True)
+class SocietyQuestChanged(Event):
+ """A quest on the society's board changed state.
+
+ Published by :class:`jarvis.society.quests.Quests` after the row was
+ updated — posted, routed to a taker, claimed, done, failed or cancelled.
+ The WebSocket forwards it; the Quest Board in the world re-reads its list
+ within a second instead of on the next poll.
+ """
+
+ quest_id: str = ""
+ state: str = ""
+ previous: str = ""
+ agent_id: str = ""
+ title: str = ""
+
+
# ----------------------------------------------------------------------
# Visible-Feedback Contract (ADR-0016)
# ----------------------------------------------------------------------
diff --git a/jarvis/society/README.md b/jarvis/society/README.md
index a0778f4964..56d1d78650 100644
--- a/jarvis/society/README.md
+++ b/jarvis/society/README.md
@@ -26,6 +26,7 @@ live under the scheduler and the voice router tool (M4) are not.
| `shell.py` | the shell backend seam: `LocalBackend` now (local by decision), path containment, caps |
| `browser/` | the agent's browser: one-click venv install of browser-use, the in-venv runner, per-agent persistent profiles + login sessions, `society_browser` |
| `learning.py` | automatic learning: turn digest → skill in the agent's own namespace, `society_run_skill`, promotion to the global registry as a draft |
+| `quests.py` | the Quest Board: a job the person posts becomes ONE `ASSIGN` to the agent deterministic routing picks (focus overlap, name/title, description words); nobody fits → the foundry forges the seed teammate for the quest's capability, else the one generalist `Runner`; the lifecycle is read back off the trace (CLAIM → running, RESULT → done/failed, VETO → failed) and pushed as `SocietyQuestChanged` |
| `seeds.py` | the starter team (Scout + Archivist) and proposals from connected capabilities |
| `chat_binding.py` | roster row → canonical `agent_chat` session; delivers board envelopes as framed turns |
| `runtime.py` | the lazily built singleton wiring all of it; `current_runtime()` for the surface |
diff --git a/jarvis/society/events.py b/jarvis/society/events.py
index 6375645c47..7152909c46 100644
--- a/jarvis/society/events.py
+++ b/jarvis/society/events.py
@@ -30,6 +30,7 @@ __all__ = [
"KnowledgeScope",
"MsgType",
"PermissionCeiling",
+ "QuestState",
"RoomState",
"RunState",
"SocietyEnvelope",
@@ -133,6 +134,22 @@ class RoomState(StrEnum):
FAILED = "failed"
+class QuestState(StrEnum):
+ """A quest on the board: posted by the person, taken by one agent.
+
+ ``open`` = no taker yet (routing found nobody and forging was not
+ possible); ``assigned`` = an ASSIGN is on the board; ``running`` = the
+ taker CLAIMed it; the three terminal states never change again.
+ """
+
+ OPEN = "open"
+ ASSIGNED = "assigned"
+ RUNNING = "running"
+ DONE = "done"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+
+
class ApprovalState(StrEnum):
PENDING = "pending"
APPROVED = "approved"
diff --git a/jarvis/society/quests.py b/jarvis/society/quests.py
new file mode 100644
index 0000000000..23cdf7d440
--- /dev/null
+++ b/jarvis/society/quests.py
@@ -0,0 +1,517 @@
+"""Quests — one job the person posts on the board; the society takes it.
+
+A quest is the game-shaped front of an ``ASSIGN``: the person writes "the
+five most important mails of today" on the Quest Board in the middle of the
+market square, trusted Python picks the ONE agent that should take it, and
+from there the ordinary machinery runs — the scheduler starts the work, the
+board carries CLAIM / RESULT / VETO on the quest's trace, and this module
+only *reads* those envelopes back into the quest's state. Nothing here
+starts work on its own and no model decides who takes what (AP-3/AP-5).
+
+Routing (``choose_taker``) is deterministic and free, like ``focus.py``:
+
+1. the quest text is folded into capability ids the way an agent description
+ is (``derive_focus``), then every active non-lead agent is scored — focus
+ overlap, its name or title named in the quest, description words shared
+ with the quest; a busy agent loses a point per running task;
+2. the best agent takes it when it scores at all;
+3. nobody fits → the Agent Foundry forges a teammate: the seed proposal
+ whose capability the quest points at (a mail quest forges "Mailbox" when
+ a mail plugin is connected), else the one generalist "Runner" that is
+ created once and takes everything unclaimed. Jarvis, the lead, never
+ works a quest — it delegates.
+
+The person sees why in ``routing`` ("focus-match", "forged:plugin:gmail",
+"generalist"). A refusal from the scheduler (budget, cap, kill switch) makes
+the quest ``failed`` with the typed reason; ``retry`` routes it again.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass, field
+from typing import Any, Final
+
+from jarvis.missions.ids import uuid7_str
+
+from .capabilities import CapabilityRow
+from .events import USER_ACTOR, MsgType, QuestState, SocietyEnvelope, Tier, now_ms
+from .focus import derive_focus
+from .roster import AgentRecord, AgentState
+from .seeds import proposal_for_capability
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "GENERALIST",
+ "QuestRecord",
+ "Quests",
+ "RoutingChoice",
+ "choose_taker",
+ "quest_title",
+]
+
+#: Trace prefix every quest's envelopes share; the listener keys on it.
+TRACE_PREFIX: Final[str] = "quest:"
+#: Below this score a match is noise and the foundry is the better option.
+MIN_MATCH_SCORE: Final[int] = 3
+#: Terminal states never change again — a late RESULT on a cancelled quest is ignored.
+TERMINAL: Final[frozenset[QuestState]] = frozenset(
+ {QuestState.DONE, QuestState.FAILED, QuestState.CANCELLED}
+)
+
+#: The generalist the foundry forges once when no specialist fits a quest.
+GENERALIST: Final[dict[str, Any]] = {
+ "name": "Runner",
+ "title": "Errand runner",
+ "description": (
+ "You take the quests from the board that no specialist claims: small, "
+ "clearly worded jobs of any kind. You work with the tools the quest needs, "
+ "keep to what was asked, and hand off with what is done, where it is and "
+ "what remains open."
+ ),
+ "permission_ceiling": "monitor",
+ "daily_budget_usd": 2.0,
+}
+
+_WORD_RE: Final[re.Pattern[str]] = re.compile(r"[a-z0-9][a-z0-9\-]{2,}")
+_STOP: Final[frozenset[str]] = frozenset(
+ {
+ "the",
+ "and",
+ "for",
+ "with",
+ "from",
+ "that",
+ "this",
+ "into",
+ "your",
+ "you",
+ "are",
+ "all",
+ "der",
+ "die",
+ "das",
+ "und",
+ "mit",
+ "von",
+ "für", # i18n-allow: speech-input vocabulary (stop word)
+ "fuer", # i18n-allow: speech-input vocabulary (stop word)
+ "den",
+ "dem",
+ "des",
+ "ein",
+ "eine",
+ "einen",
+ "meine",
+ "meinen",
+ "mir",
+ "mich",
+ "bitte",
+ "please",
+ "heute",
+ "today",
+ "agent",
+ "quest",
+ }
+)
+
+
+def _fold(text: str) -> str:
+ text = text.lower()
+ for src, dst in (("ä", "ae"), ("ö", "oe"), ("ü", "ue"), ("ß", "ss")): # i18n-allow: folding
+ text = text.replace(src, dst)
+ return text
+
+
+def _words(text: str) -> set[str]:
+ return {w for w in _WORD_RE.findall(_fold(text)) if w not in _STOP}
+
+
+def quest_title(text: str, explicit: str = "") -> str:
+ """The board's one-line title: the explicit one, else the first line, trimmed."""
+ title = (explicit or "").strip()
+ if not title:
+ first = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
+ title = first
+ if len(title) > 72:
+ title = title[:69].rstrip() + "…"
+ return title or "Quest"
+
+
+# ------------------------------------------------------------------ routing
+
+
+@dataclass(frozen=True, slots=True)
+class RoutingChoice:
+ """Who takes the quest and why — persisted on the row as ``routing``."""
+
+ agent_id: str | None
+ reason: str
+ score: int = 0
+ focus: list[str] = field(default_factory=list)
+ #: A roster spec the foundry should create first (``agent_id`` is then
+ #: the name's slug, created by the caller).
+ forge: dict[str, Any] | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "agent_id": self.agent_id,
+ "reason": self.reason,
+ "score": self.score,
+ "focus": list(self.focus),
+ "forged": bool(self.forge),
+ }
+
+
+def score_agent(agent: AgentRecord, text: str, focus: list[str], busy: int = 0) -> int:
+ """How well ``agent`` fits a quest — 0 means no signal at all."""
+ score = 0
+ for rank, cap_id in enumerate(focus):
+ if cap_id in agent.focus:
+ score += 6 if rank == 0 else 4
+ folded = _fold(text)
+ for word in _words(agent.name):
+ if re.search(rf"(?<![a-z0-9]){re.escape(word)}(?![a-z0-9])", folded):
+ score += 3
+ for word in _words(agent.title):
+ if re.search(rf"(?<![a-z0-9]){re.escape(word)}(?![a-z0-9])", folded):
+ score += 2
+ shared = _words(text) & _words(agent.description)
+ score += min(5, len(shared))
+ if agent.tier is Tier.SPECIALIST and score > 0:
+ score += 1
+ return max(0, score - busy)
+
+
+def choose_taker(
+ text: str,
+ agents: list[AgentRecord],
+ catalog: list[CapabilityRow],
+ *,
+ busy: Mapping[str, int] | None = None,
+) -> RoutingChoice:
+ """Pure: the taker for ``text`` among ``agents``, or what to forge."""
+ focus = derive_focus("", text, catalog)
+ busy = busy or {}
+ candidates = [a for a in agents if a.state is AgentState.ACTIVE and a.tier is not Tier.LEAD]
+ ranked = sorted(
+ ((score_agent(a, text, focus, busy.get(a.agent_id, 0)), a) for a in candidates),
+ key=lambda pair: (-pair[0], pair[1].tier is not Tier.SPECIALIST, pair[1].created_ms),
+ )
+ if ranked and ranked[0][0] >= MIN_MATCH_SCORE:
+ best_score, best = ranked[0]
+ reason = "focus-match" if any(c in best.focus for c in focus) else "keyword-match"
+ return RoutingChoice(best.agent_id, reason, best_score, focus)
+ taken = {a.name.lower() for a in agents}
+ for cap_id in focus:
+ spec = proposal_for_capability(cap_id, catalog)
+ if spec is None or spec["name"].lower() in taken:
+ continue
+ return RoutingChoice(None, f"forged:{cap_id}", 0, focus, forge=spec)
+ generalist = next((a for a in candidates if a.name.lower() == GENERALIST["name"].lower()), None)
+ if generalist is not None:
+ return RoutingChoice(generalist.agent_id, "generalist", 0, focus)
+ orchestrator = next((a for a in candidates if a.tier is Tier.ORCHESTRATOR), None)
+ if orchestrator is not None:
+ return RoutingChoice(orchestrator.agent_id, "orchestrator", 0, focus)
+ return RoutingChoice(None, "forged:generalist", 0, focus, forge=dict(GENERALIST))
+
+
+# ------------------------------------------------------------------- record
+
+
+def _loads(value: Any, default: Any) -> Any:
+ if isinstance(value, str) and value:
+ try:
+ return json.loads(value)
+ except ValueError:
+ return default
+ return default
+
+
+@dataclass(frozen=True, slots=True)
+class QuestRecord:
+ quest_id: str
+ title: str
+ text: str
+ state: QuestState
+ created_by: str
+ agent_id: str | None
+ trace_id: str
+ assign_event_id: str | None
+ run_id: str
+ routing: dict[str, Any]
+ result: dict[str, Any]
+ created_ms: int
+ updated_ms: int
+ done_ms: int | None
+
+ @classmethod
+ def from_row(cls, row: Mapping[str, Any]) -> QuestRecord:
+ return cls(
+ quest_id=str(row["quest_id"]),
+ title=str(row.get("title") or ""),
+ text=str(row.get("text") or ""),
+ state=QuestState(str(row.get("state") or "open")),
+ created_by=str(row.get("created_by") or USER_ACTOR),
+ agent_id=row.get("agent_id"),
+ trace_id=str(row["trace_id"]),
+ assign_event_id=row.get("assign_event_id"),
+ run_id=str(row.get("run_id") or ""),
+ routing=_loads(row.get("routing_json"), {}),
+ result=_loads(row.get("result_json"), {}),
+ created_ms=int(row.get("created_ms") or 0),
+ updated_ms=int(row.get("updated_ms") or 0),
+ done_ms=row.get("done_ms"),
+ )
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "quest_id": self.quest_id,
+ "title": self.title,
+ "text": self.text,
+ "state": str(self.state),
+ "created_by": self.created_by,
+ "agent_id": self.agent_id,
+ "trace_id": self.trace_id,
+ "assign_event_id": self.assign_event_id,
+ "run_id": self.run_id,
+ "routing": dict(self.routing),
+ "result": dict(self.result),
+ "created_ms": self.created_ms,
+ "updated_ms": self.updated_ms,
+ "done_ms": self.done_ms,
+ }
+
+
+# ------------------------------------------------------------------ service
+
+
+class Quests:
+ """The quest board over the runtime: create → route → listen."""
+
+ def __init__(self, runtime: Any, *, publish: Callable[[Any], Any] | None = None) -> None:
+ self._runtime = runtime
+ self._publish = publish
+ self._unsubscribe: Callable[[], None] | None = None
+
+ # ------------------------------------------------------------ wiring
+
+ def attach(self) -> None:
+ if self._unsubscribe is None:
+ self._unsubscribe = self._runtime.store.bus.subscribe_all(self._on_envelope)
+
+ def detach(self) -> None:
+ if self._unsubscribe is not None:
+ self._unsubscribe()
+ self._unsubscribe = None
+
+ # ------------------------------------------------------------- reads
+
+ async def get(self, quest_id: str) -> QuestRecord | None:
+ row = await self._runtime.store.get_quest_row(quest_id)
+ return QuestRecord.from_row(row) if row else None
+
+ async def list(
+ self, *, state: QuestState | str | None = None, limit: int = 200
+ ) -> list[QuestRecord]:
+ rows = await self._runtime.store.list_quest_rows(
+ state=str(state) if state else None, limit=limit
+ )
+ return [QuestRecord.from_row(r) for r in rows]
+
+ # ------------------------------------------------------------ writes
+
+ async def create(
+ self,
+ text: str,
+ *,
+ title: str = "",
+ created_by: str = USER_ACTOR,
+ lang: str | None = None,
+ ) -> QuestRecord:
+ """Post a quest and route it right away."""
+ clean = text.strip()
+ if not clean:
+ raise ValueError("a quest needs text")
+ quest_id = uuid7_str()
+ now = now_ms()
+ await self._runtime.store.insert_quest(
+ {
+ "quest_id": quest_id,
+ "title": quest_title(clean, title),
+ "text": clean,
+ "state": str(QuestState.OPEN),
+ "created_by": created_by,
+ "trace_id": f"{TRACE_PREFIX}{quest_id}",
+ "created_ms": now,
+ "updated_ms": now,
+ }
+ )
+ quest = await self.get(quest_id)
+ assert quest is not None
+ await self._announce(quest, previous=None)
+ return await self.route(quest_id, lang=lang)
+
+ async def route(self, quest_id: str, *, lang: str | None = None) -> QuestRecord:
+ """Pick the taker (forging one when nobody fits) and put the ASSIGN on the board."""
+ quest = await self.get(quest_id)
+ if quest is None:
+ raise KeyError(quest_id)
+ if quest.state in TERMINAL and quest.state is not QuestState.FAILED:
+ return quest
+ roster = self._runtime.roster
+ agents = await roster.list()
+ busy = {a.agent_id: self._runtime.scheduler.active_runs(a.agent_id) for a in agents}
+ choice = choose_taker(quest.text, agents, self._runtime.catalog(), busy=busy)
+ agent_id = choice.agent_id
+ if choice.forge is not None:
+ spec = dict(choice.forge)
+ skip = ("name", "title", "description", "tier", "reason")
+ fields = {k: v for k, v in spec.items() if k not in skip}
+ if "focus" not in fields and choice.focus:
+ fields["focus"] = list(choice.focus)
+ record, created = await roster.create(
+ name=spec["name"],
+ title=spec.get("title", ""),
+ description=spec.get("description", ""),
+ tier=spec.get("tier", Tier.SPECIALIST),
+ **fields,
+ )
+ agent_id = record.agent_id
+ if created:
+ log.info("society quests: forged %s for quest %s", record.name, quest_id)
+ if agent_id is None:
+ await self._set(quest, state=QuestState.OPEN, routing_json=json.dumps(choice.to_dict()))
+ fresh = await self.get(quest_id)
+ assert fresh is not None
+ return fresh
+ payload: dict[str, Any] = {
+ "text": quest.text,
+ "quest_id": quest_id,
+ "title": quest.title,
+ }
+ if lang in ("de", "en"):
+ payload["lang"] = lang
+ await self._set(
+ quest,
+ state=QuestState.ASSIGNED,
+ agent_id=agent_id,
+ run_id="",
+ result_json="{}",
+ done_ms=None,
+ routing_json=json.dumps({**choice.to_dict(), "agent_id": agent_id}),
+ )
+ env = await self._runtime.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.ASSIGN,
+ from_agent=quest.created_by or USER_ACTOR,
+ to_agent=agent_id,
+ trace_id=quest.trace_id,
+ payload=payload,
+ )
+ )
+ await self._runtime.store.update_quest(quest_id, {"assign_event_id": env.event_id})
+ fresh = await self.get(quest_id)
+ assert fresh is not None
+ return fresh
+
+ async def retry(self, quest_id: str, *, lang: str | None = None) -> QuestRecord:
+ """A failed or open quest goes back on the board and is routed again."""
+ quest = await self.get(quest_id)
+ if quest is None:
+ raise KeyError(quest_id)
+ if quest.state not in (QuestState.FAILED, QuestState.OPEN):
+ return quest
+ return await self.route(quest_id, lang=lang)
+
+ async def cancel(self, quest_id: str) -> QuestRecord:
+ """Take the quest off the board; a run in flight frees its slot and its
+ late RESULT is ignored (the turn itself finishes on its own)."""
+ quest = await self.get(quest_id)
+ if quest is None:
+ raise KeyError(quest_id)
+ if quest.state in TERMINAL:
+ return quest
+ if quest.run_id:
+ self._runtime.scheduler.note_run_ended(quest.run_id)
+ await self._set(quest, state=QuestState.CANCELLED, done_ms=now_ms())
+ fresh = await self.get(quest_id)
+ assert fresh is not None
+ return fresh
+
+ # ---------------------------------------------------------- listener
+
+ async def _on_envelope(self, env: SocietyEnvelope) -> None:
+ if not env.trace_id.startswith(TRACE_PREFIX):
+ return
+ row = await self._runtime.store.get_quest_row_by_trace(env.trace_id)
+ if row is None:
+ return
+ quest = QuestRecord.from_row(row)
+ if quest.state in TERMINAL:
+ return
+ if env.msg_type is MsgType.CLAIM:
+ run_id = str(env.payload.get("run_id") or "")
+ await self._set(quest, state=QuestState.RUNNING, agent_id=env.from_agent, run_id=run_id)
+ elif env.msg_type is MsgType.RESULT:
+ status = str(env.payload.get("status") or "done")
+ result = {
+ "status": status,
+ "done": env.payload.get("done", ""),
+ "output": env.payload.get("output", []),
+ "open": env.payload.get("open", []),
+ "text": env.text,
+ }
+ state = QuestState.FAILED if status == "blocked" else QuestState.DONE
+ await self._set(quest, state=state, result_json=json.dumps(result), done_ms=env.ts_ms)
+ elif env.msg_type is MsgType.VETO:
+ result = {
+ "status": "vetoed",
+ "reason": env.payload.get("reason", ""),
+ "retry": env.payload.get("retry", ""),
+ "text": env.text,
+ }
+ await self._set(
+ quest, state=QuestState.FAILED, result_json=json.dumps(result), done_ms=env.ts_ms
+ )
+
+ # ----------------------------------------------------------- helpers
+
+ async def _set(self, quest: QuestRecord, *, state: QuestState, **fields: Any) -> None:
+ fields["state"] = str(state)
+ fields["updated_ms"] = now_ms()
+ await self._runtime.store.update_quest(quest.quest_id, fields)
+ if state is not quest.state or "agent_id" in fields:
+ fresh = await self.get(quest.quest_id)
+ if fresh is not None:
+ await self._announce(fresh, previous=quest.state)
+
+ async def _announce(self, quest: QuestRecord, *, previous: QuestState | None) -> None:
+ """``SocietyQuestChanged`` on the app bus — the WebSocket forwards it,
+ the board in every open window re-reads within a second."""
+ try:
+ from jarvis.core.events import SocietyQuestChanged
+
+ event = SocietyQuestChanged(
+ source_layer="society",
+ quest_id=quest.quest_id,
+ state=str(quest.state),
+ previous=str(previous) if previous is not None else "",
+ agent_id=quest.agent_id or "",
+ title=quest.title,
+ )
+ if self._publish is not None:
+ maybe = self._publish(event)
+ else:
+ from jarvis.core.bus import get_default_bus
+
+ maybe = get_default_bus().publish(event)
+ if hasattr(maybe, "__await__"):
+ await maybe
+ except Exception: # noqa: BLE001 — a window that misses the push falls back to its poll
+ log.debug("society quests: change not pushed", exc_info=True)
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index 86128da649..7e5939252c 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -28,10 +28,11 @@ from .bridge import MissionBridge
from .browser.session import BrowserJobs
from .capabilities import CapabilityRow, build_catalog
from .checkpoints import CheckpointEngine
-from .events import MsgType, RoomState, SocietyEnvelope, Tier
+from .events import MsgType, QuestState, RoomState, SocietyEnvelope, Tier
from .focus import derive_approval_rules, derive_focus
from .learning import AgentSkills, LearningPass, TurnDigest, default_creator_factory
from .memory import SocietyMemory
+from .quests import Quests
from .rooms import Rooms
from .roster import LEAD_AGENT_ID, AgentRecord, Roster
from .scheduler import DeliverHook, SocietyScheduler
@@ -119,6 +120,8 @@ class SocietyRuntime:
self.checkpoints = CheckpointEngine(self)
#: The society's one memory service; every touch moves the figure to the Memory House.
self.memory = SocietyMemory(self, on_activity=self.checkpoints.note_memory_activity)
+ #: The Quest Board: the person's jobs, routed to one taker, read back off the board.
+ self.quests = Quests(self)
#: Roster rows the society surface read for a turn - the sync tool
#: filter reads them here (the briefing fills the cache first).
self._agent_cache: dict[str, AgentRecord] = {}
@@ -142,6 +145,7 @@ class SocietyRuntime:
if bus is not None:
self.bridge.attach(bus)
self.checkpoints.attach()
+ self.quests.attach()
await self.seed_lead()
if self._seed_starter_team:
created = await seed_first_run(self.roster, self.store)
@@ -164,6 +168,7 @@ class SocietyRuntime:
self.scheduler.detach()
self.bridge.detach()
self.checkpoints.detach()
+ self.quests.detach()
await self.store.close()
self._started = False
if current_runtime() is self:
@@ -416,6 +421,9 @@ class SocietyRuntime:
"running": running,
"last_seq": await self.store.last_seq(),
"rooms_running": len(await self.rooms.list(state=RoomState.RUNNING)),
+ "quests_open": len(await self.quests.list(state=QuestState.OPEN))
+ + len(await self.quests.list(state=QuestState.ASSIGNED))
+ + len(await self.quests.list(state=QuestState.RUNNING)),
"db_path": str(self.store.path),
}
diff --git a/jarvis/society/seeds.py b/jarvis/society/seeds.py
index 51004e6c27..7c3549dd6a 100644
--- a/jarvis/society/seeds.py
+++ b/jarvis/society/seeds.py
@@ -23,7 +23,7 @@ from .events import Tier
from .focus import derive_approval_rules, derive_focus
from .roster import Roster
-__all__ = ["STARTER_TEAM", "propose_seeds", "seed_first_run"]
+__all__ = ["STARTER_TEAM", "proposal_for_capability", "propose_seeds", "seed_first_run"]
_SEEDED_KEY: Final[str] = "seeded_starter_team"
@@ -136,6 +136,26 @@ def propose_seeds(
return out
+def proposal_for_capability(cap_id: str, catalog: list[CapabilityRow]) -> dict[str, Any] | None:
+ """The teammate proposed for ONE connected capability, ready for ``Roster.create``
+ (the quest board forges it when nobody on the roster fits a quest)."""
+ if not any(row.id == cap_id and row.connected for row in catalog):
+ return None
+ for proposal_cap, proposal in _PROPOSALS:
+ if proposal_cap != cap_id:
+ continue
+ focus = derive_focus(proposal["title"], proposal["description"], catalog)
+ if cap_id not in focus:
+ focus = [cap_id, *focus]
+ return {
+ **proposal,
+ "tier": str(Tier.SPECIALIST),
+ "focus": focus,
+ "approval_rules": derive_approval_rules(proposal["description"], focus),
+ }
+ return None
+
+
async def seed_first_run(roster: Roster, store: Any) -> list[str]:
"""Create the starter team once. Returns the ids created (empty later)."""
if await store.get_meta(_SEEDED_KEY, "0") == "1":
diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sql
index b7c51c9de4..1dc6fc0f57 100644
--- a/jarvis/society/society_schema.sql
+++ b/jarvis/society/society_schema.sql
@@ -122,6 +122,29 @@ CREATE TABLE IF NOT EXISTS approvals (
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);
+-- Quests: one job the person posts on the board; trusted Python routes it to
+-- exactly one agent (jarvis/society/quests.py) and the lifecycle is read off
+-- society_events on the quest's trace, never written by a model.
+CREATE TABLE IF NOT EXISTS society_quests (
+ quest_id TEXT PRIMARY KEY,
+ title TEXT NOT NULL,
+ text TEXT NOT NULL DEFAULT '',
+ state TEXT NOT NULL DEFAULT 'open'
+ CHECK (state IN ('open', 'assigned', 'running', 'done', 'failed', 'cancelled')),
+ created_by TEXT NOT NULL DEFAULT 'user',
+ agent_id TEXT, -- the taker, once routed
+ trace_id TEXT NOT NULL UNIQUE,
+ assign_event_id TEXT,
+ run_id TEXT NOT NULL DEFAULT '',
+ routing_json TEXT NOT NULL DEFAULT '{}', -- how the taker was chosen
+ result_json TEXT NOT NULL DEFAULT '{}', -- the handoff, or the typed refusal
+ created_ms INTEGER NOT NULL,
+ updated_ms INTEGER NOT NULL,
+ done_ms INTEGER
+);
+
+CREATE INDEX IF NOT EXISTS idx_society_quests_state ON society_quests(state, created_ms);
+
-- Kill switch, schema version and other single values.
CREATE TABLE IF NOT EXISTS society_meta (
key TEXT PRIMARY KEY,
diff --git a/jarvis/society/store.py b/jarvis/society/store.py
index 0c137c0c5a..2ff9a371ee 100644
--- a/jarvis/society/store.py
+++ b/jarvis/society/store.py
@@ -423,6 +423,62 @@ class SocietyStore:
# ----------------------------------------------------------- knowledge
+ # -------------------------------------------------------------- quests
+
+ async def insert_quest(self, row: dict[str, Any]) -> None:
+ cols = ", ".join(row)
+ marks = ", ".join("?" for _ in row)
+ await self.conn.execute(
+ f"INSERT INTO society_quests ({cols}) VALUES ({marks})", # noqa: S608 — identifiers from the caller's fixed dict, values bound
+ tuple(row.values()),
+ )
+
+ async def update_quest(self, quest_id: str, fields: dict[str, Any]) -> bool:
+ if not fields:
+ return False
+ sets = ", ".join(f"{k} = ?" for k in fields)
+ cur = await self.conn.execute(
+ f"UPDATE society_quests SET {sets} WHERE quest_id = ?", # noqa: S608 — identifiers from a fixed allowlist, values bound
+ (*fields.values(), quest_id),
+ )
+ await cur.close()
+ return bool(cur.rowcount)
+
+ async def get_quest_row(self, quest_id: str) -> dict[str, Any] | None:
+ self.conn.row_factory = aiosqlite.Row
+ cur = await self.conn.execute(
+ "SELECT * FROM society_quests WHERE quest_id = ?", (quest_id,)
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ return dict(row) if row else None
+
+ async def get_quest_row_by_trace(self, trace_id: str) -> dict[str, Any] | None:
+ self.conn.row_factory = aiosqlite.Row
+ cur = await self.conn.execute(
+ "SELECT * FROM society_quests WHERE trace_id = ?", (trace_id,)
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ return dict(row) if row else None
+
+ async def list_quest_rows(
+ self, *, state: str | None = None, limit: int = 200
+ ) -> list[dict[str, Any]]:
+ self.conn.row_factory = aiosqlite.Row
+ if state is not None:
+ cur = await self.conn.execute(
+ "SELECT * FROM society_quests WHERE state = ? ORDER BY created_ms DESC LIMIT ?",
+ (state, int(limit)),
+ )
+ else:
+ cur = await self.conn.execute(
+ "SELECT * FROM society_quests ORDER BY created_ms DESC LIMIT ?", (int(limit),)
+ )
+ rows = await cur.fetchall()
+ await cur.close()
+ return [dict(r) for r in rows]
+
async def insert_knowledge(self, row: dict[str, Any]) -> int:
cols = ", ".join(row.keys())
marks = ", ".join("?" for _ in row)
diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.ts
index cb6f76ec0f..c9a6e4ec0b 100644
--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts
@@ -55,6 +55,9 @@ 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];
+export const QUEST_STATES = ["open", "assigned", "running", "done", "failed", "cancelled"] as const;
+export type QuestState = (typeof QUEST_STATES)[number];
+
/** One row of the board, as GET /api/society/events returns it. */
export interface SocietyEnvelope {
seq: number;
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index c5e6600c60..849b7e126f 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -127,6 +127,12 @@ class AssignBody(BaseModel):
lang: str | None = None
+class CreateQuestBody(BaseModel):
+ text: str = Field(min_length=1, max_length=20_000)
+ title: str = Field(default="", max_length=120)
+ lang: str | None = None
+
+
class OpenRoomBody(BaseModel):
members: list[str] = Field(min_length=2, max_length=6)
topic: str = ""
@@ -311,6 +317,66 @@ async def kill_agent(agent_id: str, request: Request) -> dict[str, Any]:
return {"agent": paused.to_dict(), "runs_dropped": dropped}
+# ------------------------------------------------------------------ quests
+
+
+async def list_quests(
+ request: Request, state: str | None = None, limit: int = 200
+) -> dict[str, Any]:
+ """The Quest Board: newest first, optionally one state only."""
+ rt = await _runtime(request)
+ quests = await rt.quests.list(state=state or None, limit=max(1, min(int(limit), 1000)))
+ return {"quests": [q.to_dict() for q in quests]}
+
+
[email protected]("/quests", openapi_extra={"x-jarvis-dangerous": True})
+async def create_quest(body: CreateQuestBody, request: Request) -> dict[str, Any]:
+ """Post a quest: trusted Python routes it to one agent (forging one when
+ nobody fits) and the scheduler starts the work — this spends."""
+ rt = await _runtime(request)
+ try:
+ quest = await rt.quests.create(body.text, title=body.title, lang=body.lang)
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ except ValueError as exc:
+ raise HTTPException(422, str(exc)) from exc
+ return {"quest": quest.to_dict()}
+
+
[email protected]("/quests/{quest_id}")
+async def get_quest(quest_id: str, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ quest = await rt.quests.get(quest_id)
+ if quest is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ events = await rt.store.events_for_trace(quest.trace_id)
+ return {"quest": quest.to_dict(), "events": [e.model_dump() for e in events]}
+
+
[email protected]("/quests/{quest_id}/cancel", openapi_extra={"x-jarvis-dangerous": True})
+async def cancel_quest(quest_id: str, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ try:
+ quest = await rt.quests.cancel(quest_id)
+ except KeyError as exc:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc
+ return {"quest": quest.to_dict()}
+
+
[email protected]("/quests/{quest_id}/retry", openapi_extra={"x-jarvis-dangerous": True})
+async def retry_quest(quest_id: str, request: Request) -> dict[str, Any]:
+ """A failed or open quest is routed again (the taker may differ)."""
+ rt = await _runtime(request)
+ try:
+ quest = await rt.quests.retry(quest_id)
+ except KeyError as exc:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ return {"quest": quest.to_dict()}
+
+
# ------------------------------------------------------------------- board
diff --git a/tests/unit/society/test_quests.py b/tests/unit/society/test_quests.py
new file mode 100644
index 0000000000..6b774d8f16
--- /dev/null
+++ b/tests/unit/society/test_quests.py
@@ -0,0 +1,247 @@
+"""The Quest Board: routing, forging, the board-driven lifecycle, the push."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.society.capabilities import CapabilityKind, CapabilityRow
+from jarvis.society.events import MsgType, QuestState, SocietyEnvelope, Tier
+from jarvis.society.quests import GENERALIST, choose_taker, quest_title
+from jarvis.society.roster import AgentRecord
+from jarvis.society.runtime import SocietyRuntime
+
+
+def _cap(cap_id: str, label: str, *, connected: bool = True) -> CapabilityRow:
+ kind, _, name = cap_id.partition(":")
+ return CapabilityRow(
+ id=cap_id,
+ kind=CapabilityKind(kind),
+ tool_name=name,
+ label=label,
+ one_liner="",
+ risk_tier="safe",
+ connected=connected,
+ aliases=(),
+ )
+
+
+CATALOG = [
+ _cap("plugin:gmail", "Gmail"),
+ _cap("plugin:google-calendar", "Google Calendar"),
+ _cap("core:search-web", "Search the web"),
+]
+
+
+class FakeDispatcher:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, str]] = []
+
+ async def __call__(self, target: AgentRecord, env: SocietyEnvelope) -> str:
+ self.calls.append((target.agent_id, env.trace_id))
+ return f"run-{len(self.calls)}"
+
+
+async def rt(tmp_path: Path):
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ runtime.catalog = lambda: CATALOG # type: ignore[method-assign]
+ await runtime.ensure_started()
+ dispatcher = FakeDispatcher()
+ runtime.scheduler._dispatch = dispatcher # noqa: SLF001 — swap the hook for the fake
+ runtime.dispatcher = dispatcher # type: ignore[attr-defined]
+ pushed: list = []
+ runtime.quests._publish = pushed.append # noqa: SLF001
+ runtime.pushed = pushed # type: ignore[attr-defined]
+ try:
+ yield runtime
+ finally:
+ await runtime.close()
+
+
+# ------------------------------------------------------------------ routing
+
+
+def test_title_is_the_first_line_trimmed():
+ assert quest_title("Find the five most important mails\nfrom today") == (
+ "Find the five most important mails"
+ )
+ assert quest_title("x" * 100).endswith("…")
+ assert quest_title(" ", "Given") == "Given"
+ assert quest_title("") == "Quest"
+
+
+async def test_focus_match_picks_the_specialist(rt: SocietyRuntime):
+ mailbox, _ = await rt.roster.create(
+ name="Mailbox", title="Mail assistant", focus=["plugin:gmail"]
+ )
+ await rt.roster.create(
+ name="Planner", title="Calendar assistant", focus=["plugin:google-calendar"]
+ )
+ agents = await rt.roster.list()
+ choice = choose_taker("Summarize the five most important emails of today", agents, CATALOG)
+ assert choice.agent_id == mailbox.agent_id
+ assert choice.reason == "focus-match"
+ assert choice.forge is None
+
+
+async def test_name_in_the_quest_wins_without_focus(rt: SocietyRuntime):
+ scout, _ = await rt.roster.create(
+ name="Scout", title="Research coordinator", tier=Tier.ORCHESTRATOR
+ )
+ await rt.roster.create(name="Archivist", title="Knowledge curator")
+ agents = await rt.roster.list()
+ choice = choose_taker("Scout, what is new about solid-state batteries?", agents, CATALOG)
+ assert choice.agent_id == scout.agent_id
+ assert choice.reason == "keyword-match"
+
+
+async def test_the_lead_never_takes_a_quest(rt: SocietyRuntime):
+ agents = await rt.roster.list() # only Jarvis
+ choice = choose_taker("Jarvis, tidy the workshop", agents, CATALOG)
+ assert choice.agent_id is None
+ assert choice.forge is not None and choice.forge["name"] == GENERALIST["name"]
+ assert choice.reason == "forged:generalist"
+
+
+async def test_nobody_fits_forges_the_seed_for_the_capability(rt: SocietyRuntime):
+ await rt.roster.create(name="Archivist", title="Knowledge curator")
+ agents = await rt.roster.list()
+ choice = choose_taker("Sort my inbox and draft replies", agents, CATALOG)
+ assert choice.forge is not None and choice.forge["name"] == "Mailbox"
+ assert choice.reason == "forged:plugin:gmail"
+ assert "plugin:gmail" in choice.forge["focus"]
+
+
+async def test_a_disconnected_capability_forges_nothing_specific(rt: SocietyRuntime):
+ catalog = [_cap("plugin:gmail", "Gmail", connected=False)]
+ agents = await rt.roster.list()
+ choice = choose_taker("Sort my inbox", agents, catalog)
+ assert choice.forge is not None and choice.forge["name"] == GENERALIST["name"]
+
+
+async def test_busy_agents_lose_points_and_the_generalist_is_reused(rt: SocietyRuntime):
+ runner, _ = await rt.roster.create(name="Runner", title="Errand runner")
+ agents = await rt.roster.list()
+ choice = choose_taker("Water the plants", agents, CATALOG)
+ assert choice.agent_id == runner.agent_id and choice.reason == "generalist"
+ a, _ = await rt.roster.create(name="Alpha", focus=["plugin:gmail"])
+ b, _ = await rt.roster.create(name="Beta", focus=["plugin:gmail"])
+ agents = await rt.roster.list()
+ choice = choose_taker("mails", agents, CATALOG, busy={a.agent_id: 5})
+ assert choice.agent_id == b.agent_id
+
+
+# ---------------------------------------------------------------- lifecycle
+
+
+async def test_create_routes_assigns_and_the_claim_makes_it_running(rt: SocietyRuntime):
+ mailbox, _ = await rt.roster.create(name="Mailbox", focus=["plugin:gmail"])
+ quest = await rt.quests.create("Find the five most important mails of today")
+ assert quest.state is QuestState.RUNNING
+ assert quest.agent_id == mailbox.agent_id
+ assert quest.run_id == "run-1"
+ assert quest.routing["reason"] == "focus-match"
+ assert rt.dispatcher.calls == [(mailbox.agent_id, quest.trace_id)] # type: ignore[attr-defined]
+ events = await rt.store.events_for_trace(quest.trace_id)
+ assert [e.msg_type for e in events] == [MsgType.ASSIGN, MsgType.CLAIM]
+ assert events[0].payload["quest_id"] == quest.quest_id
+ states = [(p.state, p.previous) for p in rt.pushed] # type: ignore[attr-defined]
+ assert states == [("open", ""), ("assigned", "open"), ("running", "assigned")]
+
+
+async def test_result_closes_the_quest(rt: SocietyRuntime):
+ mailbox, _ = await rt.roster.create(name="Mailbox", focus=["plugin:gmail"])
+ quest = await rt.quests.create("Sort my mails")
+ await rt.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent=mailbox.agent_id,
+ to_agent=None,
+ trace_id=quest.trace_id,
+ payload={
+ "run_id": quest.run_id,
+ "status": "done",
+ "done": "Five mails summarized.",
+ "output": ["chat:society:mailbox"],
+ "text": "Five mails summarized.",
+ },
+ )
+ )
+ fresh = await rt.quests.get(quest.quest_id)
+ assert fresh is not None and fresh.state is QuestState.DONE
+ assert fresh.result["done"] == "Five mails summarized."
+ assert fresh.done_ms is not None
+ assert rt.scheduler.active_runs(mailbox.agent_id) == 0
+
+
+async def test_blocked_result_and_veto_fail_the_quest_and_retry_routes_again(rt: SocietyRuntime):
+ mailbox, _ = await rt.roster.create(
+ name="Mailbox", focus=["plugin:gmail"], max_concurrent_runs=1
+ )
+ first = await rt.quests.create("Sort my mails")
+ # The one slot is taken: the next quest is vetoed by the concurrency cap.
+ second = await rt.quests.create("Archive old mails")
+ assert second.state is QuestState.FAILED
+ assert second.result["status"] == "vetoed"
+ assert second.result["reason"] == "concurrency_cap"
+ # The first one ends blocked.
+ await rt.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent=mailbox.agent_id,
+ trace_id=first.trace_id,
+ payload={
+ "run_id": first.run_id,
+ "status": "blocked",
+ "done": "no login",
+ "open": ["login"],
+ },
+ )
+ )
+ assert (await rt.quests.get(first.quest_id)).state is QuestState.FAILED # type: ignore[union-attr]
+ # Retry: the slot is free again, the second quest runs.
+ retried = await rt.quests.retry(second.quest_id)
+ assert retried.state is QuestState.RUNNING
+ assert retried.result == {}
+
+
+async def test_cancel_frees_the_slot_and_ignores_the_late_result(rt: SocietyRuntime):
+ mailbox, _ = await rt.roster.create(name="Mailbox", focus=["plugin:gmail"])
+ quest = await rt.quests.create("Sort my mails")
+ cancelled = await rt.quests.cancel(quest.quest_id)
+ assert cancelled.state is QuestState.CANCELLED
+ assert rt.scheduler.active_runs(mailbox.agent_id) == 0
+ await rt.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent=mailbox.agent_id,
+ trace_id=quest.trace_id,
+ payload={"run_id": quest.run_id, "status": "done", "done": "late", "output": ["x"]},
+ )
+ )
+ assert (await rt.quests.get(quest.quest_id)).state is QuestState.CANCELLED # type: ignore[union-attr]
+ assert await rt.quests.cancel(quest.quest_id) is not None # idempotent
+
+
+async def test_forging_creates_the_teammate_on_the_roster(rt: SocietyRuntime):
+ quest = await rt.quests.create("Summarize my inbox")
+ assert quest.state is QuestState.RUNNING
+ forged = await rt.roster.get("mailbox")
+ assert forged is not None and forged.tier is Tier.SPECIALIST
+ assert "plugin:gmail" in forged.focus
+ assert quest.agent_id == "mailbox"
+ assert quest.routing["forged"] is True
+ # A second mail quest reuses it instead of forging again.
+ again = await rt.quests.create("Reply to yesterday's mails", title="Replies")
+ assert again.agent_id == "mailbox" and again.title == "Replies"
+ assert again.routing["forged"] is False
+
+
+async def test_status_counts_open_quests(rt: SocietyRuntime):
+ await rt.quests.create("Water the plants")
+ status = await rt.status()
+ assert status["quests_open"] == 1
+ listed = await rt.quests.list(state=QuestState.RUNNING)
+ assert len(listed) == 1 and listed[0].agent_id == "runner"
diff --git a/tests/unit/society/test_society_enum_parity.py b/tests/unit/society/test_society_enum_parity.py
index a8489ab833..ee2444e566 100644
--- a/tests/unit/society/test_society_enum_parity.py
+++ b/tests/unit/society/test_society_enum_parity.py
@@ -32,6 +32,7 @@ _PINS = [
(events.KnowledgeOrigin, "origin", "KNOWLEDGE_ORIGINS"),
(events.RoomState, None, "ROOM_STATES"),
(events.ApprovalState, None, "APPROVAL_STATES"),
+ (events.QuestState, "society_quests.state", "QUEST_STATES"),
(events.RunState, None, "RUN_STATES"),
]