Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 8 min read

A free risk hook for Claude Code: make the agent flag prod, data and money commands before it runs them

It's late, the agent has been working well for an hour, and you have started approving things on reflex. The next command in the queue is this: kubectl delete deployment api -n production Maybe that is what you

It's late, the agent has been working well for an hour, and you have started approving things on reflex. The next command in the queue is this:

kubectl delete deployment api -n production

Maybe that is what you asked for. Maybe the agent read "clean up the old deployment" more broadly than you meant. Either way, the moment to notice is before it runs, and by hour two your attention is the weakest part of the setup.

The risk hook is a small Node script that makes that moment hard to miss. It reads every Bash command Claude Code is about to run, sorts risky ones into three tiers, and denies them until the agent has written a plain risk flag in the chat and re-run the command with an explicit acknowledgement. This post shows how to install it, what a flag looks like, how to tune it, and where it stops.

What it does

The hook sits on two Claude Code events:

  • UserPromptSubmit: on every prompt it re-injects a short rule that tells the agent how to flag risk before acting.
  • PreToolUse (Bash): it checks each Bash command. A match is denied, with a reason, until the agent re-runs it with RISK_ACK=<tier>.

The three tiers:

Tier Ack value What it covers What the agent must write first
πŸŸ₯ HIGH RISK high Prod or staging changes, data writes, DDL and migrations, killing machines, services, containers or processes, sudo, disk ops, deploys and publishes A diff block with risk, blast, undo, gate. The gate defaults to waiting for your OK.
🟧 WARNING warn Money or credits: paid APIs, cloud, payment processors, enrichment, backfill and scrape runs A diff block with cost, cap, gate, then a spent: line after the run
🟨 CAUTION caution Local but recoverable only with effort (rm -r, reset --hard, branch -D, rebase, force-push to a feature branch, .env exposure) or outward-facing (merge, post, message) One line with what, why, and how to undo

Some examples of what lands where:

  • kubectl delete ..., terraform apply, vercel --prod, npm publish: HIGH.
  • psql "$DATABASE_URL" -c "DROP TABLE users": HIGH, as destructive DDL.
  • A curl POST to api.openai.com: WARNING, as a mutating call to a paid service.
  • git reset --hard HEAD~3: CAUTION.
  • rm -rf node_modules or rm -rf /tmp/build: allowed with no flag, because build output and temp folders are cheap to lose.

A hit on something environment-touching escalates to HIGH when the command carries a prod or staging marker. A local operation on a file that merely has "prod" in its name is not escalated.

The parser is quote-aware. It follows bash -c, eval and $(...) up to two levels down, normalises the command name (path, case, quotes), and skips the body of a heredoc that only writes a file.

Install it in two minutes

You need Node and Claude Code.

  1. Download risk-flag.js from https://github.com/ashwaniarya/effective-agent/blob/main/hooks/risk-flag/risk-flag.js and save it as ~/.claude/hooks/risk-flag.js.
  2. Open ~/.claude/settings.json and add the two entries below under "hooks". If you already have PreToolUse or UserPromptSubmit arrays, add these objects to them instead of replacing them.
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node ~/.claude/hooks/risk-flag.js",
            "timeout": 5,
            "statusMessage": "Checking risk flags..."
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node ~/.claude/hooks/risk-flag.js",
            "timeout": 5,
            "statusMessage": "Injecting risk-flag rule..."
          }
        ]
      }
    ]
  }
}
  1. Start a new Claude Code session. Ask the agent to run git reset --hard HEAD~1 in a scratch repo. It should come back with a CAUTION flag instead of running it straight away.

What a flag looks like

When the agent tries the kubectl command from the top of this post, the hook denies it and Claude Code shows the agent this reason:

