timurgaleev/vibestack / skills/careful
careful
FlaggedSafety guardrails that warn before destructive commands like rm -rf, DROP TABLE, force-push or reset --hard.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 12.4 KB |
| bin/check-careful.shexecutable | script | 37.3 KB |
| bin/hook-extract.shexecutable | script | 3.5 KB |
| bin/mask-commit-message.awk | other | 7.0 KB |
bin/check-careful.sh
View on GitHub#!/usr/bin/env bash
# check-careful.sh — PreToolUse hook for /careful skill
# Reads JSON from stdin, checks a Bash or PowerShell command for destructive
# patterns.
# Two tiers:
# HIGH — a tiny set of catastrophic SIMPLE commands returns "deny"
# (best-effort advisory hard-stop, not a policy boundary).
# MEDIUM — the destructive families below return "ask" (always overridable).
# The decision MUST be nested under hookSpecificOutput — Claude Code ignores a
# top-level permissionDecision, which silently no-ops the warning.
# The same decision is also emitted flat at the top level, the form Copilot CLI
# documents; the inline fallback envelope below carries both copies too.
set -euo pipefail
# bash 5.2+ writes a heredoc or here-string under 64 KiB into a pipe and can hang
# on a small macOS pipe; compat 5.0 keeps the temp file (test/test-heredoc-compat.sh).
[ "${BASH_VERSINFO[0]}" -lt 5 ] || BASH_COMPAT=50
# Opt-in debug logging. No-op unless VIBESTACK_DEBUG=1.
# All side effects run in a subshell so errors never propagate back into the
# hook's decision flow (preserves set -euo pipefail safety).
# WARNING: when enabled, this records the full bash command being evaluated.
# Commands may contain secrets. Only enable on machines where ~/.vibestack/hook.log
# is acceptable as an audit trail.
_vibestack_log() {
[ "${VIBESTACK_DEBUG:-0}" = "1" ] || return 0
(
set +e
local hook="$1" decision="$2" reason="$3" payload="${4:-}"
local log_dir="${VIBESTACK_HOME:-$HOME/.vibestack}"
local log_file="$log_dir/hook.log"
local lock_file="$log_dir/hook.log.lock"
mkdir -p "$log_dir" 2>/dev/null
# Rotate at >1MB via atomic rename (never truncate-in-place)
if [ -f "$log_file" ]; then
local size
size=$(wc -c < "$log_file" 2>/dev/null || echo 0)
if [ "$size" -gt 1048576 ] 2>/dev/null; then
mv "$log_file" "$log_file.1" 2>/dev/null
fi
fi
local ts
ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
local line
line=$(printf '%s hook=%s decision=%s reason=%s payload=%q\n' \
"$ts" "$hook" "$decision" "$reason" "$payload")
if command -v flock >/dev/null 2>&1; then
(
flock 9
printf '%s\n' "$line" >> "$log_file"
) 9>"$lock_file"
else
printf '%s\n' "$line" >> "$log_file"
fi
) 2>/dev/null
return 0
}
# Opt-in structured analytics event (same VIBESTACK_DEBUG gate as hook.log — no
# unconditional egress, honoring the no-telemetry-by-default policy). Records
# only skill/decision/pattern/ts/repo, never the command text.
_vibestack_analytics() {
[ "${VIBESTACK_DEBUG:-0}" = "1" ] || return 0
(
set +e
local decision="$1" pattern="$2"
local dir="${VIBESTACK_HOME:-$HOME/.vibestack}/analytics"
mkdir -p "$dir" 2>/dev/null
local ts repo
ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
repo=$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo unknown)
printf '{"event":"hook_fire","skill":"careful","decision":"%s","pattern":"%s","ts":"%s","repo":"%s"}\n' \
"$decision" "$pattern" "$ts" "$repo" >> "$dir/skill-usage.jsonl" 2>/dev/null
) 2>/dev/null
return 0
}
INPUT=$(cat)
# Shared JSON helpers (extractor + encoder) — one copy for careful AND freeze.
# See hook-extract.sh for the drift history that motivated the shared file.
_HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# bash treats `.` on a MISSING file as fatal non-interactively; a partial
# install must degrade to an ASK (this is the ask-tier hook), never silence.
_HOOK_HELPER="$_HOOK_DIR/hook-extract.sh"
if [ ! -f "$_HOOK_HELPER" ] || ! . "$_HOOK_HELPER" 2>/dev/null; then
printf '{"permissionDecision":"ask","permissionDecisionReason":"[careful] Hook helpers unavailable (broken install?) - cannot safety-check this command. Approve only if you know what it does.","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"[careful] Hook helpers unavailable (broken install?) - cannot safety-check this command. Approve only if you know what it does."}}\n'
exit 0
fi
# Extract the "command" field value from tool_input with a real JSON parser.
#
# The previous extractor was
# grep -o '"command"[[:space:]]*:[[:space:]]*"[^"]*"'
# whose [^"]* stops at the first escaped quote in the JSON string value. Any
# destructive command preceded by a quoted argument was therefore truncated
# away before the pattern checks ever ran:
#
# git commit -m "wip" && rm -rf / -> CMD='git commit -m \' -> allowed
# bash -c "rm -rf /" -> CMD='bash -c \' -> allowed
# echo "x"; rm -rf ~ -> CMD='echo \' -> allowed
#
# The python fallback only ran when the grep result was EMPTY, so a truncated
# extraction was never repaired. Parse the payload properly instead, and fail
# CLOSED when it cannot be parsed at all — a hook that gates destructive
# commands must not allow-by-default on unreadable input.
set +e
CMD=$(vibe_hook_extract_field "$INPUT" command)
EXTRACT_RC=$?
set -e
# No parser available, or the payload is not parseable JSON. Fail closed.
# Empty stdin counts as unreadable too: a PreToolUse call always carries a
# payload, so nothing on stdin means something upstream broke — not that there
# is nothing to check.
if [ "$EXTRACT_RC" -ne 0 ]; then
_vibestack_log careful ask unparseable-payload ""
vibe_hook_decision ask "[careful] Could not parse the tool payload to safety-check this command. Approve only if you know what it does."
exit 0
fi
# Parsed fine, but there is no command field: an Edit/Write payload, or nothing
# to check. An edit to a file that gates the build (lint, type, CI, migrations)
# asks — the cheap way past a failing check is to loosen the check.
if [ -z "$CMD" ]; then
set +e
_FILE_PATH=$(vibe_hook_extract_field "$INPUT" file_path)
# Copilot CLI's edit and create tools name the file tool_input.path.
[ -n "$_FILE_PATH" ] || _FILE_PATH=$(vibe_hook_extract_field "$INPUT" path)
set -e
# The basename is compared lower-cased: on a case-insensitive filesystem
# ESLINT.CONFIG.JS is the same gate as eslint.config.js.
_GATE_PATH="$_FILE_PATH"
if [ -n "$_FILE_PATH" ]; then
_GATE_BASE=$(printf '%s' "${_FILE_PATH##*/}" | tr '[:upper:]' '[:lower:]')
case "$_FILE_PATH" in */*) _GATE_PATH="${_FILE_PATH%/*}/$_GATE_BASE" ;; *) _GATE_PATH="$_GATE_BASE" ;; esac
fi
_IS_GATE=0
# An ignore file only ever exempts files from a check, so creating one asks
# as well. Any other gate that does not exist yet is being added, not loosened.
if [ -n "$_FILE_PATH" ] && printf '%s' "$_GATE_PATH" | grep -qE \
'(^|/)(\.(eslint|stylelint|markdownlint|semgrep|gitleaks)ignore|\.gitleaks\.toml)$' 2>/dev/null; then
_IS_GATE=1
elif [ -n "$_FILE_PATH" ] && { [ -e "$_FILE_PATH" ] || [ -L "$_FILE_PATH" ]; } && printf '%s' "$_GATE_PATH" | grep -qE \
-e '(^|/)(\.(eslint|stylelint|markdownlint)rc(\.[a-z0-9_-]+)*|eslint\.config\.[a-z]+|(eslint|prettier|stylelint|commitlint|oxlint)\.config(\.[a-z0-9_-]+)*\.(c|m)?(j|t)s|biome\.jsonc?|\.?ruff\.toml|\.pre-commit-config\.ya?ml|tsconfig(\.[a-z]+)?\.json|\.gitlab-ci\.ya?ml|jenkinsfile|codecov\.ya?ml|\.golangci\.ya?ml|pytest\.ini|\.flake8|mypy\.ini|\.?lefthook\.ya?ml)$' \
-e '(^|/)\.github/workflows/.+\.ya?ml$' \
-e '(^|/)(migrations|migrate|alembic/versions)/.+$' \
-e '(^|/)(\.husky|\.git/hooks)/.+$' 2>/dev/null; then
_IS_GATE=1
fi
if [ "$_IS_GATE" -eq 1 ]; then
_vibestack_log careful ask gate-file "$_FILE_PATH"
_vibestack_analytics ask gate_file
vibe_hook_decision ask "[careful] Gate file: ${_FILE_PATH##*/}. Fix the code, not the gate — confirm this edit tightens or keeps the check rather than silencing a failure."
exit 0
fi
_vibestack_log careful allow no-command ""
echo '{}'
exit 0
fi
CMD_LOWER=$(printf '%s' "$CMD" | tr '[:upper:]' '[:lower:]')
# --- Shell-obfuscation tripwire ---
# Every check below inspects the command as a STRING, but bash executes what the
# string MEANS after expansion. ${IFS} holds the default field separator and
# contains no literal whitespace, so
#
# rm${IFS}-rf${IFS}/
#
# matches none of the `rm\s+` patterns while executing as a full recursive
# delete. The same holds for a command assembled by a base64 decode piped to a
# shell. Rather than try to out-parse bash, treat these splitting/decoding
# primitives as a reason to ask: they are vanishingly rare in commands a human
# actually means to run unattended.
if printf '%s' "$CMD" | grep -qE '\$\{IFS\}|\$IFS|\$\(echo[^)]*base64[^)]*\)|base64[[:space:]]+(-d|--decode)[^|]*\|[[:space:]]*(sh|bash)' 2>/dev/null; then
_vibestack_log careful ask shell-obfuscation "$CMD"
_vibestack_analytics ask shell_obfuscation
vibe_hook_decision ask "[careful] Shell obfuscation detected (IFS word-splitting or base64-to-shell). Read the command carefully before approving."
exit 0
fi
# --- HIGH tier: hard deny (best-effort advisory hard-stop, NOT a policy boundary) ---
# Only SIMPLE commands are eligible: string matching cannot resolve what a
# compound command does (`cd X && git push --force` — whose cwd? which repo?),
# so anything containing ; && || | or a newline falls through to the MEDIUM ask
# families below — conservative failure = ask, never guess.
# --force-with-lease is deliberately NOT matched here (it is the safe variant).
_IS_SIMPLE=1
case "$CMD" in
*';'*|*'&&'*|*'||'*|*'|'*|*$'\n'*) _IS_SIMPLE=0 ;;
esac
if [ "$_IS_SIMPLE" -eq 1 ]; then
# Recursive delete aimed at the filesystem root or the whole home directory.
# Tokenized: options (long or short, any position — --no-preserve-root may
# trail the target) are skipped; EVERY non-option token must be a root-class
# target (/, ~, $HOME, /*), and a recursive flag must be present. noglob is
# forced around word-splitting so a literal /* token never expands.
# A wrapper in front runs the same rm, so sudo/doas (with their options),
# env (with its assignments), command, nice and a leading backslash are
# stripped first; their option values would otherwise count as targets.
# Repeated until nothing changes: wrappers chain in any order (env sudo rm).
_RM_CMD="$CMD"
_RM_PREV=""
while [ "$_RM_CMD" != "$_RM_PREV" ]; do
_RM_PREV="$_RM_CMD"
_RM_CMD=$(printf '%s' "$_RM_CMD" | sed -E \
-e 's/^[[:space:]]+//' \
-e 's/^(sudo|doas)([[:space:]]+-[ugCpDrtTU][[:space:]]+[^-[:space:]][^[:space:]]*|[[:space:]]+-[^[:space:]]+)*[[:space:]]+//' \
-e 's/^env([[:space:]]+-u[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+|[[:space:]]+[A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*)*[[:space:]]+//' \
-e 's/^command([[:space:]]+-[pvV]+)*[[:space:]]+//' \
-e 's/^nice([[:space:]]+-n[[:space:]]+-?[0-9]+|[[:space:]]+-[^[:space:]]+)*[[:space:]]+//' \
-e 's/^\\//')
done
if printf '%s' "$_RM_CMD" | grep -qE '^rm[[:space:]]' 2>/dev/null \
&& printf '%s' "$_RM_CMD" | grep -qE '(^|[[:space:]])(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)([[:space:]]|$)' 2>/dev/null; then
_ROOT_TARGETS=0
_SAFE_TARGETS=0
set -f
for _TOK in $_RM_CMD; do
# Strip one layer of surrounding quotes: rm -rf "/" is still rm -rf /.
_TOK="${_TOK#\"}"; _TOK="${_TOK%\"}"; _TOK="${_TOK#\'}"; _TOK="${_TOK%\'}"
case "$_TOK" in
# Skip non-target decoration: options, `--`, redirections (2>/dev/null
# is the most common suffix on agent-generated commands), backgrounding.
sudo|rm|-*|--|[0-9]'>'*|'>'*|'<'*|'&') continue ;;
'/'|'~'|'~/'|'$HOME'|'$HOME/'|'${HOME}'|'${HOME}/'|'/*'|'//') _ROOT_TARGETS=1 ;;
*)
# `rm -rf /Users/alice` is the same command as `rm -rf ~` when that
# IS the home directory; matching only the textual forms let the
# spelled-out path through with an overridable warning.
_TOK_NOSLASH="${_TOK%/}"
if [ -n "${HOME:-}" ] && { [ "$_TOK_NOSLASH" = "${HOME%/}" ] || [ "$_TOK_NOSLASH" = "${HOME%/}/*" ]; }; then
_ROOT_TARGETS=1
else
_SAFE_TARGETS=1
fi
;;
esac
done
set +f
if [ "$_ROOT_TARGETS" -eq 1 ] && [ "$_SAFE_TARGETS" -eq 0 ]; then
_vibestack_log careful deny high-rm-root "$CMD"
_vibestack_analytics deny high_rm_root
vibe_hook_decision deny "[careful][HIGH] Recursive delete of / or the home directory is blocked while /careful is active. If you truly mean it, end the /careful session first."
exit 0
fi
fi
# Force-push to the repo's default branch (the shared history everyone pulls).
# Force is carried by -f/--force OR by git's plus-refspec syntax (+main,
# +HEAD:main) which needs no flag at all. --force-with-lease never matches.
# git's global options (-C dir, -c k=v, --git-dir=...) are dropped WITH their
# values first: `git -C r push` is still a push, and in `git -C main push`
# the `main` is a directory, not the ref being pushed.
_GIT_CMD=$(printf '%s' "$CMD" | sed -E 's/^([[:space:]]*git)([[:space:]]+(-C|-c|--git-dir|--work-tree|--namespace|--config-env|--super-prefix)[[:space:]]+[^[:space:]]+|[[:space:]]+-[^[:space:]]+)*/\1/')
if printf '%s' "$_GIT_CMD" | grep -qE '^[[:space:]]*git[[:space:]]+push([[:space:]]|$)' 2>/dev/null; then
_HAS_FORCE=0
if printf '%s' "$_GIT_CMD" | grep -qE '(^|[[:space:]])(-f|--force)($|[[:space:]])' 2>/dev/null; then
_HAS_FORCE=1
elif printf '%s' "$_GIT_CMD" | grep -qE '(^|[[:space:]])\+[^[:space:]]' 2>/dev/null; then
_HAS_FORCE=1
fi
if [ "$_HAS_FORCE" -eq 1 ]; then
# Full branch path (slashed defaults like release/2.0 stay intact) and
# FIXED-STRING token comparison — never interpolate a branch name into
# an ERE (metacharacters would over/under-match).
# Branch facts come from the repo the push runs in: `git -C <dir> push`
# reads <dir>, not the hook's cwd.
# ponytail: last unquoted -C wins; stacked relative -C values are not
# composed, and an unusable dir falls back to the cwd as before.
_C_DIR=""
_PREV=""
set -f
for _TOK in $CMD; do
[ "$_PREV" = "-C" ] && _C_DIR="$_TOK"
[ "$_TOK" = "push" ] && break
_PREV="$_TOK"
done
set +f
_git_repo() {
if [ -n "$_C_DIR" ] && [ -d "$_C_DIR" ]; then git -C "$_C_DIR" "$@"; else git "$@"; fi
}
_DEFAULT_BRANCH=$(_git_repo symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's|^refs/remotes/origin/||' || true)
# A fresh clone or a worktree often lacks the origin/HEAD symbolic ref —
# without a fallback the HIGH tier would be silently inert there. Probe
# the two conventional defaults.
if [ -z "$_DEFAULT_BRANCH" ]; then
if _git_repo show-ref --verify -q refs/remotes/origin/main 2>/dev/null; then
_DEFAULT_BRANCH="main"
elif _git_repo show-ref --verify -q refs/remotes/origin/master 2>/dev/null; then
_DEFAULT_BRANCH="master"
fi
fi
if [ -n "$_DEFAULT_BRANCH" ]; then
_TARGETS_DEFAULT=0
set -f
for _TOK in $_GIT_CMD; do
# Strip one layer of surrounding quotes: `git push -f origin "main"`
# must not dodge the deny just because the ref is quoted.
_TOK="${_TOK#\"}"; _TOK="${_TOK%\"}"; _TOK="${_TOK#\'}"; _TOK="${_TOK%\'}"
case "$_TOK" in git|push|sudo|-*) continue ;; esac
_REF="${_TOK#+}" # +main -> main
_REF="${_REF##*:}" # HEAD:main / src:main -> main
_REF="${_REF#refs/heads/}" # refs/heads/main -> main; a fully
# qualified destination is the same push
if [ "$_REF" = "$_DEFAULT_BRANCH" ]; then
_TARGETS_DEFAULT=1
break
fi
done
set +f
if [ "$_TARGETS_DEFAULT" -eq 0 ] && printf '%s' "$_GIT_CMD" | grep -qE '^[[:space:]]*git[[:space:]]+push([[:space:]]+(-f|--force))*([[:space:]]+[A-Za-z0-9._-]+)?([[:space:]]+(-f|--force))*[[:space:]]*$' 2>/dev/null; then
# `git push --force` with no refspec — with or without a remote name —
# targets the current branch's upstream, which is the default branch
# exactly when you are standing on it. A remote alone is not a target;
# `git push --force origin main` names one and is caught by the token
# loop above, so it never reaches here.
_CURRENT_BRANCH=$(_git_repo branch --show-current 2>/dev/null || true)
[ -n "$_CURRENT_BRANCH" ] && [ "$_CURRENT_BRANCH" = "$_DEFAULT_BRANCH" ] && _TARGETS_DEFAULT=1
fi
if [ "$_TARGETS_DEFAULT" -eq 1 ]; then
_vibestack_log careful deny high-force-push-default "$CMD"
_vibestack_analytics deny high_force_push_default
vibe_hook_decision deny "[careful][HIGH] Force-push to the default branch ($_DEFAULT_BRANCH) is blocked while /careful is active. Use --force-with-lease on a feature branch, or end the /careful session if you truly mean it."
exit 0
fi
fi
fi
fi
fi
# Safe exceptions: rm -rf of build artifacts is always allowed.
# Multi-line commands never ride the whitelist — `rm -rf /` on one line and
# `rm -rf node_modules` on the next must not be allowed by the second line.
_SKIP_SAFE_EXCEPTION=0
case "$CMD" in
*$'\n'*) _SKIP_SAFE_EXCEPTION=1 ;;
esac
if [ "$_SKIP_SAFE_EXCEPTION" -eq 0 ] \
&& printf '%s' "$CMD" | grep -qE 'rm[[:space:]]+(-[a-zA-Z]*[rR][a-zA-Z]*[[:space:]]+|--recursive[[:space:]]+)' 2>/dev/null; then
SAFE_ONLY=true
# Strip 'rm' and all leading flags; remaining tokens are the target paths
RM_ARGS=$(printf '%s' "$CMD" | sed -E 's/^[[:space:]]*rm[[:space:]]+(-[a-zA-Z]+[[:space:]]+)*(--[a-z-]+[[:space:]]+)*(--[[:space:]]+)?//')
set -f
for target in $RM_ARGS; do
case "$target" in
# Command substitution that merely ENDS in a whitelisted suffix
# (`rm -rf $(./wipe-all)/node_modules`) must not ride the whitelist.
*'('*|*'`'*)
SAFE_ONLY=false
break
;;
*/node_modules|node_modules|*/\.next|\.next|*/dist|dist|*/__pycache__|__pycache__|*/\.cache|\.cache|*/build|build|*/\.turbo|\.turbo|*/coverage|coverage)
;;
-*)
;;
*)
SAFE_ONLY=false
break
;;
esac
done
set +f
if [ "$SAFE_ONLY" = true ]; then
_vibestack_log careful allow safe-build-artifact "$CMD"
echo '{}'
exit 0
fi
fi
# The warn tier reads the command with every commit message masked: a message
# that says "drop table" describes a change, it does not run one. The masker
# hands back the command unchanged whenever it cannot be sure what is message
# and what is command. The deny tier and the obfuscation tripwire above keep
# reading the raw text.
CMD_MEDIUM="$CMD"
case "$CMD" in
*commit*)
_MASKED=$(printf '%s' "$CMD" | awk -f "$_HOOK_DIR/mask-commit-message.awk" 2>/dev/null) \
&& [ -n "$_MASKED" ] && CMD_MEDIUM="$_MASKED"
;;
esac
CMD_MEDIUM_LOWER=$(printf '%s' "$CMD_MEDIUM" | tr '[:upper:]' '[:lower:]')
WARN=""
# --- PowerShell and cmd ---
# Scans the PowerShell tool's command (Claude Code's shell on Windows, which
# carries its text in the same tool_input.command field as Bash), and the part
# of any other command from a nested `powershell`/`pwsh`/`cmd` launcher onward
# (`pwsh -c "..."`, `cmd /c rd /s /q x`, Git Bash's `cmd //c`). A plain Bash
# command never reaches the table, so Bash keeps exactly its own families.
# Best-effort: PowerShell can assemble a command at runtime, so encoded and
# evaluated forms ask instead of being parsed.
_careful_tool_name() {
# Only a payload that names the PowerShell tool pays for a second parse.
case "$INPUT" in *'"PowerShell"'*) ;; *) return 0 ;; esac
if command -v python3 >/dev/null 2>&1; then
printf '%s' "$INPUT" | python3 -I -c 'import sys,json
d = json.loads(sys.stdin.read())
t = d.get("tool_name", "") if isinstance(d, dict) else ""
sys.stdout.write(t.strip() if isinstance(t, str) else "")' 2>/dev/null && return 0
fi
if command -v node >/dev/null 2>&1; then
printf '%s' "$INPUT" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{const t=(JSON.parse(s)||{}).tool_name;process.stdout.write(typeof t==="string"?t.trim():"")}catch(e){}})' 2>/dev/null
fi
return 0
}
_WIN_SCAN=""
[ "$(_careful_tool_name)" = "PowerShell" ] && _WIN_SCAN="$CMD_LOWER"
# A launcher run by quoted full path ("C:/Program Files/PowerShell/7/pwsh.exe")
# ends in its closing quote, not whitespace.
_WIN_LAUNCH_RE="(^|[^a-z0-9_.\$-])((powershell|pwsh|cmd)(\\.exe)?[\"']?([[:space:]].*)?)\$"
if [ -z "$_WIN_SCAN" ] && [[ $CMD_LOWER =~ $_WIN_LAUNCH_RE ]]; then
_WIN_SCAN="${BASH_REMATCH[2]}"
fi
if [ -n "$_WIN_SCAN" ]; then
# cmd escapes with ^ (r^d is rd) and PowerShell with a backtick
# (Re`move-Item is Remove-Item); dropping both only joins characters.
_WIN_SCAN="${_WIN_SCAN//^/}"
_WIN_SCAN="${_WIN_SCAN//\`/}"
# PowerShell takes an en dash, em dash or horizontal bar as a parameter
# prefix (Remove-Item x –Recurse); fold them to the ASCII hyphen.
_WIN_SCAN="${_WIN_SCAN//–/-}"
_WIN_SCAN="${_WIN_SCAN//—/-}"
_WIN_SCAN="${_WIN_SCAN//―/-}"
_NL=$'\n'
# Command position: start of text, a statement or pipeline separator, an
# opening bracket or quote, or right after a shell launcher and its switches.
# The same names elsewhere (ord, --del, /rd/) never match.
_CP="(^|[;&|({}\"'${_NL}]|(powershell|pwsh|cmd)(\.exe)?([[:space:]]+(-|/+)[a-z]+([[:space:]:=]+[a-z0-9_.-]+)?)*)[[:space:]]*"
_STMT="[^;|${_NL}]*"
# One statement's arguments, where a quoted argument may hold ; or |
# (Remove-Item 'C:\a;b' -Recurse is one statement, not two).
_PS_STMT="([^;|'\"${_NL}]|'[^']*'|\"[^\"]*\")*"
# A cmdlet may be module-qualified: Microsoft.PowerShell.Management\Remove-Item.
_MOD="([a-z0-9_.]+\\\\)?"
# A switch ends at anything that cannot continue its name: whitespace, the
# :$true form, or the closing quote, brace, paren or ; of its statement.
_SW_END="([^[:alnum:]_-]|$)"
_CMD_STMT="[^;|&${_NL}]*"
_WHY_DYNAMIC="/careful cannot see what encoded or evaluated PowerShell will run. Read it before approving."
# Name, ERE, warning. Parameters match any prefix PowerShell accepts
# (-r/-rec/-recurse, -fo/-forc/-force; -f alone is ambiguous with -Filter).
_WIN_RULES=(
ps_remove_item
"${_CP}${_MOD}(remove-item|rm|ri|del|erase|rd|rmdir)[[:space:]](${_PS_STMT}[[:space:]])?-(r|re|rec|recu|recur|recurs|recurse|fo|for|forc|force)${_SW_END}"
"Destructive: PowerShell Remove-Item (or rm/ri/del/erase/rd/rmdir) with -Recurse or -Force. This permanently removes files."
ps_pipe_remove
"${_CP}${_MOD}(gci|get-childitem|ls|dir)[[:space:]](${_PS_STMT}[[:space:]])?-(r|re|rec|recu|recur|recurs|recurse)([^[:alnum:]_|-]${_PS_STMT})?\\|[[:space:]]*((foreach-object|foreach|%)[[:space:]]*\\{[[:space:]]*)?${_MOD}(remove-item|rm|ri|del|erase|rd|rmdir)${_SW_END}"
"Destructive: Get-ChildItem -Recurse piped into Remove-Item deletes every file it lists."
ps_pipe_delete_method
"${_CP}${_MOD}(gci|get-childitem|ls|dir)[[:space:]]${_PS_STMT}\\|[^;${_NL}]*\\\$(_|psitem)\\.delete[[:space:]]*\\("
"Destructive: Get-ChildItem piped into a .Delete() call removes every item it lists."
cmd_rd_s
"${_CP}(rd|rmdir)[[:space:]]${_CMD_STMT}/s([[:space:]/]|$)"
"Destructive: cmd rd/rmdir /s deletes a whole directory tree."
cmd_del_s
"${_CP}(del|erase)[[:space:]]${_CMD_STMT}/s([[:space:]/]|$)"
"Destructive: cmd del/erase /s deletes matching files in every subdirectory."
ps_format_volume
"${_CP}(format-volume|clear-disk)([[:space:]]|$)"
"Destructive: Format-Volume / Clear-Disk erases a whole volume or disk."
ps_dotnet_delete
'\[(system\.)?io\.(directory|file)\]::delete'
"Destructive: [IO.Directory]::Delete / [IO.File]::Delete removes files without Remove-Item."
ps_encoded_command
"(^|[^a-z0-9_.\$-])(powershell|pwsh)(\\.exe)?[\"']?[[:space:]](${_STMT}[[:space:]])?-(e|ec|en|enc[a-z]*)([[:space:]:]|\$)"
"PowerShell -EncodedCommand. ${_WHY_DYNAMIC}"
ps_start_process_shell
"${_CP}${_MOD}(start-process|saps|start)([[:space:]]${_STMT})?[[:space:]\"'\\\\/:=](cmd|powershell|pwsh|bash|sh|wsl)(\\.exe)?[\"']?([[:space:]]|$)"
"Start-Process launching a shell (cmd, PowerShell, bash, sh, wsl). /careful cannot see what its -ArgumentList will run. Read it before approving."
ps_scriptblock_create
'\[(system\.management\.automation\.)?scriptblock\]::create'
"PowerShell [scriptblock]::Create. ${_WHY_DYNAMIC}"
ps_invoke_expression
"${_CP}(invoke-expression|iex)([[:space:](]|$)"
"PowerShell Invoke-Expression (iex). ${_WHY_DYNAMIC}"
ps_call_operator
'(^|[^&])&[[:space:]]*[$(]'
"PowerShell call operator (&) on a variable or expression. ${_WHY_DYNAMIC}"
)
_WI=0
while [ "$_WI" -lt "${#_WIN_RULES[@]}" ]; do
_WRE="${_WIN_RULES[$((_WI + 1))]}"
if [[ $_WIN_SCAN =~ $_WRE ]]; then
WARN="${_WIN_RULES[$((_WI + 2))]}"
break
fi
_WI=$((_WI + 3))
done
fi
# Global options, each with an optional value in its own token (`--profile
# prod`, `-n prod`, `git -C repo`), may sit between a CLI and its subcommand.
# Prod commands usually carry them, so a rule that wants the subcommand right
# after the CLI misses exactly the commands it exists for.
_OPTS='([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*'
_GIT="git${_OPTS}[[:space:]]+"
# One argument of the same command: it may be quoted (a message can hold a `;`)
# but cannot cross a command separator.
_ARG="([^;&|[:space:]\"']|\"[^\"]*\"|'[^']*')+"
_END="([[:space:];&|]|\$)"
# rm must start a word: `terraform -chdir=x` ends in "rm -" followed by an "r".
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE '(^|[^[:alnum:]_.-])rm[[:space:]]+(-[a-zA-Z]*[rR]|--recursive)' 2>/dev/null; then
WARN="Destructive: recursive delete (rm -r). This permanently removes files."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM_LOWER" | grep -qE 'drop[[:space:]]+(table|database)' 2>/dev/null; then
WARN="Destructive: SQL DROP detected. This permanently deletes database objects."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM_LOWER" | grep -qE '(^|[^[:alnum:]_])truncate([^[:alnum:]_]|$)' 2>/dev/null; then
WARN="Destructive: SQL TRUNCATE detected. This deletes all rows from a table."
fi
# git carries force either by flag or by a leading + on the refspec (+main,
# +HEAD:refs/heads/main), which needs no flag at all. Matching only the flag
# let the refspec form through with no warning whatsoever.
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}push[[:space:]]+.*(-f([[:space:]]|\$)|--force)" 2>/dev/null; then
WARN="Destructive: git force-push rewrites remote history. Other contributors may lose work."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}push[[:space:]]" 2>/dev/null \
&& printf '%s' "$CMD_MEDIUM" | grep -qE '(^|[[:space:]])\+[^[:space:]-][^[:space:]]*' 2>/dev/null; then
WARN="Destructive: git force-push (+refspec) rewrites remote history. Other contributors may lose work."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}push([[:space:]]+${_ARG})*[[:space:]]+(--delete|-d|--mirror|:[^;&|[:space:]]+)${_END}" 2>/dev/null; then
WARN="Destructive: git push --delete / --mirror / :ref deletes branches on the remote."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}reset[[:space:]]+--hard" 2>/dev/null; then
WARN="Destructive: git reset --hard discards all uncommitted changes."
fi
# A whole tree: `.`, `..`, `:/` (the repository root) or a directory written
# with its trailing slash, after any options or `--`. One named file stays
# quiet, and so does `restore --staged` alone, which only unstages.
_TREE='[[:space:]](\.|\.\.|\./|\.\./|:/|[^-[:space:]][^[:space:]]*/)([[:space:]]|$)'
_WIPES_TREE=0
if printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}(checkout|restore)[[:space:]]+\\." 2>/dev/null; then
_WIPES_TREE=1
else
_COS=$(printf '%s' "$CMD_MEDIUM" | grep -oE "${_GIT}(checkout|restore)([[:space:]]+${_ARG})*" 2>/dev/null || true)
while IFS= read -r _CO; do
[ -n "$_CO" ] || continue
# The targets follow the subcommand: `git -C . checkout f` names one file.
printf '%s' "$_CO" | awk '{
i = 2
while (i <= NF && $i ~ /^-/) i += ($i ~ /^(-C|-c|--git-dir|--work-tree|--namespace|--config-env|--super-prefix)$/) ? 2 : 1
out = ""; for (; i <= NF; i++) out = out " " $i
print out " "
}' | grep -qE "$_TREE" 2>/dev/null || continue
case "$_CO" in
*restore*)
if printf '%s' "$_CO" | grep -qE '[[:space:]](--staged|-S)([[:space:]]|$)' 2>/dev/null \
&& ! printf '%s' "$_CO" | grep -qE '[[:space:]](--worktree|-W)([[:space:]]|$)' 2>/dev/null; then
continue
fi
;;
esac
_WIPES_TREE=1
done <<< "$_COS"
fi
if [ -z "$WARN" ] && [ "$_WIPES_TREE" -eq 1 ]; then
WARN="Destructive: discards all uncommitted changes in the working tree."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}clean([[:space:]]+${_ARG})*[[:space:]]+(-[a-zA-Z]*f[a-zA-Z]*|--force)${_END}" 2>/dev/null; then
WARN="Destructive: git clean -f deletes untracked files, which git cannot bring back."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE \
-e "${_GIT}branch([[:space:]]+${_ARG})*[[:space:]]+-[a-zA-Z]*(D|d[a-zA-Z]*f|f[a-zA-Z]*d)[a-zA-Z]*${_END}" \
-e "${_GIT}branch([[:space:]]+${_ARG})*[[:space:]]+(-d|--delete)([[:space:]]+${_ARG})*[[:space:]]+(-f|--force)${_END}" \
-e "${_GIT}branch([[:space:]]+${_ARG})*[[:space:]]+(-f|--force)([[:space:]]+${_ARG})*[[:space:]]+(-d|--delete)${_END}" 2>/dev/null; then
WARN="Destructive: git branch -D deletes a branch even when its commits are merged nowhere."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "${_GIT}stash[[:space:]]+(drop|clear)${_END}" 2>/dev/null; then
WARN="Destructive: git stash drop/clear discards stashed work."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE \
-e "${_GIT}reflog[[:space:]]+(expire|delete)${_END}" \
-e "${_GIT}update-ref([[:space:]]+${_ARG})*[[:space:]]+(-d|--delete)${_END}" 2>/dev/null; then
WARN="Destructive: rewrites git's ref history (reflog expire/delete, update-ref -d); lost commits may not be recoverable."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "kubectl${_OPTS}[[:space:]]+delete" 2>/dev/null; then
WARN="Destructive: kubectl delete removes Kubernetes resources. May impact production."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE 'docker[[:space:]]+(rm[[:space:]]+-f|system[[:space:]]+prune)' 2>/dev/null; then
WARN="Destructive: Docker force-remove or prune. May delete running containers or cached images."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE '(terraform|tofu)([[:space:]]+-[^[:space:]]+)*[[:space:]]+destroy' 2>/dev/null; then
WARN="Destructive: terraform destroy tears down every resource in the state."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE '(terraform|tofu)([[:space:]]+-[^[:space:]]+)*[[:space:]]+apply([[:space:]]+[^[:space:]]+)*[[:space:]]+--?auto-approve' 2>/dev/null; then
WARN="Destructive: terraform apply -auto-approve changes infrastructure without showing the plan first."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "aws${_OPTS}[[:space:]]+[a-z0-9-]+[[:space:]]+(delete-[a-z-]+|terminate-instances|deregister-[a-z-]+)" 2>/dev/null; then
WARN="Destructive: AWS delete/terminate/deregister removes cloud resources. May impact production."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE "helm${_OPTS}[[:space:]]+(uninstall|delete)([[:space:]]|\$)" 2>/dev/null; then
WARN="Destructive: helm uninstall removes a release and its Kubernetes resources."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE 'argocd[[:space:]]+app[[:space:]]+delete' 2>/dev/null; then
WARN="Destructive: argocd app delete can cascade-delete the application's resources."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE 'sudo[[:space:]]+rm([[:space:]]|$)' 2>/dev/null; then
WARN="Destructive: sudo rm deletes as root, past every file permission."
fi
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE 'chmod[[:space:]]+(-[a-zA-Z]+[[:space:]]+)*[0-7]?777' 2>/dev/null; then
WARN="Destructive: chmod 777 makes files world-writable."
fi
# A permission rule cannot catch this: Claude Code splits on | before matching,
# so no single rule sees the download and the shell together.
# Joined onto one line first: `curl x |` + newline + `bash` is the same pipeline.
# Any later stage counts (`curl x | tee f | sh`), as do a wrapper (sudo -E, doas,
# env), a path-qualified shell (/bin/bash) and process substitution.
_FETCH='(^|[^[:alnum:]_])(curl|wget)([[:space:]]|$)'
_SHNAME='(/[^[:space:]|;&]*/)?(ba|z|da|k|fi)?sh'
_WRAP='((sudo|doas)([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]|][^[:space:]|]*)?)*[[:space:]]+(--[[:space:]]+)?|env[[:space:]]+)?'
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | tr '\n' ' ' | grep -qE \
-e "${_FETCH}.*\\|&?[[:space:]]*(\\([[:space:]]*)?${_WRAP}${_SHNAME}([^[:alnum:]_-]|\$)" \
-e "(^|[^[:alnum:]_])${_SHNAME}[[:space:]]+(-c[[:space:]]+)?[\"']?(<\\(|\\\$\\()[[:space:]]*(curl|wget)([[:space:]]|\$)" 2>/dev/null; then
WARN="Destructive: piping a download into a shell runs code nobody has read."
fi
# The bypass flag has to belong to the commit or push itself, not to a command
# chained after it. `-n` is --no-verify on commit only; on push it is --dry-run.
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | grep -qE \
-e "${_GIT}(commit|push)([[:space:]]+${_ARG})*[[:space:]]+--no-verify${_END}" \
-e "${_GIT}commit([[:space:]]+${_ARG})*[[:space:]]+-[aeiopqsvz]*n[a-zA-Z]*${_END}" 2>/dev/null; then
WARN="Destructive: --no-verify skips the git hooks. A bypassed hook hides the failure it exists to catch."
fi
# Pointing core.hooksPath elsewhere (or dropping it), or HUSKY=0, skips the
# hooks as surely as --no-verify, and so does the same key handed over through
# the environment (GIT_CONFIG_KEY_<n>, GIT_CONFIG_PARAMETERS). Config keys are
# case-insensitive. Reading the key (`git config --get core.hooksPath`, or
# with only a redirect after it) passes; a value of digits is still a value.
if [ -z "$WARN" ] && { printf '%s' "$CMD_MEDIUM_LOWER" | grep -qE \
-e "git${_OPTS}[[:space:]]+(-c[[:space:]]*|--config-env[=[:space:]])[\"']?core\\.hookspath=" \
-e "${_GIT}config([[:space:]]+${_ARG})*[[:space:]]+[\"']?core\\.hookspath[\"']?[[:space:]]+([^;&|<>[:space:]0-9]|[0-9]+([^0-9<>]|\$))" \
-e "git_config_key_[0-9]+=[\"']?core\\.hookspath" \
-e "git_config_parameters=[^[:space:]]*core\\.hookspath=" \
-e "${_GIT}config([[:space:]]+${_ARG})*[[:space:]]+(--unset(-all)?|unset)([[:space:]]+${_ARG})*[[:space:]]+[\"']?core\\.hookspath" 2>/dev/null \
|| printf '%s' "$CMD_MEDIUM" | grep -qE "(^|[;&|({])[[:space:]]*(export[[:space:]]+|env([[:space:]]+-[^[:space:]]+)*[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*=[^;&|[:space:]]*[[:space:]]+)*HUSKY=[\"']?0[\"']?${_END}" 2>/dev/null; }; then
WARN="Destructive: disabling git hooks (core.hooksPath, HUSKY=0) skips the checks they run, the same as --no-verify."
fi
# Judged per command: `npm publish --dry-run` uploads nothing, but a dry run
# chained ahead of a real publish must not excuse it.
if [ -z "$WARN" ] && printf '%s' "$CMD_MEDIUM" | tr ';&|' '\n\n\n' \
| grep -E "(npm|pnpm)${_OPTS}([[:space:]]+recursive)?[[:space:]]+publish([[:space:]]|\$)|yarn[[:space:]]+(npm[[:space:]]+)?publish" 2>/dev/null \
| grep -qvE -- '--dry-run' 2>/dev/null; then
WARN="Destructive: package publish is public and cannot be cleanly taken back."
fi
# --- Project patterns (additive only) ---
# One POSIX ERE per line; blank lines and `#` comments are ignored. Consulted
# only after every built-in family above, so a config file can ADD a warning but
# can never suppress a baseline one — a guard a project can silence is not a
# guard. An unusable regex is skipped rather than aborting: a typo in a config
# file must not take the whole hook down.
_match_pattern_file() {
local _pf="$1" _line _lineno=0 _rc
[ -f "$_pf" ] || return 1
while IFS= read -r _line || [ -n "$_line" ]; do
_lineno=$((_lineno + 1))
case "$_line" in ''|'#'*) continue ;; esac
# grep exits 2 on a regex it cannot compile. Say so on stderr, so a typo
# is visible instead of a rule that silently never fires.
_rc=0
printf '' | grep -qE -- "$_line" 2>/dev/null || _rc=$?
if [ "$_rc" -eq 2 ]; then
printf '[careful] skipped unusable pattern in %s:%s: %s\n' "$_pf" "$_lineno" "$_line" >&2
continue
fi
# `--` first: a project pattern may legitimately start with a dash (say
# `--destroy`), and without the terminator grep reads it as an option,
# exits 2, and the discarded stderr makes the guard silently skip it.
if printf '%s' "$CMD_MEDIUM" | grep -qE -- "$_line" 2>/dev/null; then
printf '%s' "$_line"
return 0
fi
done < "$_pf"
return 1
}
if [ -z "$WARN" ]; then
_CFG_DIR="${VIBESTACK_HOME:-$HOME/.vibestack}"
_PAT=$(_match_pattern_file "$_CFG_DIR/careful-patterns.txt") || _PAT=""
# The per-project file needs a slug, and resolving one costs a git call on
# every command — only pay it when project state actually exists.
if [ -z "$_PAT" ] && [ -d "$_CFG_DIR/projects" ] && [ -x "$HOME/.vibestack/bin/vibe-slug" ]; then
SLUG=""
eval "$(VIBESTACK_SLUG_NO_MIGRATE=1 "$HOME/.vibestack/bin/vibe-slug" 2>/dev/null || true)" 2>/dev/null || SLUG=""
if [ -n "${SLUG:-}" ]; then
_PAT=$(_match_pattern_file "$_CFG_DIR/projects/$SLUG/careful-patterns.txt") || _PAT=""
fi
fi
if [ -n "$_PAT" ]; then
WARN="Destructive (project rule): this command matches the configured pattern /$_PAT/."
fi
fi
if [ -n "$WARN" ]; then
_vibestack_log careful ask "$WARN" "$CMD"
_vibestack_analytics ask "$(printf '%s' "$WARN" | cut -d: -f1)"
vibe_hook_decision ask "[careful] $WARN"
else
_vibestack_log careful allow no-pattern-match "$CMD"
echo '{}'
fi
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |