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.

fix(agents): make Ask binding on Claude seats and deliver proposal decisions as notes (#1031)

Ruben Lütked198d7e2c2eb
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index b16678e844..8db8a3dc53 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -251,6 +251,18 @@ replayed during `session/load` is swallowed because the chat already shows it.
`approvals.mode: manual` and OpenClaw with `tools.exec.mode: ask`; every
request reaches Dodaios over ACP and is answered from the chat's stance —
Bypass allows without a card, Ask shows the card, Plan refuses.
+- **Approval modes per runner.** An agent's Ask and Always ask are binding
+ whichever runner answers; a runner that cannot honor a mode is refused when
+ the chat binds (`permissions.society_mode_supported`), never run with
+ hidden prompts. What each runner does:
+
+ | Runner | Ask | Always ask | How it is enforced |
+ | --- | --- | --- | --- |
+ | Dodaios runtime (brain) | yes | yes | The Dodaios tool gate (`society/approvals.decide`): reads run, everything else shows the card; Always ask shows it for every call. |
+ | Claude Code seat (`claude-cli`, `glm-cli`) | yes | no | `--permission-mode default`, prompts answered on the chat card (`--permission-prompt-tool stdio`), plus ask rules for this process only (`--settings`, `runner_cli.claude_ask_settings`) for `Edit`, `Write`, `MultiEdit`, `NotebookEdit`, `Bash` and `PowerShell`. Claude Code checks deny, then ask, then allow rules across all settings sources, so the allow list in the person's own `~/.claude/settings.json` can no longer skip the card (checked on Claude Code 2.1.310 against a local mock endpoint: without the ask rules `Write`, `PowerShell` and `Bash` ran with no prompt, with them each one asked); their deny rules still apply and their files are never edited. Reads of Dodaios' own tools (`readOnlyHint`) are answered without a card (`runner_cli.dodaios_read_free`), and a call that an earlier "Always allow" in the same process covers is answered by the runner (a shell prefix rule never covers a chained, piped or redirected command line). Bypass is unchanged. |
+ | Codex seat (`codex-cli`) | yes | yes | The seat runs with `--ignore-user-config --ignore-rules`, a read-only sandbox, `approval_policy="never"` and its shell, plugins, apps and browser disabled, so the person's `~/.codex/config.toml` cannot widen it and its only hands are the Dodaios tools, gated like the Dodaios runtime. |
+ | Hermes, OpenClaw | yes | no | The runtime's config is written per turn (`approvals.mode: manual`, `tools.exec.mode: ask`) and every request comes over ACP to the chat card. |
+ | Other CLI seats | no | no | No relay for their own prompts: Ask and Always ask are refused when the chat binds. |
- **Warm processes** (`warm.py`). An agent's runtime process stays up
between its turns, initialized and with its conversation open, so a message
only costs `session/prompt` (Hermes: first answer text 0.03 s instead of
diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.py
index 90cce6a185..7d83929e59 100644
--- a/dodaios/agent_chat/runner_cli.py
+++ b/dodaios/agent_chat/runner_cli.py
@@ -628,6 +628,126 @@ def claude_session_rules(tool_name: str, suggestions: Any) -> list[dict[str, Any
]
+#: Claude Code's own tools that change files or run commands. In "Ask before
+#: acting" (``default``) every call of these must reach the chat's approval
+#: card. Claude Code also loads the person's own settings files, and their
+#: ``permissions.allow`` (``Edit``, ``Write``, ``PowerShell``, …) would let
+#: those calls run without a prompt, so the chat would silently act like
+#: "Bypass". Claude Code evaluates deny, then ask, then allow rules across all
+#: sources: ask rules added for this process (``--settings``) win over any
+#: allow rule without touching the person's files. Their deny rules still win.
+CLAUDE_GATED_TOOLS: Final[tuple[str, ...]] = (
+ "Edit",
+ "Write",
+ "MultiEdit",
+ "NotebookEdit",
+ "Bash",
+ "PowerShell",
+)
+#: The gated tools that Claude Code's "accept edits" mode lets through.
+_CLAUDE_EDIT_TOOLS: Final[frozenset[str]] = frozenset(
+ {"Edit", "Write", "MultiEdit", "NotebookEdit"}
+)
+_CLAUDE_SHELL_TOOLS: Final[frozenset[str]] = frozenset({"Bash", "PowerShell"})
+#: Characters that chain, redirect or substitute shell commands. A prefix rule
+#: ("git log:*") speaks for ONE command; Claude Code splits a compound line
+#: before matching, this matcher does not, so such a line always asks again.
+_SHELL_CHAINING: Final[tuple[str, ...]] = (";", "&", "|", "<", ">", "`", "$(", "\n", "\r")
+
+
+def claude_ask_settings(mode: str) -> str | None:
+ """The ``--settings`` JSON that makes ``mode``'s prompts binding, or None.
+
+ Only "Ask before acting" (Claude Code's ``default``) needs it: every other
+ mode either never asks (bypass, auto), changes nothing (plan) or denies
+ what would ask (dontAsk). Bypass therefore behaves exactly as before.
+ """
+ if mode != "default":
+ return None
+ return json.dumps({"permissions": {"ask": list(CLAUDE_GATED_TOOLS)}}, ensure_ascii=False)
+
+
+def claude_rules_cover(rules: Iterable[dict[str, Any]], tool_name: str, tool_input: Any) -> bool:
+ """Whether a rule from an earlier "Always allow" in this process covers a call.
+
+ The ask rules of :func:`claude_ask_settings` rank above the session allow
+ rule "Always allow" hands the CLI, so the CLI asks again at the next call;
+ the runner answers that repeat itself. Only what the rule clearly covers
+ is answered: the whole tool, a shell command prefix, or the edit tools of
+ an "accept edits" mode. Anything else asks again (the safe side).
+ """
+ from fnmatch import fnmatchcase
+
+ command = ""
+ if isinstance(tool_input, dict):
+ command = str(tool_input.get("command") or "").strip()
+ for rule in rules:
+ if not isinstance(rule, dict):
+ continue
+ kind = rule.get("type")
+ if kind == "setMode":
+ mode = rule.get("mode")
+ if mode == "bypassPermissions":
+ return True
+ if mode == "acceptEdits" and tool_name in _CLAUDE_EDIT_TOOLS:
+ return True
+ continue
+ if kind not in ("addRules", "replaceRules") or rule.get("behavior") != "allow":
+ continue
+ for entry in rule.get("rules") or ():
+ if not isinstance(entry, dict) or entry.get("toolName") != tool_name:
+ continue
+ content = str(entry.get("ruleContent") or "").strip()
+ if not content:
+ return True
+ if tool_name in _CLAUDE_SHELL_TOOLS and command:
+ if any(mark in command for mark in _SHELL_CHAINING):
+ continue
+ pattern = content[:-2] + " *" if content.endswith(":*") else content
+ if command == content or command == pattern.removesuffix(" *"):
+ return True
+ if fnmatchcase(command, pattern):
+ return True
+ return False
+
+
+async def dodaios_read_free(session: Any, tool_name: str, tool_input: Any) -> bool:
+ """Whether a Claude Code prompt for one of Dodaios' own tools needs no card.
+
+ In "Ask" a read runs freely and only actions and writes ask. Claude Code
+ asks about every MCP tool it has no allow rule for, so a listing such as
+ ``society_routines`` would put a card in front of the person. A tool the
+ Dodaios tool server marks read-only (``readOnlyHint``, for these
+ arguments) is answered here; a write still goes to the card, and the
+ Dodaios tool gate checks it again when it runs. "Always ask", Plan, and an
+ agent's own require-approval rule keep asking.
+ """
+ from dodaios.core.branding import MCP_TOOLS_SERVER_NAME
+
+ prefix = f"mcp__{MCP_TOOLS_SERVER_NAME}__"
+ if not tool_name.startswith(prefix):
+ return False
+ stance = str(getattr(session, "permission_mode", "") or "")
+ if stance in ("always_ask", "plan", "read-only"):
+ return False
+ wire = tool_name[len(prefix) :]
+ args = tool_input if isinstance(tool_input, dict) else {}
+ session_id = str(getattr(session, "session_id", "") or "")
+ try:
+ from dodaios.mcp.dodaios_tools_server import wire_read_only
+
+ if not await wire_read_only(session_id, wire, args):
+ return False
+ if session_id.startswith("society:"):
+ from dodaios.society.surface import requires_explicit_approval
+
+ return not requires_explicit_approval(session_id, wire, args)
+ except Exception: # noqa: BLE001 — unsure means the card asks, as before
+ log.debug("agent chat: read-only check failed for %s", tool_name, exc_info=True)
+ return False
+ return True
+
+
def claude_stream_input(prompt: str) -> str:
"""One NDJSON user message for ``--input-format stream-json``."""
return (
@@ -726,6 +846,10 @@ def _plan_claude_code(
"--permission-mode",
mode,
]
+ ask_settings = claude_ask_settings(mode)
+ if ask_settings:
+ # The person's own allow rules must not turn "Ask" into "Bypass".
+ argv += ["--settings", ask_settings]
if model:
argv += ["--model", model]
if effort:
@@ -3918,6 +4042,8 @@ async def _drive_cli(
"""
session = handle.session
chat_ref = approval_ref(session.session_id)
+ #: The session rules this process was given by "Always allow" (Claude Code).
+ always_rules: list[dict[str, Any]] = []
status = "done"
error_text: str | None = None
vendor_session = plan.vendor_session
@@ -4081,6 +4207,14 @@ async def _drive_cli(
if tool_name == "AskUserQuestion":
await _respond(request_id, await _claude_question(tool_input))
return
+ if tool_name != "ExitPlanMode" and (
+ claude_rules_cover(always_rules, tool_name, tool_input)
+ or await dodaios_read_free(session, tool_name, tool_input)
+ ):
+ # Covered by this process's own "Always allow", or a read of
+ # Dodaios' own tools that Ask never puts in front of the person.
+ await _respond(request_id, {"behavior": "allow", "updatedInput": tool_input})
+ return
summary = str(req.get("description") or "") or _claude_request_summary(
tool_name, tool_input
)
@@ -4117,6 +4251,7 @@ async def _drive_cli(
body["updatedPermissions"] = claude_session_rules(
tool_name, req.get("permission_suggestions")
)
+ always_rules.extend(body["updatedPermissions"])
if bridge is not None and subtype == "can_use_tool":
# A Jarvis tool the CLI just asked about will hit the executor's
# own gate over MCP in a moment; the person has answered once.
diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.py
index e9ae99e8da..e1cb3a7fb2 100644
--- a/dodaios/agent_chat/service.py
+++ b/dodaios/agent_chat/service.py
@@ -1376,6 +1376,18 @@ class AgentChatService:
# What the turn receives; ``text`` stays what the person typed so the
# timeline shows their sentence rather than a page of extracted PDF.
prompt = chat_attachments.compose(text, attached)
+ if session.surface == "society" and not text.startswith("/"):
+ # Decisions on the agent's proposals reach it here, once, as a
+ # system note in front of its next message: never as a message
+ # from the person, and never as a turn of their own. A slash
+ # command stays the first thing a CLI seat reads.
+ from dodaios.society.proposals import decision_context
+
+ decided = decision_context(self.store.list_events(session_id, tail=200))
+ if decided:
+ prompt = decided + "\n\n" + prompt
+ if display_text is None:
+ display_text = text
# A plain chat shows its pictures to the model itself.
images: tuple[str, ...] = ()
if attached and kit.plain:
diff --git a/dodaios/mcp/dodaios_tools_server.py b/dodaios/mcp/dodaios_tools_server.py
index e97a131111..fbf5ac8e18 100644
--- a/dodaios/mcp/dodaios_tools_server.py
+++ b/dodaios/mcp/dodaios_tools_server.py
@@ -143,6 +143,40 @@ async def _session_wire_catalog() -> dict[str, Any]:
return _wire_catalog(entries)
+def _read_only(entry: Any, args: dict[str, Any] | None = None) -> bool:
+ """Whether a catalog entry only reads: the ``readOnlyHint`` it is listed with.
+
+ With ``args`` a tool whose tier depends on its arguments is judged for
+ those arguments too.
+ """
+ if str(getattr(entry, "risk_tier", "")) != "safe" or getattr(entry, "is_action_tool", True):
+ return False
+ hook = getattr(entry, "risk_tier_for_args", None)
+ if args is not None and callable(hook):
+ try:
+ tier = hook(dict(args))
+ except Exception: # noqa: BLE001 - unsure means not read-only
+ return False
+ if tier is not None and str(tier) != "safe":
+ return False
+ return True
+
+
+async def wire_read_only(session_id: str, wire: str, args: dict[str, Any] | None = None) -> bool:
+ """Whether ``wire`` (a tool as this server lists it to ``session_id``) only reads.
+
+ A vendor CLI asks the chat before an MCP call; a read of Dodaios' own tools
+ needs no card in Ask (``runner_cli.dodaios_read_free``). An unknown tool is
+ not read-only.
+ """
+ token = CHAT_SESSION_REF.set(session_id or None)
+ try:
+ entry = (await _session_wire_catalog()).get(wire)
+ finally:
+ CHAT_SESSION_REF.reset(token)
+ return entry is not None and _read_only(entry, args)
+
+
def _gateway() -> Any | None:
from dodaios.core import runtime_refs
@@ -212,9 +246,7 @@ def build_server() -> Any:
else str(entry.description or entry.name)
),
inputSchema=schema,
- annotations=types.ToolAnnotations(
- readOnlyHint=entry.risk_tier == "safe" and not entry.is_action_tool,
- ),
+ annotations=types.ToolAnnotations(readOnlyHint=_read_only(entry)),
)
)
return tools
@@ -311,4 +343,5 @@ __all__ = [
"approval_snapshot",
"build_server",
"offered_tools",
+ "wire_read_only",
]
diff --git a/dodaios/society/agent_tools.py b/dodaios/society/agent_tools.py
index a1bc184de0..c7dac304d3 100644
--- a/dodaios/society/agent_tools.py
+++ b/dodaios/society/agent_tools.py
@@ -641,7 +641,11 @@ class ProposeChangeTool:
"kind": kind,
"status": "pending",
"summary": item.summary,
- "note": "waiting for the user to confirm on the card in this chat",
+ "note": (
+ "waiting for the user to confirm on the card in this chat; the card "
+ "shows it, so never quote the proposal id. The decision reaches you "
+ "as a system note on your next turn"
+ ),
},
)
diff --git a/dodaios/society/approvals.py b/dodaios/society/approvals.py
index 448e8eaffd..e650c6dcec 100644
--- a/dodaios/society/approvals.py
+++ b/dodaios/society/approvals.py
@@ -47,6 +47,8 @@ __all__ = [
]
DEFAULT_TTL_MS: Final[int] = 24 * 60 * 60 * 1000
+#: The capability of a configuration proposal (``proposals.CAPABILITY_PREFIX``).
+CONFIG_CAPABILITY_PREFIX: Final[str] = "core:config:"
_TIER_RANK: Final[dict[str, int]] = {"safe": 0, "monitor": 1, "ask": 2, "block": 3}
@@ -245,7 +247,15 @@ class Approvals:
from_agent="user",
# Inline workers already await this row. A RELEASE addressed to
# the agent would enqueue an extra chat turn and repeat the task.
- to_agent="user" if current.action.get("resume_in_place") else current.agent_id,
+ # A configuration proposal is applied by the app itself; the
+ # agent reads the outcome on its next turn (``proposals.
+ # decision_context``) instead of being woken by a fake message.
+ to_agent=(
+ "user"
+ if current.action.get("resume_in_place")
+ or current.capability.startswith(CONFIG_CAPABILITY_PREFIX)
+ else current.agent_id
+ ),
trace_id=current.trace_id,
payload={
"approval_id": approval_id,
diff --git a/dodaios/society/proposals.py b/dodaios/society/proposals.py
index a25e086f3f..b7791c7933 100644
--- a/dodaios/society/proposals.py
+++ b/dodaios/society/proposals.py
@@ -27,7 +27,7 @@ from __future__ import annotations
import logging
from typing import Any, Final
-from .approvals import Approval
+from .approvals import CONFIG_CAPABILITY_PREFIX, Approval
from .capabilities import CapabilityRow
from .display_name import display_name
from .events import ApprovalState
@@ -42,6 +42,7 @@ __all__ = [
"ProposalRefused",
"apply",
"capability_for",
+ "decision_context",
"kind_of",
"propose",
"proposal_notice",
@@ -54,7 +55,7 @@ __all__ = [
PROPOSAL_KINDS: Final[frozenset[str]] = frozenset(
{"rule", "skill", "routine", "approval_rule", "focus", "team", "identity"}
)
-CAPABILITY_PREFIX: Final[str] = "core:config:"
+CAPABILITY_PREFIX: Final[str] = CONFIG_CAPABILITY_PREFIX
#: Schedule kinds the Automations scheduler can keep (``dodaios/tasks/schema.py``).
#: Calendar rules carry explicit local clock and IANA timezone semantics.
SCHEDULE_KINDS: Final[frozenset[str]] = frozenset(
@@ -338,15 +339,65 @@ def resolved_notice(
"proposal_kind": str(item.action.get("kind") or kind_of(item.capability) or ""),
"status": status,
"text": text,
+ "summary": item.summary,
"agent_id": agent.agent_id,
"agent_name": display_name(agent),
}
if previous is not None:
# What an undo restores (identity only): the fields as they were.
notice["previous"] = previous
+ if item.action.get("resume_in_place"):
+ # Settled inside the agent's own turn: the tool already returned the
+ # outcome, so ``decision_context`` must not repeat it next turn.
+ notice["in_turn"] = True
return notice
+#: How the agent reads each outcome on its next turn.
+_DECISION_WORDS: Final[dict[str, str]] = {
+ "applied": "approved and applied",
+ "rejected": "rejected; nothing changed",
+ "failed": "approved, but it could not be applied",
+}
+
+
+def decision_context(events: list[dict[str, Any]]) -> str:
+ """The person's decisions on proposals since the agent's last turn, or "".
+
+ A decision is a notice in the chat (``resolved_notice``), never a message
+ from the person and never a turn of its own: the agent learns it here, in
+ front of the next message it gets, exactly once (the next turn starts
+ after it). Each line names the change and the outcome, without ids.
+ """
+ lines: list[str] = []
+ for event in reversed(events):
+ kind = event.get("kind")
+ if kind == "turn_started":
+ break
+ payload = event.get("payload") or {}
+ if kind != "notice" or payload.get("kind") != "proposal_resolved":
+ continue
+ if payload.get("in_turn"):
+ continue
+ status = str(payload.get("status") or "")
+ word = _DECISION_WORDS.get(status)
+ if word is None:
+ continue
+ summary = str(payload.get("summary") or payload.get("proposal_kind") or "a change")
+ line = f"- {summary.strip()}: {word}"
+ if status == "failed" and payload.get("text"):
+ line += f" ({str(payload['text']).strip()[:200]})"
+ lines.append(line)
+ if not lines:
+ return ""
+ lines.reverse()
+ return (
+ "[System note, not from the person: decisions on your proposals since your "
+ "last turn. Take them into account; do not thank for or repeat them.]\n"
+ + "\n".join(lines)
+ )
+
+
async def propose(
rt: Any,
agent: AgentRecord,
diff --git a/dodaios/ui/web/agent_chat_routes.py b/dodaios/ui/web/agent_chat_routes.py
index 70ca2ef711..f6008b7c56 100644
--- a/dodaios/ui/web/agent_chat_routes.py
+++ b/dodaios/ui/web/agent_chat_routes.py
@@ -63,7 +63,7 @@ from pydantic import BaseModel, Field
from dodaios.agent_chat import attachments as chat_attachments
from dodaios.agent_chat import runner_cli, typeahead
-from dodaios.agent_chat.catalog import claude_code_models, offers, rows_for
+from dodaios.agent_chat.catalog import ACCESS_ACCOUNTS, claude_code_models, offers, rows_for
from dodaios.agent_chat.control_types import CommandRequest, CommandResult
from dodaios.agent_chat.credential_requests import CredentialRequestBusy
from dodaios.agent_chat.effort import normalize_effort
@@ -472,6 +472,42 @@ def _validate_cwd(raw: str | None) -> str | None:
return str(p.resolve())
+async def _session_or_bound_agent_chat(svc: Any, session_id: str) -> Any | None:
+ """The chat session, binding an agent's own chat that does not exist yet.
+
+ An agent's chat (``society:<agent_id>``) is created by binding it to its
+ roster row (``POST /api/society/agents/{id}/chat``). A panel that opens a
+ brand-new agent asks for its catalog and warm-up in the same moment, so
+ those requests bind it themselves instead of answering 404. Binding is
+ idempotent and runs nothing. Any other id is only looked up.
+ """
+ session = svc.store.get_session(session_id)
+ if session is not None or not session_id.startswith("society:"):
+ return session
+ agent_id = session_id.removeprefix("society:")
+ if not agent_id or ":" in agent_id:
+ return None
+ try:
+ from dodaios.society.chat_binding import ensure_session
+ from dodaios.society.runtime import current_runtime
+
+ runtime = current_runtime()
+ if runtime is None:
+ return None
+ agent = await runtime.roster.get(agent_id)
+ if agent is None or agent.session_id != session_id or str(agent.state) != "active":
+ return None
+ if await runtime.store.kill_switch():
+ return None
+ return ensure_session(svc, runtime.config(), agent)
+ except PermissionError as exc:
+ log.debug("agent chat: %s not bound on demand: %s", session_id, exc)
+ return None
+ except Exception: # noqa: BLE001 - an unbound chat stays "not found", never a 500
+ log.warning("agent chat: could not bind %s on demand", session_id, exc_info=True)
+ return None
+
+
# ------------------------------------------------------------------ catalog
@@ -501,12 +537,14 @@ async def get_catalog(
from dodaios.agent_chat.runner_cli import cli_catalog_scope
if session_id:
- session = svc.store.get_session(session_id)
+ session = await _session_or_bound_agent_chat(svc, session_id)
if session is None or session.surface != surface:
raise HTTPException(status_code=404, detail="Chat session not found")
account_id = session.account_id
cwd = session.cwd
- if account_id:
+ if account_id and account_id not in ACCESS_ACCOUNTS:
+ # "subscription" / "api-key" pin a way of paying, not a login: the
+ # seat's active login answers for them (``runner_cli._login_id``).
from dodaios import agent_accounts
if agent_accounts.resolve(account_id) is None:
@@ -1305,7 +1343,7 @@ _WARMING: dict[str, asyncio.Task[bool]] = {}
)
async def warm_session(session_id: str, request: Request) -> dict[str, Any]:
svc = await _async_service(request)
- session = svc.store.get_session(session_id)
+ session = await _session_or_bound_agent_chat(svc, session_id)
if session is None:
raise HTTPException(status_code=404, detail="session not found")
if session.surface != "society" or not session.runtime:
diff --git a/tests/unit/agent_chat/test_cli_ask_enforced.py b/tests/unit/agent_chat/test_cli_ask_enforced.py
new file mode 100644
index 0000000000..be29c149e2
--- /dev/null
+++ b/tests/unit/agent_chat/test_cli_ask_enforced.py
@@ -0,0 +1,265 @@
+"""Ask is binding on a Claude Code seat (dodaios/agent_chat/runner_cli.py).
+
+Claude Code loads the person's own settings files, whose allow list can name
+``Edit``, ``Write`` or ``PowerShell``; without more, an agent in Ask wrote
+files with no approval card (live finding 2026-10-28). The seat adds ask rules
+for this process only, answers reads of Dodaios' own tools without a card,
+and answers a repeat that an earlier "Always allow" covers itself.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from dataclasses import replace
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from dodaios.agent_chat import runner_cli as rc
+from dodaios.agent_chat.runner_api import TurnHandle
+from dodaios.core.branding import MCP_TOOLS_SERVER_NAME
+from tests.unit.agent_chat.test_turn_prompts import (
+ _can_use,
+ _fake_claude,
+ _FakeChat,
+ _session,
+)
+
+_MCP = f"mcp__{MCP_TOOLS_SERVER_NAME}__"
+
+
+def _plan(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mode: str) -> list[str]:
+ monkeypatch.setattr(rc, "claude_argv_prefix", lambda: ["claude"])
+ return rc.plan_claude(
+ prompt="hi", cwd=tmp_path, model="", effort="", permission_mode=mode, resume=None
+ ).argv
+
+
+def test_ask_adds_process_only_ask_rules_for_writes_and_commands(monkeypatch, tmp_path):
+ argv = _plan(monkeypatch, tmp_path, "default")
+ assert argv[argv.index("--permission-mode") + 1] == "default"
+ settings = json.loads(argv[argv.index("--settings") + 1])
+ assert set(settings) == {"permissions"}
+ assert set(settings["permissions"]) == {"ask"}
+ assert {"Edit", "Write", "MultiEdit", "NotebookEdit", "Bash", "PowerShell"} <= set(
+ settings["permissions"]["ask"]
+ )
+ # The person's settings are never replaced: no source is switched off.
+ assert "--setting-sources" not in argv
+ # The society word "ask" lands on the same mode and the same rules.
+ assert "--settings" in _plan(monkeypatch, tmp_path, "ask")
+
+
[email protected]("mode", ["bypassPermissions", "acceptEdits", "plan", "auto", "dontAsk"])
+def test_other_modes_behave_as_before(monkeypatch, tmp_path, mode):
+ assert "--settings" not in _plan(monkeypatch, tmp_path, mode)
+
+
+def test_glm_rides_the_same_rules(monkeypatch, tmp_path):
+ monkeypatch.setattr(rc, "claude_argv_prefix", lambda: ["claude"])
+ monkeypatch.setattr(rc, "_registry_env", lambda agent, base: dict(base))
+ argv = rc.plan_glm(
+ prompt="hi", cwd=tmp_path, model="", effort="", permission_mode="default", resume=None
+ ).argv
+ assert "Write" in json.loads(argv[argv.index("--settings") + 1])["permissions"]["ask"]
+
+
+def test_always_allow_rules_cover_only_what_they_name():
+ whole = [{"type": "addRules", "behavior": "allow", "rules": [{"toolName": "Write"}]}]
+ assert rc.claude_rules_cover(whole, "Write", {"file_path": "a.txt"})
+ assert not rc.claude_rules_cover(whole, "Edit", {"file_path": "a.txt"})
+
+ prefix = [
+ {
+ "type": "addRules",
+ "behavior": "allow",
+ "rules": [{"toolName": "Bash", "ruleContent": "git log:*"}],
+ }
+ ]
+ assert rc.claude_rules_cover(prefix, "Bash", {"command": "git log --oneline"})
+ assert rc.claude_rules_cover(prefix, "Bash", {"command": "git log"})
+ assert not rc.claude_rules_cover(prefix, "Bash", {"command": "git push"})
+ assert not rc.claude_rules_cover(prefix, "PowerShell", {"command": "git log"})
+ # A prefix rule speaks for one command, never for a chained or redirected line.
+ for chained in (
+ "git log && rm -rf ~",
+ "git log; del x",
+ "git log | sh",
+ "git log > out.txt",
+ "git log $(whoami)",
+ "git log `whoami`",
+ "git log\nrm -rf ~",
+ ):
+ assert not rc.claude_rules_cover(prefix, "Bash", {"command": chained}), chained
+ # The whole tool allowed (no rule content) still covers any line.
+ whole_shell = [{"type": "addRules", "behavior": "allow", "rules": [{"toolName": "Bash"}]}]
+ assert rc.claude_rules_cover(whole_shell, "Bash", {"command": "git log && ls"})
+
+ edits = [{"type": "setMode", "mode": "acceptEdits", "destination": "session"}]
+ assert rc.claude_rules_cover(edits, "Edit", {})
+ assert not rc.claude_rules_cover(edits, "Bash", {"command": "ls"})
+
+ deny = [{"type": "addRules", "behavior": "deny", "rules": [{"toolName": "Write"}]}]
+ assert not rc.claude_rules_cover(deny, "Write", {})
+ assert not rc.claude_rules_cover([], "Write", {})
+
+
+def _turn(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ requests: list[dict[str, Any]],
+ *,
+ decision: str = "allow",
+ surface: str = "agent",
+ mode: str = "default",
+ session_id: str = "s1",
+) -> tuple[list[dict[str, Any]], list[str]]:
+ out = tmp_path / "answers.json"
+ plan = rc.CliPlan(
+ _fake_claude(requests, out),
+ dict(os.environ),
+ rc.claude_stream_input("hi"),
+ "claude",
+ "v1",
+ keep_stdin=True,
+ control_init=rc.claude_control_init(),
+ )
+ monkeypatch.setitem(rc._PLANNERS, "claude-cli", lambda **kw: plan)
+ asked: list[str] = []
+
+ async def emit(_ev: dict[str, Any]) -> None:
+ return None
+
+ async def ask(_call_id: str, name: str, *_: object) -> str:
+ asked.append(name)
+ return decision
+
+ session = replace(
+ _session(tmp_path, "claude-api", surface=surface, mode=mode), session_id=session_id
+ )
+ handle = TurnHandle(
+ session=session,
+ turn_id="t1",
+ emit=emit,
+ request_approval=ask,
+ cancel=asyncio.Event(),
+ control_service=_FakeChat(),
+ )
+ asyncio.run(rc.run_cli_turn(handle, "hi", "claude-cli"))
+ return json.loads(out.read_text(encoding="utf-8")), asked
+
+
+def test_a_write_asks_on_the_card_and_always_allow_answers_the_repeat(monkeypatch, tmp_path):
+ requests = [
+ _can_use("Write", {"file_path": "a.txt", "content": "x"}, "r1"),
+ _can_use("Write", {"file_path": "b.txt", "content": "y"}, "r2"),
+ _can_use("Bash", {"command": "echo hi"}, "r3"),
+ ]
+ answers, asked = _turn(monkeypatch, tmp_path, requests, decision="allow_always")
+ # The first Write and the shell command reach the card; the second Write
+ # is covered by the rule the first "Always allow" gave this process.
+ assert asked == ["Write", "Bash"]
+ assert [a["behavior"] for a in answers] == ["allow", "allow", "allow"]
+ assert answers[0]["updatedPermissions"][0]["destination"] == "session"
+ assert "updatedPermissions" not in answers[1]
+
+
+def test_a_denied_write_does_not_run(monkeypatch, tmp_path):
+ answers, asked = _turn(
+ monkeypatch, tmp_path, [_can_use("Write", {"file_path": "a.txt"})], decision="deny"
+ )
+ assert asked == ["Write"]
+ assert answers == [{"behavior": "deny", "message": "The person declined this action."}]
+
+
+def _read_only(names: set[str]):
+ async def wire_read_only(_session_id: str, wire: str, _args: Any = None) -> bool:
+ return wire in names
+
+ return wire_read_only
+
+
+def test_reads_of_dodaios_tools_need_no_card_but_writes_do(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ "dodaios.mcp.dodaios_tools_server.wire_read_only", _read_only({"society_routines"})
+ )
+ requests = [
+ _can_use(_MCP + "society_routines", {}, "r1"),
+ _can_use(_MCP + "society-create-routine", {"title": "x"}, "r2"),
+ ]
+ answers, asked = _turn(monkeypatch, tmp_path, requests)
+ assert asked == [_MCP + "society-create-routine"]
+ assert [a["behavior"] for a in answers] == ["allow", "allow"]
+
+
+def test_an_agents_own_require_approval_rule_still_asks_for_a_read(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ "dodaios.mcp.dodaios_tools_server.wire_read_only", _read_only({"society_routines"})
+ )
+ ruled: list[str] = []
+
+ def requires(_session_id: str, tool: str, _args: dict[str, Any]) -> bool:
+ ruled.append(tool)
+ return True
+
+ monkeypatch.setattr("dodaios.society.surface.requires_explicit_approval", requires)
+ _, asked = _turn(
+ monkeypatch,
+ tmp_path,
+ [_can_use(_MCP + "society_routines", {})],
+ surface="society",
+ mode="ask",
+ session_id="society:reader",
+ )
+ assert ruled == ["society_routines"]
+ assert asked == [_MCP + "society_routines"]
+
+
+def test_always_ask_and_other_servers_keep_asking_for_reads(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ "dodaios.mcp.dodaios_tools_server.wire_read_only", _read_only({"society_routines"})
+ )
+ _, asked = _turn(
+ monkeypatch, tmp_path, [_can_use(_MCP + "society_routines", {})], mode="always_ask"
+ )
+ assert asked == [_MCP + "society_routines"]
+ _, asked = _turn(monkeypatch, tmp_path, [_can_use("mcp__other__society_routines", {})])
+ assert asked == ["mcp__other__society_routines"]
+
+
+async def test_the_tool_server_judges_reads_like_its_read_only_hint(monkeypatch):
+ from types import SimpleNamespace
+
+ from dodaios.mcp import dodaios_tools_server as server
+
+ entries = [
+ SimpleNamespace(name="society_routines", risk_tier="safe", is_action_tool=False),
+ SimpleNamespace(name="society_shell", risk_tier="monitor", is_action_tool=False),
+ SimpleNamespace(name="open-app", risk_tier="safe", is_action_tool=True),
+ SimpleNamespace(
+ name="society_propose_change",
+ risk_tier="safe",
+ is_action_tool=False,
+ risk_tier_for_args=lambda args: "monitor" if args.get("mode") == "apply" else "safe",
+ ),
+ ]
+ seen: list[str | None] = []
+
+ async def catalog() -> dict[str, Any]:
+ seen.append(server.CHAT_SESSION_REF.get())
+ return {entry.name: entry for entry in entries}
+
+ monkeypatch.setattr(server, "_session_wire_catalog", catalog)
+ assert await server.wire_read_only("society:a", "society_routines")
+ assert not await server.wire_read_only("society:a", "society_shell")
+ assert not await server.wire_read_only("society:a", "open-app")
+ assert not await server.wire_read_only("society:a", "missing")
+ assert await server.wire_read_only("society:a", "society_propose_change", {})
+ assert not await server.wire_read_only(
+ "society:a", "society_propose_change", {"mode": "apply"}
+ )
+ assert set(seen) == {"society:a"}
+ assert server.CHAT_SESSION_REF.get() is None
diff --git a/tests/unit/agent_chat/test_society_chat_open.py b/tests/unit/agent_chat/test_society_chat_open.py
new file mode 100644
index 0000000000..7240108ccd
--- /dev/null
+++ b/tests/unit/agent_chat/test_society_chat_open.py
@@ -0,0 +1,187 @@
+"""Opening a brand-new agent's chat: catalog and warm-up answer at once.
+
+Live finding 2026-10-28: the panel asks for the catalog and the warm-up in the
+same moment it binds the chat, so both answered 404 for a new agent, and the
+catalog then refused the agent's seat pin ``subscription`` (a way of paying,
+not a login) with 400 "Unknown subscription account".
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+from tests.unit.agent_chat.test_agent_chat_service import _app, scripted # noqa: F401
+
+
+def quiet_catalog(monkeypatch: pytest.MonkeyPatch):
+ import dodaios.ui.web.agent_chat_routes as routes
+
+ async def no_live_models() -> dict[str, Any]:
+ return {}
+
+ monkeypatch.setattr(routes, "_live_cli_models", no_live_models)
+ monkeypatch.setattr(routes, "_cli_installed", lambda runner: False)
+
+
+def _fake_society(
+ monkeypatch: pytest.MonkeyPatch, *, agent_id: str, runtime: str = "", killed: bool = False
+) -> list[str]:
+ """A society runtime with one active agent; binding creates its chat."""
+ bound: list[str] = []
+ agent = SimpleNamespace(
+ agent_id=agent_id, session_id=f"society:{agent_id}", state="active", name="QA"
+ )
+
+ class Roster:
+ async def get(self, wanted: str) -> Any:
+ return agent if wanted == agent_id else None
+
+ class Store:
+ async def kill_switch(self) -> bool:
+ return killed
+
+ fake = SimpleNamespace(roster=Roster(), store=Store(), config=lambda: None)
+
+ def ensure_session(svc: Any, _cfg: Any, row: Any) -> Any:
+ bound.append(row.agent_id)
+ existing = svc.store.get_session(row.session_id)
+ if existing is not None:
+ return existing
+ return svc.store.create_session(
+ provider="claude-api",
+ model="claude-sonnet-5-5",
+ effort="",
+ cwd=str(Path.cwd()),
+ permission_mode="ask",
+ title=row.name,
+ session_id=row.session_id,
+ surface="society",
+ account_id="subscription",
+ runtime=runtime,
+ )
+
+ monkeypatch.setattr("dodaios.society.runtime.current_runtime", lambda: fake)
+ monkeypatch.setattr("dodaios.society.chat_binding.ensure_session", ensure_session)
+ return bound
+
+
+def test_the_catalog_binds_a_new_agents_chat_and_accepts_the_subscription_pin(
+ tmp_path: Path, monkeypatch, quiet_catalog
+):
+ bound = _fake_society(monkeypatch, agent_id="qa-starter")
+ with TestClient(_app(tmp_path)) as client:
+ res = client.get("/api/agent-chat/catalog?surface=society&session_id=society:qa-starter")
+ assert res.status_code == 200, res.text
+ assert res.json()["providers"]
+ # The bound chat stays; a second read does not bind again.
+ again = client.get("/api/agent-chat/catalog?surface=society&session_id=society:qa-starter")
+ assert again.status_code == 200
+ assert bound == ["qa-starter"]
+
+
[email protected]("pin", ["subscription", "api-key"])
+def test_the_catalog_reads_access_pins_as_ways_of_paying(
+ tmp_path: Path, monkeypatch, quiet_catalog, pin: str
+):
+ with TestClient(_app(tmp_path)) as client:
+ res = client.get(f"/api/agent-chat/catalog?surface=society&account_id={pin}")
+ assert res.status_code == 200, res.text
+ unknown = client.get("/api/agent-chat/catalog?surface=society&account_id=nobody-here")
+ assert unknown.status_code == 400
+
+
+def test_unknown_or_nested_society_ids_are_still_not_found(
+ tmp_path: Path, monkeypatch, quiet_catalog
+):
+ bound = _fake_society(monkeypatch, agent_id="qa-starter")
+ with TestClient(_app(tmp_path)) as client:
+ for sid in ("society:ghost", "society:qa-starter:routine:1", "plain-id"):
+ res = client.get(f"/api/agent-chat/catalog?surface=society&session_id={sid}")
+ assert res.status_code == 404, sid
+ assert client.post(f"/api/agent-chat/sessions/{sid}/warm").status_code == 404
+ assert bound == []
+
+
+def test_warm_binds_a_new_runtime_agents_chat(tmp_path: Path, monkeypatch):
+ from dodaios.agent_chat import runner_acp
+
+ warmed: list[str] = []
+
+ async def fake_warm(session: Any, store: Any = None) -> bool:
+ warmed.append(session.session_id)
+ return True
+
+ monkeypatch.setattr(runner_acp, "warm_session", fake_warm)
+ bound = _fake_society(monkeypatch, agent_id="hermit", runtime="hermes")
+ with TestClient(_app(tmp_path)) as client:
+ res = client.post("/api/agent-chat/sessions/society:hermit/warm")
+ assert res.status_code == 200, res.text
+ assert res.json() == {"warming": True, "session_id": "society:hermit"}
+ assert bound == ["hermit"]
+ assert warmed == ["society:hermit"]
+
+
[email protected]("scripted")
+async def test_the_next_message_carries_the_decisions_once(tmp_path: Path, monkeypatch):
+ """The decided proposals ride in front of the agent's next message, once;
+ the person's bubble keeps only what they typed."""
+ from dodaios.agent_chat.events import make_event
+ from dodaios.agent_chat.service import AgentChatService
+ from dodaios.agent_chat.store import AgentChatStore
+
+ svc = AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ session = svc.store.create_session(
+ provider="fakeprov", model="m", effort="", cwd=str(tmp_path),
+ session_id="society:writer", surface="society", permission_mode="ask",
+ )
+
+ async def bind(_sid: str, **_: Any) -> Any:
+ return svc.store.get_session(session.session_id)
+
+ monkeypatch.setattr(svc, "bind_society_session", bind)
+ await svc.post_notice(
+ session.session_id,
+ {
+ "kind": "proposal_resolved",
+ "proposal_id": "01a18010-70bf-70d5-957a-57ba4d79b664",
+ "status": "rejected",
+ "summary": "Add a standing rule: Keep every answer under three sentences.",
+ },
+ )
+ note_events = svc.store.list_events(session.session_id)
+ assert [e["kind"] for e in note_events] == ["notice"]
+ await svc.send(session.session_id, "Hello again")
+ await svc.wait_turn(session.session_id)
+ user = [e for e in svc.store.list_events(session.session_id) if e["kind"] == "user_message"]
+ assert len(user) == 1
+ sent = user[0]["payload"]
+ assert sent["typed"] == "Hello again"
+ assert sent["text"].startswith("[System note, not from the person")
+ assert "three sentences.: rejected; nothing changed" in sent["text"]
+ assert "01a18010" not in sent["text"]
+ assert sent["text"].endswith("Hello again")
+ # After that turn started, the same decision is not repeated.
+ svc.store.append_event(session.session_id, make_event("turn_started", {"turn_id": "x"}))
+ from dodaios.society.proposals import decision_context
+
+ assert decision_context(svc.store.list_events(session.session_id)) == ""
+
+
+def test_the_kill_switch_keeps_a_new_agents_chat_unbound(
+ tmp_path: Path, monkeypatch, quiet_catalog
+):
+ bound = _fake_society(monkeypatch, agent_id="qa-starter", killed=True)
+ with TestClient(_app(tmp_path)) as client:
+ sid = "society:qa-starter"
+ res = client.get(f"/api/agent-chat/catalog?surface=society&session_id={sid}")
+ assert res.status_code == 404
+ assert client.post(f"/api/agent-chat/sessions/{sid}/warm").status_code == 404
+ assert bound == []
diff --git a/tests/unit/society/test_proposal_decisions.py b/tests/unit/society/test_proposal_decisions.py
new file mode 100644
index 0000000000..d4e9563784
--- /dev/null
+++ b/tests/unit/society/test_proposal_decisions.py
@@ -0,0 +1,116 @@
+"""Decisions on an agent's proposals reach it as a system note, never as a turn.
+
+Live finding 2026-10-28: confirming one proposal and rejecting another woke
+the agent with a fake "Message from user", it thanked for an approval that was
+half a rejection, quoted proposal ids and drew duplicate bubbles. The board
+envelope now goes to the person, and the agent reads one accurate note in
+front of its next message.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from dodaios.agent_chat.events import make_event
+from dodaios.society.approvals import Approvals
+from dodaios.society.events import MsgType
+from dodaios.society.proposals import capability_for, decision_context, resolved_notice
+from dodaios.society.roster import Roster
+from dodaios.society.store import SocietyStore
+
+
+async def world(tmp_path: Path):
+ store = SocietyStore(tmp_path / "society.db")
+ await store.open()
+ try:
+ yield store, Roster(store), Approvals(store, ttl_ms=60_000)
+ finally:
+ await store.close()
+
+
[email protected]("approve", [True, False])
+async def test_a_proposal_decision_never_queues_an_agent_turn(world, approve):
+ store, roster, approvals = world
+ await roster.create(name="Writer")
+ item = await approvals.enqueue(
+ agent_id="writer",
+ trace_id="config:writer:society:writer",
+ capability=capability_for("rule"),
+ action={"kind": "rule", "payload": {"rule": "Always answer in English."}},
+ summary="Add a standing rule: Always answer in English.",
+ )
+ await approvals.resolve(item.id, approve=approve)
+ event = (await store.events_for_trace("config:writer:society:writer"))[-1]
+ assert event.msg_type is (MsgType.RELEASE if approve else MsgType.VETO)
+ assert event.to_agent == "user"
+ assert event.payload["agent_id"] == "writer"
+ assert await store.pending_deliveries() == []
+
+
+async def test_other_approvals_still_release_to_the_agent(world):
+ store, roster, approvals = world
+ await roster.create(name="Mailbox")
+ item = await approvals.enqueue(
+ agent_id="mailbox", trace_id="mail", capability="plugin:gmail", action={}, summary="x"
+ )
+ await approvals.resolve(item.id, approve=True)
+ assert (await store.events_for_trace("mail"))[-1].to_agent == "mailbox"
+
+
+def _resolved(status: str, summary: str, text: str = "") -> dict:
+ agent = SimpleNamespace(agent_id="writer", name="Writer", title="", description="")
+ item = SimpleNamespace(
+ id="01a18010-5e86-7736-93b9-3b04015fd851",
+ action={"kind": "rule"},
+ capability=capability_for("rule"),
+ summary=summary,
+ )
+ return make_event(
+ "notice",
+ resolved_notice(agent, item, status=status, text=text or status), # type: ignore[arg-type]
+ )
+
+
+def test_the_note_lists_each_outcome_once_without_ids():
+ events = [
+ make_event("turn_started", {"turn_id": "t1"}),
+ _resolved("applied", "Add a standing rule: Always answer in English."),
+ _resolved("rejected", "Add a standing rule: Keep every answer under three sentences."),
+ _resolved("failed", "Create routine: QA weekly check", "The task store is unavailable"),
+ ]
+ note = decision_context(events)
+ assert note.startswith("[System note, not from the person")
+ assert "Always answer in English.: approved and applied" in note
+ assert "three sentences.: rejected; nothing changed" in note
+ assert "could not be applied (The task store is unavailable)" in note
+ assert "01a18010" not in note
+ # Order kept: the person's decisions in the order they made them.
+ assert note.index("English") < note.index("three sentences") < note.index("QA weekly")
+
+
+def test_the_note_is_given_once():
+ old = [_resolved("applied", "Old rule"), make_event("turn_started", {"turn_id": "t2"})]
+ assert decision_context(old) == ""
+ assert decision_context([]) == ""
+ assert decision_context([make_event("notice", {"kind": "proposal", "status": "pending"})]) == ""
+
+
+def test_a_decision_settled_inside_the_turn_is_not_repeated():
+ """``mode=apply`` resolves in the agent's own turn; the tool returned it."""
+ agent = SimpleNamespace(agent_id="writer", name="Writer", title="", description="")
+ item = SimpleNamespace(
+ id="p1",
+ action={"kind": "rule", "resume_in_place": True},
+ capability=capability_for("rule"),
+ summary="Add a standing rule: Be brief.",
+ )
+ inline = make_event(
+ "notice",
+ resolved_notice(agent, item, status="applied", text="applied"), # type: ignore[arg-type]
+ )
+ assert decision_context([inline]) == ""
+ assert "Later rule" in decision_context([inline, _resolved("applied", "Later rule")])