Harden an agent's command interception layer safely: snapshot the baseline, test a matrix of should-block, negative-control, and known-bypass cases, verify classification rather than executing destructive commands, and document the bypass surface. Use when adding or changing guards around rm, mv, chmod, sudo, launchctl, dd, or any command wrapper. Tool-agnostic; includes a matrix runner and a bypass scanner.
--- name: agent-command-guard-hardening description: "Harden an agent's command interception layer safely: snapshot the baseline, test a matrix of should-block, negative-control, and known-bypass cases, verify classification rather than executing destructive commands, and document the bypass surface. Use when adding or changing guards around rm, mv, chmod, sudo, launchctl, dd, or any command wrapper. Tool-agnostic; includes a matrix runner and a bypass scanner." license: MIT --- # Agent Command Guard Hardening Changing a guard is a safety change, and safety changes need evidence. This skill makes the evidence reproducible: baseline first, matrix before and after, negative controls always, bypass surface stated. > Developed through agent operation and corrected against real failures, not hand-authored as a prompt template. ## Applicability **Use for** - Adding or modifying interception for destructive or privileged commands. - A guard that is suspected of being bypassed (absolute paths, `bash -c`, interpreter one-liners). - Proving that a new guard blocks more without blocking routine use. **Do not use for** - General code review. - Replacing OS-level permissions. A wrapper is convenience and logging, not a security boundary. - Environments where you cannot test safely; test classification, not execution. ## Boundary Required: a place to store the baseline, a way to invoke the classifier without executing the command, and the ability to restore the previous wrapper. Known limits: - A wrapper in `PATH` cannot stop absolute-path invocation unless the filesystem denies it. - Nested interpreters (`bash -c`, `python -c`, `eval`) can reconstruct any command. - Cron and services may not inherit the modified `PATH`. - Blocking without logging is worse than logging without blocking: you lose the evidence and keep the breakage. **Never claim a bypass is closed when it is only narrowed.** State the residual surface. ## Step 1 — Baseline before touching anything Snapshot, in a timestamped directory: - the current wrapper files (byte copies), - SHA-256 of each, - the effective `PATH` and `which -a` for every controlled command. **Completion criterion:** all three artefacts exist and are non-empty; the hash file covers every wrapper you will modify. ## Step 2 — Build the matrix Three classes, all mandatory: | Class | Purpose | Example | |---|---|---| | Should block | proves the guard works | `rm -rf /tmp/x`, `sudo ...`, `chmod -R 777 .` | | Negative control | proves no over-blocking | `mv --help`, `chmod --help`, `launchctl list` | | Known bypass | keeps you honest | absolute path invocation, `bash -c '...'`, interpreter one-liner | A matrix without negative controls only measures enthusiasm. **Completion criterion:** every case has an expected decision (`allow` / `deny`), and at least three negative controls exist. ## Step 3 — Classify, do not execute The guard must expose a classification entry point, for example: ``` guard_classify <bin> <arg>... # prints allow | deny, exit 0 ``` Run the matrix against that entry point. **Never run the destructive command to “see what happens”.** Classification and execution are separate contracts. **Completion criterion:** `scripts/matrix_run.py` produces a pass/fail line per case, with zero command execution. ## Step 4 — Implementation shape - One shared library holds logging, real-binary resolution (skipping its own directory), deny/allow policy, and argument-level rules. - Each wrapper is two lines: source the library, call `guard_main <bin> "$@"`. - Argument-level rules matter: `chmod` only when `-R` or `777`; `mv` only when the source is in a protected path; `osascript` only for quit or `do shell script`. **Completion criterion:** every wrapper has a corresponding case in the matrix. ## Step 5 — Syntax check before enabling A wrapper with a syntax error makes the wrapped command fail silently — worse than no guard. Run the interpreter's syntax check (`bash -n`, `node --check`, `python -m py_compile`) on every modified file before it is reachable. **Completion criterion:** syntax check passes on all modified files; a deliberate broken copy is confirmed to fail the check. ## Step 6 — Re-run the same matrix Same cases, same classifier contract, after the change. Diff the decisions line by line. Every difference must be explained as either an intended new block or a regression to fix. **Completion criterion:** a diff table exists; no negative control changed to `deny`. ## Step 7 — Log, document, roll back - Log every decision as JSONL: `ts, pid, ppid, cwd, bin, argv, decision`. - Log escape-hatch usage too (for example `GUARD_ALLOW_DESTRUCTIVE=1`, whatever the local convention is) as `allow` with a reason. - Document the bypass surface at the level of the wrapper: absolute paths, nested interpreters, non-inherited `PATH`, direct syscalls. - Provide rollback: restore from the byte copies; remember that rollback may itself need the escape hatch. **Completion criterion:** a sample log line exists; the bypass list is written in the same document as the guarantee. ## Detection layer (separate from blocking) If the goal is to record outbound actions rather than block them, do not match the whole command string. `echo 'git push'` and `pgrep -f 'git push'` will both false-positive. 1. Split on `;`, `&&`, `||`, `|`, newline. 2. Take the first token of each segment as the command name; skip `sudo`, `env`, and `VAR=` prefixes. 3. Apply argument-level rules to the remainder (`-X POST`, `--data`, `-F` for HTTP clients; `:` for rsync). 4. Self-test with positive and negative samples before enabling. `scripts/bypass_scan.py` finds the risky invocation forms in a set of files; it is a scanner, not a blocker. ## Discipline - Every interception needs an escape hatch, and every use of it is logged. - Negative controls are not optional: testing only what should be blocked measures nothing. - Do not describe a narrowed bypass as closed. - A wrapper that silently breaks routine commands is a regression, not a hardening. ## Final self-check 1. Baseline artefacts exist and are non-empty. 2. Matrix has should-block, negative-control, and known-bypass classes. 3. Classification was tested without executing destructive commands. 4. Syntax check passed before enabling. 5. Before/after diff explained; no negative control regressed. 6. Bypass surface documented next to the guarantee. 7. Rollback procedure exists and was read by someone other than its author.
don't have the plugin yet? install it then click "run inline in claude" again.
Changing a guard is a safety change, and safety changes need evidence. This skill makes the evidence reproducible: baseline first, matrix before and after, negative controls always, bypass surface stated.
Developed through agent operation and corrected against real failures, not hand-authored as a prompt template.
Harden an agent's command interception layer by establishing a reproducible baseline, running a comprehensive test matrix (should-block, negative-control, known-bypass cases), verifying classification without executing destructive commands, and documenting the residual bypass surface. use this skill when adding or modifying guards around destructive or privileged commands (rm, mv, chmod, sudo, launchctl, dd) or when a guard is suspected of being bypassed. goal is to prove that a new guard blocks the intended targets without breaking routine use.
guard classifier endpoint
guard_classify <bin> <arg>... and prints allow or deny to stdout, returning exit code 0. no execution happens; classification only.GUARD_CLASSIFIER_CMD (default: guard_classify). if not set, skill will fail at step 3.baseline storage directory
GUARD_BASELINE_DIR (default: ./guard_baseline_$(date +%s)). directory must be writable; will be created if missing.wrapper file locations
/usr/local/bin/rm, /opt/agent/wrappers/chmod.sh).GUARD_WRAPPER_FILES or as positional args to the skill.previous wrapper backup
GUARD_BASELINE_DIR. used for rollback.wrapper_<hash>.orig (e.g., wrapper_abc123def.orig).test matrix definition
class (should-block | negative-control | known-bypass), command, expected_decision (allow | deny), description.GUARD_MATRIX_FILE (default: ./guard_matrix.csv).matrix runner script
scripts/matrix_run.py: takes GUARD_CLASSIFIER_CMD, GUARD_MATRIX_FILE, and outputs pass/fail per case without executing any command.bypass scanner script
scripts/bypass_scan.py: scans wrapper files for risky invocation forms (absolute paths, nested interpreters, unquoted variables).escape hatch environment variable
GUARD_ALLOW_DESTRUCTIVE=1, SKIP_GUARD=rm).allow with reason escape_hatch.interpreter syntax checkers
bash -n, python -m py_compile, node --check, or equivalent for your wrapper language.external connections
mkdir -p "$GUARD_BASELINE_DIR".GUARD_WRAPPER_FILES:GUARD_BASELINE_DIR/wrapper_<filename>.orig (e.g., wrapper_rm.orig)./usr/local/bin/rm.sha256sum wrapper_*.orig > sha256.txt..orig files.sha256.txt in baseline dir, one line per file.echo $PATH > effective_path.txt.effective_path.txt in baseline dir.which -a <cmd> and save: which -a rm >> which_output.txt.which_output.txt in baseline dir showing all PATH entries.completion criterion: ls -la $GUARD_BASELINE_DIR shows at least 4 files (at least one .orig, sha256.txt, effective_path.txt, which_output.txt). all files are non-empty. the hash file covers every wrapper you intend to modify.
edge case - wrapper does not exist yet: if adding a new guard for a command that currently has no wrapper, create a placeholder baseline entry documenting "no wrapper present" with timestamp.
edge case - wrapped command is in multiple locations: document all instances in which_output.txt; baseline must capture all of them if you plan to modify more than one.
edge case - PATH changes between snapshot and test: capture PATH at baseline time and again at test time; diff them in the completion log.
class, command, expected_decision, description.should-block, rm -rf /tmp/x, deny, destructive recursive delete.rm -rf /tmp/x, sudo launchctl stop com.apple.WiFi, chmod -R 777 ., dd if=/dev/zero of=/tmp/disk.img, mv /etc/passwd /tmp/.expected_decision: deny.rm --help, chmod --help, mv /tmp/file1 /tmp/file2, sudo -v, launchctl list.expected_decision: allow./bin/rm /tmp/x, /bin/bash -c 'rm /tmp/x', /usr/bin/python -c "import os; os.system('rm /tmp/x')".rm /tmp/x && touch /tmp/y, chmod 0777 . && rm /tmp/x, sudo sudo rm /tmp/x.expected_decision: allow or deny depending on your guard design.$GUARD_MATRIX_FILE (e.g., guard_matrix.csv).completion criterion: $GUARD_MATRIX_FILE exists and is non-empty. it has at least 5 should-block rows, at least 5 negative-control rows, at least 3 known-bypass rows. every row has a non-empty expected_decision column.
edge case - matrix is empty: skill cannot proceed; explicitly require at least 13 test cases (5 + 5 + 3) before running matrix_run.py.
edge case - negative controls are missing: skill warns and fails at completion check; negative controls are not optional. forcing you to think about what should not break is the discipline.
$GUARD_CLASSIFIER_CMD on each test case:command field. split on spaces or parse as shell tokens if needed.$GUARD_CLASSIFIER_CMD rm -rf /tmp/x should print deny\n or allow\n.python3 scripts/matrix_run.py --classifier "$GUARD_CLASSIFIER_CMD" --matrix "$GUARD_MATRIX_FILE" --output before_matrix.json.before_matrix.json with fields: case_id, class, command, expected_decision, actual_decision, passed (true if actual == expected), error (null if ok, otherwise error message).before_matrix.json for failures. if any case failed:completion criterion: before_matrix.json exists and all rows have non-null actual_decision. zero commands were executed (verify via process audit or by inspection of matrix_run.py). if classifier crashes, log the error and return failure; do not proceed to step 4 until classification works.
edge case - classifier is slow or hangs: set a timeout (e.g., timeout 5s $GUARD_CLASSIFIER_CMD ...). if classifier hangs on any case, log it and mark as error; do not deadlock.
edge case - classifier returns invalid output: if output is not allow or deny, log the raw output and fail the case.
edge case - empty result set: if matrix file is empty or malformed, matrix_run.py will fail immediately; check file format and encoding.
guard_lib.sh, guard_lib.py, or equivalent for your language):guard_main <bin> "$@": entry point that evaluates policy and logs decision.real_binary <bin>: resolves to the actual binary on disk, skipping the wrapper's own directory.classify_args <bin> <arg>...: applies argument-level rules (e.g., "only block chmod -R or chmod 777").log_decision <ts> <pid> <ppid> <cwd> <bin> <argv> <decision>: writes JSONL.check_escape_hatch <bin>: returns 0 (allow via hatch) or 1 (no hatch).guard_lib.sh (or language equivalent).#!/bin/bash
source /path/to/guard_lib.sh
guard_main rm "$@"
/usr/local/bin/rm), with exec bit set.chmod: block only if -R present or target perms match dangerous pattern (e.g., 777, 666).rm: block only if -r or -R present (recursive delete).mv: block only if source path is in protected set (e.g., /etc/*, /root/*).sudo: block only if target command would be blocked (e.g., sudo rm -rf /).osascript (macOS): block only if quit or do shell script clauses present.completion criterion: guard_lib.sh exists and is syntactically valid (checked at step 5). every wrapper has a corresponding case in the matrix. argument-level rules are documented in guard_lib.sh as comments.
edge case - nested interpreters: if a rule must cover bash -c '...', the library must parse the argument after -c as a command string (or refuse it outright). document this in the library.
edge case - variable substitution: if argv contains $VAR, decide: does the guard evaluate it (risky), or block conservatively? document the choice.
bash -n /usr/local/bin/rm.python -m py_compile /path/to/wrapper.py.node --check /path/to/wrapper.js.echo "syntax error )" > /tmp/bad_wrapper.sh), then confirm the syntax check fails on that copy.completion criterion: all modified wrappers pass syntax check. a deliberate broken copy is confirmed to fail. syntax_check.log exists with one line per wrapper: <wrapper_path>, <exit_code>, <timestamp>.
edge case - wrapper is a symlink: syntax check the symlink target, and also verify the target is readable from the final location (some filesystems may deny access).
edge case - wrapper uses sourcing: if wrapper sources guard_lib.sh, verify guard_lib.sh exists and is readable at invocation time. do not assume relative paths.
python3 scripts/matrix_run.py --classifier "$GUARD_CLASSIFIER_CMD" --matrix "$GUARD_MATRIX_FILE" --output after_matrix.json.after_matrix.json.python3 scripts/matrix_diff.py --before before_matrix.json --after after_matrix.json --output matrix_diff.txt.case_id, expected, before_actual, after_actual, changed, status.changed == true:before_actual != expected and after_actual == expected: ok, a previously failing case now passes. log as "fix".before_actual == expected and after_actual != expected: regression. log as "regression" and investigate before proceeding.after_actual == allow. if any negative-control changed to deny, skill fails; regression is unacceptable.completion criterion: matrix_diff.txt exists. every changed row is explained with a reason (e.g., "intended new block on -R flag", "fixed parsing of sudo prefix"). zero negative-control rows changed from allow to deny. diff is human-reviewed before proceeding.
edge case - classifier behavior changed: if guard_classify itself changed between steps 3 and 6, matrix comparisons are invalid. re-baseline and re-run.
edge case - matrix is large: if matrix has hundreds of cases, matrix_diff.py should highlight only changed rows. add --changes-only flag.
ts (ISO 8601), pid (process ID), ppid (parent PID), cwd (working directory), bin (command name), argv (array of arguments), decision (allow | deny), reason (string).{"ts":"2025-01-15T10:34:22Z","pid":1234,"ppid":1200,"cwd":"/home/user","bin":"rm","argv":["-rf","/tmp/x"],"decision":"deny","reason":"recursive delete blocked"}.$GUARD_LOG_FILE (default: /var/log/guard.jsonl or ./guard.jsonl if not privileged).$GUARD_ALLOW_DESTRUCTIVE=1 is set, guard_main allows the command anyway.decision: allow, reason: escape_hatch_GUARD_ALLOW_DESTRUCTIVE.BYPASS_SURFACE.md:/bin/rm instead of rm, the wrapper is bypassed unless the OS denies access." (state this even if you believe it's closed).bash -c 'rm /tmp/x', the wrapper sees bash -c rm... and must parse inside -c argument or block all -c invocations." (state your choice).