SLOPSHOPPER

blast-radius

Previews what a risky shell command would touch and asks before it runs

guardprocess
★ 4v0.1.0MITupdated 2026-10-13ThisaruGuruge/dotfiles/claude-mods/blast-radius
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · blast-radius
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(rm -rf build && git push --force origin main) ⎿ Denied by blast-radius: blast-radius: you cancelled "rm -rf build && git push --force origin main". ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Thisaru's Dotfiles

A macOS-focused developer workstation built around Zsh, Powerlevel10k, modern CLI tools, and battle-tested automation. Everything is wired together with bestow (a Go-based GNU Stow successor), encrypted secrets, and a centralized package manifest so each new machine behaves exactly like the last one.

Highlights

  • Fast Zsh environment – zinit-managed plugins, fzf-tab completion, syntax highlighting, autosuggestions, zoxide (via z command), Atuin history (Ctrl+R and up-arrow), and Ghostty compatible key bindings
  • Powerlevel10k prompt – pure-Zsh rendering (no binary subprocess per draw), instant prompt on startup, contextual Git state, Go/Java/Python/Ballerina indicators, transient prompt for clean scrollback, full Catppuccin Mocha theme matching the tmux status bar
  • Modern CLI stack – eza, bat, dust, ripgrep, fd, yazi (with inline image previews in Ghostty/iTerm2, chafa fallback for other terminals), jless, lazygit, lazydocker, tmux, direnv, atuin, gh, git-delta, gng (gw), uv (Python packages and projects), and curated helper aliases/functions (take, kill_by_port, show_tools, etc.)
  • Debugging in Neovim – nvim-dap with a DAP UI, inline variable values while stepping, and one keymap set (<leader>d… plus F5/F10/F11) shared by every language. Go (delve) supports debugging the test under the cursor, launching the program with arguments, and attaching to a remote dlv --headless; Python, Java, and Ballerina are wired in too. Adding another debugger is a single drop-in file: a module at nvim/.config/nvim/lua/thisarug/dap/<lang>.lua exporting setup(dap) is picked up automatically by lua/plugins/dap.lua
  • Go tooling in Neovim – gopls with inlay hints and codelenses, <leader>G… for code generation (if err != nil guards, struct tags, interface stubs, test and doc-comment generation), and <leader>T… to run tests from the buffer with a summary tree and watch mode (Go, plus pytest and Vitest via neotest adapters)
  • Sessions and branch review in Neovim – persistence.nvim restores a project's buffers and layout on demand (<leader>qs, or s on the dashboard), and diffview.nvim reviews a branch against the default branch (<leader>gv) or walks a file's history (<leader>gh)
  • Smart aliases – Single-letter shortcuts for modern tools (v for nvim, g for ripgrep, f for fd, z for zoxide) while keeping original commands for scripts
  • Suffix aliases – Automatically open files with the right tool based on extension (.md → mdcat, .json/.yaml → jless, .py/.bash/.zsh/.bal → $EDITOR)
  • Language runtimes – pyenv, rbenv, nvm, SDKMAN, and Ballerina (plus uv for Python packages and projects) with lazy-loading shell glue so heavy managers don't slow startup
  • Touch ID for sudo – Use your fingerprint instead of typing passwords in the terminal (works inside tmux too via pam-reattach)
  • Caps Lock remap – Hammerspoon + ControlEscape.spoon: tap Caps Lock for Escape, hold for Control — a Karabiner alternative that needs only Accessibility/Input Monitoring permissions, no blockable system extension
  • Claude Code, two accounts – ccp (personal) and cce (enterprise) run Claude Code against separate config dirs, with TypeScript mods for a status band, risk previews, secret redaction and a subagent pane (see Claude Code); tmux shows which windows are waiting on Claude
  • Project sessions in tmux – prefix + f opens a project with three windows ([Claude], [Nvim], [Shell])
  • Secrets handled correctly – SOPS + age encryption, edit_secrets workflow, and automatic .env handling inside init.sh
  • Brewfile-driven – Curated Brewfile with optional category files in packages/ for modular installation
  • Validation + profiling – bin/lint (shellcheck, shfmt, zsh -n, stylua, mod tests; also run by CI), test-zsh integration tests, dotdoctor health check, profile_startup quick timing, and bin/profile-zsh-startup for deep dives

Prerequisites

  1. macOS – Tested on Sonoma/Ventura (Apple Silicon friendly)
  2. Git – Already on macOS, confirm with git --version
  3. Homebrew – Install if missing:
   /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  1. Terminal – Ghostty (recommended and configured), iTerm2, or Terminal.app all work
  2. Nerd Font – Needed for icons in Powerlevel10k/lazygit:
   brew install --cask font-fira-code-nerd-font

Set the font once inside your terminal profile (Appearance/Text settings).

Installation

Option 1 – Automated (init.sh)

git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles
./init.sh

The checkout can live anywhere (the script finds the repo from its own path). The rest of the setup hard-codes ~/dotfiles, so when the checkout is elsewhere init.sh creates a ~/dotfiles symlink pointing at it (and stops with a clear message if ~/dotfiles is already something else). ./init.sh --dry-run is a preflight only: it checks the checkout and ~/dotfiles and changes nothing; ./init.sh --help lists the steps.

The script is interactive; it will:

  • Validate macOS + Xcode CLT, install Homebrew, jq, Go (needed to install bestow)
  • Install core packages from Brewfile with Brew
  • Offer opt-in categories (development, terminals, editors, etc.)
  • Install SDKMAN + Java 21 (optional) and brew-based Ballerina
  • Enable Touch ID for sudo (with tmux support via pam-reattach, loaded from a root-owned copy in /opt/pam)
  • Configure Atuin, direnv, tmux, git delta, lazygit, lazydocker, aliases, and helper functions
  • Generate/restore encrypted .env with SOPS + age (keys stored at ~/.config/sops/age/keys.txt, per-machine ~/.sops.yaml)
  • Create Nerd Font + terminal integrations
  • Back up existing dotfiles and symlink everything via bestow
  • Install TPM (pinned release) and the tmux plugins
  • Check that the SSH commit-signing key exists (offers to create it)
  • Verify the install and show next steps (run dotdoctor for a full health check; the final output also lists the manual steps: the Hammerspoon spoon and permissions, the ~/.claude symlink, tmux plugins)

Option 2 – Manual setup

git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles

# Install everything that is currently enabled in Brewfile
brew bundle --file=Brewfile

# Install bestow (requires Go)
go install github.com/redpierrot/bestow@latest

# Bootstrap bestow's own config (source: this repo, destination: $HOME)
bestow init --source ~/dotfiles --destination ~/

# Symlink the packages you need (add/remove as desired)
bestow stow zsh git tmux direnv bash
bestow stow bin -d ~/bin   # bin links into ~/bin, not ~

# Secrets: an age key and this machine's own sops config (not tracked)
mkdir -p ~/.config/sops/age && age-keygen -o ~/.config/sops/age/keys.txt
sed "s/AGE_PUBLIC_KEY/$(grep '^# public key:' ~/.config/sops/age/keys.txt | cut -d' ' -f4)/g" \
  bash/.sops.yaml.example > ~/.sops.yaml

# Reload configuration, then create the encrypted ~/.env
source ~/.zshrc
edit_secrets

Git signs every commit with SSH (gpgSign = true), so set user.signingkey in ~/.gitconfig.local (see git/.gitconfig.local.example) and create the key it names (ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_signing) before your first commit.

Edit the Brewfile directly or use category Brewfiles in packages/ before running brew bundle if you want to customize packages.

Option 3 – Brewfile only

Already have a preferred dotfiles strategy but want the curated tools? Run brew bundle --file=Brewfile and manually pick pieces (aliases, functions, etc.). Edit the Brewfile directly or use the category files in packages/ to customize your installation.

Package Management

The main Brewfile contains core packages that are always installed. Optional packages are organized into category files in packages/:

packages/
├── cloud.brewfile       # aws-vault, gcloud CLI
├── containers.brewfile  # colima, Docker CLI + Compose + credential helper
├── development.brewfile # pyenv, rbenv, nvm, flutter
├── editors.brewfile     # VS Code
├── productivity.brewfile # Raycast, Rectangle, Alfred, Caffeine, etc.
└── terminals.brewfile   # iTerm2

Installing optional categories

brew bundle --file=Brewfile                      # Core packages
brew bundle --file=packages/development.brewfile # Add dev tools
brew bundle --file=packages/editors.brewfile     # Add editors

Categories available

  • core – powerlevel10k, zoxide, eza, bat, ripgrep, lazygit, lazydocker, tmux, direnv, atuin, gh, etc.
  • security – sops + age for encrypted secrets (always enabled)
  • development – pyenv, rbenv, nvm, flutter (optional)
  • cloud – aws-vault and the gcloud CLI
  • editors – VS Code
  • terminals – iTerm2 (casks)
  • containers – colima (container runtime), Docker CLI + Compose + credential helper
  • productivity – Raycast, Rectangle, TablePlus, Alfred, Postman, Caffeine

Comment out what you do not need in the Brewfile, then rerun brew bundle.

brew-sync (or ./bin/sync-brewfile) is a read-only drift report: it lists formulae and casks that are installed but in no Brewfile, and declared packages that are not installed. It never rewrites a Brewfile; add or remove lines by hand. brew-check verifies the core Brewfile is satisfied.

Repository Layout & Symlink Packages

PathNotes
zsh/.zshrc, .zshrc.d/ (modular shell config), .functions.d/ (modular functions), aliases, paths
zsh/.zshrc.d/6 modules: plugins, completion, keybindings, history, integrations, environment
zsh/.functions.d/9 modules: colors, core, navigation, archives, git, system, dotfiles, docs, packages
<tool>/.config/<tool>/XDG configs, one stow package per tool (ghostty, lazygit, nvim, yazi, ripgrep, typos)
zsh/.p10k.zshPowerlevel10k prompt config (Catppuccin Mocha, stowed to ~/.p10k.zsh)
git/.gitconfig, ignore rules, delta settings
tmux/Modern tmux config + keybinds, project session layout, Claude state in status bar
claude/Per-account Claude Code settings.json and status line, stowed to ~/.claude-personal and ~/.claude-enterprise
claude-mods/Claude Code mods (not a stow package; loaded through CLAUDE_CODE_PLUGIN_DIRS)
tests/Golden-output and behaviour tests for the Claude Code helpers (tests/claude/check.sh, run by test-zsh)
direnv/Project-specific environment automation
packages/Optional category Brewfiles (cloud, containers, development, etc.)
bin/Helper scripts (lint, dotdoctor, test-zsh-config, profile-zsh-startup, audit-configs, adopt-config; see bin/README.md)
docs/Additional documentation (prompt guide, tmux keybindings, config management)

Ghostty Configuration

