Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(safety): impact classification for shell commands + revive dead list patterns

rubenluetke10-beep6893135e6ad6
diff --git a/jarvis/plugins/tool/command_impact.py b/jarvis/plugins/tool/command_impact.py
new file mode 100644
index 0000000000..8a05dcc82d
--- /dev/null
+++ b/jarvis/plugins/tool/command_impact.py
@@ -0,0 +1,163 @@
+"""Deterministic impact classification for shell commands.
+
+Answers, without any LLM involvement, the question a non-technical user needs
+answered before a command runs: does this only READ, does it MODIFY something,
+or does it DELETE/destroy something? Used by ``RunShellTool`` to escalate
+destructive commands to the ``ask`` tier via the ``risk_tier_for_args`` hook
+(same pattern as the gmail per-action tiers, forensic 2026-06-19), and
+intended as the basis for plain-language previews in the UI/voice surface.
+
+Design constraints:
+- Pure token heuristics, no shell parser: commands are split at pipe/chain
+ separators and the leading word of every segment is classified. False
+ positives escalate (a read misread as modify is harmless); unknown commands
+ default to MODIFY, never to READ.
+- Cross-shell: understands POSIX names (``rm``, ``ls``), PowerShell
+ Verb-Noun cmdlets (``Remove-Item``) and their aliases (``del``, ``gci``).
+- A ``>`` / ``>>`` redirect escalates a read to MODIFY (it writes a file),
+ quoted ``>`` characters cause at most an over-escalation, never an
+ under-escalation.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+READ = "read"
+MODIFY = "modify"
+DESTRUCTIVE = "destructive"
+
+_SEVERITY = {READ: 0, MODIFY: 1, DESTRUCTIVE: 2}
+
+# Segment separators: |, ||, &&, ;, newlines. Splitting inside quotes is
+# acceptable — extra segments can only escalate severity, never lower it.
+_SEGMENT_SPLIT = re.compile(r"\|\||&&|;|\||\n")
+_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+_REDIRECT = re.compile(r">{1,2}")
+
+# Prefix words that wrap the real command.
+_WRAPPERS = frozenset({
+ "sudo", "time", "nohup", "env", "command", "builtin", "exec", "xargs",
+})
+
+_DESTRUCTIVE_COMMANDS = frozenset({
+ # POSIX
+ "rm", "rmdir", "shred", "dd", "mkfs", "fdisk", "parted", "wipefs",
+ "shutdown", "reboot", "poweroff", "halt", "truncate",
+ # Windows / PowerShell (aliases included)
+ "del", "erase", "rd", "format", "diskpart",
+ "remove-item", "ri", "remove-itemproperty",
+ "clear-content", "clc", "clear-item", "cli", "clear-disk",
+ "clear-recyclebin", "stop-computer", "restart-computer",
+})
+
+_READ_COMMANDS = frozenset({
+ # POSIX
+ "ls", "cat", "head", "tail", "grep", "find", "pwd", "whoami", "echo",
+ "printf", "date", "uname", "hostname", "df", "du", "free", "ps", "top",
+ "wc", "sort", "uniq", "which", "file", "stat", "env", "id", "uptime",
+ "tr", "cut", "less", "more", "basename", "dirname", "tree",
+ # NOT listed on purpose: sed (-i edits in place), awk (can invoke
+ # system()), tee (writes files) — they fall through to MODIFY.
+ # Windows / PowerShell (aliases included)
+ "dir", "type", "where.exe", "findstr", "hostname.exe", "ver", "systeminfo",
+ "get-childitem", "gci", "get-content", "gc", "get-item", "gi",
+ "get-process", "gps", "get-date", "get-location", "gl", "get-service",
+ "get-command", "gcm", "get-help", "select-string", "sls", "select-object",
+ "select", "measure-object", "measure", "test-path", "resolve-path",
+ "write-output", "write-host", "format-table", "ft", "format-list", "fl",
+ "out-string", "compare-object", "sort-object", "where-object", "foreach-object",
+})
+
+# PowerShell Verb-Noun classification for cmdlets not covered above. The verb
+# is the part before the dash; e.g. ``Uninstall-Module`` → "uninstall".
+_DESTRUCTIVE_VERBS = frozenset({"remove", "clear", "reset", "uninstall"})
+_READ_VERBS = frozenset({
+ "get", "select", "measure", "test", "find", "resolve", "compare", "show",
+ "read", "convertto", "convertfrom", "out",
+})
+
+# Subcommand-sensitive commands: "git status" reads, "git reset" destroys.
+_GIT_READ = frozenset({
+ "status", "log", "diff", "show", "branch", "remote", "describe", "blame",
+ "shortlog", "tag", "ls-files", "rev-parse", "config",
+})
+_GIT_DESTRUCTIVE = frozenset({"reset", "clean"})
+
+
+@dataclass(frozen=True, slots=True)
+class CommandImpact:
+ """Classification result: the worst level across all command segments."""
+
+ level: str # READ | MODIFY | DESTRUCTIVE
+ commands: tuple[str, ...] # the classified leading words, for previews
+
+
+def _leading_word(segment: str) -> tuple[str, str]:
+ """Return (command, subcommand) of a segment, normalized.
+
+ Strips wrapper words, env assignments, path prefixes and ``.exe``
+ suffixes; lowercases. Empty strings when the segment has no word.
+ """
+ tokens = segment.strip().split()
+ while tokens and (
+ tokens[0].lower() in _WRAPPERS or _ENV_ASSIGN.match(tokens[0])
+ ):
+ tokens = tokens[1:]
+ if not tokens:
+ return "", ""
+ word = tokens[0].lower().replace("\\", "/").rsplit("/", 1)[-1]
+ word = word.removesuffix(".exe")
+ sub = tokens[1].lower() if len(tokens) > 1 else ""
+ return word, sub
+
+
+def _classify_segment(segment: str) -> tuple[str, str]:
+ """Return (level, command_word) for one pipe/chain segment."""
+ word, sub = _leading_word(segment)
+ if not word:
+ return READ, ""
+
+ if word == "git":
+ if sub in _GIT_DESTRUCTIVE:
+ return DESTRUCTIVE, f"git {sub}"
+ if sub in _GIT_READ:
+ return READ, f"git {sub}"
+ return MODIFY, f"git {sub}".strip()
+ if word == "reg":
+ return (DESTRUCTIVE if sub == "delete" else MODIFY), f"reg {sub}".strip()
+
+ if word == "find" and "-delete" in segment.lower():
+ return DESTRUCTIVE, "find -delete"
+
+ if word in _DESTRUCTIVE_COMMANDS:
+ return DESTRUCTIVE, word
+ if word in _READ_COMMANDS:
+ return READ, word
+
+ # PowerShell Verb-Noun fallback ("format" alone is format.com, handled
+ # above; "format-table" reaches this branch and reads).
+ if "-" in word:
+ verb = word.split("-", 1)[0]
+ if verb in _DESTRUCTIVE_VERBS:
+ return DESTRUCTIVE, word
+ if verb in _READ_VERBS:
+ return READ, word
+
+ # Unknown commands default to MODIFY — never assume a stranger only reads.
+ return MODIFY, word
+
+
+def classify_command(command: str) -> CommandImpact:
+ """Classify a full shell command string (worst segment wins)."""
+ level = READ
+ words: list[str] = []
+ for segment in _SEGMENT_SPLIT.split(command):
+ seg_level, word = _classify_segment(segment)
+ if _REDIRECT.search(segment) and _SEVERITY[seg_level] < _SEVERITY[MODIFY]:
+ seg_level = MODIFY
+ if word:
+ words.append(word)
+ if _SEVERITY[seg_level] > _SEVERITY[level]:
+ level = seg_level
+ return CommandImpact(level=level, commands=tuple(words))
diff --git a/jarvis/plugins/tool/run_shell.py b/jarvis/plugins/tool/run_shell.py
index 82e634cae7..6f8cd51f11 100644
--- a/jarvis/plugins/tool/run_shell.py
+++ b/jarvis/plugins/tool/run_shell.py
@@ -34,6 +34,7 @@ from typing import Any
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.core.protocols import ExecutionContext, ToolResult
+from jarvis.plugins.tool.command_impact import DESTRUCTIVE, classify_command
if sys.platform == "win32":
_SHELL_LABEL = "Windows PowerShell 5.1"
@@ -124,6 +125,10 @@ class RunShellTool:
risk_tier: str = "monitor"
description: str = (
f"Runs a shell command via {_SHELL_LABEL} on this machine. "
+ "Use it for ANY local outcome a command can achieve: create/delete/"
+ "rename/move/copy files and folders, list directories, read file "
+ "contents, start programs, timers, system queries — the user never "
+ "needs to mention a terminal; translate their goal into a command. "
f"{_SHELL_HINT} "
"Commands are matched against the whitelist/blacklist. "
"Default timeout 30s."
@@ -143,6 +148,24 @@ class RunShellTool:
"required": ["command"],
}
+ def risk_tier_for_args(self, args: dict[str, Any]) -> str | None:
+ """Escalate destructive commands to the ``ask`` tier.
+
+ Same per-action pattern as the gmail tool (forensic 2026-06-19): the
+ static ``monitor`` tier stays for reading/modifying commands, but a
+ command classified as destructive (rm, del, format, Remove-Item, …)
+ requires user confirmation. Whitelist and blacklist keep priority in
+ ``RiskTierEvaluator`` — a ``run_shell *`` whitelist entry still
+ downgrades everything, so confirmation-averse setups are unchanged.
+ Returning ``None`` falls back to the static tier.
+ """
+ command = (args.get("command") or "").strip()
+ if not command:
+ return None
+ if classify_command(command).level == DESTRUCTIVE:
+ return "ask"
+ return None
+
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
command = (args.get("command") or "").strip()
timeout_s = float(args.get("timeout_s", 30))
diff --git a/jarvis/safety/risk_tier.py b/jarvis/safety/risk_tier.py
index 0cc48c44f8..60cf8ee3bb 100644
--- a/jarvis/safety/risk_tier.py
+++ b/jarvis/safety/risk_tier.py
@@ -8,7 +8,13 @@ The priority order matters and is non-negotiable:
solution for "anti-confirmation-fatigue" (user preference).
3. **Tool default**, or fallback to `config.safety.default_tier`.
-Matching runs via an `fnmatch` glob against `"<tool_name> <serialized_args>"`.
+Matching runs via an `fnmatch` glob against BOTH `"<tool_name>
+<serialized_args>"` and the bare `"<serialized_args>"`. The second form exists
+because shipped configs wrote bare command patterns (`"format *"`,
+`"rm -rf /"`) that could never match the prefixed string — audit 2026-08-08
+found every blacklist entry in the default config dead for `run_shell` calls.
+Accepting both forms makes existing user configs behave as their authors
+obviously intended, in the safety-increasing direction for blacklists.
"""
from __future__ import annotations
@@ -102,21 +108,34 @@ class RiskTierEvaluator:
try:
whitelist, blacklist = self._extra_patterns_fn()
patterns.extend(whitelist if kind == "whitelist" else blacklist)
- except Exception: # noqa: BLE001
- pass
+ except Exception as exc: # noqa: BLE001 — a broken catalog must never hang the gate
+ log.debug("extra_patterns_fn failed (%s patterns unaffected): %s", kind, exc)
return patterns
+ @staticmethod
+ def _pattern_matches(pattern: str, candidates: tuple[str, ...]) -> bool:
+ """Case-sensitive and case-insensitive fnmatch over all candidates."""
+ return any(
+ fnmatch.fnmatchcase(candidate, pattern)
+ or fnmatch.fnmatchcase(candidate.lower(), pattern.lower())
+ for candidate in candidates
+ )
+
def evaluate(self, tool: Tool, args: dict[str, Any]) -> TierDecision:
- cmd = f"{tool.name} {_serialize_args(args)}".strip()
+ args_str = _serialize_args(args)
+ cmd = f"{tool.name} {args_str}".strip()
+ # Patterns match with and without the tool-name prefix (see module
+ # docstring: bare patterns in shipped configs were silently dead).
+ candidates = (cmd, args_str) if args_str else (cmd,)
# 1. Blacklist — hard block
for pattern in self._collect_patterns("blacklist"):
- if fnmatch.fnmatchcase(cmd, pattern) or fnmatch.fnmatchcase(cmd.lower(), pattern.lower()):
+ if self._pattern_matches(pattern, candidates):
raise ActionBlocked(pattern=pattern, matched=cmd)
# 2. Whitelist — downgrade to safe
for pattern in self._collect_patterns("whitelist"):
- if fnmatch.fnmatchcase(cmd, pattern) or fnmatch.fnmatchcase(cmd.lower(), pattern.lower()):
+ if self._pattern_matches(pattern, candidates):
return TierDecision(
tier="safe",
approved_by="whitelist",
diff --git a/tests/unit/plugins/tool/test_command_impact.py b/tests/unit/plugins/tool/test_command_impact.py
new file mode 100644
index 0000000000..a4322f31b3
--- /dev/null
+++ b/tests/unit/plugins/tool/test_command_impact.py
@@ -0,0 +1,107 @@
+"""command_impact must never under-escalate: reads may be misread as modify,
+but a destructive command must never classify as read."""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.plugins.tool.command_impact import (
+ DESTRUCTIVE,
+ MODIFY,
+ READ,
+ classify_command,
+)
+from jarvis.plugins.tool.run_shell import RunShellTool
+
+
+ "command",
+ [
+ "ls -la",
+ "cat notes.txt",
+ "Get-ChildItem -Name",
+ "gci",
+ "dir",
+ "git status",
+ "git log --oneline",
+ "echo hello | tr a-z A-Z",
+ "ps aux | grep python | wc -l",
+ "Get-Process | Select-Object -First 3",
+ ],
+)
+def test_read_commands(command: str) -> None:
+ assert classify_command(command).level == READ
+
+
+ "command",
+ [
+ "mv a.txt b.txt",
+ "mkdir new-folder",
+ "New-Item -ItemType File probe.md",
+ "npm install",
+ "git push origin main",
+ "sed -i s/a/b/ file.txt",
+ "echo data > out.txt", # redirect escalates a read
+ "cat a.txt >> b.txt",
+ "some-unknown-binary --flag", # unknown must never default to read
+ "Stop-Process -Name notepad",
+ ],
+)
+def test_modify_commands(command: str) -> None:
+ assert classify_command(command).level == MODIFY
+
+
+ "command",
+ [
+ "rm -rf ~/old-project",
+ "sudo rm -rf /var/log/foo",
+ "del C:\\temp\\x.txt",
+ "Remove-Item -Recurse -Force C:\\temp",
+ "Clear-Content log.txt",
+ "format d:",
+ "dd if=/dev/zero of=/dev/sda",
+ "shutdown -h now",
+ "Stop-Computer",
+ "git reset --hard HEAD~1",
+ "git clean -fd",
+ "reg delete HKCU\\Software\\Foo /f",
+ "find . -name '*.tmp' -delete",
+ "echo ok && rm -rf build", # worst segment wins across chains
+ "ls | xargs rm", # destructive after a pipe...
+ ],
+)
+def test_destructive_commands(command: str) -> None:
+ assert classify_command(command).level == DESTRUCTIVE
+
+
+def test_powershell_verb_fallback() -> None:
+ assert classify_command("Uninstall-Module Foo").level == DESTRUCTIVE
+ assert classify_command("Get-Whatever").level == READ
+ assert classify_command("Set-Whatever x").level == MODIFY # unknown verb
+
+
+def test_empty_command_reads() -> None:
+ assert classify_command("").level == READ
+
+
+def test_commands_are_collected_for_previews() -> None:
+ impact = classify_command("ls | grep foo && rm -rf build")
+ assert "ls" in impact.commands
+ assert "rm" in impact.commands
+
+
+# ── risk_tier_for_args hook on RunShellTool ──────────────────────────────
+
+
+def test_run_shell_escalates_destructive_to_ask() -> None:
+ tier = RunShellTool().risk_tier_for_args({"command": "rm -rf ~/x"})
+ assert tier == "ask"
+
+
+def test_run_shell_keeps_static_tier_for_reads_and_modifies() -> None:
+ tool = RunShellTool()
+ assert tool.risk_tier_for_args({"command": "ls -la"}) is None
+ assert tool.risk_tier_for_args({"command": "mkdir x"}) is None
+ assert tool.risk_tier_for_args({"command": ""}) is None
diff --git a/tests/unit/test_risk_tier.py b/tests/unit/test_risk_tier.py
index 3bce9214b7..ccdd08b973 100644
--- a/tests/unit/test_risk_tier.py
+++ b/tests/unit/test_risk_tier.py
@@ -69,6 +69,31 @@ def test_blacklist_beats_whitelist():
ev.evaluate(tool, {"command": "format c:"})
+def test_unprefixed_blacklist_pattern_matches_args_only():
+ # Audit 2026-08-08: shipped configs wrote bare patterns ("format *")
+ # that never matched the "run_shell format c:" candidate — every default
+ # blacklist entry was dead. Bare patterns must match the serialized args.
+ ev = RiskTierEvaluator(_make_safety(blacklist=["format *"]))
+ tool = _StubTool("run_shell", risk_tier="safe")
+ with pytest.raises(ActionBlocked):
+ ev.evaluate(tool, {"command": "format c:"})
+
+
+def test_unprefixed_whitelist_pattern_matches_args_only():
+ ev = RiskTierEvaluator(_make_safety(whitelist=["git status"]))
+ tool = _StubTool("run_shell", risk_tier="ask")
+ decision = ev.evaluate(tool, {"command": "git status"})
+ assert decision.tier == "safe"
+ assert decision.approved_by == "whitelist"
+
+
+def test_unprefixed_pattern_does_not_match_other_strings():
+ ev = RiskTierEvaluator(_make_safety(blacklist=["format *"]))
+ tool = _StubTool("run_shell", risk_tier="monitor")
+ decision = ev.evaluate(tool, {"command": "echo format is a word"})
+ assert decision.tier == "monitor"
+
+
def test_case_insensitive_match():
ev = RiskTierEvaluator(_make_safety(blacklist=["run_shell FORMAT*"]))
tool = _StubTool("run_shell")
@@ -79,14 +104,14 @@ def test_case_insensitive_match():
def test_needs_confirmation_ask_tier():
ev = RiskTierEvaluator(_make_safety())
tool = _StubTool("delete_file", risk_tier="ask")
- decision = ev.evaluate(tool, {"path": "/tmp/x"})
+ decision = ev.evaluate(tool, {"path": "sandbox/x"})
assert ev.needs_user_confirmation(decision) is True
def test_needs_confirmation_whitelist_skips():
ev = RiskTierEvaluator(_make_safety(whitelist=["delete_file *"]))
tool = _StubTool("delete_file", risk_tier="ask")
- decision = ev.evaluate(tool, {"path": "/tmp/x"})
+ decision = ev.evaluate(tool, {"path": "sandbox/x"})
assert ev.needs_user_confirmation(decision) is False