πŸŸ₯ risk-flag HIGH RISK [infra]: kubectl mutates a cluster. Flag it FIRST with
the HIGH RISK block (πŸŸ₯ **HIGH RISK** line + ```

diff with '- ' lines:
risk / blast / undo / gate). gate defaults to 'waiting for your OK': re-run
with RISK_ACK=high as the leading assignment ONLY if the user explicitly
asked for exactly this step; otherwise stop here. (A trailing '# RISK_ACK=<tier>'
comment also works.)


The agent then writes something like this in the chat:

πŸŸ₯ HIGH RISK delete the api deployment in the production namespace


diff
- risk : removes the live api deployment; traffic to it fails until redeployed
- blast: every client of the production api
- undo : kubectl apply -f k8s/api.yaml, minutes of downtime
- gate : waiting for your OK


The diff fence is there for colour: lines starting with - render red in most viewers, so the block stands out from normal output. You read four lines and decide. That is the whole point.

A paid API call gets the WARNING version:

🟧 WARNING run the enrichment backfill against the OpenAI API


diff
! cost : one call per row, total not estimated yet
! cap  : none set
! gate : waiting for your OK


A CAUTION is a single line, for example: 🟨 CAUTION git reset --hard HEAD~3 drops the last three commits · undo: git reflog then reset back.

The RISK_ACK override

Once the flag is written and you have said yes (or you asked for exactly that step), the agent re-runs the command with the tier as a leading assignment:


bash
RISK_ACK=high kubectl delete deployment api -n production


A trailing comment works too, which is handy for multi-line commands:


bash
kubectl delete deployment api -n production # RISK_ACK=high


The hook then lets it through and shows πŸŸ₯ HIGH RISK acknowledged [infra]: kubectl mutates a cluster.

The ack must be at or above the detected tier. RISK_ACK=caution on a HIGH command is denied again with a message saying it was acked too low. The values are high, warn and caution.

Tuning the rules

Everything lives in the one file, as plain regex tables near the top:

  • INFRA_RULES is a list of [tier, command, arguments, reason] rows. For example, the kubectl row matches delete, apply, scale, rollout and similar. Add a row for a CLI your team uses, or drop a row to caution if it is too noisy for you.
  • PROD_MARKERS decides what counts as prod or staging. Add your own production hostnames, database ports and live-key prefixes here. This is the most useful edit you can make, because it turns generic hits into HIGH ones on your real targets.
  • MONEY_MARKERS lists paid services and words like backfill and scrape that mean credits are being spent. Add the vendors you pay for.
  • RULE_TEXT is the rule injected on every prompt. Change the wording if you want a different flag format.

After an edit, run the hook against a command by piping a payload into it, for example {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"git reset --hard"}}. An empty output means allowed; a JSON deny means flagged.

Limits, said plainly

This is a guardrail against inattention, not a security boundary.

  • It fails open. If the payload can't be parsed or the script throws, the command runs. The one exception is ssh: if the hook can't prove a remote command is read-only, it treats it as HIGH.
  • It only sees Bash. File edits, MCP tools and anything else the agent does are not checked.
  • It is pattern matching. A determined or prompt-injected model can phrase a command the rules don't recognise. Parsing goes two levels into bash -c, eval and $(...), not deeper.
  • The agent writes the ack. Nothing stops an agent from adding RISK_ACK=high without a flag. The rule tells it not to, and the flag in the chat is what you review, so keep reading them.

The gap it can't close

The risk hook stops the dangerous command. It can't stop your API key landing in the model's context.

Most key leaks are not attacks. They are ordinary debugging steps that print a value where the model reads it:

  • .env reads. The agent runs cat .env, or opens it with a file tool, to "check the config". Every value in the file is now in the conversation.
  • echo and printenv. echo $STRIPE_KEY to confirm it is set, or printenv to find a missing variable, prints the values.
  • Verbose tool output. curl -v prints the Authorization header. Some CLIs print their config or the full request when they fail.
  • Logs. A failing server dumps its config, or a stack trace carries a connection string with the password in it, and the agent reads that log to debug.
  • Pasting. You paste a key into chat so the agent can test an integration.

Once a value is in context it can end up in transcripts and logs too. None of these is a risky command, so no risk rule fires.

Habits that cut most of it, no tool needed

  • Check that a key is set, not what it is. Ask the agent to run [ -n "$STRIPE_KEY" ] && echo set || echo missing. To list what exists, printenv | cut -d= -f1 shows names only.
  • Keep the agent out of .env. Commit a .env.example with names and no values and point the agent at that. Add "deny": ["Read(./.env)", "Read(./.env.*)"] under "permissions" in your settings so file tools can't open the real one. That rule does not cover cat .env in Bash, which is one reason the risk hook flags .env exposure as CAUTION.
  • Drop verbose flags. Leave -v off curl and debug modes off CLIs that print headers, unless you are reading the output yourself.
  • Give the agent test keys. Sandbox and short-lived keys are cheap to rotate. If a live key did land in chat, rotate it rather than hoping the transcript stays private.

When habits are not enough

Sometimes the agent needs to use a real key, not only check it exists. That is the case we built EnvSecure for. It is a Claude Code mod for macOS: the value sits in Keychain, the agent writes $NAME in a Bash command, you approve the command in a side pane, and the model gets back envsecure: ok or envsecure: failed. The output goes to the pane, not the chat.

Who it helps:

  • A solo dev with a Stripe test key and an OpenAI key who wants the agent to run the billing sandbox without either key showing up in chat.
  • An agency with several clients' keys. Each key has a name, a description and its own list of hosts it may reach.
  • Anyone running subagents. Their commands go through the same approval in the pane.
  • People who screen-share while coding. Values stay hidden in the pane.

If the habits above don't cover your setup, it's at https://envsecure.syncoderslabs.com/.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.