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): every agent gets its own contained shell and file hands
rubenluetke10-beep2a308da34ea2
diff --git a/jarvis/platform/probes.py b/jarvis/platform/probes.pyindex 5bda08e3a8..f0e2a7de28 100644--- a/jarvis/platform/probes.py+++ b/jarvis/platform/probes.py@@ -196,3 +196,14 @@ __all__ = ["has_elevation","webview_backend_available",]+++def has_container() -> bool:+ """Whether an agent-society container backend could run here.++ Deliberately ``False`` for now: the society runs agents' shells locally by+ decision (Hermes' default backend is local, OpenClaw's sandbox is off by+ default). When a Docker/Podman backend lands, this probe is where its+ availability is answered - never a hardcoded platform check.+ """+ return Falsediff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex d047afbe37..42c20797d1 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -36,10 +36,18 @@ from .roster import AgentState, slugifylog = logging.getLogger(__name__)-__all__ = ["MESSAGE_TOOL_NAME", "WIKI_NOTE_TOOL_NAME", "MessageAgentTool", "WikiNoteTool"]+__all__ = [+ "MESSAGE_TOOL_NAME",+ "SHELL_TOOL_NAME",+ "WIKI_NOTE_TOOL_NAME",+ "MessageAgentTool",+ "ShellTool",+ "WikiNoteTool",+]MESSAGE_TOOL_NAME: Final[str] = "society_message_agent"WIKI_NOTE_TOOL_NAME: Final[str] = "society_wiki_note"+SHELL_TOOL_NAME: Final[str] = "society_shell"_KINDS: Final[dict[str, MsgType]] = {"say": MsgType.SAY,"query": MsgType.QUERY,@@ -265,3 +273,130 @@ class WikiNoteTool:"reviewed: false\n""---\n")+++class ShellTool:+ """Run a command in the agent's OWN workspace folder (agent-definition §3).++ Local by decision (see ``jarvis/society/shell.py``): no container, but+ path containment, the destructive-command escalation the global shell+ tool uses, capped output and a hard timeout. Above the agent's ceiling or+ on a require-approval rule the call parks in the approvals queue instead+ of running (the chat shows the card; the person decides).+ """++ name: str = SHELL_TOOL_NAME+ risk_tier: str = "monitor"+ description: str = (+ "Run a shell command in YOUR workspace folder (your files live there; relative paths "+ "resolve inside it, paths outside it are refused). Use it for scripts, file "+ "conversions, git, package managers and small tools. Output is capped; long jobs get "+ "a timeout_s up to 900. Destructive commands (delete, format, reset) ask the user first."+ )+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "command": {"type": "string", "description": "The command line to run."},+ "cwd": {+ "type": "string",+ "description": "Subfolder of your workspace to run in (default: the workspace).",+ },+ "timeout_s": {+ "type": "number",+ "description": "Seconds before the command is killed.",+ },+ },+ "required": ["command"],+ }+ is_action_tool: bool = True++ def __init__(+ self, runtime: Any, agent_id: str, *, workspace: Path, backend: Any = None+ ) -> None:+ from .shell import default_backend++ self._runtime = runtime+ self._agent_id = agent_id+ self._workspace = Path(workspace)+ self._backend = backend or default_backend()++ @staticmethod+ def _level(command: str) -> str:+ from jarvis.safety.command_impact import classify_command++ return str(classify_command(command).level)++ def risk_tier_for_args(self, args: dict[str, Any]) -> str | None:+ from jarvis.safety.command_impact import DESTRUCTIVE++ command = str(args.get("command") or "").strip()+ if command and self._level(command) == DESTRUCTIVE:+ return "ask"+ return None++ def describe_args(self, args: dict[str, Any]) -> dict[str, str] | None:+ command = str(args.get("command") or "").strip()+ if not command:+ return None+ return {"command": command[:300], "folder": str(self._workspace)}++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ from jarvis.safety.command_impact import DESTRUCTIVE++ from .approvals import Verdict, decide+ from .shell import DEFAULT_TIMEOUT_S, ContainmentError, resolve_contained++ rt = self._runtime+ 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")+ if await rt.store.kill_switch():+ return _failure(FailureReason.KILL_SWITCH, "the society is halted")+ command = str(args.get("command") or "").strip()+ if not command:+ return _failure(FailureReason.BLOCKED_BY_POLICY, "command is required")+ try:+ cwd = resolve_contained(self._workspace, args.get("cwd"))+ except ContainmentError as exc:+ return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))+ level = self._level(command)+ tier = "ask" if level == DESTRUCTIVE else "monitor"+ verdict = decide(caller, "core:shell", tier, verb=level)+ if verdict is Verdict.BLOCK:+ return _failure(FailureReason.BLOCKED_BY_POLICY, "command class is blocked")+ if verdict is Verdict.QUEUE:+ item = await rt.approvals.enqueue(+ agent_id=caller.agent_id,+ trace_id=f"shell:{caller.agent_id}:{getattr(ctx, 'trace_id', '')}"[:120],+ capability="core:shell",+ action={"command": command[:2000], "cwd": str(cwd), "level": level},+ summary=f"Run in {cwd.name}: {command[:200]}",+ )+ return ToolResult(+ success=False,+ output={+ "reason": str(FailureReason.APPROVAL_REQUIRED),+ "retry": str(retry_action(FailureReason.APPROVAL_REQUIRED)),+ "approval_id": item.id,+ },+ error="approval_required: the user has to allow this command",+ )+ cwd.mkdir(parents=True, exist_ok=True)+ try:+ timeout = float(args.get("timeout_s") or DEFAULT_TIMEOUT_S)+ except (TypeError, ValueError):+ timeout = DEFAULT_TIMEOUT_S+ result = await self._backend.run(command, cwd=cwd, timeout_s=timeout)+ body = {+ "output": result.output,+ "exit_code": result.exit_code,+ "seconds": round(result.seconds, 2),+ "folder": str(cwd),+ "backend": getattr(self._backend, "name", "local"),+ }+ if result.timed_out:+ return ToolResult(success=False, output=body, error="command timed out")+ if result.failed_to_start:+ return ToolResult(success=False, output=body, error=result.output)+ error = None if result.ok else f"exit {result.exit_code}"+ return ToolResult(success=result.ok, output=body, error=error)diff --git a/jarvis/society/failure_reasons.py b/jarvis/society/failure_reasons.pyindex c58109cafb..2114c54c91 100644--- a/jarvis/society/failure_reasons.py+++ b/jarvis/society/failure_reasons.py@@ -48,6 +48,7 @@ class FailureReason(StrEnum):MESSAGE_CAP = "message_cap"KILL_SWITCH = "kill_switch"BLOCKED_BY_POLICY = "blocked_by_policy"+ APPROVAL_REQUIRED = "approval_required"INVALID_RESULT = "invalid_result"# Everything elseINTERNAL_ERROR = "internal_error"@@ -81,6 +82,7 @@ _RETRY: Final[dict[FailureReason, RetryAction]] = {FailureReason.MESSAGE_CAP: RetryAction.NEVER,FailureReason.KILL_SWITCH: RetryAction.NEVER,FailureReason.BLOCKED_BY_POLICY: RetryAction.NEVER,+ FailureReason.APPROVAL_REQUIRED: RetryAction.RETRY_LATER,FailureReason.INVALID_RESULT: RetryAction.NEVER,FailureReason.INTERNAL_ERROR: RetryAction.RETRY_LATER,}diff --git a/jarvis/society/shell.py b/jarvis/society/shell.pynew file mode 100644index 0000000000..7458b7ab5e--- /dev/null+++ b/jarvis/society/shell.py@@ -0,0 +1,169 @@+"""An agent's own shell: commands run in ITS workspace folder, nowhere else.++Sandbox stance (maintainer decision 2026-09-02, after checking the field):+Hermes Agent's default terminal backend is local and OpenClaw ships with its+sandbox off, so the society does the same — a local shell with path+containment and the existing risk tiers, no container by default. The+``ShellBackend`` protocol is the seam for an optional container backend+later (capability-probed, one class); it is deliberately not built now.++Containment is the one thing the ordinary folder tools do not do: every path+the agent names is resolved and must stay under the workspace, and the+command itself always starts there. Output is capped, stdin is closed, the+child gets ``CI=1`` / ``NO_COLOR`` so tools drop prompts and colours, and no+console window is ever created (AP-1).+"""++from __future__ import annotations++import asyncio+import contextlib+import os+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Final, Protocol++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++__all__ = [+ "ContainmentError",+ "DEFAULT_TIMEOUT_S",+ "LocalBackend",+ "MAX_TIMEOUT_S",+ "OUTPUT_CAP_CHARS",+ "ShellBackend",+ "ShellResult",+ "resolve_contained",+]++DEFAULT_TIMEOUT_S: Final[float] = 120.0+MAX_TIMEOUT_S: Final[float] = 900.0+OUTPUT_CAP_CHARS: Final[int] = 30_000+++class ContainmentError(ValueError):+ """A path left the agent's workspace."""+++def resolve_contained(workspace: Path, raw: str | None) -> Path:+ """Resolve ``raw`` relative to ``workspace``; refuse anything outside it.++ ``..``, absolute paths and symlinks pointing out of the folder all+ resolve to a real location — that location has to sit under the real+ workspace or the call is refused. An empty path is the workspace itself.+ """+ root = workspace.resolve()+ text = (raw or "").strip() or "."+ candidate = Path(os.path.expanduser(text))+ if not candidate.is_absolute():+ candidate = root / candidate+ resolved = candidate.resolve()+ try:+ resolved.relative_to(root)+ except ValueError as exc:+ raise ContainmentError(f"path leaves the agent workspace: {text}") from exc+ return resolved+++@dataclass(frozen=True, slots=True)+class ShellResult:+ output: str+ exit_code: int | None+ seconds: float+ timed_out: bool = False+ failed_to_start: bool = False++ @property+ def ok(self) -> bool:+ return self.exit_code == 0 and not self.timed_out and not self.failed_to_start+++class ShellBackend(Protocol):+ """Where an agent's commands run. ``LocalBackend`` today; a container+ backend would implement the same two members behind a capability probe."""++ name: str++ async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult: ...+++def _cap(text: str, limit: int) -> str:+ if len(text) <= limit:+ return text+ head = text[: limit // 2]+ tail = text[-(limit // 2) :]+ return f"{head}\n…[{len(text) - limit} characters cut]…\n{tail}"+++class LocalBackend:+ """The host shell, started inside the workspace (Git Bash / PowerShell /+ bash / sh — the same pick the chat's folder tools make)."""++ name: str = "local"++ async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult:+ from jarvis.agent_chat.tools import shell_argv++ timeout = max(1.0, min(float(timeout_s or DEFAULT_TIMEOUT_S), MAX_TIMEOUT_S))+ env = dict(os.environ)+ env.setdefault("PYTHONIOENCODING", "utf-8")+ env["CI"] = env.get("CI", "1")+ env.setdefault("NO_COLOR", "1")+ argv = [*shell_argv(), command]+ started = time.perf_counter()+ try:+ proc = await asyncio.create_subprocess_exec(+ *argv,+ cwd=str(cwd),+ env=env,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, ValueError) as exc:+ return ShellResult(+ output=f"Could not start the shell: {exc}",+ exit_code=None,+ seconds=0.0,+ failed_to_start=True,+ )+ try:+ raw, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)+ except TimeoutError:+ with contextlib.suppress(OSError, ProcessLookupError):+ proc.kill()+ with contextlib.suppress(OSError, ProcessLookupError):+ await proc.wait()+ return ShellResult(+ output=f"Command timed out after {int(timeout)} s",+ exit_code=None,+ seconds=time.perf_counter() - started,+ timed_out=True,+ )+ except asyncio.CancelledError:+ with contextlib.suppress(OSError, ProcessLookupError):+ proc.kill()+ raise+ text = raw.decode("utf-8", errors="replace").rstrip()+ return ShellResult(+ output=_cap(text, OUTPUT_CAP_CHARS),+ exit_code=proc.returncode,+ seconds=time.perf_counter() - started,+ )+++def default_backend() -> ShellBackend:+ """The backend this box runs agents' commands on — local, by decision.++ A container backend would be chosen here behind ``probes.has_container``+ once it exists; today the probe answers False and this returns the host+ shell.+ """+ return LocalBackend()+++def summarize_for_card(command: str, cwd: Path) -> dict[str, Any]:+ """What the approval card shows for a shell call."""+ return {"command": command[:300], "folder": str(cwd)}diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 29e31dc6c8..5e74a1c10f 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -27,7 +27,7 @@ from typing import Any, Final, castfrom jarvis.core.protocols import Tool-from .agent_tools import MessageAgentTool, WikiNoteTool+from .agent_tools import MessageAgentTool, ShellTool, WikiNoteToolfrom .capabilities import CapabilityKind, CapabilityRow, select_toolsfrom .roster import AgentRecord, canonical_session_idfrom .runtime import current_runtime@@ -49,8 +49,11 @@ _PREFIX: Final[str] = "society:"#: Tools every society session keeps regardless of grants — its own hands._OWN_PREFIX: Final[str] = "society_"#: Tools a society session never gets even in ``all`` mode: the agent writes-#: the wiki only through its namespaced note tool.-_SOCIETY_DENIED: Final[frozenset[str]] = frozenset({"wiki-ingest"})+#: the wiki only through its namespaced note tool and runs commands only+#: through its own contained shell (never the free-cwd shell tools).+_SOCIETY_DENIED: Final[frozenset[str]] = frozenset(+ {"wiki-ingest", "run-shell", "run_shell", "RunCommand"}+)_ECOSYSTEM_CARD: Final[str] = """\## The Jarvis ecosystem you work in@@ -61,6 +64,8 @@ an assignment into a run under the assignee's identity. You never spawn agents oanswer, propose). Compose it yourself. When you finish work for someone, end with a handoff: \what is done, where the output is, what evidence you used, what remains open, who owns the \next step.+- Shell: society_shell runs commands in YOUR workspace folder only (relative paths stay inside it; \+outside paths are refused). Destructive commands ask the user first.- Memory: the user's Obsidian wiki is the shared memory. Read it with wiki-recall and \wiki-page-read (pages marked unreviewed came from agents or the web — verify before relying \on them). Write only into your own folder with society_wiki_note (kind note for findings, \@@ -109,10 +114,69 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:agent_id = agent_id_of(getattr(session, "session_id", "") or "")if rt is None or agent_id is None:return {}- return {- MessageAgentTool.name: cast(Tool, MessageAgentTool(rt, agent_id)),- WikiNoteTool.name: cast(Tool, WikiNoteTool(rt, agent_id, vault_root=_vault_root(cfg))),- }+ workspace = Path(getattr(session, "cwd", "") or _workspace_fallback(cfg, agent_id))+ tools: dict[str, Tool] = {}+ # The folder tools of the chat surface, contained: on the society surface the+ # kit's tools REPLACE the folder tools (runner_brain.build_override), so the+ # agent would otherwise have no file hands at all; and the plain folder tools+ # accept absolute paths, which its workspace rule forbids.+ tools.update(_contained_folder_tools(workspace, getattr(session, "permission_mode", "")))+ tools.update(+ {+ MessageAgentTool.name: cast(Tool, MessageAgentTool(rt, agent_id)),+ WikiNoteTool.name: cast(Tool, WikiNoteTool(rt, agent_id, vault_root=_vault_root(cfg))),+ ShellTool.name: cast(Tool, ShellTool(rt, agent_id, workspace=workspace)),+ }+ )+ return tools+++class _ContainedTool:+ """A folder tool whose path arguments must stay inside the workspace."""++ _PATH_KEYS = ("file_path", "path", "directory", "cwd")++ def __init__(self, inner: Any, workspace: Path) -> None:+ self._inner = inner+ self._workspace = workspace+ self.name = inner.name+ self.description = inner.description+ self.schema = inner.schema+ self.risk_tier = inner.risk_tier++ def __getattr__(self, item: str) -> Any:+ return getattr(self._inner, item)++ async def execute(self, args: dict[str, Any], ctx: Any) -> Any:+ from jarvis.core.protocols import ToolResult++ from .shell import ContainmentError, resolve_contained++ for key in self._PATH_KEYS:+ raw = args.get(key)+ if isinstance(raw, str) and raw.strip():+ try:+ resolve_contained(self._workspace, raw)+ except ContainmentError as exc:+ return ToolResult(success=False, output=None, error=str(exc))+ return await self._inner.execute(args, ctx)+++def _contained_folder_tools(workspace: Path, permission_mode: str) -> dict[str, Tool]:+ from jarvis.agent_chat.folder_tools import folder_tools++ stance = "plan" if permission_mode == "plan" else "ask"+ out: dict[str, Tool] = {}+ for name, tool in folder_tools(workspace, stance=stance).items():+ if name == "RunCommand":+ continue # the agent's own contained shell replaces it+ out[name] = cast(Tool, _ContainedTool(tool, workspace))+ return out+++def _workspace_fallback(cfg: Any, agent_id: str) -> Path:+ data_dir = Path(getattr(getattr(cfg, "memory", None), "data_dir", None) or "data")+ return data_dir / "society" / agent_id / "workspace"def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]] | None:@@ -130,12 +194,12 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T}def _apply(tools: dict[str, Tool]) -> dict[str, Tool]:- own = {n: t for n, t in tools.items() if n.startswith(_OWN_PREFIX)}- rest = {+ own = {n: tfor n, t in tools.items()- if not n.startswith(_OWN_PREFIX) and n not in _SOCIETY_DENIED+ if n.startswith(_OWN_PREFIX) or isinstance(t, _ContainedTool)}+ rest = {n: t for n, t in tools.items() if n not in own and n not in _SOCIETY_DENIED}picked = select_tools(rest,grant_mode=str(agent.grant_mode),diff --git a/tests/unit/society/test_shell.py b/tests/unit/society/test_shell.pynew file mode 100644index 0000000000..959f238b90--- /dev/null+++ b/tests/unit/society/test_shell.py@@ -0,0 +1,150 @@+"""The agent's own shell: containment, tiers, timeout, cap — local by decision."""++from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.society.agent_tools import ShellTool+from jarvis.society.runtime import SocietyRuntime+from jarvis.society.shell import (+ OUTPUT_CAP_CHARS,+ ContainmentError,+ LocalBackend,+ ShellResult,+ resolve_contained,+)++CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)+++def test_containment(tmp_path: Path):+ ws = tmp_path / "ws"+ ws.mkdir()+ (ws / "sub").mkdir()+ assert resolve_contained(ws, None) == ws.resolve()+ assert resolve_contained(ws, "sub") == (ws / "sub").resolve()+ assert resolve_contained(ws, str(ws / "sub")) == (ws / "sub").resolve()+ with pytest.raises(ContainmentError):+ resolve_contained(ws, "..")+ with pytest.raises(ContainmentError):+ resolve_contained(ws, str(tmp_path))+ with pytest.raises(ContainmentError):+ resolve_contained(ws, "sub/../../")+ with pytest.raises(ContainmentError):+ resolve_contained(ws, "~")++[email protected](sys.platform == "win32", reason="symlink creation needs privileges on Windows")+def test_symlink_out_of_workspace_is_refused(tmp_path: Path):+ ws = tmp_path / "ws"+ ws.mkdir()+ (ws / "escape").symlink_to(tmp_path)+ with pytest.raises(ContainmentError):+ resolve_contained(ws, "escape")+++async def test_local_backend_runs_in_cwd_and_caps(tmp_path: Path):+ backend = LocalBackend()+ result = await backend.run("echo hello", cwd=tmp_path, timeout_s=30)+ assert result.ok and "hello" in result.output+ long = await backend.run("python -c \"print('x' * 70000)\"", cwd=tmp_path, timeout_s=60)+ assert long.ok and len(long.output) <= OUTPUT_CAP_CHARS + 100+ assert "characters cut" in long.output+++async def test_local_backend_timeout(tmp_path: Path):+ backend = LocalBackend()+ result = await backend.run('python -c "import time; time.sleep(5)"', cwd=tmp_path, timeout_s=1)+ assert result.timed_out and not result.ok+++class FakeBackend:+ name = "fake"++ def __init__(self) -> None:+ self.calls: list[tuple[str, Path, float]] = []++ async def run(self, command: str, *, cwd: Path, timeout_s: float) -> ShellResult:+ self.calls.append((command, cwd, timeout_s))+ return ShellResult(output="ok", exit_code=0, seconds=0.01)+++async def rt(tmp_path: Path):+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ await runtime.ensure_started()+ await runtime.roster.create(name="Scout")+ try:+ yield runtime+ finally:+ await runtime.close()+++async def test_tool_runs_inside_the_workspace_only(rt: SocietyRuntime, tmp_path: Path):+ ws = tmp_path / "ws"+ backend = FakeBackend()+ tool = ShellTool(rt, "scout", workspace=ws, backend=backend)+ res = await tool.execute({"command": "ls", "cwd": "notes"}, CTX)+ assert res.success, res.error+ assert backend.calls[0][1] == (ws / "notes").resolve()+ assert (ws / "notes").is_dir()+ assert res.output["backend"] == "fake"+ out = await tool.execute({"command": "ls", "cwd": ".."}, CTX)+ assert out.success is False and out.output["reason"] == "blocked_by_policy"+ assert len(backend.calls) == 1+ empty = await tool.execute({"command": " "}, CTX)+ assert empty.success is False+++async def test_tool_escalates_destructive_commands(rt: SocietyRuntime, tmp_path: Path):+ tool = ShellTool(rt, "scout", workspace=tmp_path / "ws", backend=FakeBackend())+ assert tool.risk_tier == "monitor"+ assert tool.risk_tier_for_args({"command": "rm -rf build"}) == "ask"+ assert tool.risk_tier_for_args({"command": "ls -la"}) is None+ assert tool.describe_args({"command": "rm -rf build"}) == {+ "command": "rm -rf build",+ "folder": str(tmp_path / "ws"),+ }+++async def test_tool_respects_kill_switch_and_state(rt: SocietyRuntime, tmp_path: Path):+ backend = FakeBackend()+ tool = ShellTool(rt, "scout", workspace=tmp_path / "ws", backend=backend)+ await rt.store.set_kill_switch(True)+ assert (await tool.execute({"command": "ls"}, CTX)).output["reason"] == "kill_switch"+ await rt.store.set_kill_switch(False)+ await rt.roster.update("scout", {"state": "paused"})+ assert (await tool.execute({"command": "ls"}, CTX)).success is False+ assert backend.calls == []+++def test_container_probe_is_false_by_decision():+ from jarvis.platform.probes import has_container++ assert has_container() is False+++async def test_folder_tools_are_contained(rt: SocietyRuntime, tmp_path: Path):+ from jarvis.society.surface import society_tools++ ws = tmp_path / "ws"+ ws.mkdir()+ (ws / "inside.txt").write_text("in", encoding="utf-8")+ (tmp_path / "outside.txt").write_text("out", encoding="utf-8")+ cfg = SimpleNamespace(+ wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")),+ memory=SimpleNamespace(data_dir=str(tmp_path / "data")),+ )+ session = SimpleNamespace(session_id="society:scout", cwd=str(ws), permission_mode="ask")+ tools = society_tools(cfg, None, session)+ read = tools["Read"]+ ok = await read.execute({"file_path": "inside.txt"}, CTX)+ assert ok.success and "in" in str(ok.output)+ refused = await read.execute({"file_path": str(tmp_path / "outside.txt")}, CTX)+ assert refused.success is False and "leaves the agent workspace" in str(refused.error)+ assert "RunCommand" not in tools and "society_shell" in toolsdiff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex f167ed420a..354f94b072 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -8,7 +8,7 @@ from types import SimpleNamespaceimport pytestfrom jarvis.society import runtime as runtime_mod-from jarvis.society.agent_tools import MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME+from jarvis.society.agent_tools import MESSAGE_TOOL_NAME, SHELL_TOOL_NAME, WIKI_NOTE_TOOL_NAMEfrom jarvis.society.runtime import SocietyRuntimefrom jarvis.society.surface import (agent_id_of,@@ -20,6 +20,9 @@ from jarvis.society.surface import ()+FOLDER = ["Read", "Write", "Edit", "Ls", "Glob", "Grep"]++def _tool(name: str, desc: str = "x.") -> SimpleNamespace:return SimpleNamespace(name=name, description=desc, risk_tier="monitor", schema={})@@ -68,7 +71,8 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pacfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))session = SimpleNamespace(session_id="society:mailbox")own = society_tools(cfg, None, session)- assert set(own) == {MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME}+ assert set(own) == {MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME, SHELL_TOOL_NAME, *FOLDER}+ assert "RunCommand" not in own# The briefing fills the cache the sync filter reads.extra = await society_system_extra(cfg, None, session)@@ -77,8 +81,9 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pafilt = society_tool_filter(session)assert filt is not Nonepicked = list(filt(merged))- assert picked[:2] == [MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME]- assert picked[2] == "gmail" # focus first+ own_names = {MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME, SHELL_TOOL_NAME, *FOLDER}+ assert set(picked[: len(own_names)]) == own_names+ assert picked[len(own_names)] == "gmail" # focus firstassert "spawn-worker" not in picked and "cli_gh" not in pickedassert "wiki-ingest" not in picked # writes go through the namespaced note toolassert "wiki-recall" in picked@@ -94,7 +99,9 @@ async def test_allowlist_mode_keeps_only_grants(rt: SocietyRuntime, tmp_path: Pafilt = society_tool_filter(session)assert filt is not Nonepicked = list(filt({**TOOLS, **society_tools(cfg, None, session)}))- assert picked == [MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME, "search-web"]+ assert picked[-1] == "search-web"+ assert {MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME, SHELL_TOOL_NAME, *FOLDER} <= set(picked)+ assert "gmail" not in picked and "cli_gh" not in pickedasync def test_unknown_agent_gets_no_briefing(rt: SocietyRuntime):