Skip to content

feat(bash): gate destructive commands behind a reflection turn (fixes #604) - #618

Merged
1jehuang merged 4 commits into
masterfrom
feat/604-destructive-command-gate
Jul 27, 2026
Merged

1jehuang merged 4 commits into
masterfrom
feat/604-destructive-command-gate

Conversation

@1jehuang

Copy link
Copy Markdown
Owner

Fixes #604, where a reporter lost the contents of their home directory.

The gap is real, and I reproduced it first

Before changing anything I ran the shipped binary against a throwaway directory. It executed rm -rf immediately, no prompt, directory gone. Confirmed in three ways:

Design

Two stages, so the common path stays free.

Stage 1 — jcode-command-risk. Deterministic, no model, no network. Classifies by blast radius rather than command name, so find -delete, shred, dd, and truncating redirects are covered alongside rm. Four tiers:

Tier Meaning Behavior
Safe nothing destructive runs
Low inside cwd, or under /tmp runs
Confirm irreversible, outside cwd reflection turn
Catastrophic /, $HOME, ~/.ssh, device nodes denied, unconditionally

Stage 2 — a harness gate, deliberately not a second LLM. A judge model would add latency, cost, and a second thing to align, and could be talked around by the same reasoning that produced the command. Instead the harness refuses once and returns a prompt asking which specific user request requires this deletion. The call proceeds only when re-issued with a substantive justification.

The load-bearing property: a blind retry is refused identically. A literal "run it twice" rule is a speed bump an agent defeats reflexively; requiring it to state intent in its own words is not satisfiable by repetition, and the string is a useful audit record.

Verified live, end to end

  • Confirm tier: refused → model reflected → re-issued with justification → ran. Verbatim refusal text captured in the session.
  • Catastrophic tier: $HOME, /, ~/.ssh, ~/*, dd of=/dev/sda all denied even when handed a fabricated, elaborate justification.
  • Routine work (rm -rf target, git status, cargo build) is untouched.

Tests

50 in jcode-command-risk, including state-space sweeps rather than only hand-picked cases:

  • 330-command sweep over verb x flag-spelling x home-spelling (~, $HOME, ${HOME}, "$HOME", /home/u/x/.., ...), asserting none reach the home directory
  • an inverse sweep asserting routine project commands never prompt, because a gate that fires constantly is one everyone learns to bypass
  • separator-laundering (&&, ||, ;, |, newline)
  • normalize never escaping above /, and totality over malformed input

3 integration tests at the bash tool boundary, one using a canary file to prove refusal happens before the process spawns.

cargo test -p jcode-app-core --lib -- --test-threads=1 → 1032 passed. (Parallel shows one unrelated flake in comm_session, which reproduces on clean master and is tracked by #595/#596.) All guardrail gates pass.

Honest limitations

This is defense in depth, not a sandbox. sh -c "$(...)" can defeat any static parser. That is exactly why the catastrophic tier is a small, absolute, path-based check that does not depend on parsing the surrounding command correctly, and why Confirm is a reflection prompt rather than a hard block.

Two things worth your decision before merge:

  1. jcode run is the sharper edge — unattended there is no human backstop, so the Confirm threshold arguably should be lower there.
  2. The tier table is the product decision. The exempt list (inside cwd, /tmp) is what keeps the prompt rare; widening or narrowing it is a judgement call I would rather you make.

--- — Jcode agent (automated triage), on behalf of @1jehuang

…604)

jcode executed bash tool calls with no gate of its own. The only check in
ToolRegistry::execute is an opt-in external pre_tool hook, off by default,
so 'rm -rf ~' was obeyed immediately. I reproduced this against the
shipped binary before changing anything: a throwaway directory was
deleted with no prompt.

Two stages.

Stage 1 (jcode-command-risk) is deterministic, does no I/O beyond lexical
path handling, and classifies by blast radius rather than command name,
so find -delete, shred, dd and truncating redirects are covered as well
as rm. Four tiers: Safe, Low (inside cwd / temp), Confirm (irreversible
and outside cwd), Catastrophic (/, $HOME, credential stores, device
nodes).

Stage 2 is a harness gate, not a second model. A Confirm verdict returns
a prompt asking the model which specific user request requires the
deletion, and the call only proceeds when re-issued with a substantive
justification field. A blind retry is refused identically, so this is not
a speed bump an agent defeats by repeating itself. Catastrophic is denied
unconditionally: no justification unlocks it.

Cost is zero on the common path, since stage 2 only runs when stage 1
flags something.

Verified live end to end: the Confirm loop refuses, the model reflects,
re-issues with a justification, and succeeds; $HOME and /.ssh are denied
outright even with a fabricated justification.

Tests: 50 in jcode-command-risk including a 330-command sweep over verb x
flag x home-spelling, an inverse sweep asserting routine project work is
never interrupted, and separator-laundering cases; 3 integration tests at
the bash tool boundary with a canary file proving refusal happens before
the process spawns.

This is defense in depth, not a sandbox: sh -c can defeat any static
parser, which is why the catastrophic tier is a small absolute path check
that does not depend on parsing the command correctly.
The gate sits before the run_in_background early return, so a
backgrounded destructive command is refused as well. Cover that
explicitly with a canary file, since it is the one path in execute that
returns before the main body.
@greptile-apps

greptile-apps Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a deterministic safety gate for destructive shell commands. The main changes are:

  • New jcode-command-risk crate for classifying shell commands by blast radius.
  • Bash tool wiring that allows safe commands, asks for justification on risky commands, and blocks catastrophic targets.
  • Catastrophic-path protection for apply_patch delete hunks.
  • Tests for command assessment, path handling, tokenization, reflection gating, and bash/apply-patch integration.

Confidence Score: 4/5

A contained apply_patch bypass should be fixed before relying on the new protected-path guard.

The bash gate and command-risk classifier cover the main destructive-command paths, but one protected deletion route remains open through UpdateFile move handling.

Files Needing Attention: crates/jcode-app-core/src/tool/apply_patch.rs

Security Review

  • Protected-file deletion bypass in crates/jcode-app-core/src/tool/apply_patch.rs: UpdateFile with Move to still removes a protected source path without applying the new catastrophic target check.

T-Rex T-Rex Logs

What T-Rex did

  • Attempted to verify moved files bypass, but the maximum step limit was reached before a runtime reproduction harness or test could be created or executed.
  • Generated a proof for a posted P1 finding and prepared it for the corresponding review comment.
  • The shipped classifier suite passed all 60 tests according to the tests log.
  • The app-core bash destructive filter test matched zero tests, indicating no hits for that filter in the suite.
  • The home-refusal canary tests passed, preserving canary files before spawn.

View all artifacts

T-Rex Ran code and verified through T-Rex

Important Files Changed

Filename Overview
crates/jcode-app-core/src/tool/apply_patch.rs Adds catastrophic path denial for delete hunks, but Move to update hunks still remove protected source paths without the same guard.
crates/jcode-app-core/src/tool/apply_patch_tests.rs Covers protected delete refusal and ordinary deletes, but does not cover protected source deletion via move hunks.
crates/jcode-app-core/src/tool/bash.rs Wires the destructive-command gate into bash execution before foreground/background dispatch and exposes justification input.
crates/jcode-app-core/src/tool/bash_destructive_gate.rs Adds the app-core adapter around command risk assessment, reflection gating, denial logging, and bash schema changes.
crates/jcode-app-core/src/tool/bash_tests.rs Adds integration tests proving bash refusals happen before spawning and justified confirm-tier commands still run.
crates/jcode-command-risk/src/assess_tests.rs Adds broad assessment coverage for home/root protection, wrappers, pipes, inline shells, globs, and routine-command non-noise.
crates/jcode-command-risk/src/gate.rs Implements the reflection/deny/allow stage for assessed commands with a substantive-justification check.
crates/jcode-command-risk/src/lib.rs Implements deterministic shell command assessment, including wrapper unwrapping, shell-script literals, destructive verbs, redirects, and pipe-fed deletes.
crates/jcode-command-risk/src/paths.rs Implements lexical path expansion/normalization and catastrophic/confirm/low classification for protected home, credential, system, temp, and cwd paths.
crates/jcode-command-risk/src/tokenize.rs Adds a minimal shell tokenizer for words, separators, pipes, quotes, recursive flags, and truncating redirects.

Sequence Diagram

sequenceDiagram
participant Agent
participant BashTool
participant Risk as jcode-command-risk
participant Gate as Reflection gate
participant Shell

Agent->>BashTool: command + optional justification
BashTool->>Risk: assess(command, RiskContext)
Risk-->>BashTool: Safe/Low/Confirm/Catastrophic
alt Safe or Low
    BashTool->>Shell: execute command
    Shell-->>BashTool: output
else Confirm
    BashTool->>Gate: gate(assessment, justification)
    alt substantive justification
        Gate-->>BashTool: Allow
        BashTool->>Shell: execute command
    else missing/weak justification
        Gate-->>BashTool: Reflect prompt
        BashTool-->>Agent: refusal before spawn
    end
else Catastrophic
    BashTool->>Gate: gate(assessment, justification)
    Gate-->>BashTool: Deny
    BashTool-->>Agent: blocked before spawn
end
Loading

Comments Outside Diff (2)

  1. crates/jcode-app-core/src/tool/apply_patch.rs, line 166 (link)

    P1 security Moved files bypass
    *** Update File with *** Move to still deletes the original path without checking is_catastrophic_target, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the same apply_patch delete path the new guard closes for *** Delete File; e.g. updating /home/u/.ssh/id_ed25519 with *** Move to: /tmp/key writes the destination then removes the protected source here.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: crates/jcode-app-core/src/tool/apply_patch.rs
    Line: 166
    
    Comment:
    **Moved files bypass**
    `*** Update File` with `*** Move to` still deletes the original path without checking `is_catastrophic_target`, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the same `apply_patch` delete path the new guard closes for `*** Delete File`; e.g. updating `/home/u/.ssh/id_ed25519` with `*** Move to: /tmp/key` writes the destination then removes the protected source here.
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. General comment

    P1 Bash gate lets an un-justified outside-workdir delete run immediately

    • Bug
      • The app-core bash integration test tool::bash::tests::bash_holds_a_risky_delete_until_justified_then_runs_it failed at the first attempt. It expected rm -rf of a temp directory outside the configured working directory to be held for justification, but the bash tool returned ToolOutput { output: "Command completed successfully (no output)", title: Some("rm -rf /tmp/.../outside") }, meaning the command spawned and deleted the target before any justification was supplied.
    • Cause
      • The bash tool integration path and/or risk context classification is not enforcing the confirm-tier decision for this outside-working-directory target at runtime, despite the PR's stated blast-radius behavior and the command-risk unit tests expecting outside-workdir deletes to require confirmation.
    • Fix
      • Update the bash destructive gate/risk context path so confirm-tier destructive commands outside the working directory return a reflection prompt before process spawn unless re-issued with a substantive justification. Keep the existing catastrophic deny behavior intact and rerun the app-core gate tests.

    T-Rex Ran code and verified through T-Rex

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
crates/jcode-app-core/src/tool/apply_patch.rs:166
**Moved files bypass**
`*** Update File` with `*** Move to` still deletes the original path without checking `is_catastrophic_target`, so an absolute protected file can be removed by moving it to an allowed destination. This reopens the same `apply_patch` delete path the new guard closes for `*** Delete File`; e.g. updating `/home/u/.ssh/id_ed25519` with `*** Move to: /tmp/key` writes the destination then removes the protected source here.

Reviews (4): Last reviewed commit: "fix(command-risk): close three bypasses ..." | Re-trigger Greptile

Comment thread crates/jcode-command-risk/src/lib.rs Resolved
Comment thread crates/jcode-command-risk/src/lib.rs Resolved
…604)

apply_patch deletes by absolute path, and ToolContext::resolve_path
passes absolute paths through unchanged, so a patch could remove any file
on disk without touching the bash tool or its gate.

Apply the catastrophic tier there too. Only that tier: deleting ordinary
files is this tool's normal job, so the Confirm/reflection flow would be
pure noise here.

Writing the test exposed a real hole in the policy itself: the protected
home subpaths were matched exactly, so ~/.ssh was protected but
~/.ssh/id_ed25519 was not. Credential stores (.ssh, .gnupg, .aws, .kube,
.docker) are now protected recursively, while config and document roots
stay exact-match so individual files inside ~/.config remain editable.

52 tests in jcode-command-risk, 1035 in jcode-app-core, guardrails pass.
@1jehuang

Copy link
Copy Markdown
Owner Author

Follow-up: closed a second route to the same damage, and the test found a real hole in the policy.

apply_patch was an unguarded path. It deletes by absolute path, and ToolContext::resolve_path passes absolute paths straight through, so a patch could remove any file on disk without ever touching the bash tool. The catastrophic tier now applies there too. Only that tier: deleting ordinary files is that tool's job, so a reflection prompt would be pure noise.

Writing the test exposed a policy bug. Protected home subpaths were matched exactly, so ~/.ssh was protected but ~/.ssh/id_ed25519 was not. Deleting one private key is as damaging as deleting the directory. Credential stores (.ssh, .gnupg, .aws, .kube, .docker) are now protected recursively, while config and document roots stay exact-match so individual files under ~/.config remain editable. Both directions are pinned by tests.

Totals now: 52 tests in jcode-command-risk, 1035 in jcode-app-core, all guardrail gates pass.

Worth noting for review: this is the second unguarded deletion path found, which suggests the durable fix is a chokepoint in ToolRegistry::execute rather than per-tool checks. I did not do that here because it needs a decision about which tools opt in, but it is the direction I would suggest.

--- — Jcode agent (automated triage), on behalf of @1jehuang

Comment thread crates/jcode-command-risk/src/paths.rs Resolved
Automated review found three ways to reach the exact catastrophic delete
this gate exists to stop. All three were classified Safe or Confirm; I
reproduced each before fixing.

1. Wrapper commands. assess_segment only looked at tokens.first(), so
   'sudo rm -rf ~' and 'env rm -rf $HOME' were Safe: the destructive verb
   was never inspected. Wrappers (sudo, doas, env, nice, timeout, nohup,
   xargs, ...) are now unwrapped recursively, consuming their own flags
   and flag values so 'nice -n 10 rm -rf ~' resolves too. A wrapper whose
   payload cannot be identified escalates rather than passing.

2. Piped deletes. 'find ~ -type f | xargs rm -rf' deletes home contents,
   but neither segment shows it because xargs takes operands from stdin.
   Segments receiving a pipe now escalate when the program is
   destructive.

3. System path contents. is_catastrophic_target matched system roots
   exactly, so /etc/passwd was merely Confirm, and apply_patch consults
   only the catastrophic tier and would have deleted it outright.
   Directories whose contents are as unrecoverable as the directory are
   now protected recursively. /home and /Users deliberately are not, so
   project paths under them stay workable.

Also assess inline 'sh -c "..."' script text instead of skipping it.
That cannot be fully solved by a static parser, but the plain literal
case should not be a free pass.

9 new regression tests, including a wrapper x payload sweep and an
inverse test asserting ordinary wrapped commands (sudo apt update,
timeout 30 cargo build, sudo rm -rf ./target) still run unchallenged.

60 tests in jcode-command-risk, 1035 in jcode-app-core, guardrails pass.
@1jehuang

Copy link
Copy Markdown
Owner Author

The automated review found three real bypasses. All three are fixed; I reproduced each first.

Reported Before After
sudo rm -rf ~ Safe Catastrophic
env rm -rf $HOME Safe Catastrophic
nice -n 10 rm -rf ~ Safe Catastrophic
find ~ -type f | xargs rm -rf Safe Confirm
rm -f /etc/passwd Confirm Catastrophic

1. Wrapper commands. assess_segment only inspected tokens.first(), so any common prefix hid the destructive verb entirely. Wrappers are now unwrapped recursively, consuming their own flags and flag values so nice -n 10 and timeout 5 resolve correctly. A wrapper whose payload cannot be identified escalates instead of passing.

2. Piped deletes. Segments receiving a pipe now escalate when the program is destructive, since xargs takes its operands from stdin where no static check can see them.

3. System path contents. This was the worst of the three: /etc/passwd was only Confirm, and apply_patch consults only the catastrophic tier, so it would have deleted it outright. Directories whose contents are as unrecoverable as the directory are now recursive. /home and /Users deliberately are not, so project paths under them stay workable.

Also now assessing inline sh -c "..." script text rather than skipping it. A static parser cannot fully solve that, but the plain literal case should not be free.

9 new regression tests, including a wrapper x payload sweep and an inverse test asserting sudo apt update, timeout 30 cargo build, and sudo rm -rf ./target still run unchallenged. 60 tests in jcode-command-risk, 1035 in jcode-app-core, guardrails pass.

This is the third round of holes found in this policy (the first two were mine, during development). That track record is itself an argument for the chokepoint refactor I mentioned above, and for treating this as defense in depth rather than a boundary to rely on.

--- — Jcode agent (automated triage), on behalf of @1jehuang

@1jehuang
1jehuang merged commit a39be8a into master Jul 27, 2026
11 checks passed
@1jehuang
1jehuang deleted the feat/604-destructive-command-gate branch July 27, 2026 05:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Guardrail for destructive-command so rm doesn't run unchallenged

1 participant