The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Shell guard for Swarm agents: no kill by name, sudo, fixed /tmp names, or removing a live worktree (#3304)
harness-for-autonomous[bot]3aa5a1a3e39e
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 609626362..f4228c094 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -99,6 +99,8 @@ const IN_PROCESS_ONLY = 'services/inline.ts'* them, so a process with the Swarm off loads none of its code; a static import of the same file is walked.*/const SWARM_DOORS: Readonly<Record<string, readonly string[]>> = {+ // The Swarm's internal pre-command hook: loaded only for that command, without starting any daemon.+ 'entry.ts': ['superTabs/shellGuardHook.ts'],// Its side of the core's process, and of the services that act on it when they run there.'core/main.ts': ['superTabs/inCore.ts', 'superTabs/inServices.ts'],// Its side of the services that act on it, in their own processes, and its own service's process, which the masterdiff --git a/cli/src/engines/__fixtures__/hook-installers.golden.json b/cli/src/engines/__fixtures__/hook-installers.golden.jsonindex 04d277312..3c819f83f 100644--- a/cli/src/engines/__fixtures__/hook-installers.golden.json+++ b/cli/src/engines/__fixtures__/hook-installers.golden.json@@ -1514,7 +1514,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -1562,7 +1562,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -1987,7 +1987,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2035,7 +2035,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2083,7 +2083,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2131,7 +2131,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:2:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:2:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:2:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:2:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2179,7 +2179,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2226,7 +2226,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2273,7 +2273,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2320,7 +2320,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2367,7 +2367,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn timeout 30>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn timeout 30>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn timeout 30>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn timeout 30>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2415,7 +2415,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2462,7 +2462,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2510,7 +2510,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2558,7 +2558,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2606,7 +2606,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2654,7 +2654,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -2702,7 +2702,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "link",@@ -2753,7 +2753,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "link",@@ -2880,7 +2880,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -3004,7 +3004,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -3078,7 +3078,7 @@"moved/codex-work/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/moved/codex-work/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 installIn>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 installIn>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/moved/codex-work/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"moved/codex-work/hooks.json": {"type": "file",@@ -3127,7 +3127,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "file",@@ -3175,7 +3175,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "file",@@ -3250,7 +3250,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "file",@@ -3298,7 +3298,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "file",@@ -3345,7 +3345,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:0:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:0:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "file",@@ -3393,7 +3393,7 @@"home/.codex/config.toml": {"type": "file","mode": "600",- "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"+ "text": "[hooks.state.\"<root>/home/.codex/hooks.json:session_start:1:0\"]\ntrusted_hash = \"<hash SessionStart command codex 19473 install>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:user_prompt_submit:1:0\"]\ntrusted_hash = \"<hash UserPromptSubmit command codex 19473 install>\"\n\n[hooks.state.\"/<session-flags>/config.toml:pre_tool_use:0:0\"]\ntrusted_hash = \"<hash shell guard>\"\n\n[hooks.state.\"<root>/home/.codex/hooks.json:post_tool_use:0:0\"]\ntrusted_hash = \"<hash PostToolUse messages>\"\n"},"home/.codex/hooks.json": {"type": "link",diff --git a/cli/src/engines/codex/hookContract.ts b/cli/src/engines/codex/hookContract.tsindex 847be7c11..667d0fb6f 100644--- a/cli/src/engines/codex/hookContract.ts+++ b/cli/src/engines/codex/hookContract.ts@@ -64,6 +64,9 @@ export const hooks: HookContract = {events: { SessionStart: 'session_start', UserPromptSubmit: 'user_prompt_submit', PostToolUse: 'post_tool_use' },matcherEvents: ['SessionStart'],defaultTimeout: 600,+ // The Swarm's shell guard (task #3596), given to a Swarm session by `-c` and never written in hooks.json: Codex runs+ // a session flag's hook only once its hash is recorded here (codex-cli 0.166.0, `hooks/list`).+ sessionHooks: ['shell-guard'],messages: {recorded: "[hooks] recorded Harness's own Codex hooks as reviewed → {config}",skipped: "[hooks] {config} defines hooks.state in a form Harness does not edit; Codex will ask to review Harness's hooks",diff --git a/cli/src/engines/facets/hooks.ts b/cli/src/engines/facets/hooks.tsindex 2ae9bf35a..ce29554ff 100644--- a/cli/src/engines/facets/hooks.ts+++ b/cli/src/engines/facets/hooks.ts@@ -132,9 +132,26 @@ export type HarnessAllowance =* `<real path of the settings file>:<event>:<block>:<hook>`, holding the hash the engine computes of that hook* (Codex 0.162 `hooks.state`, `trusted_hash`). A hook whose hash differs from the recorded one is asked about again.*/+/** The hooks Harness gives an engine on its command line for some sessions. */+export type SessionHookName = 'shell-guard'++/** A hook the engine is given on its command line for a session, not in its hooks file: what its record holds. */+export interface SessionHook {+ /** The record's key, as the engine names a session flag's hook. */+ key: string+ /** The engine's name for the hook's event, in the hash. */+ label: string+ matcher: string+ command: string+ timeout: number+}+export interface HookReviewRecord {/** The engine's config file, in the settings' home. */file: string+ /** Hooks Harness gives on the command line for some sessions (lib/agentShellGuard.ts, task #3596), recorded beside its own.+ * Named, not built here: a contract stays plain data (hooks.spec.ts), and kit/hookReview.ts builds each for the platform. */+ sessionHooks?: readonly SessionHookName[]/** The TOML table the records are sub-tables of. */table: string/** The field of a record that holds the hash. */diff --git a/cli/src/engines/hookInstallers.golden.spec.ts b/cli/src/engines/hookInstallers.golden.spec.tsindex ae50b18cf..dc5ca02f5 100644--- a/cli/src/engines/hookInstallers.golden.spec.ts+++ b/cli/src/engines/hookInstallers.golden.spec.ts@@ -328,6 +328,9 @@ beforeAll(async () => {const messages = messagesCommand(join(root, 'home', '.harness', 'agent-messages'))for (const timeout of [5, 30]) hashes.push([reviewHash(codex.settings.reviewed!, 'PostToolUse', undefined, { command: messages, timeout }), `<hash PostToolUse messages${timeout === 5 ? '' : ` timeout ${timeout}`}>`])hashes.push([messages, '<messages command>'])+ // The Swarm's shell guard (task #3596): one record, a session flag's, whose hash names this machine's Node and CLI.+ const { sessionReviewRecords } = await import('./kit/hookReview.js')+ for (const [, hash] of sessionReviewRecords(codex.settings.reviewed!)) hashes.push([hash, '<hash shell guard>'])// The real path first: on macOS the temporary folder is reached through /var, and Codex keys by /private/var.tokens = [...hashes, ...commands, [notify.HOOK_SCRIPT, '<script>'], [process.execPath, '<node>'], [realpathSync(root), '<root>'], [root, '<root>'], [`.${process.pid}.`, '.<pid>.']]})diff --git a/cli/src/engines/kit/hookRemoval.ts b/cli/src/engines/kit/hookRemoval.tsindex 52683b349..d451a89f2 100644--- a/cli/src/engines/kit/hookRemoval.ts+++ b/cli/src/engines/kit/hookRemoval.ts@@ -9,7 +9,7 @@ import { parse as parseToml } from 'smol-toml'import { basename, join } from 'node:path'import type { HookReviewRecord } from '../facets/hooks.js'import { HookPreparationHeld, inspectHookFile, runHookPreparation } from './nativeHookFiles.js'-import { reviewRecords, withoutReviewRecords } from './hookReview.js'+import { reviewRecords, sessionReviewRecords, withoutReviewRecords } from './hookReview.js'import { IdentityReadUnavailable } from './identityScan.js'import { isMessagesBlock } from './messagesHook.js'import { foreignHookBlocks, isManagedHookCommand, isOurs, type HookBlock, type Settings } from './notifyHooks.js'@@ -170,8 +170,12 @@ export async function removeReviewedHooks(record: HookReviewRecord, home: stringlet current: Settingstry { current = held.now() } catch { current = { hooks: {} } }const now = new Set(reviewRecords(record, keyed, current, platform).values())- if (before.size === 0 && now.size === 0) return { file: config, removed: 0 }- const owned = (key: string, hash: string) => before.get(key) === hash || (key.startsWith(`${keyed}:`) && now.has(hash))+ // The session flags' hooks (the Swarm's shell guard) are recorded with Harness's own (prepareReviewed), so they go+ // with them: by their exact key and the hash this release gives them.+ const session = sessionReviewRecords(record, platform)+ if (before.size === 0 && now.size === 0 && session.size === 0) return { file: config, removed: 0 }+ const owned = (key: string, hash: string) => before.get(key) === hash || session.get(key) === hash+ || (key.startsWith(`${keyed}:`) && now.has(hash))try { parseToml(observed.content, { integersAsBigInt: true, maxDepth: 64 }) }catch { throw new HookPreparationHeld('the hook review configuration is not complete TOML') }const { text, removed } = withoutReviewRecords(observed.content, record, owned)diff --git a/cli/src/engines/kit/hookReview.spec.ts b/cli/src/engines/kit/hookReview.spec.tsindex 51934a03c..ed5e00e3c 100644--- a/cli/src/engines/kit/hookReview.spec.ts+++ b/cli/src/engines/kit/hookReview.spec.ts@@ -4,7 +4,8 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { hooks } from '../codex/hookContract.js'import { installHookSettings } from './hookSettings.js'-import { recordReviewed, reviewHash, reviewRecords, withoutReviewRecords, withReviewRecords } from './hookReview.js'+import { CODEX_SHELL_GUARD } from '../../lib/agentShellGuard.js'+import { recordReviewed, reviewHash, reviewRecords, sessionHookHash, sessionReviewRecords, withoutReviewRecords, withReviewRecords } from './hookReview.js'const record = hooks.settings.reviewed!const roots: string[] = []@@ -72,8 +73,8 @@ describe('Harness’s own Codex hooks, recorded as reviewed', () => {// Another port: another command, so another hash, in the same tables.await installHookSettings('codex', hooks.settings, 18999, codexHome)const second = readFileSync(join(codexHome, 'config.toml'), 'utf8')- // Agent Messages' block makes three: notify.mjs's two, and its one.- expect(second.match(/^\[hooks\.state\./gm)).toHaveLength(3)+ // Agent Messages' block makes three: notify.mjs's two, and its one; the Swarm's shell guard a fourth (task #3596).+ expect(second.match(/^\[hooks\.state\./gm)).toHaveLength(4)expect(second).not.toBe(first)const installed = JSON.parse(readFileSync(join(codexHome, 'hooks.json'), 'utf8'))for (const [, hash] of reviewRecords(record, join(codexHome, 'hooks.json'), installed)) expect(second).toContain(hash)@@ -213,3 +214,33 @@ describe('Harness’s review records, taken out for harness uninstall', () => {]) expect(withoutReviewRecords(text, record, records)).toEqual({ text, removed: 0 })})})++// What `codex app-server` `hooks/list` of codex-cli 0.166.0 reported (2026-11-06) for the Swarm's shell guard given as a+// session flag (task #3596): `-c hooks.PreToolUse=[{matcher="*",hooks=[{type="command",command=GUARD,timeout=30}]}]`,+// keyed `/<session-flags>/config.toml:pre_tool_use:0:0`, `untrusted` until the home's config.toml records this hash and+// `trusted` once it does. A `hooks.state` given by `-c` as well is ignored ("unrecognized configuration setting").+const GUARD = "'/opt/harness/runtime/node' '/opt/harness/cli/superTabs/shellGuardHook.js'"+const GUARD_0_166 = 'sha256:e1f9e0b5b2f45f3edb26336eedc79c1fca60a8b4c6ecfc8e36ed4e61ab13592c'++describe('the Swarm shell guard, a Codex session flag, recorded as reviewed (task #3596)', () => {+ it('hashes it as codex-cli 0.166.0 does', () => {+ expect(sessionHookHash({ key: CODEX_SHELL_GUARD.key, label: 'pre_tool_use', matcher: '*', command: GUARD, timeout: 30 })).toBe(GUARD_0_166)+ })++ it('records the guard as this machine launches it, under the key Codex reads', () => {+ expect([...sessionReviewRecords(record, 'darwin')]).toEqual([[CODEX_SHELL_GUARD.key, sessionHookHash({+ key: CODEX_SHELL_GUARD.key, label: 'pre_tool_use', matcher: '*', command: CODEX_SHELL_GUARD.command('darwin'), timeout: 30 })]])+ })++ it('writes it beside Harness\'s own records at each install, so a Swarm Codex session runs it without asking', async () => {+ const codexHome = home()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ await installHookSettings('codex', hooks.settings, 19473, codexHome)+ const config = readFileSync(join(codexHome, 'config.toml'), 'utf8')+ for (const [key, hash] of sessionReviewRecords(record)) {+ expect(config).toContain(`[hooks.state.${JSON.stringify(key)}]\ntrusted_hash = ${JSON.stringify(hash)}\n`)+ }+ // The hooks file itself holds no guard: a person's own Codex session never runs it.+ expect(readFileSync(join(codexHome, 'hooks.json'), 'utf8')).not.toContain('shellGuardHook')+ })+})diff --git a/cli/src/engines/kit/hookReview.ts b/cli/src/engines/kit/hookReview.tsindex fb380c548..d67f76d3a 100644--- a/cli/src/engines/kit/hookReview.ts+++ b/cli/src/engines/kit/hookReview.ts@@ -17,7 +17,8 @@import { parse as parseToml } from 'smol-toml'import { createHash } from 'node:crypto'import { basename, join } from 'node:path'-import type { HookReviewRecord } from '../facets/hooks.js'+import type { HookReviewRecord, SessionHook, SessionHookName } from '../facets/hooks.js'+import { codexShellGuardSessionHook } from '../../lib/agentShellGuard.js'import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationAttempt } from './nativeHookFiles.js'import { isMessagesBlock } from './messagesHook.js'import { isOurs, type HookBlock, type Settings } from './notifyHooks.js'@@ -35,14 +36,28 @@ function sortedKeys(value: unknown): unknown {return value}+const identityHash = (identity: unknown): string => `sha256:${createHash('sha256').update(JSON.stringify(sortedKeys(identity))).digest('hex')}`+/** The engine's hash of one command hook, as `hooks/list` reports it in `currentHash`. */export function reviewHash(record: HookReviewRecord, event: string, matcher: string | undefined, hook: { command: string; timeout?: number; async?: boolean }): string {- const identity = {+ return identityHash({event_name: record.events[event],...(record.matcherEvents.includes(event) && matcher !== undefined ? { matcher } : {}),hooks: [{ type: 'command', command: hook.command, timeout: Math.max(1, hook.timeout ?? record.defaultTimeout), async: hook.async === true }],- }- return `sha256:${createHash('sha256').update(JSON.stringify(sortedKeys(identity))).digest('hex')}`+ })+}++/** The engine's hash of a session flag's hook: its matcher counts (codex-cli 0.166.0, `pre_tool_use`, measured). */+export function sessionHookHash(hook: SessionHook): string {+ return identityHash({ event_name: hook.label, matcher: hook.matcher, hooks: [{ type: 'command', command: hook.command, timeout: Math.max(1, hook.timeout), async: false }] })+}++/** Each session hook a contract names, built for the platform it launches on. */+const sessionHook: Record<SessionHookName, (platform: NodeJS.Platform) => SessionHook> = { 'shell-guard': codexShellGuardSessionHook }++/** The records the session flags' hooks Harness gives need, as this machine launches them: key → hash. */+export function sessionReviewRecords(record: HookReviewRecord, platform: NodeJS.Platform = process.platform): Map<string, string> {+ return new Map((record.sessionHooks ?? []).map((name) => sessionHook[name](platform)).map((hook) => [hook.key, sessionHookHash(hook)]))}/** The records Harness's own blocks in `settings` need: key → hash. */@@ -213,6 +228,9 @@ export function prepareReviewed(record: HookReviewRecord, home: string, settings// leaf is an alias. The config's own leaf alias does not change that home.const records = reviewRecords(record, join(observed.directory, basename(settingsFile)), settings, platform)if (records.size === 0) throw new HookPreparationHeld('the hooks have no verifiable approval records')+ // In the same write as Harness's own, so a Swarm session's guard (lib/agentShellGuard.ts) is trusted in every home+ // Harness prepares: the default one at each hook refresh, an agent's own profile before it starts.+ for (const [key, hash] of sessionReviewRecords(record, platform)) records.set(key, hash)const text = observed.content ?? ''try { parseToml(text, { integersAsBigInt: true, maxDepth: 64 }) }catch { throw new HookPreparationHeld('the hook review configuration is not complete TOML') }diff --git a/cli/src/entry.ts b/cli/src/entry.tsindex 713495271..e31c1669c 100644--- a/cli/src/entry.ts+++ b/cli/src/entry.ts@@ -17,7 +17,10 @@ import './lib/connectWait.js'import { fileURLToPath } from 'node:url'const [, , command, name] = process.argv-if (command === '__harnessd') {+if (command === '__swarm-shell-guard') {+ // Engine hooks need only the guard; ordinary CLI initialization would touch account and daemon state.+ ;(await import('./superTabs/shellGuardHook.js')).runShellGuard()+} else if (command === '__harnessd') {// This file is the bundle: the master starts the core from it, as cli.ts's own `SCRIPT_PATH` names it// for a master started from the sources, and itself and the services from the lean bundle it carries.(await import('./masterProcess.js')).startMasterFromBundle(fileURLToPath(import.meta.url))diff --git a/cli/src/lib/agentShellGuard.ts b/cli/src/lib/agentShellGuard.tsnew file mode 100644index 000000000..f3a02d7aa--- /dev/null+++ b/cli/src/lib/agentShellGuard.ts@@ -0,0 +1,62 @@+/**+ * The shell guard's hook (superTabs/shellGuard.ts, task #3596) as each engine runs it, for the sessions the Swarm starts+ * (lib/swarmEngineArgs.ts) and never a person's own. Claude Code takes it as a `--settings` value, which adds hooks to the+ * person's own settings for that session only. Codex takes it as a session flag (`-c hooks.PreToolUse=…`), which it runs+ * only once the home's config.toml records its hash as trusted (`codex app-server` `hooks/list`, codex-cli 0.166.0: the+ * key below, `untrusted` until recorded; a `hooks.state` given by `-c` is ignored), so Harness's Codex hook installation+ * records it beside its own (engines/codex/hookContract.ts). The hook names the script by its path only: nothing here+ * loads the Swarm's code.+ */+import { fileURLToPath } from 'node:url'+import { quoteHookCommand } from '../engines/kit/notifyHooks.js'+import { managedNodePath } from './nodeRuntime.js'+import type { SessionHook } from '../engines/facets/hooks.js'++/** Seconds an engine waits for the hook: lsof, read only for a worktree's removal, is given 5 of them. */+const TIMEOUT = 30+/** Claude Code's tools that run a shell or write a file at a path. */+const CLAUDE_MATCHER = 'Bash|Write|Edit|MultiEdit|NotebookEdit'++/** A release carries the guard inside cli.js, not as a separate script. The lean core sets argv[1] to that CLI+ * before installing hooks (leanCoreEntry.ts). Source/per-file builds use their lightweight entry instead. */+export function shellGuardArgv(): string[] {+ const file = fileURLToPath(import.meta.url)+ const source = /[/\\]agentShellGuard\.ts$/.test(file)+ const perFile = /[/\\]agentShellGuard\.[jt]s$/.test(file)+ const script = perFile ? fileURLToPath(new URL(source ? '../entry.ts' : '../entry.js', import.meta.url)) : process.argv[1]+ const loader = source ? ['--import', fileURLToPath(new URL('../../node_modules/tsx/dist/loader.mjs', import.meta.url))] : []+ return [managedNodePath(), ...loader, script, '__swarm-shell-guard']+}++/** Claude Code's `--settings` for the guard: a shell line, or on Windows exec form, as Harness's own hooks there. */+export function claudeShellGuardArgs(platform: NodeJS.Platform = process.platform, argv: string[] = shellGuardArgv()): string[] {+ const quoted = quoteHookCommand(platform === 'win32' ? 'argv' : 'bash', argv)+ const hook = Array.isArray(quoted)+ ? { type: 'command', command: quoted[0], args: quoted.slice(1), timeout: TIMEOUT }+ : { type: 'command', command: quoted, timeout: TIMEOUT }+ return ['--settings', JSON.stringify({ hooks: { PreToolUse: [{ matcher: CLAUDE_MATCHER, hooks: [hook] }] } })]+}++/** The guard as Codex runs it and hashes it: every tool, a POSIX line, or on Windows a PowerShell one. */+export const CODEX_SHELL_GUARD = {+ /** Where Codex keeps the record of the one session flag hook: its file, its event, its block and hook. */+ key: '/<session-flags>/config.toml:pre_tool_use:0:0',+ event: 'PreToolUse',+ matcher: '*',+ timeout: TIMEOUT,+ command: (platform: NodeJS.Platform = process.platform, argv: string[] = shellGuardArgv()): string =>+ quoteHookCommand(platform === 'win32' ? 'powershell' : 'bash', argv) as string,+}++/** Codex's session flag for the guard. TOML's basic strings read JSON's escapes. */+export function codexShellGuardArgs(platform: NodeJS.Platform = process.platform, argv: string[] = shellGuardArgv()): string[] {+ const { matcher, timeout } = CODEX_SHELL_GUARD+ const command = CODEX_SHELL_GUARD.command(platform, argv)+ return ['-c', `hooks.PreToolUse=[{matcher=${JSON.stringify(matcher)},hooks=[{type="command",command=${JSON.stringify(command)},timeout=${timeout}}]}]`]+}++/** The guard as Codex records it as reviewed (engines/kit/hookReview.ts): its key, its event's name in the hash, its hook. */+export function codexShellGuardSessionHook(platform: NodeJS.Platform = process.platform): SessionHook {+ const { key, matcher, timeout } = CODEX_SHELL_GUARD+ return { key, label: 'pre_tool_use', matcher, command: CODEX_SHELL_GUARD.command(platform), timeout }+}diff --git a/cli/src/lib/swarmEngineArgs.spec.ts b/cli/src/lib/swarmEngineArgs.spec.tsindex 39e27c126..75d7227ea 100644--- a/cli/src/lib/swarmEngineArgs.spec.ts+++ b/cli/src/lib/swarmEngineArgs.spec.ts@@ -1,17 +1,54 @@import { describe, expect, it } from 'vitest'+import { spawnSync } from 'node:child_process'+import { claudeShellGuardArgs, codexShellGuardArgs, shellGuardArgv } from './agentShellGuard.js'import { swarmEngineArgs } from './swarmEngineArgs.js'+const settingsOf = (args: string[]) => JSON.parse(args[args.indexOf('--settings') + 1]) as {+ hooks: { PreToolUse: { matcher: string; hooks: { type: string; command: string; args?: string[]; timeout: number }[] }[] }+}+describe('what the Swarm adds to an engine\'s argv', () => {it('turns off Codex\'s startup update check, whose "Update available" screen holds an agent nobody is at', () => {- expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false'])+ expect(swarmEngineArgs('codex').slice(0, 2)).toEqual(['-c', 'check_for_update_on_startup=false'])+ })++ it('runs the shell guard before each of a Swarm Claude Code session\'s shell and file-writing tools (task #3596)', () => {+ const args = swarmEngineArgs('claude')+ expect(args).toEqual(claudeShellGuardArgs())+ const blocks = settingsOf(args).hooks.PreToolUse+ expect(blocks).toHaveLength(1)+ expect(blocks[0].matcher).toBe('Bash|Write|Edit|MultiEdit|NotebookEdit')+ expect(blocks[0].hooks).toEqual([{ type: 'command', command: expect.stringContaining('__swarm-shell-guard'), timeout: 30 }])+ })++ it('runs it before each of a Swarm Codex session\'s tool calls, as a session flag', () => {+ expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false', ...codexShellGuardArgs()])+ const [flag, value] = codexShellGuardArgs('darwin', ['/opt/node', '/x/cli.js', '__swarm-shell-guard'])+ expect(flag).toBe('-c')+ expect(value).toBe(`hooks.PreToolUse=[{matcher="*",hooks=[{type="command",command="'/opt/node' '/x/cli.js' __swarm-shell-guard",timeout=30}]}]`)+ })++ it('starts the hook as each engine\'s runner on Windows takes it: exec form for Claude Code, a PowerShell line for Codex', () => {+ const argv = ['C:\\Harness\\node.exe', 'C:\\Harness\\cli\\cli.js', '__swarm-shell-guard']+ expect(settingsOf(claudeShellGuardArgs('win32', argv)).hooks.PreToolUse[0].hooks[0])+ .toEqual({ type: 'command', command: argv[0], args: argv.slice(1), timeout: 30 })+ expect(codexShellGuardArgs('win32', argv)[1]).toContain(JSON.stringify(`& '${argv[0]}' '${argv[1]}' ${argv[2]}`))+ })++ it('runs the hook from a source checkout with its TypeScript loader', () => {+ const [program, ...args] = shellGuardArgv()+ const run = spawnSync(program, args, { input: JSON.stringify({ tool_name: 'Bash', tool_input: { command: 'sudo ls' } }),+ encoding: 'utf8', timeout: 15_000, windowsHide: true })+ expect({ status: run.status, stderr: run.stderr }).toEqual({ status: 0, stderr: '' })+ expect(JSON.parse(run.stdout).hookSpecificOutput.permissionDecision).toBe('deny')})it('adds nothing for the other engines', () => {- for (const engine of ['claude', 'opencode', 'gemini', 'not-an-engine']) expect(swarmEngineArgs(engine)).toEqual([])+ for (const engine of ['opencode', 'gemini', 'not-an-engine']) expect(swarmEngineArgs(engine)).toEqual([])})it('hands out a copy, so a caller\'s edit never reaches the next launch', () => {swarmEngineArgs('codex').push('--oops')- expect(swarmEngineArgs('codex')).toEqual(['-c', 'check_for_update_on_startup=false'])+ expect(swarmEngineArgs('codex')).not.toContain('--oops')})})diff --git a/cli/src/lib/swarmEngineArgs.ts b/cli/src/lib/swarmEngineArgs.tsindex c11787cd4..8e064e3fe 100644--- a/cli/src/lib/swarmEngineArgs.ts+++ b/cli/src/lib/swarmEngineArgs.ts@@ -1,11 +1,14 @@/*** What the Swarm adds to an engine's argv for the agents it starts, beside the instructions it gives them* (lib/agentAttribution.ts) and never for a person's own session: declared as `swarmArgs` in the engine's launch- * (engines/codex/launch.ts).+ * (engines/codex/launch.ts), and the shell guard's hook (lib/agentShellGuard.ts, task #3596).*/import { launchContract } from '../engines/launches.js'+import { claudeShellGuardArgs, codexShellGuardArgs } from './agentShellGuard.js'++const SHELL_GUARD = new Map<string, () => string[]>([['claude', () => claudeShellGuardArgs()], ['codex', () => codexShellGuardArgs()]])/** The argv for a session the Swarm started, or none. */export function swarmEngineArgs(engine: string): string[] {- return [...launchContract(engine)?.swarmArgs ?? []]+ return [...launchContract(engine)?.swarmArgs ?? [], ...SHELL_GUARD.get(engine)?.() ?? []]}diff --git a/cli/src/superTabs/shellGuard.spec.ts b/cli/src/superTabs/shellGuard.spec.tsnew file mode 100644index 000000000..2aff205d5--- /dev/null+++ b/cli/src/superTabs/shellGuard.spec.ts@@ -0,0 +1,306 @@+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { GUARD_REASONS, fileRefusal, shellRefusal, type GuardFacts } from './shellGuard.js'++/** No filesystem and no live processes: each rule is read from the words alone. */+const facts = (over: Partial<GuardFacts> = {}): GuardFacts => ({+ cwd: '/work/repo', platform: 'darwin',+ privateFolder: () => false, linkedWorktree: () => false, liveCwds: () => [],+ ...over,+})++const refused = (command: string, over: Partial<GuardFacts> = {}) => shellRefusal(command, facts(over))++describe('shell guard: kill by name', () => {+ it.each([+ 'pkill -f node',+ 'killall Finder',+ '/usr/bin/pkill harness',+ 'kill $(pgrep -f vitest)',+ 'kill -9 `pidof node`',+ 'pgrep -f "next dev" | xargs kill',+ 'ps aux | grep node | awk \'{print $2}\' | xargs kill -9',+ 'lsof -ti :3000 | xargs kill',+ 'for p in $(pgrep node); do kill $p; done',+ 'fuser -k 3000/tcp',+ 'bash -lc "pkill -f tsx"',+ 'sh -c \'killall node\'',+ 'true && env FOO=1 pkill node',+ 'taskkill /IM node.exe /F',+ 'Stop-Process -Name node',+ 'Get-Process node | Stop-Process',+ ])('refuses %s', (command) => {+ expect(refused(command)).toBe(GUARD_REASONS.killByName)+ })++ it.each([+ 'kill 12345',+ 'kill -TERM 4242',+ 'kill "$SERVER_PID"',+ 'kill $(cat "$T/server.pid")',+ 'ps -p 4242 >/dev/null && kill 4242',+ 'taskkill /PID 4242 /F',+ 'Stop-Process -Id 4242',+ 'pgrep -fl vitest',+ 'ps aux | grep node',+ 'git log --grep=pkill',+ 'echo "never use pkill"',+ 'grep -rn killall src',+ ])('lets %s through', (command) => {+ expect(refused(command)).toBeNull()+ })+})++describe('shell guard: kill -1, every process the account can reach', () => {+ it.each([+ 'kill -9 -1',+ 'kill -- -1',+ 'kill -KILL -1',+ 'kill -s TERM -1',+ '/bin/kill -1 -1',+ 'kill 4242 -1',+ 'kill -1',+ '/bin/kill -9 -1 ; true',+ ])('refuses %s', (command) => {+ expect(refused(command)).toBe(GUARD_REASONS.killAll)+ })++ it.each([+ 'kill -1 4242',+ 'kill -- -4242',+ 'kill -l',+ ])('lets %s through', (command) => {+ expect(refused(command)).toBeNull()+ })+})++describe('shell guard: sudo and system-wide installs', () => {+ it.each([+ 'sudo rm -rf /opt/thing',+ 'sudo -u other whoami',+ 'doas pkg_add vim',+ 'su -c "make install"',+ 'npm install -g typescript',+ 'npm i --global pnpm',+ 'npm install --location=global tsx',+ 'pnpm add -g turbo',+ 'yarn global add serve',+ 'bun add -g vercel',+ 'brew install jq',+ 'brew upgrade',+ 'apt-get install -y ripgrep',+ 'apt install jq',+ 'dnf install gcc',+ 'port install wget',+ 'pacman -S ripgrep',+ 'pacman -Syu',+ 'pacman -Rns ripgrep',+ 'pip install --break-system-packages requests',+ 'python3 -m pip install --break-system-packages rich',+ 'installer -pkg Thing.pkg -target /',+ 'softwareupdate -i -a',+ 'winget install Git.Git',+ 'choco install nodejs',+ 'msiexec /i thing.msi',+ 'osascript -e \'do shell script "id" with administrator privileges\'',+ 'Start-Process pwsh -Verb RunAs',+ 'cd cli && sudo npm ci',+ ])('refuses %s', (command) => {+ expect(refused(command)).toBe(GUARD_REASONS.systemWide)+ })++ it.each([+ 'npm ci',+ 'npm install --save-dev vitest',+ 'npm i lodash',+ 'npx tsc --noEmit',+ 'pnpm install',+ 'brew list',+ 'brew --prefix',+ 'pacman -Qq',+ 'pacman --query ripgrep',+ 'pip install -r requirements.txt',+ 'python3 -m venv .venv && .venv/bin/pip install rich',+ 'cargo install ripgrep --root "$T/tools"',+ 'git commit -m "no sudo here"',+ 'grep -rn sudo docs',+ ])('lets %s through', (command) => {+ expect(refused(command)).toBeNull()+ })+})++describe('shell guard: heredocs', () => {+ it.each([+ "cat > notes.md <<'EOF'\nnever run sudo or pkill here\nEOF",+ 'gh pr comment 1 --body-file - <<EOF\nuse sudo apt install x, then killall Finder\nEOF',+ ])('reads a heredoc body as text, not commands: %j', (command) => {+ expect(refused(command)).toBeNull()+ })++ it('still reads the command a heredoc feeds', () => {+ expect(refused('cat <<EOF | sudo tee /etc/x\nhi\nEOF')).toBe(GUARD_REASONS.systemWide)+ expect(refused('cat <<-EOF > /tmp/x\n\tbody\n\tEOF')).toBe(GUARD_REASONS.fixedTmp)+ })+})++describe('shell guard: fixed names in /tmp', () => {+ it.each([+ 'echo hi > /tmp/out.txt',+ 'cat build.log >>/tmp/build.log',+ 'curl -o /tmp/thing.tgz https://example.com/thing.tgz',+ 'curl --output=/tmp/thing.tgz https://example.com',+ 'node script.js | tee /private/tmp/log.txt',+ 'mkdir -p /tmp/work && cp a /tmp/work/',+ 'touch /var/tmp/marker',+ 'harness super-tab instructions > /tmp/instr_wren.txt 2>&1',+ 'cd /tmp && echo x > y',+ 'bash -c "echo x > /tmp/y"',+ 'export OUT=/tmp/out.json',+ 'sh /tmp/planted.sh',+ ])('refuses %s', (command) => {+ expect(refused(command)).toBe(GUARD_REASONS.fixedTmp)+ })++ it.each([+ 'T=$(mktemp -d "${TMPDIR:-/tmp}/wren.XXXXXX")',+ 'mktemp -d /tmp/build.XXXXXX',+ 'mktemp -p /tmp',+ 'echo x > "$TMPDIR/wren.abc/out.txt"',+ 'ls /tmp',+ 'curl https://example.com/tmp/file',+ 'git log -- src/tmp/x.ts',+ 'echo "/tmpfoo"',+ ])('lets %s through', (command) => {+ expect(refused(command)).toBeNull()+ })++ it('lets through a path inside a folder only this account can open (made by mktemp -d)', () => {+ const own = (path: string) => path === '/tmp/wren.AbC123'+ expect(refused('echo x > /tmp/wren.AbC123/out.txt', { privateFolder: own })).toBeNull()+ expect(refused('echo x > /tmp/other/out.txt', { privateFolder: own })).toBe(GUARD_REASONS.fixedTmp)+ })++ it('takes Claude Code\'s own folder (mode 700, this account\'s) as private, and another account\'s as not', () => {+ const own = (path: string) => path === '/private/tmp/claude-600' || path === '/tmp/claude-600'+ expect(refused('cat /private/tmp/claude-600/project/tasks/abc.output', { privateFolder: own })).toBeNull()+ expect(refused('tail -5 /tmp/claude-600/x/y.output', { privateFolder: own })).toBeNull()+ expect(refused('cat /private/tmp/claude-501/x/scratchpad/notes.md', { privateFolder: own })).toBe(GUARD_REASONS.fixedTmp)+ })++ it('checks relative redirections against the command cwd', () => {+ expect(refused('echo hi > shared.txt', { cwd: '/tmp' })).toBe(GUARD_REASONS.fixedTmp)+ expect(refused('echo hi > shared.txt')).toBeNull()+ expect(refused('echo hi', { cwd: '/tmp' })).toBeNull()+ })++ it('does not treat an escape from a private temporary folder as private', () => {+ const own = (path: string) => path === '/tmp/private'+ expect(refused('echo hi > /tmp/private/../shared.txt', { privateFolder: own })).toBe(GUARD_REASONS.fixedTmp)+ expect(refused('echo hi > ../shared.txt', { cwd: '/tmp/private', privateFolder: own })).toBe(GUARD_REASONS.fixedTmp)+ expect(refused('echo hi > inside.txt', { cwd: '/tmp/private', privateFolder: own })).toBeNull()+ })++ it('checks relative file-tool paths before allowing a fixed temporary name', () => {+ expect(fileRefusal('shared.txt', facts({ cwd: '/tmp' }))).toBe(GUARD_REASONS.fixedTmp)+ expect(fileRefusal('../shared.txt', facts({ cwd: '/tmp/private', privateFolder: path => path === '/tmp/private' })))+ .toBe(GUARD_REASONS.fixedTmp)+ expect(fileRefusal('notes.md', facts())).toBeNull()+ })+})++describe('shell guard: removing a worktree a live process uses', () => {+ const worktree = '/work/trees/bold-pine'+ const linked = (path: string) => path === worktree++ it.each([+ `git worktree remove ${worktree}`,+ `git worktree remove --force ${worktree}`,+ `git -C /work/repo worktree remove -f ${worktree}`,+ `rm -rf ${worktree}`,+ `rm -r -f ${worktree}/`,+ 'git worktree remove ../trees/bold-pine',+ ])('refuses %s while a process works in it', (command) => {+ const liveCwds = () => [{ pid: 4242, cwd: `${worktree}/cli` }]+ expect(refused(command, { linkedWorktree: linked, liveCwds, cwd: '/work/repo' })).toBe(GUARD_REASONS.liveWorktree(worktree, 4242))+ })++ it('lets a worktree nobody works in go', () => {+ const liveCwds = () => [{ pid: 1, cwd: '/' }, { pid: 7, cwd: '/work/trees/bold-pine-2' }]+ expect(refused(`git worktree remove ${worktree}`, { linkedWorktree: linked, liveCwds })).toBeNull()+ expect(refused(`rm -rf ${worktree}`, { linkedWorktree: linked, liveCwds })).toBeNull()+ })++ it('does not check folders that are not worktrees', () => {+ const liveCwds = () => [{ pid: 4242, cwd: '/work/repo/node_modules/x' }]+ expect(refused('rm -rf node_modules', { liveCwds, cwd: '/work/repo' })).toBeNull()+ })++ // Rowan's security review (11-06): naming the worktree's parent, a glob over the worktrees or a ~/ path removed it too.+ describe('through a folder that holds it', () => {+ const live = () => [{ pid: 4242, cwd: `${worktree}/cli` }]+ const holding = { linkedWorktree: linked, liveCwds: live, home: '/work', cwd: '/work/repo',+ entries: (path: string) => (path === '/work/trees' ? ['bold-pine', 'other'] : path === '/work' ? ['trees', 'repo'] : []) }++ it.each([+ ['rm -rf /work/trees', '/work/trees'],+ ['rm -rf ../trees', '/work/trees'],+ ['rm -rf ~/trees', '/work/trees'],+ ['rm -rf /work/trees/*', worktree],+ ['rm -rf /work/trees/bold-*', worktree],+ ['cd /work && rm -rf tr*', '/work/trees'],+ ])('refuses %s', (command, target) => {+ expect(refused(command, holding)).toBe(GUARD_REASONS.liveWorktree(target, 4242))+ })++ it('lets the folder go when nobody works in the worktree it holds', () => {+ expect(refused('rm -rf /work/trees', { ...holding, liveCwds: () => [{ pid: 7, cwd: '/work/repo' }] })).toBeNull()+ })++ it('reads no live processes for a folder holding no worktree', () => {+ const liveCwds = () => { throw new Error('read live processes') }+ expect(refused('rm -rf build dist/*', { ...holding, liveCwds })).toBeNull()+ })+ })++ it('refuses when it cannot tell which processes are live', () => {+ expect(refused(`git worktree remove ${worktree}`, { linkedWorktree: linked, liveCwds: () => null }))+ .toBe(GUARD_REASONS.worktreeUnknown(worktree))+ })+})++describe('shell guard: ordinary work', () => {+ it.each([+ 'git status --short',+ 'cd cli && npx vitest run src/superTabs/shellGuard.spec.ts',+ 'harness super-tab --tab abc mine',+ 'gh pr view 12 --json title',+ 'make check-ui-style',+ 'flutter test test/super_tab_discovery_test.dart',+ 'git worktree list',+ 'rm -f build/out.js',+ '',+ ])('lets %s through', (command) => {+ expect(refused(command)).toBeNull()+ })+})++describe('shell guard: real folders', () => {+ const made: string[] = []+ afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true }) })++ it('reads a mktemp -d folder as private and a shared one as not', async () => {+ const { privateFolderOf, linkedWorktreeOf } = await import('./shellGuard.js')+ const own = mkdtempSync(join(tmpdir(), 'guard-'))+ made.push(own)+ expect(privateFolderOf(own)).toBe(true)+ chmodSync(own, 0o755)+ expect(privateFolderOf(own)).toBe(false)+ const tree = join(own, 'tree')+ mkdirSync(tree)+ expect(linkedWorktreeOf(tree)).toBe(false)+ writeFileSync(join(tree, '.git'), 'gitdir: /work/repo/.git/worktrees/tree\n')+ expect(linkedWorktreeOf(tree)).toBe(true)+ })+})diff --git a/cli/src/superTabs/shellGuard.ts b/cli/src/superTabs/shellGuard.tsnew file mode 100644index 000000000..0663a1fb3--- /dev/null+++ b/cli/src/superTabs/shellGuard.ts@@ -0,0 +1,578 @@+import { spawnSync } from 'node:child_process'+import { lstatSync, readdirSync, readlinkSync, realpathSync } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute, posix, resolve } from 'node:path'++/**+ * The shell guard of a Swarm agent's session (task #3596, inventory Table A #5; anh Dee 11-06: a rule that can be checked+ * runs as code, not as a line in the instructions). Every Swarm agent was told, in its skill and its project's rules, never+ * to stop processes by name, use sudo or install system-wide, write fixed names in /tmp, or remove a worktree a live process+ * uses; they still did (one wrote `> /tmp/instr_wren.txt` on 11-05). Shared machines run several accounts' agents at once,+ * so each of these breaks someone else's work: a `pkill -f node` stops every agent's servers, a fixed /tmp name can be read+ * or planted by any account, and a worktree removed under a live agent loses its work.+ *+ * This reads a command the way a shell splits it (quotes, `;` `&&` `||` `|`, `$(…)`, backticks, `sh -c '…'`, heredocs)+ * and refuses it with one line saying why and what to do instead. It is a guard for honest agents, not a sandbox: a+ * command built at run time (`$(echo pk)ill`) is not read. Plain text (a commit message, `grep pkill`, `echo sudo`) is+ * never taken for a command: only a word in a command's own place is.+ */++const PREFIX = 'Harness shell guard:'++export const GUARD_REASONS = {+ killByName: `${PREFIX} stop only processes you started, by the process id you recorded; never by name or pattern `+ + '(pkill, killall, kill $(pgrep …), taskkill /IM).',+ killAll: `${PREFIX} kill -1 signals every process this account can reach, every other agent's work on a shared machine; `+ + 'stop only processes you started, by the process id you recorded.',+ systemWide: `${PREFIX} no sudo and no system-wide installs on a shared machine; put the tools you need in your session folder.`,+ fixedTmp: `${PREFIX} a fixed name in /tmp can be read or planted by every account; make a folder with `+ + 'mktemp -d "${TMPDIR:-/tmp}/name.XXXXXX" and write inside it.',+ liveWorktree: (path: string, pid: number) => `${PREFIX} process ${pid} still works in a worktree in ${path}; never remove a `+ + 'worktree a live process uses.',+ worktreeUnknown: (path: string) => `${PREFIX} could not tell whether a live process uses the worktree ${path}, so it is not `+ + 'removed; stop what runs there first.',+}++/** What the guard knows of the machine: seams, so a spec reads none of the machine it runs on. */+export interface GuardFacts {+ /** The folder the command runs in. */+ cwd: string+ platform: NodeJS.Platform+ /** Whether [path] is a folder only this account can open (what `mktemp -d` makes). */+ privateFolder: (path: string) => boolean+ /** Whether [path] is a linked git worktree (its `.git` is a file). */+ linkedWorktree: (path: string) => boolean+ /** Every live process's working folder, or null when they cannot be read. */+ liveCwds: () => { pid: number; cwd: string }[] | null+ /** [path] with its links resolved; [path] itself when absent or when it cannot be. */+ realpath?: (path: string) => string+ /** The account's home, for `~` and `~/…`; left as written without it. */+ home?: string+ /** The names of the folders (not links) in [path], for a glob and for the worktrees a folder holds; none when unread. */+ entries?: (path: string) => string[]+}++/** One command in its own place: its words with quotes removed, and where its redirections write or read. */+interface Simple { words: string[]; targets: string[] }++/** The guard's answer for [command]: the reason it is refused, or null to let it run. */+export function shellRefusal(command: string, facts: GuardFacts): string | null {+ const commands = allCommands(command)+ if (commands.some(systemWide)) return GUARD_REASONS.systemWide+ if (killsByName(commands)) return GUARD_REASONS.killByName+ if (commands.some(killsAll)) return GUARD_REASONS.killAll+ if (commands.some((simple) => fixedTmp(simple, facts))) return GUARD_REASONS.fixedTmp+ return liveWorktree(commands, facts)+}++/** The guard's answer for a file tool writing [path] (Claude Code's Write, Edit, MultiEdit and NotebookEdit). */+export function fileRefusal(path: string, facts: GuardFacts): string | null {+ return tmpPathRefused(resolveIn(facts.cwd, path, facts.platform), facts) ? GUARD_REASONS.fixedTmp : null+}++// ---------------------------------------------------------------------------------------------------------------------+// Reading a command++const MAX_DEPTH = 8++/** Every command in [text], in order, with those inside `$(…)`, backticks, `<(…)`, `sh -c '…'` and `eval`. */+function allCommands(text: string, depth = 0): Simple[] {+ if (depth > MAX_DEPTH) return []+ const nested: string[] = []+ const found: Simple[] = []+ for (const simple of split(text, nested)) {+ const words = programWords(simple.words)+ found.push({ words, targets: simple.targets })+ const script = scriptOf(words)+ if (script !== null) nested.push(script)+ }+ for (const inner of nested) found.push(...allCommands(inner, depth + 1))+ return found+}++/** The script a shell or `eval` runs from its words: `bash -lc '…'`, `sh -c "…"`, `pwsh -Command …`, `eval …`. */+function scriptOf(words: string[]): string | null {+ const program = programName(words[0])+ if (program === 'eval') return words.slice(1).join(' ')+ if (SHELLS.has(program)) {+ const flag = words.findIndex((word, index) => index > 0 && /^-[a-z]*c[a-z]*$/i.test(word))+ if (flag > 0 && words[flag + 1] !== undefined) return words[flag + 1]+ }+ if (POWERSHELLS.has(program)) {+ const flag = words.findIndex((word, index) => index > 0 && /^-(c|command)$/i.test(word))+ if (flag > 0) return words.slice(flag + 1).join(' ')+ }+ return null+}++const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])+const POWERSHELLS = new Set(['pwsh', 'powershell'])++/** A program's name as matched: its last path part, lower case, without `.exe`. */+function programName(word: string | undefined): string {+ if (!word) return ''+ return (word.split(/[\\/]/).pop() ?? '').toLowerCase().replace(/\.exe$/, '')+}++/** Shell words that start a command but are not its program. */+const KEYWORDS = new Set(['!', '{', '}', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time', 'function'])+/** Programs that run the rest of their words as a command, each with the options that take a value. */+const WRAPPERS: Record<string, { values: Set<string>; first?: 'duration' }> = {+ env: { values: new Set(['-u', '--unset', '-C', '--chdir', '-S', '--split-string']) },+ command: { values: new Set() },+ builtin: { values: new Set() },+ exec: { values: new Set(['-a']) },+ nohup: { values: new Set() },+ nice: { values: new Set(['-n', '--adjustment']) },+ timeout: { values: new Set(['-s', '--signal', '-k', '--kill-after']), first: 'duration' },+ xargs: { values: new Set(['-I', '-i', '-n', '-P', '-L', '-l', '-d', '-E', '-e', '-s', '-a', '--max-args', '--max-procs', '--delimiter', '--arg-file']) },+ stdbuf: { values: new Set(['-i', '-o', '-e']) },+ caffeinate: { values: new Set(['-t', '-w']) },+}++/** [words] from the program on: leading assignments, shell keywords and wrappers (`env X=1`, `xargs -n1`, `nohup`) go. */+function programWords(words: string[]): string[] {+ let at = 0+ for (;;) {+ while (at < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[at]) || KEYWORDS.has(words[at]))) at+++ const name = programName(words[at])+ const wrapper = WRAPPERS[name]+ if (!wrapper) return words.slice(at)+ at+++ let duration = wrapper.first === 'duration'+ while (at < words.length) {+ const word = words[at]+ if (word === '--') { at++; break }+ if (word.startsWith('-') && word.length > 1) { at += wrapper.values.has(word) ? 2 : 1; continue }+ if (name === 'env' && /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) { at++; continue }+ if (duration) { duration = false; at++; continue }+ break+ }+ }+}++/**+ * The commands of [text] as a shell splits them. What `$(…)`, backticks and `<(…)` hold goes to [nested], to be read as+ * commands of their own; the word keeps its text. A heredoc's body is data, never commands (a commit message saying+ * "sudo" at a line's start is not a sudo). `#` starts a comment at a word's start.+ */+function split(text: string, nested: string[]): Simple[] {+ const out: Simple[] = []+ let words: string[] = [], targets: string[] = []+ let word = '', inWord = false, redirect = false+ const heredocs: { delimiter: string; strip: boolean }[] = []+ let pendingHeredoc: { strip: boolean } | null = null++ const endWord = () => {+ if (!inWord) return+ if (pendingHeredoc) { heredocs.push({ delimiter: word, strip: pendingHeredoc.strip }); pendingHeredoc = null }+ else if (redirect) { targets.push(word); redirect = false }+ else words.push(word)+ word = ''; inWord = false+ }+ const endCommand = () => {+ endWord()+ if (words.length || targets.length) out.push({ words, targets })+ words = []; targets = []; redirect = false+ }++ let i = 0+ while (i < text.length) {+ const c = text[i]+ if (c === '\n') {+ endCommand()+ i+++ // Skip each heredoc's body, line by line, up to its delimiter.+ for (const doc of heredocs.splice(0)) {+ while (i < text.length) {+ const end = text.indexOf('\n', i)+ const line = text.slice(i, end === -1 ? text.length : end)+ i = end === -1 ? text.length : end + 1+ if ((doc.strip ? line.replace(/^\t+/, '') : line) === doc.delimiter) break+ }+ }+ continue+ }+ if (c === ' ' || c === '\t') { endWord(); i++; continue }+ if (c === '#' && !inWord) { while (i < text.length && text[i] !== '\n') i++; continue }+ if (c === '\\') {+ if (text[i + 1] === '\n') { i += 2; continue }+ word += text[i + 1] ?? ''; inWord = true; i += 2; continue+ }+ if (c === "'") {+ const end = text.indexOf("'", i + 1)+ word += text.slice(i + 1, end === -1 ? text.length : end); inWord = true+ i = end === -1 ? text.length : end + 1+ continue+ }+ if (c === '"') {+ inWord = true; i+++ while (i < text.length && text[i] !== '"') {+ if (text[i] === '\\' && '"\\$`\n'.includes(text[i + 1] ?? '')) { word += text[i + 1]; i += 2; continue }+ const sub = substitution(text, i)+ if (sub) { nested.push(sub.inner); word += text.slice(i, sub.end); i = sub.end; continue }+ word += text[i]; i+++ }+ i+++ continue+ }+ const sub = substitution(text, i)+ if (sub) { nested.push(sub.inner); word += text.slice(i, sub.end); inWord = true; i = sub.end; continue }+ if ((c === '<' || c === '>') && text[i + 1] === '(') {+ const end = closing(text, i + 1)+ nested.push(text.slice(i + 2, end - 1)); word += text.slice(i, end); inWord = true; i = end+ continue+ }+ if (c === ';' || c === '&' || c === '|' || c === '(' || c === ')') {+ if (c === '&' && text[i + 1] === '>') { endWord(); i += text[i + 2] === '>' ? 3 : 2; redirect = true; continue }+ endCommand()+ i += (c === '&' && text[i + 1] === '&') || (c === '|' && (text[i + 1] === '|' || text[i + 1] === '&')) || (c === ';' && text[i + 1] === ';') ? 2 : 1+ continue+ }+ if (c === '<' || c === '>') {+ // A file descriptor before it (`2>`) is part of the redirection, not a word.+ if (inWord && /^\d+$/.test(word)) { word = ''; inWord = false } else endWord()+ if (c === '<' && text[i + 1] === '<' && text[i + 2] !== '<') {+ const strip = text[i + 2] === '-'+ i += strip ? 3 : 2+ pendingHeredoc = { strip }+ continue+ }+ let j = i + 1+ while (text[j] === '>' || text[j] === '<' || text[j] === '|') j+++ if (text[j] === '&') {+ // `>&2`, `2>&1`: to another descriptor, no file.+ j+++ while (/\d|-/.test(text[j] ?? '')) j+++ i = j+ continue+ }+ i = j+ redirect = true+ continue+ }+ word += c; inWord = true; i+++ }+ endCommand()+ return out+}++/** `$(…)` or `` `…` `` at [at]: what it holds and where it ends. */+function substitution(text: string, at: number): { inner: string; end: number } | null {+ if (text[at] === '$' && text[at + 1] === '(') {+ const end = closing(text, at + 1)+ return { inner: text.slice(at + 2, end - 1), end }+ }+ if (text[at] === '`') {+ const end = text.indexOf('`', at + 1)+ const stop = end === -1 ? text.length : end+ return { inner: text.slice(at + 1, stop), end: stop + 1 }+ }+ return null+}++/** Just past the `)` that closes the `(` at [open], skipping quotes and nested parentheses. */+function closing(text: string, open: number): number {+ let depth = 0+ for (let i = open; i < text.length; i++) {+ const c = text[i]+ if (c === '\\') { i++; continue }+ if (c === "'") { const end = text.indexOf("'", i + 1); i = end === -1 ? text.length : end; continue }+ if (c === '"') {+ i+++ while (i < text.length && text[i] !== '"') { if (text[i] === '\\') i++; i++ }+ continue+ }+ if (c === '(') depth+++ if (c === ')' && --depth === 0) return i + 1+ }+ return text.length+}++// ---------------------------------------------------------------------------------------------------------------------+// The rules++const lower = (words: string[]) => words.map((word) => word.toLowerCase())+/** The first word after the program that is not an option. */+const subcommand = (words: string[]) => words.slice(1).find((word) => !word.startsWith('-'))?.toLowerCase()++const ELEVATORS = new Set(['sudo', 'doas', 'su', 'pkexec', 'gsudo', 'runas'])+const NODE_MANAGERS = new Set(['npm', 'pnpm', 'bun'])+const NODE_CHANGES = new Set(['install', 'i', 'in', 'isntall', 'add', 'update', 'up', 'upgrade', 'uninstall', 'remove', 'rm', 'un', 'r', 'link', 'ln'])+const BREW_CHANGES = new Set(['install', 'reinstall', 'upgrade', 'uninstall', 'remove', 'rm', 'tap', 'untap', 'link', 'unlink'])+const SYSTEM_PACKAGES = new Set(['apt', 'apt-get', 'aptitude', 'dnf', 'yum', 'zypper', 'apk', 'snap', 'port', 'pkg', 'emerge'])+const PACKAGE_CHANGES = new Set(['install', 'reinstall', 'upgrade', 'remove', 'purge', 'add', 'del', 'erase', 'autoremove',+ 'dist-upgrade', 'full-upgrade', 'uninstall', 'selfupdate', 'selfupgrade', 'refresh'])+const WINDOWS_PACKAGES = new Set(['winget', 'choco'])++/** sudo and its kin, or an install that writes for every account on the machine. */+function systemWide({ words }: Simple): boolean {+ const program = programName(words[0])+ const all = lower(words)+ if (ELEVATORS.has(program)) return true+ if (NODE_MANAGERS.has(program)) {+ const global = all.some((word) => word === '-g' || word === '--global' || word === '--location=global')+ || all.some((word, index) => word === '--location' && all[index + 1] === 'global')+ return global && NODE_CHANGES.has(subcommand(words) ?? '')+ }+ if (program === 'yarn') return subcommand(words) === 'global'+ if (program === 'brew') return BREW_CHANGES.has(subcommand(words) ?? '')+ if (SYSTEM_PACKAGES.has(program)) return PACKAGE_CHANGES.has(subcommand(words) ?? '')+ if (program === 'pacman') return words.slice(1).some((word) => /^-[A-Za-z]*[SRU]/.test(word) || /^--(sync|remove|upgrade)$/.test(word))+ if (program === 'pip' || program === 'pip3' || (/^python[\d.]*$/.test(program) && all.includes('pip'))) {+ return all.includes('install') && all.some((word) => word === '--break-system-packages' || word === '--system')+ }+ if (program === 'installer') return all.includes('-pkg')+ if (program === 'softwareupdate') return all.slice(1).some((word) => ['-i', '--install', '-a', '--all', '-r', '--recommended'].includes(word))+ if (WINDOWS_PACKAGES.has(program)) return ['install', 'upgrade', 'uninstall'].includes(subcommand(words) ?? '')+ if (program === 'msiexec') return all.slice(1).some((word) => /^[/-](i|x|package|uninstall)$/.test(word))+ if (program === 'osascript') return all.some((word) => word.includes('with administrator privileges'))+ if (program === 'start-process') return all.some((word, index) => word === '-verb' && all[index + 1] === 'runas')+ if (['install-module', 'install-package', 'install-script'].includes(program)) {+ return all.some((word, index) => word === '-scope' && all[index + 1] === 'allusers')+ }+ return false+}++const BY_NAME = new Set(['pkill', 'killall', 'killall5'])+const KILLERS = new Set(['kill', 'stop-process', 'spps'])+const LOOKUPS = new Set(['pgrep', 'pidof', 'lsof', 'fuser', 'get-process', 'gps'])++/** pkill and its kin, or a kill fed by a lookup by name or pattern (`kill $(pgrep …)`, `lsof -ti :3000 | xargs kill`). */+function killsByName(commands: Simple[]): boolean {+ let kills = false, looksUp = false+ for (const { words } of commands) {+ const program = programName(words[0])+ const all = lower(words)+ if (BY_NAME.has(program)) return true+ if (program === 'fuser' && all.slice(1).some((word) => /^-[a-z]*k/.test(word))) return true+ if (program === 'taskkill' && all.some((word) => word === '/im' || word === '-im')) return true+ if (KILLERS.has(program) && all.some((word) => word === '-name' || word === '-processname')) return true+ if (program === 'wmic' && all.includes('process') && all.some((word) => word === 'delete' || word === 'terminate')) return true+ if (KILLERS.has(program)) kills = true+ // `ps -p 4242` checks a recorded id; `ps aux` lists everything for a pattern to pick from.+ if (LOOKUPS.has(program) || (program === 'ps' && !all.some((word) => /^-[a-z]*[pq]$/.test(word) || word === '--pid'))) {+ if (!(program === 'get-process' || program === 'gps') || !all.includes('-id')) looksUp = true+ }+ }+ return kills && looksUp+}++/**+ * `kill … -1`: a target of -1 signals every process the account may signal (POSIX kill(2)), on a shared Team account every+ * other agent's work (Rowan's security review, 11-06). The first word after `kill` that starts with `-` is the signal+ * (`kill -1 4242` sends SIGHUP to 4242), unless it is `--`; every word after it is a target. A negative group id other than+ * -1 is a process group the agent started, by its id, and passes.+ */+function killsAll({ words }: Simple): boolean {+ if (programName(words[0]) !== 'kill') return false+ // A bare `kill -1` is a usage error to a shell's kill, but a kill program may take -1 as its target: never useful, so refused.+ if (words.length === 2 && words[1] === '-1') return true+ let at = 1+ if (words[at] === '-s' || words[at] === '-n') at += 2+ else if (words[at] === '-l' || words[at] === '-L') return false+ else if (words[at]?.startsWith('-') && words[at] !== '--') at += 1+ if (words[at] === '--') at += 1+ return words.slice(at).includes('-1')+}++const TMP_ROOTS = ['/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp']+/** A path in /tmp inside a word: at its start, or after `=`, `:` or `,` (`--output=/tmp/x`, `PATH=a:/tmp/b`). */+const TMP_PATH = /(?:^|[=:,])((?:\/private)?(?:\/var)?\/tmp\/[^\s"'`;|&<>()]+)/g++/** A word or redirection writing, reading or running a fixed name in /tmp; `mktemp`'s own words are its templates. */+function fixedTmp({ words, targets }: Simple, facts: GuardFacts): boolean {+ const program = programName(words[0])+ if (targets.some((target) => fileRefusal(target, facts) !== null)) return true+ if (program === 'mktemp') return false+ // `cd /tmp` and then a plain name writes a fixed name there.+ if ((program === 'cd' || program === 'pushd') && words[1] && TMP_ROOTS.includes(words[1].replace(/\/+$/, ''))) return true+ return words.some((word) => tmpPathRefused(word, facts))+}++/** Whether [word] names a path in /tmp whose top folder is not one only this account can open. */+function tmpPathRefused(word: string, facts: GuardFacts): boolean {+ for (const match of word.matchAll(TMP_PATH)) {+ // Check the destination, not an earlier private component that `..` leaves behind.+ const path = posix.normalize(match[1])+ const root = TMP_ROOTS.find(root => path.startsWith(`${root}/`))+ if (root && !facts.privateFolder(`${root}/${path.slice(root.length + 1).split('/')[0]}`)) return true+ }+ return false+}++/**+ * `git worktree remove P`, or `rm -r P` of a folder holding a linked worktree, while a live process still works in it.+ * Rowan's security review (11-06): naming the worktree's parent, a glob over the worktrees or a `~/` path removed a live+ * worktree too, so the target is the folder after `~` and globs are read, and it counts when it holds a worktree at+ * any depth the walk reaches. Live processes are read only then: they cost an lsof on a Mac.+ */+function liveWorktree(commands: Simple[], facts: GuardFacts): string | null {+ let cwd = facts.cwd+ for (const { words } of commands) {+ const program = programName(words[0])+ if (program === 'cd' && words[1] && !words[1].startsWith('-') && !words[1].includes('$')) {+ const folder = expandHome(words[1], facts)+ if (!folder.startsWith('~')) cwd = resolveIn(cwd, folder, facts.platform)+ continue+ }+ for (const target of removedFolders(words, cwd, facts)) {+ const real = facts.realpath?.(target) ?? target+ if (!holdsWorktree(real, facts) && (real === target || !holdsWorktree(target, facts))) continue+ const live = facts.liveCwds()+ if (live === null) return GUARD_REASONS.worktreeUnknown(target)+ const user = live.find(({ cwd: there }) => within(there, real) || within(there, target))+ if (user) return GUARD_REASONS.liveWorktree(target, user.pid)+ }+ }+ return null+}++const within = (path: string, folder: string) => path === folder || path.startsWith(`${folder}/`)+const resolveIn = (cwd: string, path: string, platform: NodeJS.Platform) =>+ (platform === 'win32' ? resolve(cwd, path) : posix.resolve(cwd, path)).replace(/(.)\/+$/, '$1')++/** How deep, and through how many folders, the walk looks for a worktree: ~/harnesses/worktrees/<project>/<id> is 4. */+const WALK_DEPTH = 4+const WALK_FOLDERS = 2000+const WALK_SKIPS = new Set(['node_modules', '.git'])++/** Whether [path] is a linked worktree or holds one; a walk too big to finish counts as holding one. */+function holdsWorktree(path: string, facts: GuardFacts): boolean {+ if (facts.linkedWorktree(path)) return true+ if (!facts.entries) return false+ let seen = 0+ const walk = (folder: string, depth: number): boolean => {+ if (depth === 0) return false+ for (const name of facts.entries!(folder)) {+ if (WALK_SKIPS.has(name)) continue+ if (++seen > WALK_FOLDERS) return true+ const inner = `${folder.replace(/\/+$/, '')}/${name}`+ if (facts.linkedWorktree(inner) || walk(inner, depth - 1)) return true+ }+ return false+ }+ return walk(path, WALK_DEPTH)+}++const expandHome = (path: string, facts: GuardFacts): string =>+ facts.home && (path === '~' || path.startsWith('~/')) ? `${facts.home}${path.slice(1)}` : path++const GLOB = /[*?[]/+/** A segment's shell glob as a pattern: `*`, `?` and `[…]`; a leading `*` or `?` matches no dot file, as the shell's. */+function globPattern(segment: string): RegExp {+ let source = ''+ for (let i = 0; i < segment.length; i++) {+ const c = segment[i]+ if (c === '*') source += '[^/]*'+ else if (c === '?') source += '[^/]'+ else if (c === '[') {+ const close = segment.indexOf(']', i + 2)+ if (close === -1) { source += '\\['; continue }+ source += `[${segment.slice(i + 1, close).replace(/^!/, '^').replace(/\\/g, '\\\\')}]`+ i = close+ } else source += c.replace(/[.+^${}()|\\\]]/g, '\\$&')+ }+ return new RegExp(`^${/^[*?[]/.test(segment) ? '(?!\\.)' : ''}${source}$`)+}++/** The folders a path argument names: itself, or for a glob each folder its first glob segment matches (what is below+ * it counts, so the rest of the pattern is not needed). */+function namedFolders(path: string, cwd: string, facts: GuardFacts): string[] {+ const expanded = expandHome(path, facts)+ if (expanded.startsWith('~') || expanded.includes('$')) return []+ if (!GLOB.test(expanded)) return [resolveIn(cwd, expanded, facts.platform)]+ const segments = expanded.split('/')+ const at = segments.findIndex((segment) => GLOB.test(segment))+ const base = resolveIn(cwd, segments.slice(0, at).join('/') || (expanded.startsWith('/') ? '/' : '.'), facts.platform)+ const pattern = globPattern(segments[at])+ return (facts.entries?.(base) ?? []).filter((name) => pattern.test(name)).map((name) => `${base.replace(/\/+$/, '')}/${name}`)+}++/** The folders [words] remove: `git [-C dir] worktree remove [-f] P`, or each target of a recursive `rm`. */+function removedFolders(words: string[], cwd: string, facts: GuardFacts): string[] {+ const { platform } = facts+ const program = programName(words[0])+ if (program === 'git') {+ let at = 1, here = cwd+ while (at < words.length && words[at].startsWith('-')) {+ if (words[at] === '-C' && words[at + 1]) { here = resolveIn(here, words[at + 1], platform); at += 2; continue }+ at += words[at] === '-c' ? 2 : 1+ }+ if (words[at] !== 'worktree' || words[at + 1] !== 'remove') return []+ const path = words.slice(at + 2).find((word) => !word.startsWith('-'))+ return path ? [resolveIn(here, path, platform)] : []+ }+ if (program === 'rm') {+ const args = words.slice(1)+ const end = args.indexOf('--')+ const options = end === -1 ? args.filter((word) => word.startsWith('-')) : args.slice(0, end).filter((word) => word.startsWith('-'))+ if (!options.some((word) => word === '--recursive' || /^-[a-zA-Z]*[rR]/.test(word))) return []+ const paths = end === -1 ? args.filter((word) => !word.startsWith('-')) : [...args.slice(0, end).filter((word) => !word.startsWith('-')), ...args.slice(end + 1)]+ return paths.flatMap((path) => namedFolders(path, cwd, facts))+ }+ return []+}++// ---------------------------------------------------------------------------------------------------------------------+// The machine's facts++/** Whether [path] is a folder (not a link) this account owns and only it can open: what `mktemp -d` makes. */+export function privateFolderOf(path: string): boolean {+ try {+ const stat = lstatSync(path)+ const uid = process.getuid?.()+ return stat.isDirectory() && (uid === undefined || stat.uid === uid) && (stat.mode & 0o077) === 0+ } catch { return false }+}++/** The folders (not links) in [path]; none when it cannot be read. */+export function foldersIn(path: string): string[] {+ try { return readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name) }+ catch { return [] }+}++/** Whether [path] is a linked git worktree: a folder whose `.git` is a file naming the main repository's. */+export function linkedWorktreeOf(path: string): boolean {+ try { return lstatSync(path).isDirectory() && lstatSync(`${path}/.git`).isFile() } catch { return false }+}++/**+ * Every live process's working folder. Linux reads /proc; a Mac asks lsof for working folders only (`-d cwd`), which+ * lists this account's processes. Windows refuses by itself to remove a folder a process works in, so nothing is read+ * there. Null when they cannot be read: the guard then refuses the removal rather than guess.+ */+export function liveCwdsOf(platform: NodeJS.Platform = process.platform): { pid: number; cwd: string }[] | null {+ if (platform === 'win32') return []+ if (platform === 'linux') {+ try {+ return readdirSync('/proc').filter((name) => /^\d+$/.test(name)).flatMap((pid) => {+ try { return [{ pid: Number(pid), cwd: readlinkSync(`/proc/${pid}/cwd`) }] } catch { return [] }+ })+ } catch { return null }+ }+ const run = spawnSync('lsof', ['-a', '-d', 'cwd', '-F', 'pn', '-w'], { encoding: 'utf8', timeout: 5000, windowsHide: true })+ if (run.error || !run.stdout) return null+ const found: { pid: number; cwd: string }[] = []+ let pid = 0+ for (const line of run.stdout.split('\n')) {+ if (line.startsWith('p')) pid = Number(line.slice(1))+ else if (line.startsWith('n') && pid) found.push({ pid, cwd: line.slice(1) })+ }+ return found+}++/** The guard's facts for a command run in [cwd] on this machine. */+export function machineFacts(cwd: string): GuardFacts {+ let live: ReturnType<typeof liveCwdsOf> | undefined+ return {+ cwd: isAbsolute(cwd) ? cwd : resolve(cwd),+ platform: process.platform,+ home: homedir(),+ entries: foldersIn,+ privateFolder: privateFolderOf,+ linkedWorktree: linkedWorktreeOf,+ liveCwds: () => (live === undefined ? (live = liveCwdsOf()) : live),+ realpath: (path) => { try { return realpathSync(path) } catch { return path } },+ }+}diff --git a/cli/src/superTabs/shellGuardBundle.spec.ts b/cli/src/superTabs/shellGuardBundle.spec.tsnew file mode 100644index 000000000..36c01ad61--- /dev/null+++ b/cli/src/superTabs/shellGuardBundle.spec.ts@@ -0,0 +1,55 @@+import { execFileSync, spawnSync } from 'node:child_process'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { build } from 'esbuild'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { GUARD_REASONS } from './shellGuard.js'++const CLI_ROOT = fileURLToPath(new URL('../..', import.meta.url))++describe('the shell guard in a shipped CLI', () => {+ let scratch = ''+ let argv: string[] = []+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'guard-bundle-'))+ const out = join(scratch, 'release')+ execFileSync(process.execPath, ['build-bundle.mjs'], {+ cwd: CLI_ROOT, env: { ...process.env, BUNDLE_OUT_DIR: out }, stdio: 'pipe', timeout: 120_000,+ })+ // The lean core gives hooks the cli.js it was started for through argv[1]. Compile the real helper into+ // a separate chunk, as the release does: its import.meta.url is no longer src/lib/agentShellGuard.ts.+ const source = join(scratch, 'hook-command.ts')+ writeFileSync(source, `import { shellGuardArgv } from ${JSON.stringify(join(CLI_ROOT, 'src/lib/agentShellGuard.ts'))};+process.argv[1] = process.argv[2];+process.stdout.write(JSON.stringify(shellGuardArgv()));+`)+ const helper = join(scratch, 'hook-command.mjs')+ await build({ entryPoints: [source], outfile: helper, bundle: true, platform: 'node', format: 'esm',+ banner: { js: 'import { createRequire } from "node:module"; const require = createRequire(import.meta.url);' }, logLevel: 'silent' })+ argv = JSON.parse(execFileSync(process.execPath, [helper, join(out, 'cli.js')], { encoding: 'utf8', timeout: 15_000 }))+ }, 150_000)+ afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })++ it.each([+ ['Bash', { command: 'pkill -f node' }, GUARD_REASONS.killByName],+ ['Bash', { command: 'sudo npm ci' }, GUARD_REASONS.systemWide],+ ['Write', { file_path: '/tmp/shared-notes.txt', content: 'x' }, GUARD_REASONS.fixedTmp],+ ['exec_command', { cmd: 'killall node' }, GUARD_REASONS.killByName],+ ['shell', { command: ['bash', '-lc', 'npm install -g typescript'] }, GUARD_REASONS.systemWide],+ ])('runs the installed hook for %s %j', (tool, input, reason) => {+ const run = spawnSync(argv[0], argv.slice(1), { input: JSON.stringify({ tool_name: tool, tool_input: input, cwd: scratch }),+ encoding: 'utf8', timeout: 15_000, windowsHide: true })+ expect({ status: run.status, stderr: run.stderr }).toEqual({ status: 0, stderr: '' })+ expect(JSON.parse(run.stdout)).toEqual({ hookSpecificOutput: {+ hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason,+ } })+ })++ it('leaves ordinary commands to the engine without loading the CLI or contacting a daemon', () => {+ const run = spawnSync(argv[0], argv.slice(1), { input: JSON.stringify({ tool_name: 'Bash', tool_input: { command: 'git status' }, cwd: scratch }),+ encoding: 'utf8', timeout: 15_000, windowsHide: true })+ expect({ status: run.status, stderr: run.stderr, stdout: run.stdout }).toEqual({ status: 0, stderr: '', stdout: '' })+ })+})diff --git a/cli/src/superTabs/shellGuardHook.spec.ts b/cli/src/superTabs/shellGuardHook.spec.tsnew file mode 100644index 000000000..64193e16b--- /dev/null+++ b/cli/src/superTabs/shellGuardHook.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest'+import { GUARD_REASONS, type GuardFacts } from './shellGuard.js'+import { hookAnswer } from './shellGuardHook.js'++const facts = (cwd: string): GuardFacts => ({+ cwd, platform: 'darwin', privateFolder: () => false, linkedWorktree: () => false, liveCwds: () => [],+})+const answer = (call: unknown) => hookAnswer(JSON.stringify(call), facts)+const deny = (reason: string) =>+ `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } })}\n`++describe('shell guard hook', () => {+ it('denies a Claude Code Bash call by name with its reason', () => {+ expect(answer({ tool_name: 'Bash', tool_input: { command: 'pkill -f node' }, cwd: '/work' })).toBe(deny(GUARD_REASONS.killByName))+ })++ it('denies a file tool writing a fixed name in /tmp', () => {+ expect(answer({ tool_name: 'Write', tool_input: { file_path: '/tmp/notes.md', content: 'x' } })).toBe(deny(GUARD_REASONS.fixedTmp))+ expect(answer({ tool_name: 'NotebookEdit', tool_input: { notebook_path: '/private/tmp/n.ipynb' } })).toBe(deny(GUARD_REASONS.fixedTmp))+ expect(answer({ tool_name: 'Edit', tool_input: { file_path: '/work/src/a.ts' } })).toBe('')+ })++ it('reads a Codex shell call given as a line or as its argv', () => {+ expect(answer({ tool_name: 'Bash', tool_input: { command: 'sudo ls' } })).toBe(deny(GUARD_REASONS.systemWide))+ expect(answer({ tool_name: 'shell', tool_input: { command: ['bash', '-lc', 'npm i -g tsx'] } })).toBe(deny(GUARD_REASONS.systemWide))+ expect(answer({ tool_name: 'exec_command', tool_input: { cmd: 'killall node' } })).toBe(deny(GUARD_REASONS.killByName))+ })++ it('answers nothing for ordinary work, for patches and for what it cannot read', () => {+ expect(answer({ tool_name: 'Bash', tool_input: { command: 'git status --short' }, cwd: '/work' })).toBe('')+ expect(answer({ tool_name: 'apply_patch', tool_input: { command: '*** Add File: /tmp/x' } })).toBe('')+ expect(answer({ tool_name: 'Read', tool_input: { file_path: '/tmp/x' } })).toBe('')+ expect(answer({ tool_name: 'Bash' })).toBe('')+ expect(hookAnswer('not json', facts)).toBe('')+ })++ it('reads the command in the folder the call names', () => {+ const seen: string[] = []+ hookAnswer(JSON.stringify({ tool_name: 'Bash', tool_input: { command: 'ls' }, cwd: '/work/tree' }), (cwd) => { seen.push(cwd); return facts(cwd) })+ expect(seen).toEqual(['/work/tree'])+ })++ it('uses a Codex command workdir when checking a relative worktree removal', () => {+ const tree = '/work/trees/live'+ const result = hookAnswer(JSON.stringify({ tool_name: 'exec_command', cwd: '/work/repo',+ tool_input: { cmd: 'git worktree remove .', workdir: tree } }), cwd => ({ ...facts(cwd),+ linkedWorktree: path => path === tree, liveCwds: () => [{ pid: 4242, cwd: tree }] }))+ expect(result).toBe(deny(GUARD_REASONS.liveWorktree(tree, 4242)))+ })+})diff --git a/cli/src/superTabs/shellGuardHook.ts b/cli/src/superTabs/shellGuardHook.tsnew file mode 100644index 000000000..22252a3ca--- /dev/null+++ b/cli/src/superTabs/shellGuardHook.ts@@ -0,0 +1,60 @@+/**+ * The shell guard's hook (superTabs/shellGuard.ts), which a Swarm agent's engine runs before each tool call+ * (lib/agentShellGuard.ts). Claude Code and Codex hand it the same JSON on stdin (`tool_name`, `tool_input`, `cwd`)+ * and read the same answer on stdout: a `PreToolUse` decision of `deny` with its reason, or nothing, which leaves the call+ * to the session's own permissions (the old Buddy guard's shape, __fixtures__/buddy-guard-before-2832.mjs; Codex 0.166's+ * `PreToolUseHookSpecificOutputWire`). It imports nothing but the guard and Node's own modules: it runs at every command.+ */+import { readFileSync } from 'node:fs'+import { fileRefusal, machineFacts, shellRefusal, type GuardFacts } from './shellGuard.js'++/** Claude Code's tools that write a file at a path they are given. */+const FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])++/** The command a shell tool call runs: Claude Code's `Bash` gives a line, Codex may give a line or its argv. */+function commandOf(input: Record<string, unknown>): string | null {+ const command = input.command ?? input.cmd+ if (typeof command === 'string') return command+ if (Array.isArray(command) && command.every((word) => typeof word === 'string')) {+ return command.map((word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`)).join(' ')+ }+ return null+}++/** The reason the tool call [call] is refused, or null to leave it to the session's permissions. */+export function guardDecision(call: unknown, factsFor: (cwd: string) => GuardFacts = machineFacts): string | null {+ if (!call || typeof call !== 'object') return null+ const { tool_name: tool, tool_input: input, cwd } = call as Record<string, unknown>+ if (!input || typeof input !== 'object') return null+ const fields = input as Record<string, unknown>+ const commandCwd = tool === 'exec_command' || tool === 'shell' ? fields.workdir ?? fields.cwd : undefined+ const facts = factsFor(typeof commandCwd === 'string' && commandCwd ? commandCwd+ : typeof cwd === 'string' && cwd ? cwd : process.cwd())+ if (typeof tool === 'string' && FILE_TOOLS.has(tool)) {+ const path = fields.file_path ?? fields.notebook_path+ return typeof path === 'string' ? fileRefusal(path, facts) : null+ }+ // Codex's patches name their files inside the patch; they are not a shell's command.+ if (tool === 'apply_patch') return null+ const command = commandOf(fields)+ return command === null ? null : shellRefusal(command, facts)+}++/** What the hook prints for [reason]: a deny both engines read, or nothing. */+export function hookReply(reason: string | null): string {+ if (reason === null) return ''+ return `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } })}\n`+}++/** The hook's answer for the text the engine wrote on stdin. A call it cannot read is left to the session's permissions:+ * the engines always send JSON, and a guard that refused everything it could not parse would stop an agent's work. */+export function hookAnswer(stdin: string, factsFor?: (cwd: string) => GuardFacts): string {+ let call: unknown+ try { call = JSON.parse(stdin) } catch { return '' }+ return hookReply(guardDecision(call, factsFor))+}++/** The internal CLI entry calls this without loading the daemon or normal CLI commands. */+export function runShellGuard(): void {+ process.stdout.write(hookAnswer(readFileSync(0, 'utf8')))+}diff --git a/cli/src/superTabs/shellGuardProcess.spec.ts b/cli/src/superTabs/shellGuardProcess.spec.tsnew file mode 100644index 000000000..e4023e7fe--- /dev/null+++ b/cli/src/superTabs/shellGuardProcess.spec.ts@@ -0,0 +1,40 @@+import { execFileSync, spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdtempSync, realpathSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { expect, it } from 'vitest'+import { GUARD_REASONS, machineFacts, shellRefusal } from './shellGuard.js'++it.skipIf(process.platform === 'win32')('protects a real worktree until its child process exits', async () => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'guard-worktree-')))+ const repo = join(root, 'repo'), tree = join(root, 'tree')+ const git = (...args: string[]) => execFileSync('git', args, { cwd: root, stdio: 'pipe', timeout: 10_000, windowsHide: true })+ try {+ git('init', repo)+ git('-C', repo, '-c', 'user.name=Guard test', '-c', '[email protected]', '-c', 'commit.gpgsign=false',+ '-c', 'core.hooksPath=/dev/null', 'commit', '--allow-empty', '-m', 'fixture')+ git('-C', repo, 'worktree', 'add', '--detach', tree)+ const child = spawn(process.execPath, ['-e', 'process.stdout.write("ready"); setInterval(() => {}, 1000)'], {+ cwd: tree, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,+ })+ const exited = once(child, 'exit')+ try {+ await once(child.stdout, 'data', { signal: AbortSignal.timeout(5000) })+ const command = `git worktree remove '${tree}'`+ expect(shellRefusal(command, machineFacts(repo))).toBe(GUARD_REASONS.liveWorktree(tree, child.pid!))+ // Through the folder that holds it, a glob over it, or ~/ (Rowan's security review, 11-06).+ expect(shellRefusal(`rm -rf '${root}'`, machineFacts(repo))).toBe(GUARD_REASONS.liveWorktree(root, child.pid!))+ expect(shellRefusal(`rm -rf ${root}/t*`, machineFacts(repo))).toBe(GUARD_REASONS.liveWorktree(tree, child.pid!))+ child.kill('SIGTERM')+ await exited+ expect(shellRefusal(command, machineFacts(repo))).toBeNull()+ expect(shellRefusal(`rm -rf '${root}'`, machineFacts(repo))).toBeNull()+ } finally {+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM')+ await exited+ }+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+}, 30_000)diff --git a/docs/plans/2026-11-06-swarm-shell-guard-plan.md b/docs/plans/2026-11-06-swarm-shell-guard-plan.mdnew file mode 100644index 000000000..12478430b--- /dev/null+++ b/docs/plans/2026-11-06-swarm-shell-guard-plan.md@@ -0,0 +1,180 @@+# Shell guard for Swarm agents: implementation plan++> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,+> the failing test committed before its code. No Execution Handoff.++**Goal:** A Swarm agent's session (Claude Code and Codex) runs a pre-command hook that refuses, with a one-line reason each,+kill by name or pattern (pkill, killall, `kill $(pgrep …)`), sudo and system-wide installs, fixed names in /tmp, and+removing a worktree a live process uses (task #3596, inventory Table A #5, requested by Dee through Harness).++**Architecture:** The rules are one pure function over a command's words (`superTabs/shellGuard.ts`), with the machine's+facts (private folders, linked worktrees, live processes' working folders) as seams. The shipped lightweight CLI entry routes `__swarm-shell-guard` to+`superTabs/shellGuardHook.ts`, which reads the engine's `PreToolUse` JSON on stdin and prints a `deny` with the reason, or+nothing. The command runs without normal CLI/daemon initialization. Only Swarm sessions get it, through the existing `SwarmLaunch.args(engine)` seam (`lib/swarmEngineArgs.ts`):+Claude Code by `--settings '{"hooks":{"PreToolUse":…}}'`, Codex by `-c hooks.PreToolUse=[…]`. Codex runs a session+flag's hook only once its hash is recorded as trusted in the home's `config.toml` (measured with `codex app-server`+`hooks/list`, codex-cli 0.166.0: `/<session-flags>/config.toml:pre_tool_use:0:0`, `untrusted` until recorded, `trusted`+after; a `hooks.state` given by `-c` is ignored), so Harness's Codex hook installer records it beside its own hooks'+records, in every home it prepares.++**Tech Stack:** TypeScript CLI, vitest; Claude Code 2.1.318 and codex-cli 0.166.0 hook contracts.++**Spec:** task #3596's brief; the Swarm's rules "Stop only processes you started, by id", "Install nothing system-wide",+"Temporary files only in a mktemp -d folder", "Never remove a worktree a live process still uses".++## Global Constraints++- PR body first line: "Requested by dee through Harness."+- Swarm code stays out of `cli/src/core`; nothing in core changes.+- A person's own sessions get no guard: only `SwarmLaunch.args`, which runs for sessions with a Swarm role.+- Each refusal is one line starting `Harness shell guard:` saying why and what to do instead.+- Two security reviews before merge (a guard).+- Windows: no new process is started on Windows (lsof is not run there; Windows itself refuses to delete a folder a+ process works in). Claude's hook uses exec form there (`command` + `args`), Codex's a PowerShell line, as Harness's own.++## Design++- growth: N/A because nothing is stored but one trust record per Codex home, replaced in place when the hook's line changes.+- concurrency: the trust record is written inside the Codex hook installation's own reservation (`runHookPreparation`).+- read cost: the hook reads only the command; live processes are read only for a removal of a linked worktree.+- scale: one Node start per tool call; packaged guard p50 221.5 ms / p95 233.2 ms on macOS arm64, Node 22.23.2+ (20 measured calls after 3 warmups; no-op Node p50 29.8 ms / p95 34.4 ms). `lsof -d cwd` only on a linked+ worktree removal, 5 s timeout.+- compatibility: an engine without `PreToolUse` ignores the setting; a Codex without the trust record would ask, so the+ record is written before any Swarm Codex launch reads it (default home at the daemon's hook refresh, a profile at create).+- migration + rollback: none; reverting removes the args, and the trust record trusts only that exact line.+- audience, identity: N/A because nothing is exposed and nothing acts as a person.+- failure: a refusal says why; a hook that cannot start (a moved script) exits non-zero but not 2, which both engines+ treat as a non-blocking error, so a guard fault never stops an agent's work silently or wholly.+- platforms: Mac and Linux read live working folders (lsof, /proc); Windows refuses such removals by itself.++## Review Focus++- A heredoc body or a quoted message holding a refused word (`git commit -m "no sudo"`, `<<'EOF' … sudo … EOF`) must pass.+- `${TMPDIR:-/tmp}` in a `mktemp` template must pass; the same root without `mktemp` falls back to a fixed /tmp name on+ Linux and is not read (a variable is not expanded): recorded, not refused.+- `kill $(cat pidfile)` and `ps -p ID && kill ID` (a recorded id) must pass; `kill` fed by pgrep/pidof/lsof/ps aux refused.+- A path inside Claude Code's own `/private/tmp/claude-<uid>` (mode 700, this account's) passes; another uid's is refused.+- `rm -rf` of a worktree reached through `cd` earlier in the same line resolves against that folder.++---++### Task 1: The rules++**Files:**+- Create: `cli/src/superTabs/shellGuard.ts`+- Test: `cli/src/superTabs/shellGuard.spec.ts`++**Interfaces:**+- Produces: `shellRefusal(command: string, facts: GuardFacts): string | null`, `fileRefusal(path, facts)`,+ `GUARD_REASONS` (`killByName`, `systemWide`, `fixedTmp`, `liveWorktree(path, pid)`, `worktreeUnknown(path)`),+ `GuardFacts { cwd, platform, privateFolder, linkedWorktree, liveCwds, realpath? }`, `machineFacts(cwd)`,+ `privateFolderOf`, `linkedWorktreeOf`, `liveCwdsOf`.++- [x] Write the failing spec: each refused pattern returns its reason, each ordinary command null (pkill/killall/+ `kill $(pgrep)`/`lsof -ti | xargs kill`/taskkill /IM/Stop-Process -Name; sudo/doas/su, `npm -g`, brew install,+ apt/dnf/port, `pip --break-system-packages`, winget/choco/msiexec, `with administrator privileges`, `-Verb RunAs`;+ `> /tmp/x`, `tee /private/tmp/x`, `-o /tmp/x`, `cd /tmp`, `sh /tmp/x.sh`; `git worktree remove` and `rm -rf` of a+ worktree a process works in, and `worktreeUnknown` when processes cannot be read).+- [x] Run `npx vitest run src/superTabs/shellGuard.spec.ts`: fails (module missing).+- [x] Implement the tokenizer (quotes, operators, `$(…)`, backticks, `<(…)`, `sh -c`, `eval`, heredocs, comments,+ wrappers `env`/`xargs`/`nohup`/`timeout`/…) and the four rules.+- [x] Run the spec: passes. Commit test, then code.++### Task 2: The hook entry++**Files:**+- Create: `cli/src/superTabs/shellGuardHook.ts`+- Test: `cli/src/superTabs/shellGuardHook.spec.ts`++**Interfaces:**+- Consumes: `shellRefusal`, `fileRefusal`, `machineFacts`.+- Produces: `hookAnswer(stdin: string, factsFor?): string` (a `PreToolUse` deny line or '') and `runShellGuard()`, called by the internal CLI entry.++- [x] Failing spec: Claude `Bash` `pkill -f node` → deny JSON with `GUARD_REASONS.killByName`; `Write` to `/tmp/x` →+ `fixedTmp`; Codex argv `["bash","-lc","sudo ls"]` → `systemWide`; `git status` → ''; not JSON → ''; `apply_patch` → ''.+- [x] Implement; spec passes. Commit test, then code.++### Task 3: Swarm sessions run it++**Files:**+- Create: `cli/src/lib/agentShellGuard.ts`+- Modify: `cli/src/lib/swarmEngineArgs.ts`+- Test: `cli/src/lib/swarmEngineArgs.spec.ts`++**Interfaces:**+- Produces: `shellGuardHook(platform)` → the hook as each engine's runner takes it; `claudeShellGuardArgs(platform)` →+ `['--settings', json]`; `codexShellGuardArgs(platform)` → `['-c', 'hooks.PreToolUse=[…]']`;+ `CODEX_SHELL_GUARD` → `{ event: 'PreToolUse', matcher: '*', timeout: 30, command(platform) }`.++- [x] Failing spec: `swarmEngineArgs('claude')` holds `--settings` whose JSON has one `PreToolUse` block, matcher+ `Bash|Write|Edit|MultiEdit|NotebookEdit`, running Node on the lightweight CLI entry with `__swarm-shell-guard`; `swarmEngineArgs('codex')` keeps+ `check_for_update_on_startup=false` and adds the `-c hooks.PreToolUse` line; `swarmEngineArgs('gemini')` unchanged.+- [x] Implement; run the spec plus `src/core/agents/create.spec.ts` and `src/lib/launchOverrides.spec.ts` (a person's own+ session gets none). Commit test, then code.++### Task 4: Codex trusts it++**Files:**+- Modify: `cli/src/engines/facets/hooks.ts` (`HookReviewRecord.sessionHooks`), `cli/src/engines/kit/hookReview.ts`+ (`reviewRecords`), `cli/src/engines/codex/hookContract.ts`+- Test: `cli/src/engines/kit/hookReview.spec.ts`++**Interfaces:**+- Consumes: `CODEX_SHELL_GUARD`.++- [x] Failing spec: `reviewHash` of a `pre_tool_use` hook with matcher `*`, command `/opt/node /x/deny.mjs`, timeout 30+ equals the hash codex-cli 0.166.0 reported for it (measured); `reviewRecords` of Codex's record holds+ `/<session-flags>/config.toml:pre_tool_use:0:0` with the guard's hash, beside Harness's own records.+- [x] Implement; run the spec, `src/engines/codex/hooksReview.spec.ts` and `src/engines/hookInstallers.golden.spec.ts`.+ Commit test, then code.++### Task 5: Run the guard from the shipped CLI (takeover verification)++**Files:** `cli/src/lib/agentShellGuard.ts`, `cli/src/superTabs/shellGuardHook.ts`, `cli/src/entry.ts`,+`cli/src/architecture.spec.ts`, `cli/src/lib/swarmEngineArgs.spec.ts`,+`cli/src/superTabs/shellGuardBundle.spec.ts`, hook installer golden fixture when its trusted command changes.++**Interfaces:** Keep `hookAnswer` and the engine settings shapes. `shellGuardArgv` names the CLI entry plus+`__swarm-shell-guard`; the entry loads only the guard for that command. The source checkout uses its entry and tsx+loader, while a bundled/lean core names the CLI script it already uses for daemon commands. This replaces the+per-file hook path: a release ships cli.js and notify.mjs, without superTabs/shellGuardHook.js.++- [x] Commit and run a failing release-bundle test: build the real package in a private folder, obtain the launch+ command from the compiled helper as the core does, and send Claude/Codex hook JSON to it. It must deny each rule+ with JSON, allow an ordinary command with no output, and never initialize the daemon or touch real account data.+- [x] Route the internal command in the lightweight bundle entry; keep the Swarm import dynamic and name this+ command-only door in the architecture test. Remove the standalone-script autorun from the imported hook module.+- [x] Verify compiled, source and Windows argv quoting; update only the intentional trust-record fixture change.+- [x] Run the new test, affected launch/hook tests, architecture test and typecheck. Record red/green evidence and+ measured hook latency before Ready.++### Task 6: Close direct command gaps found during takeover++**Files:** `cli/src/superTabs/shellGuard.ts`, `cli/src/superTabs/shellGuard.spec.ts`,+`cli/src/superTabs/shellGuardHook.ts`, `cli/src/superTabs/shellGuardHook.spec.ts`.++**Interfaces:** Existing `shellRefusal`, `fileRefusal` and `hookAnswer`; no broader sandbox promise.++- [x] Add failing cases for package-manager flags with case-sensitive meanings (`pacman -S` versus `-Q`), fixed+ temporary paths reached by a relative path/cwd, and command-specific Codex workdir overriding session cwd.+- [x] Correct only those interpretations, preserving ordinary commands and quoted/heredoc text. Verify a real+ disposable worktree held by a child process is denied before any removal runs and allowed once that child exits.+- [x] Commit each failing test before its fix; run affected rules/hook specs and record the results.++## Takeover verification results++- Task 5: release-bundle regression committed at `ead89093cc`; six cases failed because the release did not ship the+ standalone hook. Fix `fab48351e3` makes all six pass through the shipped CLI entry. Source and Windows quoting+ assertions, hook trust, and architecture checks pass.+- Task 6: regressions committed at `0585caeaa2`; seven cases failed (uppercase pacman install flags, relative temporary+ paths, escaping a private folder with `..`, and Codex tool workdir). Fix `1c6f025512` passes all 124 rules/hook cases.+- `shellGuardProcess.spec.ts`: a real disposable Git worktree is refused while our own child process uses it, and+ allowed after that child exits. The test never attempts removal while the child is alive. macOS passed; Linux runs+ in CI; Windows skips the Unix process check.+- Final focused run: 432 passed, five pre-existing Buddy-launch failures across 11 files; the nine guard, packaging,+ trust, and architecture files passed. Wren recorded the same five failures on main `b8b8c8eab` in the PR evidence.+ CLI typecheck and `git diff --check` passed. No backend changes in this PR.+- This recognizes literal shell commands, not dynamically constructed programs. Worktree discovery checks direct+ linked-worktree targets, and OS process visibility limits which other accounts' working directories can be read.+ Review these boundaries in both security reads; no claim of sandbox isolation.