Ghostty is configured with:

  • Cmd+Left/Right sent as Home/End (ESC [ H / ESC [ F), which 03-keybindings.zsh binds to start/end of line (a raw Ctrl+a would be eaten as the tmux prefix)
  • Option+Left/Right for word navigation (sent as Alt+b / Alt+f, so it works inside tmux too) and Cmd+Delete for delete-to-end-of-line (sent as Alt+k)
  • Catppuccin Mocha theme
  • FiraCode Nerd Font with ligatures
  • Tmux-aware keybindings for window/pane navigation (they send the tmux prefix Ctrl+a; test-zsh fails if the prefix changes)

Containers (colima)

The optional containers category (packages/containers.brewfile) installs colima as the local container runtime, paired with the plain docker, docker-compose, and docker-credential-helper CLI formulae — no Docker Desktop app/VM required.

brew bundle --file=packages/containers.brewfile  # colima + docker CLI + compose + credential helper
colima-start                                     # boots the VM, sets the `colima` docker context
docker ps                                        # talks to colima automatically
lzd                                               # lazydocker also works unchanged — it just follows the active docker context

Colima lifecycle aliases (zsh/.aliases.sh, only defined if colima is installed):

AliasCommand
colima-startcolima start
colima-stopcolima stop
colima-restartcolima restart
colima-statuscolima status
colima-listcolima list
colima-sshcolima ssh

Homebrew's docker-compose formula installs as a CLI plugin, and docker-credential-helper installs docker-credential-osxkeychain to store registry credentials in the macOS Keychain instead of plaintext — but Docker only picks either up if ~/.docker/config.json says so:

{
  "cliPluginsExtraDirs": ["/opt/homebrew/lib/docker/cli-plugins"],
  "credsStore": "osxkeychain"
}

init.sh does not currently write these keys automatically — add them by hand (or merge into an existing ~/.docker/config.json) after installing docker-compose / docker-credential-helper.

Symlink Management (bestow)

Day-to-day package management (adding/removing symlinks after the initial install) uses bestow — a Go-based successor to GNU Stow — instead of stow directly. It replicates stow --no-folding behavior (always on, no flag needed) but is idempotent and conflict-safe with pre-existing absolute symlinks.

bestow stow zsh                    # Shell config (includes .p10k.zsh)
bestow stow nvim ghostty lazygit ripgrep yazi typos  # Per-tool packages
bestow stow git tmux direnv        # Git/Tmux/Direnv packages

# Remove a package
bestow unstow zsh

init.sh (the fresh-machine installer) installs bestow with go install github.com/redpierrot/bestow@latest and runs the same bestow stow commands per package. @latest resolves to bestow's newest tagged release once it publishes tags (until then, the newest commit on its default branch).

bin is the exception: it links into ~/bin, so always stow it as bestow stow bin -d ~/bin. Don't run a bare bestow stow across every package — with the single $HOME destination in bestow's config it would link bin/* straight into ~.

Quick Start Commands

test-zsh                                   # Full validation (tools, PATH, runtimes)
./bin/lint                                 # Lint everything, as CI does (./bin/lint --file <path> for one file)
./bin/profile-zsh-startup                  # Deep component timing (zinit plugins, SDKMAN, p10k, etc.)
help                                       # Alias documentation entry point
docs                                       # Interactive alias browser (alias_docs)
show_tools                                 # Overview of installed CLI upgrades
alias_search git                           # Search for aliases by keyword
edit_secrets                               # Safely edit encrypted ~/.env via SOPS
take my-service && code .                  # Smart project bootstrap / clone helper
kill_by_port 3000                          # Stop the process LISTENING on port 3000 (TERM, then KILL); clients are left alone
awake                                      # Keep the Mac from idle-sleeping (awake stop | status | for 2h | screen | ac)
dotdoctor                                  # Health check (changes nothing): unlinked files, dangling links, secrets, mods (--full adds brew + plugin validation)
prs                                        # Browse PRs with fzf: enter=checkout, ctrl-o=browser, ctrl-d=diff via delta
prw                                        # Watch the current PR's checks, then notify with the result
envrc work|personal|status|off             # Pin the Claude Code + gws account for this directory via direnv
lg                                         # Launch lazygit with our config (arguments are forwarded, e.g. lg log)
lzd                                        # Launch lazydocker for Docker management
gw build                                   # Run Gradle build from any subdirectory
gwt                                        # Alias for: gw test
gwc                                        # Alias for: gw clean
gwcb                                       # Alias for: gw clean build
Ctrl+R                                     # Atuin search UI (fuzzy search all history; Ctrl+R again narrows the filter)
Up arrow                                   # Atuin prefix search (as you type)
Ctrl+T / Alt+C                             # fzf file / directory picker with a preview (Ctrl+/ toggles it)

Claude Code

Two accounts, each with its own config directory (claude/ is the stow package that links settings.json and statusline-command.sh into both; history, sessions and auth stay local, auth in the macOS Keychain):

CommandAccountConfig dir
ccp, ccpr, ccpcpersonal: start, --resume, --continue~/.claude-personal
cce, ccer, ccecenterprise: start, --resume, --continue~/.claude-enterprise
  • ~/.claude must be a symlink to ~/.claude-personal (ln -s ~/.claude-personal ~/.claude), so plain claude outside a pinned directory is the personal account. dotdoctor checks it.
  • ccp/ccpr/ccpc also load ~/.claude-personal/projects.d/<repo>.json with --settings when the current git repo has one. That is where a project's own autoMode rules go, since Claude Code ignores autoMode in a project's .claude/settings*.json and they must not live in this public repo. <repo> is the main checkout's directory name, so linked worktrees share it.
  • Mods in claude-mods/ (statusbar, blast-radius, redact, agents, rabe, session-wrapped, conventions) load straight from the repo via CLAUDE_CODE_PLUGIN_DIRS in both settings.json files, with nothing to link. The band above the prompt (context bar, rate limits) is the statusbar mod, the line below it is bin/claude-statusline, and conventions runs bin/lint --file after each edit Claude makes in this repo. See claude-mods/README.md.
  • Hooks call bin/claude-tmux-state, so tmux windows show when Claude is working, waiting or done (prefix + A jumps to the next waiting window).
  • Hooks also call bin/claude-notify, which shows a macOS notification when a session finishes (Stop), asks you something (AskUserQuestion) or needs you (permission prompt, idle: Notification). It stays quiet while the terminal and the tmux window are in view. CLAUDE_NOTIFY=0 turns it off, CLAUDE_NOTIFY_SUBAGENTS=1 adds subagent completions, CLAUDE_NOTIFY_ALWAYS=1 disables the in-view suppression, CLAUDE_NOTIFY_SOUND=<name> changes the sound. One-time setup: allow banners and sounds for Script Editor under System Settings > Notifications (osascript notifications are attributed to it); Focus modes silence them. Details in bin/README.md.
  • Pin an account to a directory with envrc (below).

tmux project sessions

prefix + f (sessionizer) and prefix + S (new session) create a session with three windows: [Claude] (runs claude with the directory's .envrc applied), [Nvim] (nvim over a small shell, the window the session opens on) and [Shell] (plain shell). SESSIONIZER_LAYOUT=bare gives a single shell instead. After pulling, run bestow stow tmux if a new helper script is missing. Key reference: docs/TMUX_KEYBINDINGS.md.

Per-project accounts (envrc)

envrc work (enterprise) or envrc personal writes a .envrc in the current directory that pins CLAUDE_CONFIG_DIR and GOOGLE_WORKSPACE_CLI_CONFIG_DIR (plus the gws file keyring backend), creates the account's gws directory with mode 700, runs direnv allow and applies the pin to the current shell straight away. Plain claude and gws then use the right account anywhere under that directory, including subdirectories and new shells or tmux panes opened inside the tree (direnv stays lazy-loaded: it is only loaded once a .envrc exists in the current directory or any parent). The file is added to the repo's local exclude (info/exclude, also from a linked worktree; envrc confirms with git check-ignore) and inherits parent pins through source_up_if_exists.

  • envrc status shows which pin applies (and whether it is inherited from a parent directory)
  • envrc off removes a pin written by envrc (it never touches a .envrc it did not write)
  • Replacing an existing .envrc (not written by envrc, or edited by hand since) asks first and keeps a copy as .envrc.bak; a symlinked .envrc is refused rather than written through

What overrides what

CommandCLAUDE_CONFIG_DIRGOOGLE_WORKSPACE_CLI_CONFIG_DIR
plain claude in a pinned treepinned accountpinned account (inherited)
ccp/ccpr/ccpc, cce/ccer/ccecthe account you typedblanked for that claude, so a pin never leaks the other account's gws into it
gwsp/gwseunchangedthe account you typed
bare gws in a pinned treeunchangedpinned account: the bin/gws guard lets it through because the pin supplies the account context
bare gws anywhere elseunchangedblocked (exit 64)

Inside a pinned tree a bare gws therefore acts on the pinned account instead of being refused; that is the point of the pin. Plain claude outside any pinned directory uses ~/.claude, which should be a symlink to ~/.claude-personal (dotdoctor checks this: ln -s ~/.claude-personal ~/.claude).

GitHub PR helpers (prs, prw)

  • prs [gh pr list flags] – fzf over the repo's PRs with a gh pr view preview. enter checks the PR out, ctrl-o opens it in the browser, ctrl-d shows the full diff through delta. Example: prs --author @me
  • prw [pr] – gh pr checks --watch for the current branch's PR (or the given number/URL), then a macOS notification with the result; the exit status mirrors gh pr checks

Both need gh and jq; prs also needs fzf. PR titles are untrusted text: control characters (including ESC) are replaced with spaces before they are shown, and prw prints titles verbatim (no backslash interpretation). prw says whether the checks failed, were cancelled or are still pending, or that gh reported no result (no checks, or gh could not be reached), instead of calling every non-zero exit "failed".

Shell behaviour worth knowing

  • cp / mv are small functions, not aliases: they prompt before overwriting (-i, verbose) only when a human is at the terminal, and run the plain command otherwise (scripts, agents, pipes). They do not force -r; copy directories with cp -R. sudo cp / sudo mv run the plain commands (sudo runs the binary, not the shell function), so pass -i yourself there.
  • awake keeps the Mac from idle-sleeping in the background (caffeinate -i: the display may still sleep or lock, and it works on AC and battery). awake screen also keeps the display on, awake ac
Source 2 files
hooks/register.ts 336 lines
1import type { Register } from 'claude-code'
2
3import {
4  LABELS,
5  SHRED_OPTS,
6  TRUNCATE_OPTS,
7  classify,
8  cleanDryRun,
9  clip,
10  cluster,
11  findPreviewArgs,
12  human,
13  isGlob,
14  isLong,
15  operands,
16  rmTargets,
17} from './risk'
18import type { Risk } from './risk'
19
20const RUN = 'Run it'
21const CANCEL = 'Cancel'
22const TIMEOUT_MS = 8000
23
24// The part of `$` the previews use. `$` must stay named `$` and stay in this file.
25type Sh = {
26  process: {
27    run: (
28      argv: readonly string[],
29      init?: { cwd?: string; env?: Record<string, string>; timeoutMs?: number },
30    ) => Promise<{ exitCode: number; stdout: string; stderr: string; isStdoutTruncated?: boolean }>
31  }
32  fs: { stat: (path: string) => Promise<{ kind: string; size: number }> }
33  env: { get: (name: string) => Promise<string | undefined> }
34}
35
36/** Where a preview runs: the risk's directory with `~` expanded, or the session's. */
37type Where = { cwd?: string; home?: string }
38
39const why = (err: unknown) => (err instanceof Error ? err.message : String(err)).slice(0, 200)
40
41const expandHome = (p: string, home: string | undefined) =>
42  p === '~' ? (home ?? p) : p.startsWith('~/') && home ? home + p.slice(1) : p
43
44async function where($: Sh, risk: Risk): Promise<Where> {
45  const home = await $.env.get('HOME')
46  if (risk.cwd === undefined) return { home }
47  if (risk.cwd === '?') throw new Error('the command changes to a directory that cannot be resolved here')
48  return { cwd: expandHome(risk.cwd, home), home }
49}
50
51const run = ($: Sh, w: Where, argv: string[], env?: Record<string, string>) =>
52  $.process.run(argv, { ...(w.cwd !== undefined ? { cwd: w.cwd } : {}), ...(env ? { env } : {}), timeoutMs: TIMEOUT_MS })
53
54// The preview runs git in a directory the command names, before anyone agreed
55// to run anything there: no fsmonitor hook (repo config can name a program),
56// no untracked cache writes, no optional index lock.
57export const GIT_SAFE = ['-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false']
58const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0' }
59
60async function git($: Sh, w: Where, risk: Risk, args: string[]): Promise<string> {
61  const r = await run($, w, ['git', ...GIT_SAFE, ...(risk.gitArgs ?? []), ...args], GIT_ENV)
62  if (r.exitCode !== 0) {
63    throw new Error(`git ${args[0]} failed: ${r.stderr.trim().slice(0, 200)}`)
64  }
65  return r.stdout.trimEnd()
66}
67
68// Counting entries must not stream them into this process: `$.process.run` caps
69// stdout (4 MiB) and a big tree's listing is larger, so the count came out low.
70// The path is a positional argument of the script, never part of it.
71const COUNT_FILES = 'find -- "$1" -type f | wc -l'
72const COUNT_ALL = 'find -- "$1" | wc -l'
73
74async function countEntries($: Sh, w: Where, script: string, path: string): Promise<string> {
75  const r = await run($, w, ['sh', '-c', script, 'sh', path])
76  const n = Number.parseInt(r.stdout.trim(), 10)
77  return Number.isNaN(n) ? '?' : String(n)
78}
79
80/** A target path as the command will see it: `~` expanded, relative ones under the command's directory. */
81const resolve = (raw: string, w: Where) => {
82  const p = expandHome(raw, w.home)
83  return p.startsWith('/') || w.cwd === undefined ? p : `${w.cwd.replace(/\/+$/, '')}/${p}`
84}
85
86/** One `rm` target's lines. */
87async function previewTarget($: Sh, w: Where, raw: string): Promise<string[]> {
88  if (/[$`]/.test(raw)) return [`? ${raw}  (contains a variable or substitution, cannot resolve)`]
89  if (isGlob(raw)) return [`? ${raw}  (glob, the shell expands it at run time)`]
90  const path = resolve(raw, w)
91  try {
92    const kind = await run($, w, ['stat', '-f', '%HT', path]).then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
93    if (kind === null) return [`- ${raw}  (does not exist)`]
94    const stat = await $.fs.stat(path)
95    if (stat.kind !== 'dir') return [`- ${raw}  ${kind}, ${human(stat.size)}`]
96    const danger = path === '/' || path === w.home || `${path}/` === w.home
97    // Counting can time out on a big tree; the size is then unknown, not a reason to skip the question
98    const [count, kb] = await Promise.all([
99      countEntries($, w, COUNT_FILES, path).catch(() => '?'),
100      run($, w, ['du', '-sk', path])
101        .then(r => Number.parseInt(r.stdout.split('\t')[0] ?? '', 10))
102        .catch(() => Number.NaN),
103    ])
104    const out = [`- ${raw}/  directory: ${count} files, ${Number.isNaN(kb) ? '?' : human(kb * 1024)}`]
105    if (danger) out.push('  !! this is the filesystem root or your home directory')
106    return out
107  } catch (err) {
108    return [`? ${raw}  (preview unavailable: ${why(err)})`]
109  }
110}
111
112async function previewRm($: Sh, w: Where, risk: Risk, targets = rmTargets(risk.args)): Promise<string[]> {
113  if (targets.length === 0) {
114    return [`Could not parse targets from: ${risk.segment.slice(0, 200)}`]
115  }
116  // Targets are independent: preview them together, keep their order
117  const lines = (await Promise.all(targets.slice(0, 8).map(raw => previewTarget($, w, raw)))).flat()
118  if (targets.length > 8) {
119    lines.push(`... and ${targets.length - 8} more targets`)
120  }
121  return lines
122}
123
124async function previewChmod($: Sh, w: Where, risk: Risk): Promise<string[]> {
125  const lines: string[] = []
126  for (const t of rmTargets(risk.args).slice(1, 6)) {
127    if (isGlob(t) || /[$`]/.test(t)) {
128      lines.push(`? ${t}  (cannot resolve)`)
129      continue
130    }
131    const n = await countEntries($, w, COUNT_ALL, resolve(t, w)).catch(() => '?')
132    lines.push(`- ${t}  ${n} entries affected`)
133  }
134  return lines.length ? lines : ['Could not parse targets']
135}
136
137/**
138 * What a find that is safe to run (its delete actions taken out) matches right
139 * now. `head` words the count line.
140 */
141async function previewFindMatches($: Sh, w: Where, args: string[], head: (n: string) => string): Promise<string[]> {
142  const r = await run($, w, ['find', ...args])
143  const hits = r.stdout.split('\n').filter(Boolean)
144  // find exits non-zero on a bad expression and on unreadable directories; only the first means "unknown"
145  if (r.exitCode !== 0 && hits.length === 0) {
146    throw new Error(`find exited ${r.exitCode}: ${r.stderr.trim().slice(0, 200)}`)
147  }
148  // Output past the cap is cut mid-line: drop the partial last line and say the count is a floor
149  if (r.isStdoutTruncated) hits.pop()
150  const more = r.isStdoutTruncated ? '+' : ''
151  const out = hits.length ? [head(`${hits.length}${more}`), ...clip(hits)] : ['Nothing matches right now']
152  if (r.exitCode !== 0 && !r.isStdoutTruncated) out.push(`(find also reported errors: ${r.stderr.trim().split('\n')[0]?.slice(0, 150) ?? ''})`)
153  return out
154}
155
156/** `git worktree remove --force <wt>`: what the worktree holds that would go with it. */
157async function previewWorktree($: Sh, w: Where, risk: Risk): Promise<string[]> {
158  const wt = risk.args.slice(1).find(a => !a.startsWith('-'))
159  if (wt === undefined) return [`Could not parse the worktree from: ${risk.segment.slice(0, 200)}`]
160  if (/[$`]/.test(wt) || isGlob(wt)) return [`? ${wt}  (contains a variable, substitution or glob, cannot resolve)`]
161  // The worktree's own status: the command's --git-dir/--work-tree name the main repository, not it.
162  // Untracked files are listed even when the repo's config hides them.
163  const r = await run($, w, ['git', ...GIT_SAFE, '-C', resolve(wt, w), 'status', '--short', '--untracked-files=normal'], GIT_ENV)
164  if (r.exitCode !== 0) throw new Error(`git status failed: ${r.stderr.trim().slice(0, 200)}`)
165  const status = r.stdout.trimEnd()
166  return [
167    `Worktree: ${wt}`,
168    ...(status
169      ? ['Uncommitted and untracked files that would be deleted:', ...clip(status.split('\n'))]
170      : ['(no uncommitted or untracked files)']),
171    'Its ignored files (build output, .env) are deleted too.',
172  ]
173}
174
175async function previewFor($: Sh, risk: Risk): Promise<string[]> {
176  if (risk.remote !== undefined) return [`Runs on ${risk.remote}; nothing there can be previewed from here.`]
177  if (risk.kind === 'nested') {
178    return [
179      'It is nested deeper (bash -c, eval, $(...) inside each other) than is parsed, and mentions a destructive command.',
180      `Command: ${risk.segment.slice(0, 300)}`,
181    ]
182  }
183  if (risk.fromXargs) return ['rm under xargs or fd -x: the paths come from its input or matches, so they cannot be listed here.']
184  const w = await where($, risk)
185  if (risk.findArgs) {
186    // find -exec sh -c '...': list what find matches, never running the shell
187    const args = findPreviewArgs(risk.findArgs, true)
188    if (args === null) return ['Run by find -exec on each match, with another -exec/-ok action: not previewed, it would run it.']
189    return previewFindMatches($, w, args, n => `Run by find -exec on each of ${n} entries:`)
190  }
191  switch (risk.kind) {
192    case 'rm':
193      return previewRm($, w, risk)
194    case 'git-discard':
195    case 'git-reset-hard': {
196      const status = await git($, w, risk, ['status', '--short'])
197      const out = [
198        'Uncommitted changes that would be discarded:',
199        ...(status ? clip(status.split('\n')) : ['(working tree is clean)']),
200      ]
201      const ahead = await git($, w, risk, ['log', '--oneline', '@{u}..']).catch(() => '')
202      if (ahead) {
203        out.push('Local commits not on upstream (reset may orphan them):', ...clip(ahead.split('\n'), 6))
204      }
205      return out
206    }
207    case 'git-push-force': {
208      const branch = await git($, w, risk, ['rev-parse', '--abbrev-ref', 'HEAD'])
209      const ahead = await git($, w, risk, ['log', '--oneline', '@{u}..']).catch(() => '')
210      const behind = await git($, w, risk, ['log', '--oneline', '..@{u}']).catch(() => '')
211      const out = [`Branch: ${branch}`]
212      out.push(ahead ? 'Commits to be pushed:' : 'No unpushed commits found (or no upstream)')
213      if (ahead) out.push(...clip(ahead.split('\n'), 6))
214      if (behind) {
215        out.push('Remote-only commits that would be OVERWRITTEN:', ...clip(behind.split('\n'), 6))
216      }
217      return out
218    }
219    case 'git-push-delete': {
220      const pos = risk.args.filter(a => !a.startsWith('-'))
221      const isDelete = risk.args.some(a => isLong(a, '--delete') || cluster(a, 'd'))
222      const refs = isDelete ? pos.slice(1) : pos.filter(a => a.startsWith(':')).map(a => a.slice(1))
223      const out: string[] = []
224      if (refs.length) out.push(`Remote refs that would be deleted on ${pos[0] ?? 'the remote'}:`, ...clip(refs, 8))
225      if (risk.args.some(a => isLong(a, '--mirror'))) out.push('--mirror deletes every remote ref that does not exist locally.')
226      if (risk.args.some(a => isLong(a, '--prune'))) out.push('--prune deletes remote refs that have no local counterpart.')
227      out.push('Deleted remote branches and tags cannot be restored from here.')
228      return out
229    }
230    case 'git-clean': {
231      const dry = await git($, w, risk, cleanDryRun(risk.args))
232      return dry ? ['Would remove:', ...clip(dry.split('\n'))] : ['Nothing to remove right now']
233    }
234    case 'git-worktree-force':
235      return previewWorktree($, w, risk)
236    case 'shred':
237    case 'truncate': {
238      const targets = operands(risk.args, risk.kind === 'shred' ? SHRED_OPTS : TRUNCATE_OPTS)
239      const lines = await previewRm($, w, risk, targets)
240      lines.push(risk.kind === 'shred' ? 'Their contents are overwritten and cannot be recovered.' : 'Data past the new size is lost.')
241      return lines
242    }
243    case 'git-stash-clear': {
244      const list = await git($, w, risk, ['stash', 'list'])
245      return list ? ['Stashes that would be dropped:', ...clip(list.split('\n'), 8)] : ['(no stashes)']
246    }
247    case 'adopt': {
248      const status = await git($, w, risk, ['status', '--short'])
249      return [
250        'Live files get pulled INTO the repo, overwriting curated configs.',
251        'Run `git diff` right after. Current changes:',
252        ...(status ? clip(status.split('\n'), 8) : ['(working tree is clean)']),
253      ]
254    }
255    case 'chmod-r':
256      return previewChmod($, w, risk)
257    case 'dd': {
258      const of = risk.args.find(a => a.startsWith('of='))
259      const inp = risk.args.find(a => a.startsWith('if='))
260      return [`Raw write: ${inp ?? 'if=?'} -> ${of ?? 'of=?'}`, 'Cannot be previewed or undone.']
261    }
262    case 'mkfs':
263      return [
264        `Formats: ${risk.args.filter(a => !a.startsWith('-')).join(' ') || '(device unknown)'}`,
265        'All data on it is lost.',
266      ]
267    case 'find-delete': {
268      // Never run a find that would act on its own (-exec, -ok, -fprint...); -delete and -exec rm are dropped
269      const args = findPreviewArgs(risk.args)
270      if (args === null) return ['find with another -exec/-ok action: not previewed, it would run it.']
271      return previewFindMatches($, w, args, n => `Would delete ${n} entries:`)
272    }
273    case 'rsync-delete': {
274      const pos = risk.args.filter(a => !a.startsWith('-'))
275      return [
276        `Destination: ${pos[pos.length - 1] ?? '?'}`,
277        'Files there that are not in the source are removed. Add --dry-run first to see the list.',
278      ]
279    }
280    case 'sql':
281      return [
282        'Destructive SQL or migration detected. It cannot be previewed here.',
283        `Command: ${risk.segment.slice(0, 300)}`,
284      ]
285  }
286}
287
288/** Every risk's preview; one that fails says so and the rest still show. */
289async function buildPreview($: Sh, risks: Risk[]): Promise<string> {
290  const parts: string[] = []
291  for (const r of risks) {
292    const at = r.cwd !== undefined ? `  (in ${r.cwd === '?' ? 'an unresolved directory' : r.cwd})` : ''
293    let lines: string[]
294    try {
295      lines = await previewFor($, r)
296    } catch (err) {
297      lines = [`Preview unavailable: ${why(err)}`]
298    }
299    parts.push(`[${LABELS[r.kind]}]${at}`, ...lines)
300  }
301  return parts.join('\n')
302}
303
304/**
305 * Asks about a risky command. Undefined: nothing risky, or the person said to
306 * run it. A preview that fails still asks; a question nobody answers denies.
307 */
308async function check($: Sh & { ui: { ask: (q: string, o: { options: string[]; header: string }) => Promise<string> } }, command: string) {
309  const risks = classify(command)
310  if (risks.length === 0) return undefined
311  const preview = await buildPreview($, risks)
312  let answer: string
313  try {
314    const question = `Risky command: ${command.slice(0, 300)}\n\n${preview.slice(0, 1500)}\n\nRun it?`
315    answer = await $.ui.ask(question, { options: [RUN, CANCEL], header: 'Blast radius' })
316  } catch {
317    return {
318      deny: `blast-radius: "${command.slice(0, 120)}" needs your confirmation and nobody answered. Not run.\n${preview.slice(0, 800)}`,
319    }
320  }
321  return answer === RUN ? undefined : { deny: `blast-radius: you cancelled "${command.slice(0, 120)}".` }
322}
323
324const failed = 'blast-radius: its guard failed, so the command was not run.'
325
326export const register: Register = on => {
327  on('tool.call', { tool: 'Bash' }, async ($, e, next) => (await check($, e.command)) ?? next(e)).catch(($, e, next) =>
328    next.called ? next(e) : { deny: failed },
329  )
330
331  // Monitor runs a shell command too (each line it prints is an event)
332  on('tool.call', { tool: 'Monitor' }, async ($, e, next) =>
333    e.command === undefined ? next(e) : ((await check($, e.command)) ?? next(e)),
334  ).catch(($, e, next) => (next.called ? next(e) : { deny: failed }))
335}
336
hooks/risk.ts 1211 lines
1export type RiskKind =
2  | 'rm'
3  | 'git-reset-hard'
4  | 'git-push-force'
5  | 'git-push-delete'
6  | 'git-clean'
7  | 'git-discard'
8  | 'git-stash-clear'
9  | 'git-worktree-force'
10  | 'sql'
11  | 'adopt'
12  | 'chmod-r'
13  | 'dd'
14  | 'mkfs'
15  | 'find-delete'
16  | 'rsync-delete'
17  | 'shred'
18  | 'truncate'
19  | 'nested'
20
21export type Risk = {
22  kind: RiskKind
23  segment: string
24  args: string[]
25  /**
26   * Where the command runs, from a leading `cd X &&` and `git -C X`: absolute,
27   * `~`-relative or relative to the session's directory. `?` when a `cd`
28   * target could not be resolved (a variable, a substitution). Absent: the
29   * session's own directory.
30   */
31  cwd?: string
32  /** `--git-dir`/`--work-tree` given to git, passed on to the preview's git calls. */
33  gitArgs?: string[]
34  /** The host an `ssh host '...'` runs it on; nothing local can preview it. */
35  remote?: string
36  /** `rm` run by `xargs` or `fd -x`: its targets come from the input or the matches, not the command line. */
37  fromXargs?: true
38  /** Run by `find -exec sh -c '...'` on each match: find's own words, to preview what it matches. */
39  findArgs?: string[]
40}
41
42export const LABELS: Record<RiskKind, string> = {
43  rm: 'recursive delete (rm -r)',
44  'git-reset-hard': 'git reset --hard',
45  'git-push-force': 'forced git push',
46  'git-push-delete': 'git push that deletes remote refs (--delete, :ref, --mirror, --prune)',
47  'git-clean': 'git clean (deletes untracked files)',
48  'git-discard': 'git checkout/restore/switch that discards uncommitted changes',
49  'git-stash-clear': 'git stash clear (drops every stash)',
50  'git-worktree-force': 'git worktree remove --force (deletes its uncommitted and untracked files)',
51  sql: 'destructive SQL or migration',
52  adopt: 'stow/bestow --adopt (overwrites repo files)',
53  'chmod-r': 'recursive chmod',
54  dd: 'dd (raw block write)',
55  mkfs: 'mkfs, newfs or diskutil erase (formats a device)',
56  'find-delete': 'find that deletes (-delete, -exec rm)',
57  'rsync-delete': 'rsync --delete (removes files at the destination)',
58  shred: 'shred (overwrites file contents beyond recovery)',
59  truncate: 'truncate (cuts files to a size, losing what is past it)',
60  nested: 'destructive command nested too deeply to check',
61}
62
63// Commands that run another command. Each lists its short options that take a
64// value (`sudo -u root git ...`) and its long ones (`--user root`), so the
65// value is not mistaken for the program.
66const WRAPPERS: Record<string, { short: string; long: string[] }> = {
67  sudo: {
68    short: 'ugChprtUDTR',
69    long: ['--user', '--group', '--close-from', '--host', '--prompt', '--role', '--type', '--other-user', '--chdir', '--command-timeout', '--chroot'],
70  },
71  doas: { short: 'uC', long: [] },
72  env: { short: 'uCSP', long: ['--unset', '--chdir', '--split-string'] },
73  command: { short: '', long: [] },
74  builtin: { short: '', long: [] },
75  exec: { short: 'a', long: [] },
76  nohup: { short: '', long: [] },
77  time: { short: 'of', long: ['--output', '--format'] },
78  nice: { short: 'n', long: ['--adjustment'] },
79  xargs: {
80    short: 'IJLnPRSsEda',
81    long: ['--max-args', '--max-procs', '--max-lines', '--max-chars', '--delimiter', '--arg-file'],
82  },
83  timeout: { short: 'sk', long: ['--signal', '--kill-after'] },
84  gtimeout: { short: 'sk', long: ['--signal', '--kill-after'] },
85  caffeinate: { short: 'tw', long: [] },
86  stdbuf: { short: 'ioe', long: ['--input', '--output', '--error'] },
87  chronic: { short: '', long: [] },
88  setsid: { short: '', long: [] },
89  coproc: { short: '', long: [] },
90  unbuffer: { short: '', long: [] },
91  ionice: { short: 'cnpP', long: ['--class', '--classdata', '--pid', '--pgid', '--uid'] },
92  // watch joins the rest of its words and hands them to sh -c
93  watch: { short: 'nq', long: ['--interval', '--equexit'] },
94  // macOS: arch picks the architecture (its options are words, see SINGLE_DASH), xcrun runs a developer tool
95  arch: { short: '', long: [] },
96  xcrun: { short: '', long: ['--sdk', '--toolchain'] },
97}
98
99// Wrappers whose options are whole single-dash words (`arch -arm64`, `arch -arch x86_64`), not
100// clusters of letters: the ones listed take the next word as their value, any other takes none.
101const SINGLE_DASH: Record<string, string[]> = {
102  arch: ['-arch', '-d', '-e'],
103  xcrun: ['-sdk', '-toolchain'],
104}
105
106// Wrappers whose first positional argument is theirs, not the program (`timeout 5 git push -f`).
107const WRAPPER_POSITIONAL = new Set(['timeout', 'gtimeout'])
108
109// Shell words that can lead a segment without being the program.
110const KEYWORDS = new Set(['{', '}', '!', 'if', 'then', 'else', 'elif', 'do', 'while', 'until'])
111
112const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])
113
114// git options that come before the subcommand and take the next word as their value.
115const GIT_VALUE_OPTS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--config-env', '--list-cmds'])
116
117const SQL_DESTRUCTIVE =
118  /\b(drop\s+(table|database|schema|index|view)|truncate\s+(table\s+)?[A-Za-z_"`]|delete\s+from\s+[A-Za-z_"`.]+\s*(;|"|'|$))/i
119const MIGRATE =
120  /\b(db:migrate|migrate:(fresh|refresh|reset|rollback)|prisma\s+migrate\s+(reset|deploy|dev)|manage\.py\s+migrate|alembic\s+(upgrade|downgrade)|flyway\s+(migrate|clean)|goose\s+(up|down|reset)|dbmate\s+(up|down|drop)|sqlx\s+migrate|knex\s+migrate|sequelize\S*\s+db:migrate)\b/i
121// The lookahead finds the r once; `-[A-Za-z]*[rR][A-Za-z]*\b` backtracked quadratically on a long cluster
122const RM_FALLBACK = /(^|[\s(`;&|])rm\s+(-(?=[A-Za-z]*[rR])[A-Za-z]+|--recursive)\b/
123// A heredoc read by one of these is SQL, and its body is checked as such
124const SQL_CLIENT =
125  /\b(psql|mysql|mariadb|sqlite3?|sqlcmd|clickhouse(-client)?|cockroach|duckdb|snowsql|sqlplus|isql|usql|mongosh?)\b/
126
127/** How deep `bash -c`, `eval` and `$(...)` payloads are followed. */
128const MAX_DEPTH = 2
129
130/** `a` is the long option `name`, or an abbreviation of it (git and getopt_long accept unambiguous prefixes). */
131export const isLong = (a: string, name: string) => a.length >= 3 && a.startsWith('--') && name.startsWith(a)
132
133const ANSI_ESCAPES: Record<string, string> = { n: '\n', t: '\t', r: '\r', '\\': '\\', "'": "'", '"': '"' }
134
135type Piece = { text: string; sep: string }
136
137/**
138 * Splits on unquoted ; & | and newlines, keeping each separator. Quotes and
139 * backslash escapes are tracked as the shell reads them (no escapes inside
140 * single quotes, escapes inside $'...'); $( ) is not. The & of a redirection
141 * (`2>&1`, `>&2`, `&>file`) is not a separator.
142 */
143function splitWithSeps(command: string): Piece[] {
144  const out: Piece[] = []
145  let cur = ''
146  let quote: '"' | "'" | '$' | null = null
147  for (let i = 0; i < command.length; i++) {
148    const c = command.charAt(i)
149    if (quote === "'") {
150      cur += c
151      if (c === "'") quote = null
152      continue
153    }
154    if (c === '\\' && i + 1 < command.length) {
155      cur += c + command.charAt(++i)
156      continue
157    }
158    if (quote) {
159      cur += c
160      if (c === (quote === '$' ? "'" : quote)) quote = null
161      continue
162    }
163    if (c === '$' && command.charAt(i + 1) === "'") {
164      quote = '$'
165      cur += "$'"
166      i++
167      continue
168    }
169    if (c === '"' || c === "'") {
170      quote = c
171      cur += c
172      continue
173    }
174    if (c === '&' && (command.charAt(i + 1) === '>' || /[<>]$/.test(cur))) {
175      cur += c
176      continue
177    }
178    if (c === ';' || c === '&' || c === '|' || c === '\n') {
179      out.push({ text: cur, sep: c })
180      cur = ''
181      continue
182    }
183    cur += c
184  }
185  out.push({ text: cur, sep: '' })
186  return out
187}
188
189/** Splits on unquoted ; & | and newlines. Quotes are tracked, $( ) is not. */
190export function splitSegments(command: string): string[] {
191  return splitWithSeps(command)
192    .map(p => p.text.trim())
193    .filter(Boolean)
194}
195
196const REDIRECT = /^(?:<<<|<<-?|<>|<&|>&|>>|>\||&>>|&>|<|>)/
197
198export type Lexed = { words: string[]; hereStrings: string[] }
199
200/**
201 * Whitespace split that keeps quoted strings together and strips the quotes
202 * ($'...' escapes decoded). Redirections are dropped with their target
203 * (`2>/dev/null`, `> out`, `2>&1`, `<<EOF`), except a here-string's
204 * (`<<< 'text'`), which is kept apart. An unquoted `)` or backtick ends a word
205 * and is dropped, so `(cd x && git push -f)` and `` `git push -f` `` read as
206 * plain words.
207 */
208export function lex(segment: string): Lexed {
209  const words: string[] = []
210  const hereStrings: string[] = []
211  let cur = ''
212  let quote: '"' | "'" | '$' | null = null
213  let has = false
214  let quoted = false
215  let target: 'drop' | 'here' | null = null
216  const end = () => {
217    if (has || cur) {
218      if (target === 'here') hereStrings.push(cur)
219      else if (target === null) words.push(cur)
220      target = null
221    }
222    cur = ''
223    has = false
224    quoted = false
225  }
226  for (let i = 0; i < segment.length; i++) {
227    const c = segment.charAt(i)
228    const next = segment.charAt(i + 1)
229    if (quote === '"') {
230      if (c === '\\' && /["\\$`]/.test(next)) {
231        cur += next
232        i++
233      } else if (c === '"') quote = null
234      else cur += c
235      continue
236    }
237    if (quote === "'") {
238      if (c === "'") quote = null
239      else cur += c
240      continue
241    }
242    if (quote === '$') {
243      if (c === '\\' && i + 1 < segment.length) {
244        cur += ANSI_ESCAPES[next] ?? next
245        i++
246      } else if (c === "'") quote = null
247      else cur += c
248      continue
249    }
250    if (c === '$' && next === "'") {
251      quote = '$'
252      has = true
253      quoted = true
254      i++
255      continue
256    }
257    if (c === '"' || c === "'") {
258      quote = c
259      has = true
260      quoted = true
261      continue
262    }
263    if (c === '\\' && i + 1 < segment.length) {
264      cur += next
265      i++
266      has = true
267      quoted = true
268      continue
269    }
270    if ((c === '<' || c === '>') && next === '(') {
271      // process substitution, a word of its own
272      cur += c
273      has = true
274      continue
275    }
276    const op = c === '<' || c === '>' || (c === '&' && next === '>') ? REDIRECT.exec(segment.slice(i, i + 4))?.[0] : undefined
277    if (op) {
278      // `2>x`, `{fd}>x`: the number or name is the redirection's, not a word
279      if (!quoted && (/^\d+$/.test(cur) || /^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(cur))) {
280        cur = ''
281        has = false
282      }
283      end()
284      target = op === '<<<' ? 'here' : 'drop'
285      i += op.length - 1
286      continue
287    }
288    if (/\s/.test(c) || c === ')' || c === '`') {
289      end()
290      continue
291    }
292    cur += c
293    has = true
294  }
295  end()
296  return { words, hereStrings }
297}
298
299export const tokenize = (segment: string): string[] => lex(segment).words
300
301/**
302 * The commands inside `$(...)`, backticks and `<(...)`/`>(...)` at the top
303 * level of `command` (not inside single quotes). Nested ones stay inside
304 * their parent's text, for the next level to find. `literal`: quotes mean
305 * nothing at the top level, as in a heredoc body.
306 */
307export function substitutions(command: string, literal = false): string[] {
308  const out: string[] = []
309  let dq = false
310  for (let i = 0; i < command.length; i++) {
311    const c = command.charAt(i)
312    if (c === '\\') {
313      i++
314      continue
315    }
316    if (!literal && !dq && c === '$' && command.charAt(i + 1) === "'") {
317      let j = i + 2
318      while (j < command.length && command.charAt(j) !== "'") j += command.charAt(j) === '\\' ? 2 : 1
319      i = j
320      continue
321    }
322    if (!literal && c === "'" && !dq) {
323      const j = command.indexOf("'", i + 1)
324      if (j < 0) break
325      i = j
326      continue
327    }
328    if (!literal && c === '"') {
329      dq = !dq
330      continue
331    }
332    const opensParen = command.charAt(i + 1) === '(' && (c === '$' || (!dq && !literal && (c === '<' || c === '>')))
333    if (opensParen) {
334      let depth = 1
335      let q: string | null = null
336      let j = i + 2
337      for (; j < command.length; j++) {
338        const d = command.charAt(j)
339        if (d === '\\') {
340          j++
341          continue
342        }
343        if (q) {
344          if (d === q) q = null
345          continue
346        }
347        if (d === '"' || d === "'") q = d
348        else if (d === '(') depth++
349        else if (d === ')' && --depth === 0) break
350      }
351      out.push(command.slice(i + 2, j))
352      i = j
353      continue
354    }
355    if (c === '`') {
356      let j = i + 1
357      while (j < command.length && command.charAt(j) !== '`') j += command.charAt(j) === '\\' ? 2 : 1
358      out.push(command.slice(i + 1, j))
359      i = j
360    }
361  }
362  return out
363}
364
365const stripOpen = (t: string) => t.replace(/^(\$\(|<\(|>\(|\(|`)+/, '')
366const base = (t: string) => stripOpen(t).split('/').pop() ?? t
367
368/** Does this shell (its words after the name) read its commands from stdin: no -c, no script file? */
369function shellReadsStdin(args: string[]): boolean {
370  for (let i = 0; i < args.length; i++) {
371    const a = args[i] ?? ''
372    if (a === '--') return i + 1 >= args.length
373    if (cluster(a, 'c')) return false
374    if (cluster(a, 's')) return true
375    if (a === '-o' || a === '+o' || a === '-O' || a === '+O' || a === '--rcfile' || a === '--init-file') {
376      i++
377      continue
378    }
379    if (!a.startsWith('-') && !a.startsWith('+')) return false
380  }
381  return true
382}
383
384type Heredoc = { tabs: boolean; quoted: boolean; delim: string; cmdStart: number; opAt: number; opEnd: number }
385type Ctx = { t: 'code'; kind: 'top' | 'subst' | 'bt'; depth: number; cmdStart: number; arith: boolean } | { t: 'dq'; at: number }
386
387export type Sanitized = {
388  /** The command with comments and heredoc bodies taken out. */
389  code: string
390  /** Heredoc bodies that are data, for the SQL text check only. */
391  texts: string[]
392}
393
394/**
395 * Body of the heredoc whose lines start at `from`: its text and where it
396 * ends, or null when the delimiter never comes. `missing` remembers where a
397 * delimiter was last looked for in vain, so many unterminated heredocs stay linear.
398 */
399function heredocBody(s: string, from: number, h: Heredoc, missing: Map<string, number>): { body: string; after: number } | null {
400  const key = `${h.tabs ? '-' : ''}${h.delim}`
401  if ((missing.get(key) ?? Number.POSITIVE_INFINITY) <= from) return null
402  let p = from
403  while (p <= s.length) {
404    const nl = s.indexOf('\n', p)
405    const line = s.slice(p, nl < 0 ? s.length : nl)
406    if ((h.tabs ? line.replace(/^\t+/, '') : line) === h.delim) {
407      return { body: s.slice(from, p), after: nl < 0 ? s.length : nl + 1 }
408    }
409    if (nl < 0) break
410    p = nl + 1
411  }
412  missing.set(key, from)
413  return null
414}
415
416const HEREDOC_OP = /^<<(-?)[ \t]*(?:'([^'\n]*)'|"([^"\n]*)"|\\?([A-Za-z_][A-Za-z0-9_]*))/
417
418/**
419 * One pass over `s`. Comments (an unquoted `#` that starts a word) go up to
420 * the end of their line. A heredoc's body is replaced by what matters in it:
421 * the commands, when a shell reads it (`bash <<EOF`, `cat <<EOF | sh`); the
422 * `$(...)` it expands, when its delimiter is unquoted; nothing otherwise
423 * (the text, when SQL reads it, goes to `texts`). A heredoc whose delimiter
424 * never comes is left as code. `open` is where quotes that never close
425 * started.
426 */
427function scan(s: string, neutral: Set<number>): Sanitized & { open: number[] | null } {
428  let out = ''
429  const texts: string[] = []
430  const stack: Ctx[] = [{ t: 'code', kind: 'top', depth: 0, cmdStart: 0, arith: false }]
431  let pending: Heredoc[] = []
432  const missing = new Map<string, number>()
433  // How many $(( )) are open: no heredocs inside arithmetic (`$((x<<y))`)
434  let arith = 0
435  let i = 0
436  const n = s.length
437  const openSubst = () => {
438    const isArith = s.charAt(i + 2) === '('
439    if (isArith) arith++
440    stack.push({ t: 'code', kind: 'subst', depth: 0, cmdStart: out.length + 2, arith: isArith })
441    out += '$('
442    i += 2
443  }
444  while (i < n) {
445    const c = s.charAt(i)
446    const next = s.charAt(i + 1)
447    const top = stack[stack.length - 1] as Ctx
448    if (top.t === 'dq') {
449      if (c === '\\') {
450        out += c + next
451        i += 2
452      } else if (c === '"' && !neutral.has(i)) {
453        stack.pop()
454        out += c
455        i++
456      } else if (c === '$' && next === '(') {
457        openSubst()
458      } else if (c === '`') {
459        stack.push({ t: 'code', kind: 'bt', depth: 0, cmdStart: out.length + 1, arith: false })
460        out += c
461        i++
462      } else {
463        out += c
464        i++
465      }
466      continue
467    }
468    if (c === '\\') {
469      out += c + next
470      i += 2
471      continue
472    }
473    if (neutral.has(i)) {
474      // A quote that never closes is read as a literal character
475      out += `\\${c}`
476      i++
477      continue
478    }
479    if (c === "'") {
480      const j = s.indexOf("'", i + 1)
481      if (j < 0) return { code: out, texts, open: [i] }
482      out += s.slice(i, j + 1)
483      i = j + 1
484      continue
485    }
486    if (c === '$' && next === "'" && !neutral.has(i + 1)) {
487      let j = i + 2
488      while (j < n && s.charAt(j) !== "'") j += s.charAt(j) === '\\' ? 2 : 1
489      if (j >= n) return { code: out, texts, open: [i + 1] }
490      out += s.slice(i, j + 1)
491      i = j + 1
492      continue
493    }
494    if (c === '"') {
495      stack.push({ t: 'dq', at: i })
496      out += c
497      i++
498      continue
499    }
500    if (c === '`') {
501      if (top.kind === 'bt') stack.pop()
502      else stack.push({ t: 'code', kind: 'bt', depth: 0, cmdStart: out.length + 1, arith: false })
503      out += c
504      i++
505      continue
506    }
507    if (c === '$' && next === '(') {
508      openSubst()
509      continue
510    }
511    if (c === '(') {
512      top.depth++
513      out += c
514      i++
515      continue
516    }
517    if (c === ')') {
518      if (top.kind === 'subst' && top.depth === 0) {
519        stack.pop()
520        if (top.arith) arith--
521      } else top.depth = Math.max(0, top.depth - 1)
522      out += c
523      i++
524      continue
525    }
526    if (c === '#' && (i === 0 || /[\s;&|()]/.test(s.charAt(i - 1)))) {
527      const nl = s.indexOf('\n', i)
528      i = nl < 0 ? n : nl
529      continue
530    }
531    if (c === '<' && next === '<' && s.charAt(i + 2) !== '<' && arith === 0) {
532      const m = HEREDOC_OP.exec(s.slice(i, i + 256))
533      if (m) {
534        pending.push({
535          tabs: m[1] === '-',
536          quoted: m[4] === undefined,
537          delim: m[2] ?? m[3] ?? m[4] ?? '',
538          cmdStart: top.cmdStart,
539          opAt: out.length,
540          opEnd: out.length + m[0].length,
541        })
542        out += m[0]
543        i += m[0].length
544        continue
545      }
546    }
547    if (c === '\n') {
548      out += c
549      i++
550      const lineStart = out.lastIndexOf('\n', out.length - 2) + 1
551      for (const h of pending) {
552        const found = heredocBody(s, i, h, missing)
553        if (!found) continue
554        const consumer = lex(out.slice(Math.max(h.cmdStart, lineStart), h.opAt)).words
555        const prog = findProgram(consumer)
556        const name = base(consumer[prog.idx] ?? '')
557        const rest = out.slice(h.opEnd, out.length - 1)
558        const shell =
559          (SHELLS.has(name) && shellReadsStdin(consumer.slice(prog.idx + 1))) ||
560          /\|\s*(?:sudo\s+)?(?:\/\S*\/)?(?:ba|z|da|k)?sh\b(?!\s+-[A-Za-z]*c)/.test(rest)
561        if (shell) {
562          out += `${sanitize(found.body).code}\n`
563        } else {
564          if (!h.quoted) for (const sub of substitutions(found.body, true)) out += `$(${sub})\n`
565          if (SQL_CLIENT.test(out.slice(h.cmdStart, out.length)) || rest.includes('|')) texts.push(found.body)
566        }
567        i = found.after
568      }
569      pending = []
570      top.cmdStart = out.length
571      continue
572    }
573    if (c === ';' || c === '&' || c === '|') top.cmdStart = out.length + 1
574    out += c
575    i++
576  }
577  const open = stack.flatMap(x => (x.t === 'dq' ? [x.at] : []))
578  return { code: out, texts, open: open.length ? open : null }
579}
580
581/**
582 * The command with comments and heredoc bodies taken out (see scan). A quote
583 * that never closes would hide everything after it, so it is read as a
584 * literal character and the command scanned again. Past 32 tries the
585 * command is returned whole, nothing taken out.
586 */
587export function sanitize(command: string): Sanitized {
588  const neutral = new Set<number>()
589  for (let tries = 0; tries < 32; tries++) {
590    const r = scan(command, neutral)
591    if (r.open === null) return { code: r.code, texts: r.texts }
592    for (const at of r.open) neutral.add(at)
593  }
594  return { code: command, texts: [] }
595}
596
597/** How many words a wrapper's option at `tokens[i]` uses: itself, plus its value when separate. */
598function optionWidth(spec: { short: string; long: string[] }, t: string): number {
599  if (t.startsWith('--')) return spec.long.includes(t) ? 2 : 1
600  // A cluster (`-iu root`): the first value-taking letter takes the rest of the word, or the next word.
601  for (let k = 1; k < t.length; k++) {
602    if (spec.short.includes(t.charAt(k))) return k === t.length - 1 ? 2 : 1
603  }
604  return 1
605}
606
607type Program = { idx: number; payloads: string[]; chdir?: string; via: string[] }
608
609// Wrapper options that change the directory the program runs in.
610const CHDIR: Record<string, { short: string; long: string }> = {
611  env: { short: '-C', long: '--chdir' },
612  sudo: { short: '-D', long: '--chdir' },
613}
614
615function chdirOf(name: string, a: string, next: string | undefined): string | undefined {
616  const c = CHDIR[name]
617  if (!c) return undefined
618  if (a === c.short || a === c.long) return next
619  if (a.startsWith(`${c.long}=`)) return a.slice(c.long.length + 1)
620  if (a.startsWith(c.short) && a.length > 2) return a.slice(2)
621  return undefined
622}
623
624/**
625 * Index of the program word, skipping shell keywords, wrappers, VAR=x
626 * assignments and wrapper options with their values. `env -S '...'` and
627 * `watch ...` hand back their command as a payload to classify on its own.
628 */
629function findProgram(tokens: string[]): Program {
630  const payloads: string[] = []
631  const via: string[] = []
632  let chdir: string | undefined
633  let i = 0
634  while (i < tokens.length) {
635    const t = stripOpen(tokens[i] ?? '')
636    if (t === '' || KEYWORDS.has(t) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
637      i++
638      continue
639    }
640    const name = base(t)
641    const spec = WRAPPERS[name]
642    if (!spec) break
643    via.push(name)
644    i++
645    let positional = WRAPPER_POSITIONAL.has(name)
646    while (i < tokens.length) {
647      const a = tokens[i] ?? ''
648      if (a === '--') {
649        i++
650        break
651      }
652      if (a.startsWith('-') && a.length > 1) {
653        const single = SINGLE_DASH[name]
654        const w = single && !a.startsWith('--') ? (single.includes(a) ? 2 : 1) : optionWidth(spec, a)
655        const dir = chdirOf(name, a, tokens[i + 1])
656        if (dir !== undefined) chdir = dir
657        if (name === 'env' && (a === '-S' || a === '--split-string') && tokens[i + 1] !== undefined) {
658          payloads.push(tokens[i + 1] ?? '')
659        } else if (name === 'env' && (a.startsWith('-S') || a.startsWith('--split-string=')) && a.length > 2) {
660          payloads.push(a.startsWith('-S') ? a.slice(2) : a.slice('--split-string='.length))
661        }
662        i += w
663        continue
664      }
665      if (name === 'env' && /^[A-Za-z_][A-Za-z0-9_]*=/.test(a)) {
666        i++
667        continue
668      }
669      if (positional) {
670        positional = false
671        i++
672        continue
673      }
674      break
675    }
676    if (name === 'watch') {
677      payloads.push(tokens.slice(i).join(' '))
678      i = tokens.length
679    }
680  }
681  return { idx: i, payloads, via, ...(chdir !== undefined ? { chdir } : {}) }
682}
683
684/** Is `a` a cluster of short options (`-uf`) that holds `ch`? */
685export const cluster = (a: string, ch: string) => /^-[A-Za-z]+$/.test(a) && a.includes(ch)
686
687const hasShortFlag = (args: string[], chars: string) =>
688  args.some(a => /^-[A-Za-z]+$/.test(a) && [...chars].some(ch => a.includes(ch)))
689
690type GitCall = { sub: string | undefined; subArgs: string[]; dirs: string[]; gitArgs: string[] }
691
692/** Splits `git <globals> <sub> <args>`, collecting -C dirs and --git-dir/--work-tree. */
693export function parseGit(args: string[]): GitCall {
694  const dirs: string[] = []
695  const gitArgs: string[] = []
696  let i = 0
697  while (i < args.length) {
698    const a = args[i] ?? ''
699    if (!a.startsWith('-')) break
700    if (GIT_VALUE_OPTS.has(a)) {
701      const v = args[i + 1] ?? ''
702      if (a === '-C') dirs.push(v)
703      else if (a === '--git-dir' || a === '--work-tree') gitArgs.push(a, v)
704      i += 2
705      continue
706    }
707    if (a.startsWith('--git-dir=') || a.startsWith('--work-tree=')) gitArgs.push(a)
708    i++
709  }
710  return { sub: args[i], subArgs: args.slice(i + 1), dirs, gitArgs }
711}
712
713export type CleanOpts = { force: number; dry: boolean; letters: string[]; excludes: string[]; paths: string[] }
714
715/** `git clean`'s options as git reads them: clusters, `-e` taking a value (attached or next), long prefixes. */
716export function parseClean(args: string[]): CleanOpts {
717  let force = 0
718  let dry = false
719  const letters: string[] = []
720  const excludes: string[] = []
721  const paths: string[] = []
722  for (let i = 0; i < args.length; i++) {
723    const a = args[i] ?? ''
724    if (a === '--') {
725      paths.push(...args.slice(i + 1))
726      break
727    }
728    if (a.startsWith('--')) {
729      const eq = a.indexOf('=')
730      const name = eq < 0 ? a : a.slice(0, eq)
731      if (isLong(name, '--force')) force++
732      else if (isLong(name, '--dry-run')) dry = true
733      else if (isLong(name, '--exclude')) excludes.push(eq < 0 ? (args[++i] ?? '') : a.slice(eq + 1))
734      continue
735    }
736    if (a.startsWith('-') && a.length > 1) {
737      for (let k = 1; k < a.length; k++) {
738        const ch = a.charAt(k)
739        if (ch === 'e') {
740          excludes.push(k + 1 < a.length ? a.slice(k + 1) : (args[++i] ?? ''))
741          break
742        }
743        if (ch === 'f') force++
744        else if (ch === 'n') dry = true
745        else if ('dxX'.includes(ch) && !letters.includes(ch)) letters.push(ch)
746      }
747      continue
748    }
749    paths.push(a)
750  }
751  return { force, dry, letters, excludes, paths }
752}
753
754// Pathspecs that cover the whole working tree
755const WHOLE_TREE = new Set(['.', './', ':/', ':/.', ':(top)', '*', './*', ':/*'])
756
757/**
758 * Does this `git checkout|restore|switch` throw away uncommitted work: -f, or
759 * (checkout, restore without --staged alone) a pathspec covering the whole tree?
760 */
761function discards(sub: string, sa: string[]): boolean {
762  // short options that take a value, per subcommand
763  const valued = sub === 'restore' ? 's' : sub === 'switch' ? 'cC' : 'bB'
764  let force = false
765  let staged = false
766  let worktree = false
767  const pos: string[] = []
768  for (let i = 0; i < sa.length; i++) {
769    const a = sa[i] ?? ''
770    if (a === '--') {
771      pos.push(...sa.slice(i + 1))
772      break
773    }
774    if (a.startsWith('--')) {
775      const name = a.split('=')[0] ?? a
776      if (isLong(name, '--force') || (sub === 'switch' && isLong(name, '--discard-changes'))) force = true
777      else if (isLong(name, '--staged')) staged = true
778      else if (isLong(name, '--worktree')) worktree = true
779      else if (!a.includes('=') && ['--source', '--orphan', '--create', '--force-create'].includes(name)) i++
780      continue
781    }
782    if (a.startsWith('-') && a.length > 1) {
783      for (let k = 1; k < a.length; k++) {
784        const ch = a.charAt(k)
785        if (valued.includes(ch)) {
786          if (k + 1 === a.length) i++
787          break
788        }
789        if (ch === 'f') force = true
790        else if (ch === 'S') staged = true
791        else if (ch === 'W') worktree = true
792      }
793      continue
794    }
795    pos.push(a)
796  }
797  if (sub === 'switch') return force
798  if (sub === 'checkout' && force) return true
799  const whole = pos.some(p => WHOLE_TREE.has(p))
800  return sub === 'restore' ? whole && (worktree || !staged) : whole
801}
802
803/** ssh's remote host and command: options with values skipped, the rest after the host joined as ssh does. */
804function sshCommand(args: string[]): { host: string; command: string } | null {
805  const valued = 'BbcDEeFIiJLlmOoPpQRSWw'
806  for (let i = 0; i < args.length; i++) {
807    const a = args[i] ?? ''
808    if (a === '--') {
809      const host = args[i + 1]
810      return host === undefined ? null : { host, command: args.slice(i + 2).join(' ') }
811    }
812    if (a.startsWith('-') && a.length > 1) {
813      for (let k = 1; k < a.length; k++) {
814        if (valued.includes(a.charAt(k))) {
815          if (k + 1 === a.length) i++
816          break
817        }
818      }
819      continue
820    }
821    return { host: a, command: args.slice(i + 1).join(' ') }
822  }
823  return null
824}
825
826/** `baseDir` joined with `dir`, without resolving `..` (the shell does that). */
827export function joinPath(baseDir: string | undefined, dir: string): string {
828  if (baseDir === '?' || /[$`*?[\]{}]/.test(dir)) return '?'
829  if (baseDir === undefined || dir.startsWith('/') || dir === '~' || dir.startsWith('~/')) return dir
830  return `${baseDir.replace(/\/+$/, '')}/${dir}`
831}
832
833const RM_LIKE = new Set(['rm', 'unlink', 'shred', 'srm', 'trash'])
834
835/**
836 * find's words with -delete and any `-exec rm ... ;|+` taken out, or null when
837 * another action would run. `shells`: `-exec sh -c '...' ... ;|+` is taken out too.
838 */
839export function findPreviewArgs(args: string[], shells = false): string[] | null {
840  const out: string[] = []
841  for (let i = 0; i < args.length; i++) {
842    const a = args[i] ?? ''
843    if (a === '-delete') continue
844    if (/^-(exec|execdir|ok|okdir)$/.test(a)) {
845      const prog = base(args[i + 1] ?? '')
846      if (!RM_LIKE.has(prog) && !(shells && SHELLS.has(prog))) return null
847      while (i < args.length && args[i] !== ';' && args[i] !== '+') i++
848      continue
849    }
850    if (/^-(fprint|fprint0|fprintf|fls)$/.test(a)) return null
851    out.push(a)
852  }
853  return out
854}
855
856const findDeletes = (args: string[]) =>
857  args.some((a, i) => a === '-delete' || (/^-(exec|execdir|ok|okdir)$/.test(a) && RM_LIKE.has(base(args[i + 1] ?? ''))))
858
859/** The command a shell runs with -c: the first word after the -c cluster that is not an option. */
860function shellPayload(args: string[]): string | undefined {
861  const at = args.findIndex(a => cluster(a, 'c'))
862  return at >= 0 ? args.slice(at + 1).find(a => !a.startsWith('-') && !a.startsWith('+')) : undefined
863}
864
865/** The payloads of find's `-exec sh -c '...' ... ;|+` (and -execdir, -ok, -okdir). */
866function findShellPayloads(args: string[]): string[] {
867  const out: string[] = []
868  for (let i = 0; i < args.length; i++) {
869    if (!/^-(exec|execdir|ok|okdir)$/.test(args[i] ?? '') || !SHELLS.has(base(args[i + 1] ?? ''))) continue
870    let end = i + 2
871    while (end < args.length && args[end] !== ';' && args[end] !== '+') end++
872    const payload = shellPayload(args.slice(i + 2, end))
873    if (payload !== undefined) out.push(payload)
874    i = end
875  }
876  return out
877}
878
879/** A command's words that are not options or their values (`shred -n 3 a b`: a, b). */
880export function operands(args: string[], spec: { short: string; long: string[] }): string[] {
881  const out: string[] = []
882  for (let i = 0; i < args.length; i++) {
883    const a = args[i] ?? ''
884    if (a === '--') {
885      out.push(...args.slice(i + 1))
886      break
887    }
888    if (a.startsWith('-') && a.length > 1) {
889      i += optionWidth(spec, a) - 1
890      continue
891    }
892    out.push(a)
893  }
894  return out
895}
896
897export const SHRED_OPTS = { short: 'ns', long: ['--iterations', '--size', '--random-source'] }
898export const TRUNCATE_OPTS = { short: 'sr', long: ['--size', '--reference'] }
899
900// diskutil verbs that erase or repartition (diskutil reads verbs case-insensitively)
901const DISKUTIL_ERASE = /^(erase|zeroDisk|randomDisk|secureErase|partitionDisk|reformat)/i
902// ... and `diskutil apfs eraseVolume|deleteContainer|deleteVolume`
903const DISKUTIL_APFS_ERASE = /^(erase|delete)/i
904
905/** Strips a function definition's head (`f()`, `function f`), so its body reads as commands. */
906const stripFunction = (seg: string) =>
907  seg.replace(/^function\s+[^\s(){}]+(?:\s*\(\s*\))?\s*/, '').replace(/^[A-Za-z_][A-Za-z0-9_.:-]*\s*\(\s*\)\s*/, '')
908
909/** How many `)` in `seg` close a `(` opened before it (quotes skipped). */
910function closesIn(seg: string): number {
911  let depth = 0
912  let closes = 0
913  let q: string | null = null
914  for (let i = 0; i < seg.length; i++) {
915    const c = seg.charAt(i)
916    if (c === '\\') i++
917    else if (q) {
918      if (c === q) q = null
919    } else if (c === '"' || c === "'") q = c
920    else if (c === '(') depth++
921    else if (c === ')') {
922      if (depth > 0) depth--
923      else closes++
924    }
925  }
926  return closes
927}
928
929function classifySegment(segment: string, segCwd: string | undefined, depth: number): Risk[] {
930  const { words: tokens, hereStrings } = lex(segment)
931  const { idx, payloads, chdir, via } = findProgram(tokens)
932  const cwd = chdir !== undefined ? joinPath(segCwd, chdir) : segCwd
933  const out: Risk[] = []
934  for (const p of payloads) out.push(...classifyAt(p, depth + 1, cwd))
935  if (idx >= tokens.length) return out
936  const prog = base(tokens[idx] ?? '')
937  const args = tokens.slice(idx + 1)
938  const push = (kind: RiskKind, a: string[] = args, extra: Partial<Risk> = {}) =>
939    out.push({ kind, segment, args: a, ...(cwd !== undefined ? { cwd } : {}), ...extra })
940
941  if (prog === 'rm') {
942    // xargs rm deletes every path it is fed, recursive or not
943    if (via.includes('xargs')) push('rm', args, { fromXargs: true })
944    else if (hasShortFlag(args, 'rR') || args.includes('--recursive')) push('rm')
945  } else if (prog === 'git') {
946    const g = parseGit(args)
947    let dir = cwd
948    for (const d of g.dirs) dir = joinPath(dir, d)
949    const extra: Partial<Risk> = {
950      ...(dir !== undefined ? { cwd: dir } : {}),
951      ...(g.gitArgs.length ? { gitArgs: g.gitArgs } : {}),
952    }
953    const sa = g.subArgs
954    if (g.sub === 'reset' && sa.some(a => isLong(a, '--hard'))) push('git-reset-hard', sa, extra)
955    else if (g.sub === 'push') {
956      if (
957        // --force-with-lease and --force-if-includes refuse to clobber remote commits you have not seen, so they are not flagged.
958        sa.some(a => isLong(a, '--force')) ||
959        sa.some(a => cluster(a, 'f')) ||
960        sa.some(a => a.startsWith('+') && a.length > 1)
961      )
962        push('git-push-force', sa, extra)
963      if (
964        sa.some(a => isLong(a, '--delete') || isLong(a, '--mirror') || isLong(a, '--prune')) ||
965        sa.some(a => cluster(a, 'd')) ||
966        sa.some(a => a.startsWith(':') && a.length > 1)
967      )
968        push('git-push-delete', sa, extra)
969    } else if (g.sub === 'clean') {
970      // Not just with -f: `-c clean.requireForce=false` (or that setting in a config) deletes
971      // without it. -i is no exemption either: a pipe can answer its menu.
972      if (!parseClean(sa).dry) push('git-clean', sa, extra)
973    } else if ((g.sub === 'checkout' || g.sub === 'restore' || g.sub === 'switch') && discards(g.sub, sa)) {
974      push('git-discard', sa, extra)
975    } else if (g.sub === 'stash' && sa[0] === 'clear') push('git-stash-clear', sa, extra)
976    else if (g.sub === 'worktree' && sa[0] === 'remove' && sa.slice(1).some(a => isLong(a, '--force') || cluster(a, 'f'))) {
977      push('git-worktree-force', sa, extra)
978    }
979  } else if (prog === 'stow' || prog === 'bestow') {
980    if (args.includes('--adopt')) push('adopt')
981  } else if (prog === 'chmod' || prog === 'chown') {
982    if (hasShortFlag(args, 'R') || args.includes('--recursive')) push('chmod-r')
983  } else if (prog === 'dd') {
984    push('dd')
985  } else if (prog === 'mkfs' || prog.startsWith('mkfs.') || prog === 'newfs' || prog.startsWith('newfs_')) {
986    push('mkfs')
987  } else if (prog === 'diskutil') {
988    const verb = args[0] ?? ''
989    if (DISKUTIL_ERASE.test(verb) || (/^(apfs|ap)$/i.test(verb) && DISKUTIL_APFS_ERASE.test(args[1] ?? ''))) push('mkfs')
990  } else if (prog === 'shred' || prog === 'gshred') {
991    push('shred')
992  } else if (prog === 'truncate' || prog === 'gtruncate') {
993    push('truncate')
994  } else if (prog === 'fd' || prog === 'fdfind') {
995    // fd -x/-X rm deletes every match, like xargs rm
996    const at = args.findIndex(a => a === '-x' || a === '-X' || a === '--exec' || a === '--exec-batch')
997    if (at >= 0 && base(args[at + 1] ?? '') === 'rm') push('rm', args.slice(at + 2), { fromXargs: true })
998  } else if (prog === 'find') {
999    if (findDeletes(args)) push('find-delete')
1000    // find -exec sh -c 'rm -rf "$1"' _ {} \;: the payload runs on each match, where find runs
1001    for (const payload of findShellPayloads(args)) {
1002      for (const r of classifyAt(payload, depth + 1, cwd)) {
1003        if (r.kind === 'nested' || r.kind === 'sql' || r.remote !== undefined) {
1004          out.push(r)
1005          continue
1006        }
1007        const { cwd: _cwd, gitArgs: _g, ...rest } = r
1008        out.push({ ...rest, findArgs: args, ...(cwd !== undefined ? { cwd } : {}) })
1009      }
1010    }
1011  } else if (prog === 'rsync') {
1012    if (args.some(a => a === '--del' || a.startsWith('--delete'))) push('rsync-delete')
1013  } else if (SHELLS.has(prog)) {
1014    // bash -c 'payload' (also -lc, -ec): the payload is the first word after the flag that is not an option
1015    const payload = shellPayload(args)
1016    if (payload !== undefined) out.push(...classifyAt(payload, depth + 1, cwd))
1017    // bash <<< 'payload', sh -s <<< 'payload'
1018    if (shellReadsStdin(args)) for (const h of hereStrings) out.push(...classifyAt(h, depth + 1, cwd))
1019  } else if (prog === 'eval') {
1020    out.push(...classifyAt(args.join(' '), depth + 1, cwd))
1021  } else if (prog === 'ssh') {
1022    const remote = sshCommand(args)
1023    if (remote?.command) {
1024      for (const r of classifyAt(remote.command, depth + 1, undefined)) {
1025        const { cwd: _cwd, gitArgs: _g, ...rest } = r
1026        out.push({ ...rest, remote: remote.host })
1027      }
1028    }
1029  }
1030  return out
1031}
1032
1033/** What `echo ...` or `printf ...` prints, roughly, for a pipe into a shell. */
1034function printed(segment: string): string | undefined {
1035  const tokens = tokenize(segment)
1036  const { idx } = findProgram(tokens)
1037  const prog = base(tokens[idx] ?? '')
1038  if (prog !== 'echo' && prog !== 'printf') return undefined
1039  let args = tokens.slice(idx + 1)
1040  if (prog === 'echo') while (args[0] !== undefined && /^-[neE]+$/.test(args[0])) args = args.slice(1)
1041  return args.join(' ')
1042}
1043
1044/** Is this segment a shell reading its commands from stdin? */
1045function isStdinShell(segment: string): boolean {
1046  const tokens = tokenize(segment)
1047  const { idx } = findProgram(tokens)
1048  return SHELLS.has(base(tokens[idx] ?? '')) && shellReadsStdin(tokens.slice(idx + 1))
1049}
1050
1051/** Is this segment `git ... commit|tag|merge ...`? */
1052function isGitMessageSegment(segment: string): boolean {
1053  const tokens = tokenize(segment)
1054  const { idx } = findProgram(tokens)
1055  if (base(tokens[idx] ?? '') !== 'git') return false
1056  const sub = parseGit(tokens.slice(idx + 1)).sub
1057  return sub === 'commit' || sub === 'tag' || sub === 'merge'
1058}
1059
1060const MSG_OPT =
1061  /(^|\s)(-[A-Za-z]*[mF]|--message|--file)(=|\s+|(?=["']))("(?:[^"\\]|\\[\s\S])*"|'[^']*'|[^\s"']+)/g
1062
1063/**
1064 * The command with git commit/tag message values emptied, for the rm and SQL
1065 * text checks: `git commit -m "never rm -rf the cache"` is not a delete.
1066 * Substitutions in a message still run, so they are kept.
1067 */
1068export function scrubMessages(command: string): string {
1069  return splitWithSeps(command)
1070    .map(p => {
1071      if (!isGitMessageSegment(p.text)) return p.text + p.sep
1072      const text = p.text.replace(MSG_OPT, (_w, pre: string, opt: string, eq: string, value: string) => {
1073        const subs = value.startsWith("'") ? [] : substitutions(value)
1074        return `${pre}${opt}${eq}''${subs.map(s => ` $(${s})`).join('')}`
1075      })
1076      return text + p.sep
1077    })
1078    .join('')
1079}
1080
1081/**
1082 * Past MAX_DEPTH nothing is parsed, but a destructive-looking word still
1083 * asks: cheap tests, each linear, so a deep payload cannot slip through.
1084 */
1085function looksDestructive(text: string): boolean {
1086  return (
1087    /\brm\s+(?:-[A-Za-z]*[rR]|--recursive)/.test(text) ||
1088    (/\bgit\b/.test(text) && /\b(?:push|reset|clean|checkout|restore|switch|stash|worktree)\b/.test(text)) ||
1089    (/\bfind\b/.test(text) && /-(?:delete|exec)\b/.test(text)) ||
1090    /\bfd(?:find)?\b[^\n]{0,200}\s(?:-[xX]|--exec(?:-batch)?)\s+(?:\S*\/)?rm\b/.test(text) ||
1091    /\brsync\b[^\n]{0,200}--del/.test(text) ||
1092    /\b(?:dd|mkfs(?:\.\w+)?|newfs(?:_\w+)?|g?shred)\b/.test(text) ||
1093    /\bg?truncate\s+-/.test(text) ||
1094    /\bdiskutil\s+(?:ap(?:fs)?\s+)?(?:erase|zeroDisk|randomDisk|secureErase|partitionDisk|reformat|delete)/i.test(text) ||
1095    /\bch(?:mod|own)\s+-[A-Za-z]*R/.test(text) ||
1096    /--adopt\b/.test(text) ||
1097    SQL_DESTRUCTIVE.test(text) ||
1098    MIGRATE.test(text)
1099  )
1100}
1101
1102const keyOf = (r: Risk) => `${r.kind}\0${r.args.join('\0')}\0${r.cwd ?? ''}\0${r.remote ?? ''}`
1103
1104function classifyAt(command: string, depth: number, baseCwd: string | undefined): Risk[] {
1105  if (depth > MAX_DEPTH) {
1106    return looksDestructive(command) ? [{ kind: 'nested', segment: command, args: [] }] : []
1107  }
1108  const { code: text, texts } = sanitize(command)
1109  const risks: Risk[] = []
1110  let cwd = baseCwd
1111  // A `(` subshell keeps its `cd` to itself: the directory comes back at its `)`
1112  const saved: (string | undefined)[] = []
1113  const pieces = splitWithSeps(text)
1114  let inCase = 0
1115  for (let p = 0; p < pieces.length; p++) {
1116    const piece = pieces[p] as Piece
1117    let seg = piece.text.trim()
1118    // case x in  pattern) cmd ;;  esac: the labels are not commands
1119    if (/^case\s/.test(seg)) {
1120      inCase++
1121      seg = seg.replace(/^case\s+\S+\s+in\b\s*/, '')
1122    }
1123    if (inCase > 0) {
1124      if (/^esac\b/.test(seg)) {
1125        inCase--
1126        seg = seg.replace(/^esac\b\s*/, '')
1127      }
1128      seg = seg.replace(/^\(?[^\s()'"`;|&<>]+\)\s*/, '')
1129    }
1130    seg = stripFunction(seg)
1131    if (!seg) continue
1132    for (let k = /^\(+/.exec(seg)?.[0].length ?? 0; k > 0; k--) saved.push(cwd)
1133    const tokens = tokenize(seg)
1134    const { idx } = findProgram(tokens)
1135    const prog = base(tokens[idx] ?? '')
1136    if (prog === 'cd' || prog === 'pushd') {
1137      const rest = tokens.slice(idx + 1)
1138      const dir = rest.find(a => !a.startsWith('-'))
1139      cwd = rest.includes('-') ? '?' : dir === undefined ? '~' : joinPath(cwd, dir)
1140    } else {
1141      risks.push(...classifySegment(seg, cwd, depth))
1142    }
1143    // echo '...' | bash: what is printed is run
1144    const nextPiece = pieces[p + 1]
1145    if (piece.sep === '|' && nextPiece && isStdinShell(nextPiece.text.trim())) {
1146      const payload = printed(seg)
1147      if (payload !== undefined) risks.push(...classifyAt(payload, depth + 1, cwd))
1148    }
1149    for (let k = closesIn(seg); k > 0 && saved.length > 0; k--) cwd = saved.pop()
1150  }
1151  for (const inner of substitutions(text)) risks.push(...classifyAt(inner, depth + 1, cwd))
1152
1153  const plain = scrubMessages(text)
1154  const data = texts.join('\n')
1155  if (SQL_DESTRUCTIVE.test(plain) || MIGRATE.test(plain) || SQL_DESTRUCTIVE.test(data) || MIGRATE.test(data)) {
1156    risks.push({ kind: 'sql', segment: command, args: [] })
1157  }
1158
1159  // Fallback for forms the tokenizer misses (rm inside quotes); find -exec rm is already find-delete
1160  if (!risks.some(r => r.kind === 'rm' || r.kind === 'find-delete') && RM_FALLBACK.test(plain)) {
1161    risks.push({ kind: 'rm', segment: command, args: [] })
1162  }
1163
1164  const seen = new Set<string>()
1165  return risks.filter(r => {
1166    const k = keyOf(r)
1167    if (seen.has(k)) return false
1168    seen.add(k)
1169    return true
1170  })
1171}
1172
1173export function classify(command: string): Risk[] {
1174  const risks = classifyAt(command, 0, undefined)
1175  // One sql entry, and one nested one, is enough, whichever level found it
1176  const sql = risks.findIndex(r => r.kind === 'sql')
1177  const nested = risks.findIndex(r => r.kind === 'nested')
1178  return risks.filter((r, i) => (r.kind !== 'sql' || i === sql) && (r.kind !== 'nested' || i === nested))
1179}
1180
1181/**
1182 * `git clean -n` with what changes what goes: -d, -x, -X, a second -f
1183 * (nested repositories), -e and the pathspecs. -i and -q are dropped.
1184 */
1185export function cleanDryRun(args: string[]): string[] {
1186  const c = parseClean(args)
1187  const out = ['clean', '-n']
1188  const cluster = `${c.force >= 2 ? 'ff' : ''}${c.letters.join('')}`
1189  if (cluster) out.push(`-${cluster}`)
1190  for (const e of c.excludes) out.push('-e', e)
1191  if (c.paths.length) out.push('--', ...c.paths)
1192  return out
1193}
1194
1195export const isGlob = (p: string) => /[*?[\]{}]/.test(p)
1196export const rmTargets = (args: string[]): string[] => {
1197  const out: string[] = []
1198  let afterDashes = false
1199  for (const a of args) {
1200    if (!afterDashes && a === '--') afterDashes = true