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): an agent proposes a change to itself and the person decides
rubenluetke10-beep3a3669cc5f8e
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex a2e54cf89d..6c074ea73b 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -37,10 +37,12 @@ log = logging.getLogger(__name__)__all__ = ["MEMORY_RECALL_TOOL_NAME","MESSAGE_TOOL_NAME",+ "PROPOSE_TOOL_NAME","SHELL_TOOL_NAME","WIKI_NOTE_TOOL_NAME","MemoryRecallTool","MessageAgentTool",+ "ProposeChangeTool","ShellTool","WikiNoteTool",]@@ -49,6 +51,7 @@ MESSAGE_TOOL_NAME: Final[str] = "society_message_agent"WIKI_NOTE_TOOL_NAME: Final[str] = "society_wiki_note"SHELL_TOOL_NAME: Final[str] = "society_shell"MEMORY_RECALL_TOOL_NAME: Final[str] = "society_memory_recall"+PROPOSE_TOOL_NAME: Final[str] = "society_propose_change"_KINDS: Final[dict[str, MsgType]] = {"say": MsgType.SAY,"query": MsgType.QUERY,@@ -292,6 +295,87 @@ class MemoryRecallTool:)+class ProposeChangeTool:+ """``society_propose_change`` — configuration by chat (agent-definition §3.5).++ The agent proposes ONE change to itself; the proposal parks in the+ approvals queue and shows as a card in this chat. Nothing changes until+ the person confirms it there — proposing is therefore a safe-tier action.+ """++ name: str = PROPOSE_TOOL_NAME+ risk_tier: str = "safe"+ description: str = (+ "Propose ONE change to how you work - the user confirms it on a card in this chat "+ "before anything changes. kind 'rule' adds a standing instruction to your "+ "description ({text}); 'skill' saves the procedure you just used under a name "+ "({name, goal, steps[], outcome}); 'routine' schedules recurring work "+ "({title, prompt, schedule: {kind: every|at_time|after_delay|on_event, ...}}); "+ "'approval_rule' changes what needs the user's approval ({require_approval[], "+ "always_allow[]} of capability ids like plugin:gmail:send); 'focus' changes which "+ "tools you reach for first ({focus[]}, the full ordered list). Say why in 'reason'. "+ "Use it when the user states a lasting preference, asks you to remember a way of "+ "working, to save a procedure, or to run something regularly. Never propose the "+ "same thing twice in one turn."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "enum": ["rule", "skill", "routine", "approval_rule", "focus"],+ "description": "What kind of change you propose.",+ },+ "payload": {+ "type": "object",+ "description": "The change itself; keys depend on kind (see the tool description).",+ },+ "reason": {+ "type": "string",+ "description": "One sentence: why this change helps the user.",+ },+ },+ "required": ["kind", "payload"],+ }++ def __init__(self, runtime: Any, agent_id: str, *, session_id: str = "") -> None:+ self._runtime = runtime+ self._agent_id = agent_id+ self._session_id = session_id++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ from .proposals import ProposalRefused, propose++ rt = self._runtime+ if await rt.store.kill_switch():+ return _failure(FailureReason.KILL_SWITCH, "the society is halted")+ caller = await rt.roster.get(self._agent_id)+ if caller is None or caller.state is not AgentState.ACTIVE:+ return _failure(FailureReason.BLOCKED_BY_POLICY, "caller is not an active agent")+ kind = str(args.get("kind") or "").strip().lower()+ try:+ item = await propose(+ rt,+ caller,+ kind=kind,+ payload=args.get("payload"),+ reason=str(args.get("reason") or ""),+ session_id=self._session_id or caller.session_id,+ )+ except ProposalRefused as exc:+ return _failure(exc.reason, exc.detail)+ return ToolResult(+ success=True,+ output={+ "proposal_id": item.id,+ "kind": kind,+ "status": "pending",+ "summary": item.summary,+ "note": "waiting for the user to confirm on the card in this chat",+ },+ )++class ShellTool:"""Run a command in the agent's OWN workspace folder (agent-definition §3).diff --git a/jarvis/society/proposals.py b/jarvis/society/proposals.pynew file mode 100644index 0000000000..ad96f9bf31--- /dev/null+++ b/jarvis/society/proposals.py@@ -0,0 +1,287 @@+"""Configuration by chat: the agent PROPOSES a change to itself, the person+CONFIRMS it on a card in the chat, and only then does anything change.++A proposal is an ordinary row in the approvals queue whose capability is+``core:config:<kind>`` and whose ``action`` carries the typed payload — no new+table, no new enum, no new chat event kind. The card rides a ``notice`` event+(``payload.kind == "proposal"``), its outcome a second one+(``payload.kind == "proposal_resolved"``). Nothing here applies a change:+:func:`apply` runs only from the resolve route once the person said yes.++Kinds (agent-definition §3.5):++* ``rule`` — one standing instruction appended to the agent's description;+* ``skill`` — the procedure of the current turn saved under a name;+* ``routine`` — recurring work as a tagged Automations task;+* ``approval_rule`` — patterns for ``require_approval`` / ``always_allow``;+* ``focus`` — the full ordered list of tools the agent reaches for first;+* ``team`` — teammates proposed at onboarding (the lead only).+"""++from __future__ import annotations++import logging+from typing import Any, Final++from .approvals import Approval+from .capabilities import CapabilityRow+from .events import ApprovalState+from .failure_reasons import FailureReason+from .roster import AgentRecord++log = logging.getLogger(__name__)++__all__ = [+ "CAPABILITY_PREFIX",+ "PROPOSAL_KINDS",+ "ProposalRefused",+ "capability_for",+ "kind_of",+ "propose",+ "proposal_notice",+ "resolved_notice",+ "summarize",+ "validate",+]++PROPOSAL_KINDS: Final[frozenset[str]] = frozenset(+ {"rule", "skill", "routine", "approval_rule", "focus", "team"}+)+CAPABILITY_PREFIX: Final[str] = "core:config:"+#: Schedule kinds the Automations scheduler can keep (``jarvis/tasks/schema.py``).+#: There is deliberately no weekday form: the model must not promise what the+#: scheduler cannot run (plan decision D4).+SCHEDULE_KINDS: Final[frozenset[str]] = frozenset({"every", "at_time", "after_delay", "on_event"})+_MAX_RULE: Final[int] = 600+_MAX_TEXT: Final[int] = 2_000+_MAX_LIST: Final[int] = 24+_MAX_SUMMARY: Final[int] = 200+++class ProposalRefused(Exception):+ """A proposal the tool refuses with a typed reason (never a silent drop)."""++ def __init__(self, reason: FailureReason, detail: str) -> None:+ super().__init__(f"{reason}: {detail}")+ self.reason = reason+ self.detail = detail+++def capability_for(kind: str) -> str:+ return f"{CAPABILITY_PREFIX}{kind}"+++def kind_of(capability: str) -> str | None:+ """The proposal kind behind a capability id; ``None`` for a non-proposal."""+ if not capability.startswith(CAPABILITY_PREFIX):+ return None+ kind = capability[len(CAPABILITY_PREFIX) :]+ return kind if kind in PROPOSAL_KINDS else None+++def _text(value: Any, *, limit: int) -> str:+ return str(value or "").strip()[:limit]+++def _strings(value: Any, *, limit: int = _MAX_LIST) -> list[str]:+ if isinstance(value, str):+ value = [value]+ if not isinstance(value, list):+ return []+ out: list[str] = []+ for item in value:+ text = str(item or "").strip()+ if text and text not in out:+ out.append(text)+ return out[:limit]+++def _capability_root(pattern: str) -> str:+ """``plugin:gmail:send`` and ``plugin:gmail:*`` → ``plugin:gmail``; ``plugin:*`` stays."""+ pattern = pattern.strip()+ if pattern.endswith(":*"):+ head = pattern[:-2]+ return head if ":" in head else pattern+ parts = pattern.split(":")+ if len(parts) >= 3:+ return ":".join(parts[:2])+ return pattern+++def _check_capabilities(patterns: list[str], catalog: list[CapabilityRow]) -> None:+ known = {row.id for row in catalog}+ for pattern in patterns:+ root = _capability_root(pattern)+ if root.endswith(":*"):+ kind = root[:-2]+ if not any(row.id.startswith(kind + ":") for row in catalog):+ raise ProposalRefused(FailureReason.TARGET_UNKNOWN, f"no capability kind {kind!r}")+ continue+ if root not in known:+ raise ProposalRefused(FailureReason.TARGET_UNKNOWN, f"unknown capability {root!r}")+++def validate(kind: str, payload: Any, *, catalog: list[CapabilityRow]) -> dict[str, Any]:+ """Normalise one payload for ``kind``; extra keys are dropped, bad ones refused."""+ if kind not in PROPOSAL_KINDS:+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, f"unknown proposal kind {kind!r}")+ if not isinstance(payload, dict):+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "payload must be an object")+ if kind == "rule":+ text = _text(payload.get("text"), limit=_MAX_RULE)+ if not text:+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "a rule needs text")+ return {"text": text}+ if kind == "skill":+ name = _text(payload.get("name"), limit=80)+ goal = _text(payload.get("goal"), limit=_MAX_TEXT)+ steps = _strings(payload.get("steps"))+ outcome = _text(payload.get("outcome"), limit=_MAX_TEXT)+ if not name or not goal:+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY, "a skill needs a name and a goal"+ )+ return {"name": name, "goal": goal, "steps": steps, "outcome": outcome}+ if kind == "routine":+ title = _text(payload.get("title"), limit=120)+ prompt = _text(payload.get("prompt"), limit=_MAX_TEXT)+ schedule = payload.get("schedule")+ if not title or not prompt:+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY, "a routine needs a title and a prompt"+ )+ if not isinstance(schedule, dict):+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY, "a routine needs a schedule object"+ )+ raw_kind = schedule.get("kind") or schedule.get("type") or "every"+ schedule_kind = str(raw_kind).strip().lower()+ if schedule_kind not in SCHEDULE_KINDS:+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY,+ f"schedule kind {schedule_kind!r} is not one the scheduler keeps "+ f"({', '.join(sorted(SCHEDULE_KINDS))})",+ )+ clean = {+ "kind": schedule_kind,+ **{k: v for k, v in schedule.items() if k not in ("kind", "type")},+ }+ out: dict[str, Any] = {"title": title, "prompt": prompt, "schedule": clean}+ announce = _text(payload.get("announce_on_success"), limit=300)+ if announce:+ out["announce_on_success"] = announce+ return out+ if kind == "approval_rule":+ require = _strings(payload.get("require_approval"))+ allow = _strings(payload.get("always_allow"))+ if not require and not allow:+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY, "an approval rule needs a pattern"+ )+ _check_capabilities(require + allow, catalog)+ return {"require_approval": require, "always_allow": allow}+ if kind == "focus":+ focus = _strings(payload.get("focus"))+ if not focus:+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "a focus change needs the list")+ _check_capabilities(focus, catalog)+ return {"focus": focus}+ names = _strings(payload.get("names"))+ if not names:+ raise ProposalRefused(FailureReason.BLOCKED_BY_POLICY, "a team proposal needs names")+ out_team: dict[str, Any] = {"names": names}+ proposals = payload.get("proposals")+ if isinstance(proposals, list):+ out_team["proposals"] = [p for p in proposals if isinstance(p, dict)][:_MAX_LIST]+ return out_team+++def summarize(kind: str, payload: dict[str, Any]) -> str:+ """One card line for the person (≤200 chars)."""+ if kind == "rule":+ line = f"Add a standing rule: {payload.get('text', '')}"+ elif kind == "skill":+ line = f"Save the procedure as skill '{payload.get('name', '')}'"+ elif kind == "routine":+ schedule = payload.get("schedule") or {}+ line = f"Schedule '{payload.get('title', '')}' ({schedule.get('kind', 'every')})"+ elif kind == "approval_rule":+ parts: list[str] = []+ if payload.get("require_approval"):+ parts.append("ask first: " + ", ".join(payload["require_approval"]))+ if payload.get("always_allow"):+ parts.append("always allow: " + ", ".join(payload["always_allow"]))+ line = "Approval rules — " + "; ".join(parts)+ elif kind == "focus":+ line = "Reach first for: " + ", ".join(payload.get("focus", []))+ else:+ line = "Create teammates: " + ", ".join(payload.get("names", []))+ return line[:_MAX_SUMMARY]+++def proposal_notice(agent: AgentRecord, item: Approval) -> dict[str, Any]:+ action = item.action+ kind = str(action.get("kind") or kind_of(item.capability) or "")+ return {+ "kind": "proposal",+ "proposal_id": item.id,+ "proposal_kind": kind,+ "summary": item.summary,+ "payload": action.get("payload") or {},+ "reason": str(action.get("reason") or ""),+ "status": "pending",+ "agent_id": agent.agent_id,+ "agent_name": agent.name,+ "text": item.summary,+ }+++def resolved_notice(+ agent: AgentRecord, item: Approval, *, status: str, text: str+) -> dict[str, Any]:+ return {+ "kind": "proposal_resolved",+ "proposal_id": item.id,+ "proposal_kind": str(item.action.get("kind") or kind_of(item.capability) or ""),+ "status": status,+ "text": text,+ "agent_id": agent.agent_id,+ "agent_name": agent.name,+ }+++async def propose(+ rt: Any,+ agent: AgentRecord,+ *,+ kind: str,+ payload: Any,+ reason: str,+ session_id: str,+) -> Approval:+ """Validate, queue, and show the card. Raises :class:`ProposalRefused`."""+ clean = validate(kind, payload, catalog=rt.catalog())+ for item in await rt.approvals.items(state=ApprovalState.PENDING, agent_id=agent.agent_id):+ action = item.action+ if action.get("kind") == kind and action.get("payload") == clean:+ raise ProposalRefused(+ FailureReason.BLOCKED_BY_POLICY,+ f"the same {kind} proposal is already waiting for the user ({item.id})",+ )+ item = await rt.approvals.enqueue(+ agent_id=agent.agent_id,+ trace_id=f"config:{agent.agent_id}:{session_id}"[:120],+ capability=capability_for(kind),+ action={+ "kind": kind,+ "payload": clean,+ "reason": _text(reason, limit=600),+ "session_id": session_id,+ },+ summary=summarize(kind, clean),+ )+ try:+ await rt.post_chat_notice(agent, proposal_notice(agent, item))+ 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 itemdiff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex b12b0132f7..f91896c952 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -212,6 +212,11 @@ class SocietyRuntime:self._skills[agent_id] = skillsreturn skills+ 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."""+ await self._notify_chat(agent, payload)+async def _notify_chat(self, agent: AgentRecord, payload: dict[str, Any]) -> None:"""A society notice in the agent's own chat (learned skill, login needed)."""svc = self._get_chat()diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 00281a8ee7..80a2ace188 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -27,7 +27,13 @@ from typing import Any, Final, castfrom jarvis.core.protocols import Tool-from .agent_tools import MemoryRecallTool, MessageAgentTool, ShellTool, WikiNoteTool+from .agent_tools import (+ MemoryRecallTool,+ MessageAgentTool,+ ProposeChangeTool,+ ShellTool,+ WikiNoteTool,+)from .capabilities import CapabilityKind, CapabilityRow, select_toolsfrom .learning import RunLearnedSkillToolfrom .memory import resolve_society_vault@@ -77,6 +83,10 @@ society_wiki_note (kind memory for durable facts, note for findings, shared to pknowledge the user reviews). Never edit the user's own pages.- Routines: recurring work runs from the Automations section as tasks tagged with your name; \their results arrive in this chat.+- Configuring yourself: when the user states a lasting preference, a rule, a procedure worth \+keeping, or recurring work, call society_propose_change (kinds rule, skill, routine, \+approval_rule, focus). The user confirms it on a card in this chat; nothing changes before \+that, so never claim a rule or routine exists until the card says it was applied.- Approvals: actions above your permission ceiling queue for the user (chat card, Jarvis bar, \voice). A queued action is not refused — say what you are waiting for and continue with what \you can. Secrets are never typed into a chat; credentials come from the keyring.@@ -135,6 +145,12 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:),ShellTool.name: cast(Tool, ShellTool(rt, agent_id, workspace=workspace)),RunLearnedSkillTool.name: cast(Tool, RunLearnedSkillTool(rt, agent_id)),+ ProposeChangeTool.name: cast(+ Tool,+ ProposeChangeTool(+ rt, agent_id, session_id=str(getattr(session, "session_id", "") or "")+ ),+ ),})if rt.browser.is_installed():diff --git a/tests/fakes/fake_agent_chat.py b/tests/fakes/fake_agent_chat.pyindex 86ba1cf997..beddfd71f0 100644--- a/tests/fakes/fake_agent_chat.py+++ b/tests/fakes/fake_agent_chat.py@@ -32,6 +32,7 @@ class FakeChatService:def __init__(self, store: Any, script: list[dict[str, Any]] | None = None) -> None:self.store = storeself.sent: list[tuple[str, str]] = []+ self.notices: list[tuple[str, dict[str, Any]]] = []self.busy: set[str] = set()self._subs: dict[str, set[asyncio.Queue[Any]]] = {}self._script = script@@ -58,5 +59,12 @@ class FakeChatService:q.put_nowait({"kind": event["kind"], "payload": payload})return turn_id+ async def post_notice(self, session_id: str, payload: dict[str, Any]) -> None:+ """A notice outside a turn (a proposal card, a routine result), recorded+ and fanned out like the real service does."""+ self.notices.append((session_id, dict(payload)))+ for q in self._subs.get(session_id, set()):+ q.put_nowait({"kind": "notice", "payload": dict(payload)})+__all__ = ["FakeChatService", "default_script"]diff --git a/tests/unit/society/test_proposals.py b/tests/unit/society/test_proposals.pynew file mode 100644index 0000000000..1a916d523c--- /dev/null+++ b/tests/unit/society/test_proposals.py@@ -0,0 +1,190 @@+"""Configuration by chat: the agent proposes, the queue holds it, the card shows it,+and nothing changes until the person confirms."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.society.agent_tools import ProposeChangeTool+from jarvis.society.events import ApprovalState+from jarvis.society.proposals import (+ ProposalRefused,+ capability_for,+ kind_of,+ summarize,+ validate,+)+from jarvis.society.runtime import SocietyRuntime+from tests.fakes.fake_agent_chat import FakeChatService+++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."),+}++CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)+++class _Store:+ """The chat store the runtime asks for a bound session."""++ def __init__(self, session_ids: set[str]) -> None:+ self._ids = session_ids++ def get_session(self, session_id: str):+ return SimpleNamespace(session_id=session_id) if session_id in self._ids else None+++async def world(tmp_path: Path):+ svc = FakeChatService(_Store({"society:mailbox"}))+ runtime = SocietyRuntime(+ tmp_path,+ seed_starter_team=False,+ brain_tools=lambda: TOOLS,+ chat_service=lambda: svc,+ )+ await runtime.ensure_started()+ await runtime.roster.create(name="Mailbox", title="Gmail agent", description="Handle mail.")+ try:+ yield runtime, svc+ finally:+ await runtime.close()+++def test_capability_ids_round_trip():+ assert capability_for("rule") == "core:config:rule"+ assert kind_of("core:config:rule") == "rule"+ assert kind_of("core:config:nonsense") is None+ assert kind_of("plugin:gmail") is None+++def test_validate_normalises_and_summarises():+ catalog = [SimpleNamespace(id="plugin:gmail"), SimpleNamespace(id="cli:gh")]+ rule = validate("rule", {"text": " Answer in English. ", "extra": 1}, catalog=catalog)+ assert rule == {"text": "Answer in English."}+ assert summarize("rule", rule) == "Add a standing rule: Answer in English."+ rules = validate(+ "approval_rule",+ {+ "require_approval": ["plugin:gmail:send", "plugin:gmail:send"],+ "always_allow": "cli:gh:*",+ },+ catalog=catalog,+ )+ assert rules == {"require_approval": ["plugin:gmail:send"], "always_allow": ["cli:gh:*"]}+ routine = validate(+ "routine",+ {+ "title": "Inbox sweep",+ "prompt": "Sort the inbox.",+ "schedule": {"type": "every", "seconds": 3600},+ },+ catalog=catalog,+ )+ assert routine["schedule"] == {"kind": "every", "seconds": 3600}+ with pytest.raises(ProposalRefused) as weekly:+ validate(+ "routine",+ {"title": "x", "prompt": "y", "schedule": {"kind": "weekday", "at": "08:00"}},+ catalog=catalog,+ )+ assert "weekday" in weekly.value.detail+++async def test_a_proposal_lands_in_the_queue_and_in_the_chat(world):+ rt, svc = world+ tool = ProposeChangeTool(rt, "mailbox", session_id="society:mailbox")+ res = await tool.execute(+ {"kind": "rule", "payload": {"text": "Always answer in English."}, "reason": "asked"}, CTX+ )+ assert res.success, res.error+ assert res.output["status"] == "pending"+ pending = await rt.approvals.items(state=ApprovalState.PENDING, agent_id="mailbox")+ assert len(pending) == 1+ item = pending[0]+ assert item.capability == "core:config:rule"+ assert item.action["payload"] == {"text": "Always answer in English."}+ assert item.action["reason"] == "asked"+ assert item.id == res.output["proposal_id"]+ assert len(svc.notices) == 1+ session_id, notice = svc.notices[0]+ assert session_id == "society:mailbox"+ assert notice["kind"] == "proposal" and notice["proposal_id"] == item.id+ assert notice["proposal_kind"] == "rule" and notice["agent_name"] == "Mailbox"+ assert notice["text"] == item.summary+++async def test_an_unknown_kind_is_refused_with_a_typed_reason(world):+ rt, svc = world+ tool = ProposeChangeTool(rt, "mailbox")+ res = await tool.execute({"kind": "model", "payload": {"model": "gpt"}}, CTX)+ assert res.success is False+ assert res.output["reason"] == "blocked_by_policy"+ assert await rt.approvals.items(state=ApprovalState.PENDING) == []+ assert svc.notices == []+++async def test_a_dead_capability_id_is_refused(world):+ rt, svc = world+ tool = ProposeChangeTool(rt, "mailbox")+ res = await tool.execute(+ {"kind": "approval_rule", "payload": {"require_approval": ["plugin:spotify:play"]}}, CTX+ )+ assert res.success is False+ assert res.output["reason"] == "target_unknown"+ ok = await tool.execute(+ {"kind": "focus", "payload": {"focus": ["cli:gh", "plugin:gmail"]}}, CTX+ )+ assert ok.success, ok.error+ item = (await rt.approvals.items(state=ApprovalState.PENDING))[0]+ assert item.action["payload"]["focus"] == ["cli:gh", "plugin:gmail"] # order kept+++async def test_the_same_proposal_twice_in_a_row_is_refused(world):+ rt, svc = world+ tool = ProposeChangeTool(rt, "mailbox")+ first = await tool.execute({"kind": "rule", "payload": {"text": "Be brief."}}, CTX)+ assert first.success+ again = await tool.execute({"kind": "rule", "payload": {"text": "Be brief."}}, CTX)+ assert again.success is False+ assert "already waiting" in (again.error or "")+ assert len(await rt.approvals.items(state=ApprovalState.PENDING)) == 1+ assert len(svc.notices) == 1+++async def test_proposing_changes_nothing_until_it_is_confirmed(world):+ rt, svc = world+ before = await rt.roster.get("mailbox")+ tool = ProposeChangeTool(rt, "mailbox")+ await tool.execute({"kind": "rule", "payload": {"text": "Be brief."}}, CTX)+ await tool.execute(+ {"kind": "approval_rule", "payload": {"always_allow": ["plugin:gmail"]}}, CTX+ )+ after = await rt.roster.get("mailbox")+ assert after is not None and before is not None+ assert after.description == before.description+ assert after.approval_rules == before.approval_rules+ assert after.focus == before.focus+++async def test_gates(world):+ rt, svc = world+ await rt.roster.update("mailbox", {"state": "paused"})+ tool = ProposeChangeTool(rt, "mailbox")+ paused = await tool.execute({"kind": "rule", "payload": {"text": "x"}}, CTX)+ assert paused.success is False+ await rt.roster.update("mailbox", {"state": "active"})+ await rt.store.set_kill_switch(True)+ halted = await tool.execute({"kind": "rule", "payload": {"text": "x"}}, CTX)+ assert halted.output["reason"] == "kill_switch"diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex 88117ddab3..5b6054102f 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -11,6 +11,7 @@ from jarvis.society import runtime as runtime_modfrom jarvis.society.agent_tools import (MEMORY_RECALL_TOOL_NAME,MESSAGE_TOOL_NAME,+ PROPOSE_TOOL_NAME,SHELL_TOOL_NAME,WIKI_NOTE_TOOL_NAME,)@@ -82,6 +83,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_paWIKI_NOTE_TOOL_NAME,SHELL_TOOL_NAME,MEMORY_RECALL_TOOL_NAME,+ PROPOSE_TOOL_NAME,*FOLDER,}assert "RunCommand" not in own@@ -98,6 +100,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_paWIKI_NOTE_TOOL_NAME,SHELL_TOOL_NAME,MEMORY_RECALL_TOOL_NAME,+ PROPOSE_TOOL_NAME,*FOLDER,}assert set(picked[: len(own_names)]) == own_names