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): confirming a proposal applies it - rules, focus, approval rules, routines, skills

rubenluetke10-beep0be630cb21e0
diff --git a/jarvis/society/learning.py b/jarvis/society/learning.py
index 2c81cd3403..e706096017 100644
--- a/jarvis/society/learning.py
+++ b/jarvis/society/learning.py
@@ -208,9 +208,22 @@ class LearningPass:
self._daily_cap = daily_cap
self._notify = notify
- async def run(self, agent: AgentRecord, digest: TurnDigest) -> str | None:
- """Learn from one finished turn; returns the new skill's slug or None."""
- if not should_learn(digest):
+ async def run(
+ self,
+ agent: AgentRecord,
+ digest: TurnDigest,
+ *,
+ name_hint: str = "",
+ force: bool = False,
+ ) -> str | None:
+ """Learn from one finished turn; returns the new skill's slug or None.
+
+ ``force`` skips the deterministic pre-filter — an explicitly requested
+ save ("save this as a skill called X", a confirmed proposal) has no
+ minimum step count. ``name_hint`` names the skill. The daily cap
+ stays either way.
+ """
+ if not force and not should_learn(digest):
return None
rt = self._runtime
key = _day_key(agent.agent_id)
@@ -234,9 +247,16 @@ class LearningPass:
extra = f"Agent: {agent.name}" + (f", {agent.title}" if agent.title else "")
if agent.description.strip():
extra += f"\nStanding instructions: {agent.description.strip()[:800]}"
+ if name_hint.strip():
+ intent += f"\n\nName the skill: {name_hint.strip()[:80]}"
try:
authored = await creator.author(
- SkillCreatorInput(intent=intent, extra_context=extra, category="learned")
+ SkillCreatorInput(
+ intent=intent,
+ extra_context=extra,
+ category="learned",
+ name_hint=name_hint.strip()[:80],
+ )
)
except Exception as exc: # noqa: BLE001 — learning never breaks anything
log.info("society learning: %s could not author a skill: %s", agent.agent_id, exc)
diff --git a/jarvis/society/proposals.py b/jarvis/society/proposals.py
index ad96f9bf31..e39f33f01d 100644
--- a/jarvis/society/proposals.py
+++ b/jarvis/society/proposals.py
@@ -35,10 +35,12 @@ __all__ = [
"CAPABILITY_PREFIX",
"PROPOSAL_KINDS",
"ProposalRefused",
+ "apply",
"capability_for",
"kind_of",
"propose",
"proposal_notice",
+ "resolve",
"resolved_notice",
"summarize",
"validate",
@@ -285,3 +287,162 @@ async def propose(
except Exception: # noqa: BLE001 — the queue holds the proposal; the card is a projection
log.warning("society: proposal card not posted for %s", agent.agent_id, exc_info=True)
return item
+
+
+# ------------------------------------------------------------------- apply
+
+
+def _merge_rules(current: dict[str, list[str]], add: dict[str, Any]) -> dict[str, list[str]]:
+ merged: dict[str, list[str]] = {}
+ for key in ("require_approval", "always_allow"):
+ seen = [x for x in current.get(key, []) if x]
+ for pattern in _strings(add.get(key)):
+ if pattern not in seen:
+ seen.append(pattern)
+ merged[key] = sorted(seen)
+ return merged
+
+
+async def _notify(rt: Any, agent: AgentRecord, item: Approval, *, status: str, text: str) -> None:
+ try:
+ await rt.post_chat_notice(agent, resolved_notice(agent, item, status=status, text=text))
+ except Exception: # noqa: BLE001 — the change is applied; the card is a projection
+ log.warning("society: proposal outcome not posted for %s", agent.agent_id, exc_info=True)
+
+
+async def _apply_skill_later(rt: Any, agent: AgentRecord, item: Approval, payload: dict) -> None:
+ """Author the skill in the background (a model call) and report on the card."""
+ from .learning import TurnDigest
+
+ digest = TurnDigest(
+ task=str(payload.get("goal") or ""),
+ final_text=str(payload.get("outcome") or "") or "Done as described.",
+ tool_steps=list(payload.get("steps") or []),
+ )
+ name = str(payload.get("name") or "")
+ try:
+ slug = await rt.learning.run(agent, digest, name_hint=name, force=True)
+ except Exception: # noqa: BLE001 — reported on the card, never lost in a log line alone
+ log.warning(
+ "society: skill proposal %s failed for %s", item.id, agent.agent_id, exc_info=True
+ )
+ slug = None
+ if slug:
+ await _notify(rt, agent, item, status="applied", text=f"Skill '{name}' saved as {slug}.")
+ else:
+ await _notify(
+ rt,
+ agent,
+ item,
+ status="failed",
+ text=f"Skill '{name}' could not be authored (no brain, or the daily cap is reached).",
+ )
+
+
+async def apply(
+ rt: Any, item: Approval, *, task_store: Any = None, scheduler: Any = None
+) -> dict[str, Any]:
+ """Apply one APPROVED proposal; returns ``{"applied", "detail", "kind"}``.
+
+ Never routed through ``PATCH /agents/{id}``: that route re-derives focus
+ and may overwrite approval rules, and a confirmed change must touch
+ exactly the field the person confirmed.
+ """
+ action = item.action
+ kind = str(action.get("kind") or kind_of(item.capability) or "")
+ payload = action.get("payload") or {}
+ agent = await rt.roster.get(item.agent_id)
+ if agent is None:
+ return {"applied": False, "detail": "the agent no longer exists", "kind": kind}
+ if not isinstance(payload, dict) or kind not in PROPOSAL_KINDS:
+ return {"applied": False, "detail": "malformed proposal", "kind": kind}
+ if kind == "rule":
+ text = (agent.description.rstrip() + "\n\n" + str(payload.get("text") or "")).strip()
+ await rt.roster.update(agent.agent_id, {"description": text})
+ return {"applied": True, "detail": "standing rule added to the description", "kind": kind}
+ if kind == "approval_rule":
+ merged = _merge_rules(agent.approval_rules, payload)
+ await rt.roster.update(agent.agent_id, {"approval_rules": merged})
+ return {"applied": True, "detail": "approval rules updated", "kind": kind}
+ if kind == "focus":
+ focus = _strings(payload.get("focus"))
+ await rt.roster.update(agent.agent_id, {"focus": focus})
+ return {"applied": True, "detail": "focus order updated", "kind": kind}
+ if kind == "routine":
+ from .routines import (
+ MAX_ROUTINES_PER_AGENT,
+ build_task_spec,
+ count_routines,
+ create_routine,
+ )
+
+ if task_store is None:
+ return {"applied": False, "detail": "the task store is not available", "kind": kind}
+ if await count_routines(task_store, agent.agent_id) >= MAX_ROUTINES_PER_AGENT:
+ return {"applied": False, "detail": "routine cap reached", "kind": kind}
+ try:
+ spec = build_task_spec(
+ agent,
+ title=str(payload.get("title") or ""),
+ prompt=str(payload.get("prompt") or ""),
+ schedule=dict(payload.get("schedule") or {}),
+ announce_on_success=payload.get("announce_on_success"),
+ )
+ except (ValueError, KeyError) as exc:
+ return {"applied": False, "detail": f"invalid routine: {exc}", "kind": kind}
+ task_id = await create_routine(task_store, scheduler, spec)
+ return {"applied": True, "detail": f"routine scheduled ({task_id})", "kind": kind}
+ if kind == "skill":
+ rt.background(_apply_skill_later(rt, agent, item, payload))
+ return {"applied": True, "detail": "authoring the skill", "kind": kind}
+ # team — onboarding
+ from .seeds import create_from_proposals
+
+ created = await create_from_proposals(rt.roster, rt.catalog(), _strings(payload.get("names")))
+ detail = "created " + ", ".join(created) if created else "no teammate created"
+ return {"applied": bool(created), "detail": detail, "kind": kind}
+
+
+async def resolve(
+ rt: Any,
+ approval_id: str,
+ *,
+ approve: bool,
+ note: str = "",
+ task_store: Any = None,
+ scheduler: Any = None,
+) -> dict[str, Any]:
+ """The person decided: record it, apply on yes, and report on the card.
+
+ Raises ``KeyError`` for an unknown id and ``ValueError`` when the item is
+ not a proposal or is already resolved.
+ """
+ current = await rt.approvals.get(approval_id)
+ if current is None:
+ raise KeyError(approval_id)
+ if kind_of(current.capability) is None:
+ raise ValueError("not a configuration proposal")
+ if current.state in (ApprovalState.APPROVED, ApprovalState.DENIED):
+ raise ValueError("already resolved")
+ if note.strip() and approve and current.action.get("kind") == "team":
+ # The card sends the picked names in the note (a comma-separated list).
+ picked = _strings([n.strip() for n in note.split(",")])
+ if picked:
+ current.action["payload"] = {**current.action.get("payload", {}), "names": picked}
+ item = await rt.approvals.resolve(approval_id, approve=approve, note=note)
+ item.action = current.action # the picked names ride along for apply
+ agent = await rt.roster.get(item.agent_id)
+ if not approve:
+ if agent is not None:
+ await _notify(rt, agent, item, status="rejected", text="Rejected; nothing changed.")
+ return {"proposal": item.to_dict(), "applied": False, "detail": "rejected"}
+ outcome = await apply(rt, item, task_store=task_store, scheduler=scheduler)
+ if agent is not None and outcome["kind"] != "skill":
+ await _notify(
+ rt,
+ agent,
+ item,
+ status="applied" if outcome["applied"] else "failed",
+ text=str(outcome["detail"]),
+ )
+ return {"proposal": item.to_dict(), **outcome}
diff --git a/jarvis/society/roster.py b/jarvis/society/roster.py
index 58da00a47e..f56e7f3b86 100644
--- a/jarvis/society/roster.py
+++ b/jarvis/society/roster.py
@@ -315,6 +315,16 @@ def _coerce(field_name: str, value: Any) -> Any:
raise RosterError(
FailureReason.BLOCKED_BY_POLICY, f"{field_name} must be a list of capability ids"
)
+ if field_name == "focus":
+ # Focus is an ORDERED list: the tools the agent reaches for first, in
+ # that order (the briefing and the tool schema list follow it). Dedupe,
+ # first occurrence wins, never sort — grants and denies are sets.
+ ordered: list[str] = []
+ for raw in value:
+ cap = raw.strip()
+ if cap and cap not in ordered:
+ ordered.append(cap)
+ return json.dumps(ordered)
return json.dumps(sorted({x.strip() for x in value if x.strip()}))
if field_name == "skills":
if value is None:
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index c2d4892852..55fac42219 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -218,6 +218,14 @@ class SocietyRuntime:
self._skills[agent_id] = skills
return skills
+ def background(self, coro: Any) -> asyncio.Task[Any]:
+ """Run a coroutine as a tracked task (cancelled on close, AP-30: its
+ own body reports failures — nothing here swallows them)."""
+ task = asyncio.create_task(coro)
+ self._watchers.add(task)
+ task.add_done_callback(self._watchers.discard)
+ return task
+
async def post_chat_notice(self, agent: AgentRecord, payload: dict[str, Any]) -> None:
"""A society notice in the agent's own chat — proposals, routine results,
learned skills. A no-op without a chat service or a bound session."""
diff --git a/jarvis/society/seeds.py b/jarvis/society/seeds.py
index 7c3549dd6a..238abfd26c 100644
--- a/jarvis/society/seeds.py
+++ b/jarvis/society/seeds.py
@@ -156,6 +156,31 @@ def proposal_for_capability(cap_id: str, catalog: list[CapabilityRow]) -> dict[s
return None
+async def create_from_proposals(
+ roster: Roster, catalog: list[CapabilityRow], names: list[str] | None = None
+) -> list[str]:
+ """Create the picked seed proposals (all when ``names`` is empty). Returns
+ the ids created. Shared by the seeds route and the onboarding proposal, so
+ the two paths cannot drift."""
+ taken = {a.name for a in await roster.list(include_archived=True)}
+ wanted = {n.strip().lower() for n in (names or []) if n.strip()}
+ created: list[str] = []
+ for proposal in propose_seeds(catalog, taken):
+ if wanted and proposal["name"].lower() not in wanted:
+ continue
+ fields = {k: v for k, v in proposal.items() if k in ("focus", "approval_rules")}
+ agent, was_created = await roster.create(
+ name=proposal["name"],
+ title=proposal["title"],
+ description=proposal["description"],
+ tier=proposal["tier"],
+ **fields,
+ )
+ if was_created:
+ created.append(agent.agent_id)
+ return created
+
+
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/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 47dca23a0e..7d1d84715b 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -448,24 +448,14 @@ class ApplySeedsBody(BaseModel):
@router.post("/seeds/apply")
async def apply_seed_proposals(body: ApplySeedsBody, request: Request) -> dict[str, Any]:
"""Create the picked proposals (all of them when ``names`` is empty)."""
- from jarvis.society.seeds import propose_seeds
+ from jarvis.society.seeds import create_from_proposals
rt = await _runtime(request)
- taken = {a.name for a in await rt.roster.list(include_archived=True)}
- wanted = {n.lower() for n in body.names}
+ ids = await create_from_proposals(rt.roster, rt.catalog(), body.names)
created = []
- for proposal in propose_seeds(rt.catalog(), taken):
- if wanted and proposal["name"].lower() not in wanted:
- continue
- fields = {k: v for k, v in proposal.items() if k in ("focus", "approval_rules")}
- agent, was_created = await rt.roster.create(
- name=proposal["name"],
- title=proposal["title"],
- description=proposal["description"],
- tier=proposal["tier"],
- **fields,
- )
- if was_created:
+ for agent_id in ids:
+ agent = await rt.roster.get(agent_id)
+ if agent is not None:
created.append(agent.to_dict())
return {"agents": created, "total": len(created)}
@@ -823,7 +813,20 @@ async def list_approvals(request: Request, agent_id: str | None = None) -> dict[
async def resolve_approval(
approval_id: str, body: ResolveApprovalBody, request: Request
) -> dict[str, Any]:
+ from jarvis.society.proposals import kind_of
+
rt = await _runtime(request)
+ current = await rt.approvals.get(approval_id)
+ if current is not None and kind_of(current.capability) is not None:
+ # A configuration proposal is applied by ITS route, never by this one:
+ # confirming here would flip the row without changing the agent.
+ raise HTTPException(
+ 409,
+ {
+ "reason": str(FailureReason.BLOCKED_BY_POLICY),
+ "detail": f"use POST /api/society/proposals/{approval_id}/resolve",
+ },
+ )
try:
item = await rt.approvals.resolve(approval_id, approve=body.approve, note=body.note)
except KeyError as exc:
@@ -846,6 +849,53 @@ async def resurface_approvals(request: Request) -> dict[str, Any]:
return {"approvals": [a.to_dict() for a in revived], "total": len(revived)}
+# ---------------------------------------------------------------- proposals
+
+
+class ResolveProposalBody(BaseModel):
+ approve: bool
+ note: str = ""
+
+
[email protected]("/proposals")
+async def list_proposals(request: Request, agent_id: str | None = None) -> dict[str, Any]:
+ """Configuration proposals still waiting for the person (agent-definition §3.5)."""
+ from jarvis.society.proposals import kind_of
+
+ rt = await _runtime(request)
+ await rt.approvals.expire_due()
+ items = [a for a in await rt.approvals.pending() if kind_of(a.capability) is not None]
+ if agent_id:
+ items = [a for a in items if a.agent_id == agent_id]
+ return {"proposals": [a.to_dict() for a in items], "total": len(items)}
+
+
[email protected]("/proposals/{proposal_id}/resolve", openapi_extra={"x-jarvis-dangerous": True})
+async def resolve_proposal(
+ proposal_id: str, body: ResolveProposalBody, request: Request
+) -> dict[str, Any]:
+ """The person decided on the card: a yes APPLIES the change (rule, focus,
+ approval rules, routine, skill, team), a no changes nothing."""
+ from jarvis.society import proposals
+
+ rt = await _runtime(request)
+ try:
+ return await proposals.resolve(
+ rt,
+ proposal_id,
+ approve=body.approve,
+ note=body.note,
+ task_store=getattr(request.app.state, "task_store", None),
+ scheduler=getattr(request.app.state, "task_scheduler", None),
+ )
+ except KeyError as exc:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc
+ except ValueError as exc:
+ raise HTTPException(
+ 409, {"reason": str(FailureReason.BLOCKED_BY_POLICY), "detail": str(exc)}
+ ) from exc
+
+
# ------------------------------------------------------------------- memory
diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.py
index 48b612a48e..f0052aed26 100644
--- a/tests/contract/test_agent_mcp_harmony.py
+++ b/tests/contract/test_agent_mcp_harmony.py
@@ -61,6 +61,14 @@ WITHHELD: Final[dict[str, str]] = {
"POST /api/society/agents/{agent_id}/model": (
"provider/model choice spends the owner's subscription — theirs to make"
),
+ "GET /api/society/proposals": (
+ "configuration proposals are decided on the card in the agent's chat by the "
+ "person who owns the agent; a remote client has no such card"
+ ),
+ "POST /api/society/proposals/{proposal_id}/resolve": (
+ "confirming a proposal changes an agent's rules, routines or skills — the "
+ "owner's decision at their own keyboard, never a remote client's"
+ ),
"GET /api/society/seeds": "starter-team proposals are onboarding UI, not an API verb",
"POST /api/society/seeds/apply": (
"onboarding, and it creates several agents at once — quest_post forges "
diff --git a/tests/unit/society/test_proposals_apply.py b/tests/unit/society/test_proposals_apply.py
new file mode 100644
index 0000000000..d4b81150a9
--- /dev/null
+++ b/tests/unit/society/test_proposals_apply.py
@@ -0,0 +1,210 @@
+"""Confirming a proposal applies it: rules, focus, approval rules, routines, skills.
+Rejecting changes nothing. A resolved proposal cannot be applied twice."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.society import proposals
+from jarvis.society.events import ApprovalState
+from jarvis.society.learning import LearningPass
+from jarvis.society.runtime import SocietyRuntime
+from tests.fakes.fake_agent_chat import FakeChatService
+from tests.unit.society.test_learning import SKILL_MD
+from tests.unit.society.test_routines import FakeScheduler, FakeTaskStore
+
+
+def _tool(name: str, desc: str = "does things.") -> SimpleNamespace:
+ return SimpleNamespace(name=name, description=desc, risk_tier="monitor")
+
+
+TOOLS = {
+ "gmail": _tool("gmail", "Read and send mail."),
+ "cli_gh": _tool("cli_gh", "GitHub CLI."),
+ "search-web": _tool("search-web", "Web search."),
+}
+
+
+class _Store:
+ def get_session(self, session_id: str):
+ return SimpleNamespace(session_id=session_id)
+
+
+async def world(tmp_path: Path):
+ svc = FakeChatService(_Store())
+ runtime = SocietyRuntime(
+ tmp_path,
+ seed_starter_team=False,
+ brain_tools=lambda: TOOLS,
+ chat_service=lambda: svc,
+ cfg=lambda: SimpleNamespace(
+ memory=SimpleNamespace(data_dir=str(tmp_path)),
+ wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")),
+ ),
+ )
+ await runtime.ensure_started()
+ await runtime.roster.create(
+ name="Mailbox",
+ title="Gmail agent",
+ description="Handle my mail.",
+ focus=["plugin:gmail"],
+ approval_rules={"require_approval": ["plugin:gmail:send"], "always_allow": []},
+ )
+ try:
+ yield runtime, svc
+ finally:
+ await runtime.close()
+
+
+async def _propose(rt, kind: str, payload: dict):
+ agent = await rt.roster.get("mailbox")
+ return await proposals.propose(
+ rt, agent, kind=kind, payload=payload, reason="test", session_id="society:mailbox"
+ )
+
+
+async def test_confirming_a_rule_appends_to_the_description_and_leaves_focus_alone(world):
+ rt, svc = world
+ item = await _propose(rt, "rule", {"text": "Always answer in English."})
+ out = await proposals.resolve(rt, item.id, approve=True)
+ assert out["applied"] is True and out["kind"] == "rule"
+ agent = await rt.roster.get("mailbox")
+ assert agent.description == "Handle my mail.\n\nAlways answer in English."
+ assert agent.focus == ["plugin:gmail"]
+ assert agent.approval_rules["require_approval"] == ["plugin:gmail:send"]
+ assert (await rt.approvals.get(item.id)).state is ApprovalState.APPROVED
+ kinds = [n["kind"] for _, n in svc.notices]
+ assert kinds == ["proposal", "proposal_resolved"]
+ assert svc.notices[-1][1]["status"] == "applied"
+
+
+async def test_confirming_an_approval_rule_merges_and_dedupes_the_patterns(world):
+ rt, _ = world
+ item = await _propose(
+ rt,
+ "approval_rule",
+ {"require_approval": ["plugin:gmail:send", "cli:gh:*"], "always_allow": ["plugin:gmail"]},
+ )
+ out = await proposals.resolve(rt, item.id, approve=True)
+ assert out["applied"] is True
+ agent = await rt.roster.get("mailbox")
+ assert agent.approval_rules == {
+ "require_approval": ["cli:gh:*", "plugin:gmail:send"],
+ "always_allow": ["plugin:gmail"],
+ }
+ assert agent.description == "Handle my mail."
+
+
+async def test_confirming_a_focus_change_keeps_the_order_the_agent_asked_for(world):
+ rt, _ = world
+ item = await _propose(rt, "focus", {"focus": ["cli:gh", "plugin:gmail", "core:search-web"]})
+ await proposals.resolve(rt, item.id, approve=True)
+ agent = await rt.roster.get("mailbox")
+ assert agent.focus == ["cli:gh", "plugin:gmail", "core:search-web"]
+
+
+async def test_confirming_a_routine_creates_a_tagged_task(world):
+ rt, _ = world
+ store = FakeTaskStore()
+ scheduler = FakeScheduler(store)
+ item = await _propose(
+ rt,
+ "routine",
+ {
+ "title": "Inbox sweep",
+ "prompt": "Sort the inbox and draft replies.",
+ "schedule": {"kind": "every", "interval_seconds": 3600},
+ },
+ )
+ out = await proposals.resolve(rt, item.id, approve=True, task_store=store, scheduler=scheduler)
+ assert out["applied"] is True, out
+ assert scheduler.scheduled == ["task-1"]
+ assert store.rows[0]["title"] == "[agent:Mailbox] Inbox sweep"
+ assert "agent:mailbox" in store.rows[0]["spec_json"]
+ # Without a task store the outcome is honest, never a silent success.
+ again = await _propose(
+ rt, "routine", {"title": "B", "prompt": "b", "schedule": {"kind": "every"}}
+ )
+ out2 = await proposals.resolve(rt, again.id, approve=True)
+ assert out2["applied"] is False and "task store" in out2["detail"]
+
+
+async def test_confirming_a_skill_authors_it_in_the_background(world):
+ rt, svc = world
+
+ class FakeCreator:
+ def __init__(self, skills) -> None:
+ self.skills = skills
+ self.inputs = []
+
+ async def author(self, inp):
+ self.inputs.append(inp)
+ slug = "weekly-digest"
+ folder = self.skills.root / slug
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "SKILL.md").write_text(
+ SKILL_MD.format(name="Weekly digest", description="Digest the week"),
+ encoding="utf-8",
+ )
+ return SimpleNamespace(
+ skill=SimpleNamespace(path=folder / "SKILL.md"), name="Weekly digest", slug=slug
+ )
+
+ creators: list[FakeCreator] = []
+
+ def factory(agent, skills):
+ creator = FakeCreator(skills)
+ creators.append(creator)
+ return creator
+
+ rt.learning = LearningPass(rt, creator_factory=factory)
+ item = await _propose(
+ rt,
+ "skill",
+ {"name": "Weekly digest", "goal": "Summarise the week", "steps": [], "outcome": "ok"},
+ )
+ out = await proposals.resolve(rt, item.id, approve=True)
+ assert out["applied"] is True and out["detail"] == "authoring the skill"
+ await asyncio.gather(*list(rt._watchers)) # noqa: SLF001 — drain the background task
+ assert creators and creators[0].inputs[0].name_hint == "Weekly digest"
+ assert [s["slug"] for s in rt.skills_for("mailbox").summaries()] == ["weekly-digest"]
+ last = svc.notices[-1][1]
+ assert last["kind"] == "proposal_resolved" and last["status"] == "applied"
+ assert "weekly-digest" in last["text"]
+
+
+async def test_rejecting_a_proposal_changes_nothing_and_posts_a_notice(world):
+ rt, svc = world
+ item = await _propose(rt, "rule", {"text": "Be terse."})
+ out = await proposals.resolve(rt, item.id, approve=False)
+ assert out["applied"] is False
+ agent = await rt.roster.get("mailbox")
+ assert agent.description == "Handle my mail."
+ assert (await rt.approvals.get(item.id)).state is ApprovalState.DENIED
+ assert svc.notices[-1][1]["status"] == "rejected"
+
+
+async def test_a_resolved_proposal_cannot_be_applied_twice(world):
+ rt, _ = world
+ item = await _propose(rt, "rule", {"text": "Be terse."})
+ await proposals.resolve(rt, item.id, approve=True)
+ with pytest.raises(ValueError, match="already resolved"):
+ await proposals.resolve(rt, item.id, approve=True)
+ with pytest.raises(KeyError):
+ await proposals.resolve(rt, "nope", approve=True)
+ agent = await rt.roster.get("mailbox")
+ assert agent.description.count("Be terse.") == 1
+
+
+async def test_a_plain_approval_is_not_a_proposal(world):
+ rt, _ = world
+ plain = await rt.approvals.enqueue(
+ agent_id="mailbox", trace_id="t", capability="core:shell", action={}, summary="rm -rf"
+ )
+ with pytest.raises(ValueError, match="not a configuration proposal"):
+ await proposals.resolve(rt, plain.id, approve=True)
diff --git a/tests/unit/society/test_roster.py b/tests/unit/society/test_roster.py
index 9d432de1eb..9e1e3b05d6 100644
--- a/tests/unit/society/test_roster.py
+++ b/tests/unit/society/test_roster.py
@@ -172,3 +172,16 @@ def test_record_to_dict_is_json_shaped(tmp_path: Path):
assert d["approval_rules"] == {"require_approval": [], "always_allow": []}
assert d["skills"] == ["a"]
assert d["session_id"] == "society:x"
+
+
+async def test_focus_keeps_the_order_it_was_given(roster: Roster):
+ """Focus is what the agent reaches for FIRST, in that order — never sorted."""
+ agent, _ = await roster.create(
+ name="Mailbox",
+ focus=["plugin:gmail", "cli:gh", "plugin:gmail", "core:search-web"],
+ grants=["z", "a"],
+ )
+ assert agent.focus == ["plugin:gmail", "cli:gh", "core:search-web"]
+ assert agent.grants == ["a", "z"] # grants stay a sorted set
+ updated = await roster.update("mailbox", {"focus": ["core:search-web", "plugin:gmail"]})
+ assert updated.focus == ["core:search-web", "plugin:gmail"]