SLOPSHOPPER

afa-mods

Hub band, Token Weather and Blast Radius for Claude Code sessions.

bandguardpromptprocesstimer
v0.3.6no licenseupdated 2026-10-26TortoiseWolfe/Claude_Commandz/mods/afa-mods
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · afa-mods
› 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 afa-mods: Blast Radius: refused at the prompt. The command did not run. ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM Weather: showers 49% ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Weather: showers 49%
README

afa-mods

Three Claude Code mods in one plugin (Claude Code 2.1.296, early-access function hooks). No network calls. The only writes go to ~/.claude/state/mods/.

What they do

Hub band. In a session started in ~/repos, one line above the prompt: /prep not run until /prep has run in the session, then open lanes (rows of ~/.claude/state/lanes/index.tsv from the last 3 days whose report is missing or whose out.log has no exit line), unticked items in ~/.claude/state/hub-inbox.md, and Client mail: N new (unticked lines containing Client mail: or Client alert:). Counts are read from those private files at run time and refreshed every 5 seconds.

Token Weather. From the context percent: clear under 40%, showers 40-60%, storm past 60%. It adds "hand off and end" past 60% in ~/repos (the hub rule) and past 80% everywhere. Shown on the same line above the prompt.

Blast Radius. A safety net on Bash. It holds rm -rf, docker system|volume|image prune, docker compose down -v, docker volume rm, git push --force / -f, and production deploys (--prod, or redeploy aimed at production), plus tmux kill-server on the default server and tmux kill-session targeting the shared lanes session. These tmux holds explain that the command closes every lane window (the tmux session lanes), with no undo; a default-server kill-server also closes every other session and window there. Private tmux sockets and individual kill-window commands are not held. Interactively it lists what the command would touch and asks 1 - Run it / 2 - Refuse. In a non-interactive session (claude -p, the Console lanes) it never waits: force pushes and production deploys are denied with a reason, the rest are allowed, and each verdict is appended to ~/.claude/state/mods/blast-radius.log. Regenerable caches and paths strictly inside /tmp, $TMPDIR, or an individual lane's scratch area are allowed without a prompt and logged as allowed (own scratch). That includes a path built from variables the command sets itself (S=/tmp/x; P=$S/prof; rm -rf $P) and a relative one after a literal cd /full/path && that starts a list (cd /tmp/x && rm -rf b481); the log shows the full path. A cd followed by ;, ||, a pipe, & or a subshell proves nothing (if it fails the rm runs elsewhere), a variable nothing set or set empty still collapses to nothing, and a path that climbs out with .. is judged where it lands. A lane the dispatcher started (AFA_LANE_UNATTENDED=1, set by lane.sh) never waits either: a delete inside its own folder, a worktree or its scratchpad, by a full path, runs and is logged as allowed (lane folder); anything else held is refused with a plain reason the lane can act on. Every lane lane.sh starts sets AFA_LANE=1 (the hub does not). In such a lane two holds whose fix can be named are not a dialog: a relative rm -rf (the refusal says to write the full absolute path, cd /a/b && rm -rf c becoming rm -rf /a/b/c) and a docker run without limits (it names both fixes, timeout <secs> docker run --cpus <n> --memory <m> ... or ~/.claude/scripts/docker-heavy.sh -- docker ...). The lane corrects the command and runs it again; the log shows denied (fix named). Every other hold keeps the dialog, and the hub always does. The text of a python, node or cat heredoc is not shell, so its parentheses no longer hide a cd from the check above. A read-only production proof is not held as a deploy (rexec.sh --prod 'drush status', composer audit, a SELECT, a curl GET). The hook reads the forwarder script itself (small files only; every line must be on an allowlist, exactly one container_exec, and the repo's own source scripts/portainer-deploy.sh is the only file it may source) and each remote command (prodread.ts), and only at the top level of the command: before the call only plain assignments (never PATH, HOME, BASH_ENV and the like) or cd /abs/path joined by ;, newline or &&, then the call, then optionally 2>&1, then optionally one pipe to tail or head with a number. Anything else, a write, an unreadable or missing script, a second command, &, tee or bash -c, is held as before (hub: dialog; unattended lane: deny). Further rules (senior review of #94): a . or .. part anywhere in the script path (a symlink is followed before .. folds); a forwarder whose first line is a shebang other than #!/usr/bin/env bash or #!/bin/bash; any character in the command or the forwarder other than printable ASCII, tab or newline (bash keeps CR and no-break space that JavaScript trims); and a portainer-deploy.sh whose SHA-256 is not in DEPLOY_PINS (prodread.ts). The pin list changes only by a reviewed PR, and must change whenever a repo's scripts/portainer-deploy.sh does. The pin is per repo folder (only Chattanooga-Digital counts; Eduity's script has no source guard and defines neither find_service_container nor container_exec), the forwarder must have exactly one cd line and no indented line, and the deploy path comes from that same line. The pinned script exports every key of the repo's dotenv file, so the hook reads that file's key NAMES only (values are dropped as it reads; nothing is shown or logged) and holds unless every key is on DEPLOY_ENV_KEYS (an allowlist: no PYTHON*, LD_*, BASH_ENV, PATH, *_OVERRIDE and the like). Values of allowed keys are not checked. python3 mods/afa-mods/scripts/check-pins.py checks the pins and the key list against the real files on this machine (the plugin tests have no real filesystem); run it after a deploy script or the dotenv file changes, and expect it to fail loudly when proofs have gone back to held. hostname NAME is not a read. Known limits: a curl GET can still change state on some endpoints, the file can change between the hook's read and the run, and with sh in front the forwarder's source line fails. #!/usr/bin/env bash, the forwarder and the deploy script find timeout, bash, python3 and curl through PATH, so a lane-writable folder early in PATH (for example ~/.local/bin) defeats the check. The question and every refusal (the lane refusals, the non-interactive denial, and the guard-failure denial too) say in words what the command does, why it was held, and what it would touch: each path with (dir, N bytes, ...), (file, N bytes) or (not found); the branch and remote host of a force push (never a token); the stopped containers, unused volumes, images and disk use of a prune; the volumes of a compose stack; the service of a deploy. When the words cannot say, the line reads can't tell what this touches: <why>; it is never empty and never a code fragment. The lines are built in src/touches.ts; HELD_KINDS in src/lib.ts lists every rule, and src/touches.test.ts fails if a rule has no description or a sample command gives no targets. An rm -rf inside docker run or docker compose run is read through the container's -v, --volume and --mount flags (src/lib.ts, mapRmTargets). A path under a Docker volume (a named one, an anonymous one, tmpfs) is not a host deletion and is not held; the volume's own data is outside this check, so an rm of a volume that holds a database is not held either. A path under a host folder is shown as that folder ("/w is ~/repos/.worktrees/App--x on this machine") and judged like a host rm of it: held, unless it is own scratch, and a lane nobody watches may do it only inside its own folder or a worktree. A mount of ~, $HOME or ~/repos therefore still holds. The source resolves through ~, $HOME, variables the command sets to a plain path, and $PWD after a plain cd /full/path (not after a subshell or pushd). A source that does not resolve ($X, $(pwd), backticks) still holds and the question names the mount. A path no mount covers, a climb out of a mount with .., and a relative path still hold. Only the options before the image are read, so a -v in the container's own arguments is not a mount. When the list may be incomplete (compose run, --volumes-from, a flag not read) a path no mount covers is held, not assumed to be the container's own scratch. A named volume that docker volume inspect reports as bound to a host folder is judged as that folder; one docker cannot answer for (daemon down, timeout, or a volume it does not know yet, which the same command may make) is held, and every named volume is asked about, with no cap. A quote left in an option word, or an image word that is not plausible, also marks the list incomplete, and a source that is not a legal volume name is judged as a folder. docker exec has no mounts to read and is unchanged. A docker run or docker compose run (also podman and docker-compose) with no CPU cap and no timeout in front is held with the one-line fix: add --cpus N (and a timeout), as timeout <secs> docker run --cpus <n> --memory <m> ..., or run it through ~/.claude/scripts/docker-heavy.sh -- docker ... (19 Oct: one uncapped run took 14.6 of 16 cores and the machine stopped answering). A cap is --cpus, --cpu-quota or --cpuset-cpus among the options before the image, so a --cpus the container's own program is given does not count, and its value must be a real limit (--cpus 0, --cpu-quota -1 and $X are not). A timeout is timeout [options] DURATION with a positive duration of at most a day (timeout 0 is not one). Either a cap or a timeout in front clears it, except a detached run (-d, --detach), which outlives a timeout and needs a cap. A compose run has no --cpus flag, so its service is read in the compose file the way compose picks it: the -f files in order, else the first default file in the folder (compose.yaml, compose.yml, docker-compose.yaml, docker-compose.yml) plus its override file; the last file that says anything about the service's CPU wins, so cpus: 0 in an override uncaps it. Only a direct cpus, cpu_quota or cpuset key, or deploy.resources.limits.cpus, with a positive number counts; a ${X} value, an include, <<:, extends or !reset does not. The run stays held when it is unclear: a relative path or the default files with no plain cd before them, COMPOSE_FILE (command, environment or the project env file), --env-file, --profile, COMPOSE_PROJECT_DIR, a source, eval or export before the call, a file or service that cannot be read, or a limit set through an anchor or extends. docker-heavy.sh itself, and docker ps, logs, inspect, stats, update and exec, are never held. A lane nobody watches is refused with the fix and runs it again. The classifier judges what the command itself would run: it does not match text inside quoted message text (echo, tmux send-keys, git commit -m), heredoc bodies that only write a file (including git commit -m "$(cat <<'EOF' ...)"), or files a test runner loads (claude plugin test is not a deploy). A word containing / is a path, not a flag: ~/repos/.worktrees/App--prod-lock is not --prod, and --prod must be a whole word. When Jonathan refuses and types a reason under "Type something.", the reason is in the refusal the session reads (only the exact 1 - Run it label runs). sh -c, ssh host "..." and a heredoc fed to bash or piped into a shell are still read. Known tradeoff, asked for by the hub: tmux send-keys text is treated as a message, so a deploy command typed into another window that way is not held here; that window's own guard judges it. If the guard itself throws, the command is denied. The match is best effort (a net, not a shell parser). Existing hooks and permission rules still apply. Changes load only in new claude processes, not in sessions already running.

Install

claude plugin marketplace add TortoiseWolfe/Claude_Commandz
claude plugin install afa-mods@afa-mods --scope user

On this machine the marketplace is the local clone (claude plugin marketplace add ~/repos/Claude_Commandz), so a git pull plus /reload-plugins picks up edits.

Turn it off

claude plugin disable afa-mods     # keep it installed, stop it loading
claude plugin uninstall afa-mods   # remove it

Develop

claude plugin validate mods/afa-mods
claude plugin test mods/afa-mods
Source 5 files
src/index.tsx 358 lines
1import { atom, read, update } from 'claude-code'
2import type { Engine, Register } from 'claude-code'
3
4import {
5  bandText,
6  classify,
7  composeRunsOf,
8  composeServiceLimit,
9  countInbox,
10  explain,
11  hasExitLine,
12  hostRmSegment,
13  laneFix,
14  namedVolumesOf,
15  ownScratchTargets,
16  recentLanes,
17  realPathVerdict,
18  unattendedRmPaths,
19  unattendedRmVerdict,
20  unattendedRoots,
21  weather,
22} from './lib'
23import type { Hold } from './lib'
24import { envKeyLines } from './prodread'
25import { touches } from './touches'
26import type { Probe } from './touches'
27
28const isHub = atom({ plugin: 'afa-mods', key: 'isHub' } as const, false)
29const prepRan = atom({ plugin: 'afa-mods', key: 'prepRan' } as const, false)
30const percent = atom({ plugin: 'afa-mods', key: 'percent' } as const, null)
31const band = atom({ plugin: 'afa-mods', key: 'band' } as const, { lanes: 0, inbox: 0, client: 0 })
32
33const readText = async ($: Engine, path: string) =>
34  (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
35
36// Open lanes, the unticked inbox lines and client lines, read from private
37// files at run time. A file that fails to read counts as nothing.
38async function refreshBand($: Engine) {
39  const home = (await $.env.get('HOME')) ?? ''
40  const state = `${home}/.claude/state`
41  const lanes = recentLanes(
42    await readText($, `${state}/lanes/index.tsv`).catch(() => ''),
43    await $.clock.now(),
44  )
45  let open = 0
46  for (const l of lanes) {
47    const dir = `${state}/lanes/${l.date}-${l.name}`
48    try {
49      const report = l.report !== '-' ? l.report : `${dir}/report.md`
50      if (!(await $.fs.exists(report))) open += 1
51      else if (await $.fs.exists(`${dir}/out.log`)) {
52        if (!hasExitLine(await readText($, `${dir}/out.log`))) open += 1
53      }
54    } catch {
55      // unreadable lane: not counted
56    }
57  }
58  const { inbox, client } = countInbox(await readText($, `${state}/hub-inbox.md`).catch(() => ''))
59  const next = { lanes: open, inbox, client }
60  const prev = await read($, band)
61  if (JSON.stringify(prev) !== JSON.stringify(next)) await update($, band, () => next)
62}
63
64const LOG = '.claude/state/mods/blast-radius.log'
65
66const RUN_IT = '1 - Run it'
67const REFUSE = '2 - Refuse'
68
69// The dialog returns a label, or the text typed under "Other" ("Type something."). Only the exact Run it label runs the
70// command; anything else is a refusal, and a typed reason goes back to the session so it can adjust instead of retrying blind.
71const refusal = (choice: string) => {
72  const base = 'Blast Radius: refused at the prompt. The command did not run.'
73  const reason = choice.trim()
74  return reason === '' || reason === REFUSE
75    ? base
76    : `${base} Jonathan's reason, in his words: "${reason}". Do not resend this command or a reworded copy; change what you are doing or explain it to him in chat.`
77}
78
79const run = async ($: Engine, argv: string[]) => {
80  try {
81    const r = await $.process.run(argv, { timeoutMs: 10_000 })
82    return r.exitCode === 0 ? r.stdout : ''
83  } catch {
84    return ''
85  }
86}
87
88// What a refusal says about one hold, beyond what it does and why: the things it would have touched
89// (touches.ts, the same text the question shows). The engine is passed as the probe: it has the same fs / process calls.
90const wouldTouch = async ($: Engine, home: string, hold: Hold) =>
91  (await touches($ as unknown as Probe, hold, home)).split('\n').slice(1).map(l => l.trim()).join('; ')
92
93// Non-interactive runs have nobody to ask: the verdict is written down here.
94async function note($: Engine, home: string, verdict: string, hold: Hold) {
95  try {
96    const path = `${home}/${LOG}`
97    const old = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
98    const line = `${new Date(await $.clock.now()).toISOString()} | ${verdict} | ${hold.kind} | ${hold.segment.slice(0, 160)}`
99    const kept = old.split('\n').filter(Boolean).slice(-299)
100    await $.fs.write(path, [...kept, line].join('\n') + '\n')
101  } catch {
102    // a failed log line must not change the verdict
103  }
104}
105
106export const register: Register = on => {
107  on('session.start', async ($, e, next) => {
108    const home = (await $.env.get('HOME')) ?? ''
109    const hub = e.cwd.replace(/\/$/, '') === `${home}/repos`
110    await update($, isHub, () => hub)
111    if (hub) {
112      await refreshBand($).catch(() => undefined)
113      $.clock.every(5000, () => refreshBand($).catch(() => undefined))
114    }
115    return next(e)
116  })
117
118  // Hub band: /prep has run in this session
119  on('command.run', async ($, e, next) => {
120    if (e.command === 'prep') await update($, prepRan, () => true)
121    return next(e)
122  })
123  on('prompt.submit', async ($, e, next) => {
124    if (/^\s*\/prep\b/.test(e.text)) await update($, prepRan, () => true)
125    return next(e)
126  })
127
128  // Token Weather
129  on('session.measure', async ($, e, next) => {
130    const p = e.context.percent
131    await update($, percent, () => (p === undefined ? null : Math.round(p)))
132    return next(e)
133  })
134
135  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
136    if (e.props.hasSurvey) return next(e)
137    const hub = await read($, isHub)
138    const p = await read($, percent)
139    const w = p === null ? null : weather(p, hub)
140    if (!hub && w === null) return next(e)
141
142    const { Box, Text } = $.ui.resolve(e)
143    const color = w?.kind === 'storm' ? 'error' : w?.kind === 'showers' ? 'warning' : undefined
144    return (
145      <Box>
146        {hub && <Text dimColor>{bandText(await read($, prepRan), await read($, band))}</Text>}
147        {hub && w && <Text dimColor> | </Text>}
148        {w && (
149          <Text color={color} dimColor={color === undefined}>
150            {w.text}
151          </Text>
152        )}
153      </Box>
154    )
155  })
156
157  // Blast Radius
158  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
159    const home = (await $.env.get('HOME')) ?? ''
160    const tmpdir = (await $.env.get('TMPDIR')) ?? undefined
161    // A named Docker volume made over a host folder (local driver, device=/path) is that folder: ask docker, only when an rm is in play.
162    const volumeDevices: Record<string, string> = {}
163    const uninspectedVolumes: string[] = []
164    if (/\brm\b/.test(e.command)) {
165      // Every named volume is asked about, and only an answer from docker clears it. A volume docker does not know, or cannot be asked
166      // about (docker missing, a timeout), is unknown: the same command may make it, so no text rule can call it new. It is held,
167      // and listed apart, never as text that could be read as a path.
168      for (const name of namedVolumesOf(e.command)) {
169        try {
170          const r = await $.process.run(['docker', 'volume', 'inspect', '--format', '{{index .Options "device"}}', '--', name], { timeoutMs: 10_000 })
171          const device = r.stdout.trim()
172          if (r.exitCode === 0) {
173            if (device.startsWith('/')) volumeDevices[name] = device
174          } else uninspectedVolumes.push(name)
175        } catch {
176          uninspectedVolumes.push(name)
177        }
178      }
179    }
180    // A compose service with a cpus limit in its file is capped (docker compose run has no --cpus flag). The files are read here, as
181    // text, the way compose picks them: the -f files in order, else the first default file in the folder plus its override file; the
182    // last file that says anything about the service's CPU wins. Held instead when it is unclear: no folder the guard can know (a
183    // relative path with no plain cd before it), COMPOSE_FILE or an --env-file, a source/eval/export before it, or a project env file that could change the files, a
184    // file that cannot be read, or a limit the text reading does not see.
185    const composeLimited: string[] = []
186    const projectEnv = '.' + 'env'
187    if (/\bcompose\b|docker-compose/.test(e.command) && !/COMPOSE_FILE|--env-file|COMPOSE_PROJECT_DIR|--profile|\b(?:source|eval|export)\b|(?:^|[;&|(]\s*)\.\s/.test(e.command) && !(await $.env.get('COMPOSE_FILE'))) {
188      for (const c of composeRunsOf(e.command)) {
189        const base = c.cwd
190        if (c.needsCwd && !base) continue
191        const abs = (p: string) => (p.startsWith('/') ? p : p.startsWith('~/') ? `${home}${p.slice(1)}` : `${base}/${p}`)
192        const dir = c.projectDir ? abs(c.projectDir) : (base as string)
193        let files = c.files.map(abs)
194        if (files.length === 0) {
195          const first: string[] = []
196          for (const n of ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml']) {
197            if (await $.fs.exists(`${dir}/${n}`)) {
198              first.push(`${dir}/${n}`)
199              break
200            }
201          }
202          for (const n of ['compose.override.yaml', 'compose.override.yml', 'docker-compose.override.yaml', 'docker-compose.override.yml']) {
203            if (first.length > 0 && (await $.fs.exists(`${dir}/${n}`))) {
204              first.push(`${dir}/${n}`)
205              break
206            }
207          }
208          files = first
209        }
210        // the project env file can set COMPOSE_FILE: then the files are not the ones read here
211        if (/^\s*COMPOSE_FILE\s*=/m.test(await readText($, `${dir}/${projectEnv}`).catch(() => ''))) continue
212        let verdict: 'capped' | 'none' | 'absent' = 'absent'
213        for (const file of files) {
214          const v = composeServiceLimit(await readText($, file).catch(() => ''), c.service)
215          if (v !== 'absent') verdict = v
216        }
217        if (verdict === 'capped') composeLimited.push(c.key)
218      }
219    }
220    const baseEnv = { home, tmpdir, volumeDevices, uninspectedVolumes, composeLimited }
221    // classify asks for the files a production call needs (the forwarder, the deploy script it sources, then the repo's dotenv file); read what it asks
222    // for, up to four rounds, then classify with their text. A file over 400000 characters is not read, so it is held; the forwarder is further bounded
223    // by forwarderIsPlain's 40-line limit, the deploy script only by its SHA-256 pin. The dotenv file is reduced to its key names the moment it is read
224    // (envKeyLines): the values are never stored, shown or logged; a read error or an oversize file is stored as a mark that holds.
225    const prodScripts: Record<string, string> = {}
226    for (let round = 0; round < 4; round += 1) {
227      const wanted = new Set<string>()
228      const wantedEnv = new Set<string>()
229      classify(e.command, 0, { ...baseEnv, prodScripts, prodWanted: wanted, prodWantedEnv: wantedEnv })
230      const fresh = [...wanted].filter(path => !(path in prodScripts))
231      const freshEnv = [...wantedEnv].filter(path => !(path in prodScripts))
232      if (fresh.length === 0 && freshEnv.length === 0) break
233      for (const path of fresh) {
234        const t = await readText($, path).catch(() => undefined)
235        prodScripts[path] = t !== undefined && t.length > 0 && t.length < 400000 ? t : ''
236      }
237      // only the paths classify asked for as a dotenv file, by name; a forwarder or deploy script is never reduced this way
238      for (const path of freshEnv) {
239        const t = await readText($, path).catch(() => undefined)
240        prodScripts[path] = t !== undefined && t.length < 400000 ? envKeyLines(t) : '\u0000'
241      }
242    }
243    const scratchEnv = { ...baseEnv, prodScripts }
244    const ownScratch = ownScratchTargets(e.command, scratchEnv)
245    const holds = classify(e.command, 0, scratchEnv)
246    const noteScratch = async () => {
247      for (const { targets } of ownScratch) {
248        await note($, home, 'allowed (own scratch)', {
249          kind: 'rm -rf',
250          hard: false,
251          segment: targets.join(' '),
252        })
253      }
254    }
255    if (holds.length === 0) {
256      await noteScratch()
257      return next(e)
258    }
259    // A lane the dispatcher started has nobody at its window (lane.sh sets AFA_LANE_UNATTENDED=1): it never waits.
260    // A delete inside its own folder, a worktree or the scratchpad, by a full path, runs; everything else is refused with a reason.
261    if ((await $.env.get('AFA_LANE_UNATTENDED')) === '1') {
262      const hand = (await $.env.get('AFA_LANE_HAND')) ?? undefined
263      const approval = 'Leave it out of this job and say in your report that it needs Jonathan to approve it.'
264      const refusals: string[] = []
265      for (const h of holds) {
266        // inside `docker run -v`, the delete is judged on the host folders the mounts lead to
267        const host = h.kind === 'rm -rf' ? hostRmSegment(h) : undefined
268        let verdict: { ok: true } | { ok: false; reason: string } = !host
269          ? { ok: false as const, reason: h.kind === 'docker run without limits' ? 'Run it again with the fix named above.' : approval }
270          : 'reason' in host
271            ? { ok: false as const, reason: host.reason }
272            : unattendedRmVerdict(host.segment, { home, hand, tmpdir })
273        if (verdict.ok && host && 'segment' in host) {
274          // The words are inside the lane's folder; now make sure no link on the way leads out of it.
275          const laneEnv = { home, hand, tmpdir }
276          const resolve = async (path: string) => (await run($, ['realpath', '-m', '--', path])).trim()
277          const roots = await Promise.all(unattendedRoots(laneEnv).map(resolve))
278          const paths = unattendedRmPaths(host.segment, laneEnv)
279          verdict = realPathVerdict(
280            await Promise.all(paths.map(async path => ({ path, real: await resolve(path) }))),
281            roots.filter(Boolean),
282          )
283        }
284        if (verdict.ok && !h.hard) {
285          await note($, home, 'allowed (lane folder)', h)
286          continue
287        }
288        await note($, home, 'denied', h)
289        const { what, why } = explain(h)
290        refusals.push(
291          `${h.kind} "${h.segment.slice(0, 200)}" ${what}. Held because ${why}. It would touch: ${await wouldTouch($, home, h)}. ${verdict.ok ? approval : verdict.reason}`,
292        )
293      }
294      if (refusals.length > 0) {
295        return {
296          deny: `Blast Radius refused this command and did not wait, because nobody is at this lane's window to approve it. ${refusals.join(' ')}`,
297        }
298      }
299      await noteScratch()
300      return next(e)
301    }
302
303    // A lane someone may be watching (lane.sh sets AFA_LANE=1; the hub does not) is not left on a dialog for a hold whose fix is known:
304    // the refusal says the fix, and the lane runs the corrected command. Every other hold keeps the dialog.
305    if ((await $.env.get('AFA_LANE')) === '1') {
306      const fixable = holds.filter(h => laneFix(h))
307      if (fixable.length > 0) {
308        const refusals: string[] = []
309        for (const h of fixable) {
310          await note($, home, 'denied (fix named)', h)
311          const { what, why } = explain(h)
312          refusals.push(`${h.kind} "${h.segment.slice(0, 200)}" ${what}. Held because ${why}. ${laneFix(h)}`)
313        }
314        const rest = holds.filter(h => !laneFix(h))
315        const more = rest.length > 0 ? ` It also holds ${[...new Set(rest.map(h => h.kind))].join(', ')}, which will ask Jonathan once this is fixed.` : ''
316        return { deny: `Blast Radius held this command and did not ask, because a lane can fix it. ${refusals.join(' ')}${more}` }
317      }
318    }
319
320    const isInteractive = (await $.session.surfaces()).length > 0
321
322    if (!isInteractive) {
323      const hard = holds.find(h => h.hard)
324      if (hard) {
325        await note($, home, 'denied', hard)
326        const { what, why } = explain(hard)
327        return {
328          deny: `Blast Radius: ${hard.kind} is refused in a non-interactive session (nobody to ask). It ${what}. Held because ${why}. It would touch: ${await wouldTouch($, home, hard)}.`,
329        }
330      }
331      for (const h of holds) await note($, home, 'allowed', h)
332      await noteScratch()
333      return next(e)
334    }
335
336    const lines: string[] = []
337    const plain: string[] = []
338    for (const h of holds) {
339      lines.push(await touches($ as unknown as Probe, h, home))
340      const { what, why } = explain(h)
341      plain.push(`- ${h.kind} ${what}. Held because ${why}.`)
342    }
343    const choice = await $.ui.ask(
344      `Blast Radius stopped a command before it ran:\n${plain.join('\n')}\nIt would touch:\n${lines.join('\n')}\nRun it?`,
345      [RUN_IT, REFUSE],
346    )
347    if (choice !== RUN_IT) return { deny: refusal(choice) }
348    await noteScratch()
349    return next(e)
350  }).catch(($, e, next) =>
351    next.called
352      ? next(e)
353      : {
354          deny: "Blast Radius: its guard failed, so the command is held. It would touch: can't tell what this touches: the guard failed before it could look.",
355        },
356  )
357}
358
src/lib.ts 1226 lines
1// Pure helpers for the three mods: text in, text out, no engine calls.
2import { type DeployPins, deployEnvIsPlain, deployIsPinned, deployScript, forwarderIsPlain, hasDotPart, parseProdCall, prodLineShape, remoteIsRead } from './prodread'
3
4export type Band = { lanes: number; inbox: number; client: number }
5
6// Open lines (- [ ]) in hub-inbox.md. Client mail and client alerts are
7// counted apart from the rest so a line never shows twice.
8export function countInbox(md: string): { inbox: number; client: number } {
9  let inbox = 0
10  let client = 0
11  for (const line of md.split('\n')) {
12    if (!/^- \[ \]/.test(line)) continue
13    if (/Client mail:|Client alert:/.test(line)) client += 1
14    else inbox += 1
15  }
16  return { inbox, client }
17}
18
19// Lane rows from the last `days` days: { name, report } from index.tsv
20// (date, name, folder, model, billing, prompt, report, ...).
21export function recentLanes(
22  tsv: string,
23  nowMs: number,
24  days = 3,
25): { date: string; name: string; report: string }[] {
26  const cutoff = new Date(nowMs - days * 86_400_000).toISOString().slice(0, 10)
27  const rows: { date: string; name: string; report: string }[] = []
28  for (const line of tsv.split('\n')) {
29    const c = line.split('\t')
30    if (c.length < 2 || !/^\d{4}-\d{2}-\d{2}$/.test(c[0]) || c[0] < cutoff) continue
31    rows.push({ date: c[0], name: c[1], report: c[6] ?? '-' })
32  }
33  return rows
34}
35
36// out.log of a headless lane ends with "exit <code>" when the process is done.
37export function hasExitLine(log: string): boolean {
38  const last = log.trimEnd().split('\n').pop() ?? ''
39  return /^exit \d+$/.test(last)
40}
41
42export function bandText(prepRan: boolean, band: Band): string {
43  const parts: string[] = []
44  if (!prepRan) parts.push('/prep not run')
45  if (band.lanes > 0) parts.push(`${band.lanes} lane${band.lanes === 1 ? '' : 's'} open`)
46  if (band.inbox > 0) parts.push(`Muse inbox: ${band.inbox} open`)
47  if (band.client > 0) parts.push(`Client mail: ${band.client} new`)
48  return parts.length > 0 ? parts.join(' | ') : 'hub quiet'
49}
50
51export type Weather = { kind: 'clear' | 'showers' | 'storm'; text: string }
52
53// Clear under 40%, showers 40-60%, storm past 60%. The hub hands off past 60%;
54// every other folder hands off past 80%.
55export function weather(percent: number, isHub: boolean): Weather {
56  const kind = percent < 40 ? 'clear' : percent <= 60 ? 'showers' : 'storm'
57  const handOff = (isHub && percent > 60) || percent > 80
58  return {
59    kind,
60    text: `Weather: ${kind} ${percent}%${handOff ? ' - hand off and end' : ''}`,
61  }
62}
63
64// Every rule classify can raise. `add` takes only these, and a test fails when one has no description of its
65// targets (touches.ts RULE_SAMPLES) or no plain words (explain), so a new rule cannot ship undescribed.
66export const HELD_KINDS = [
67  'rm -rf',
68  'docker system prune',
69  'docker image prune',
70  'docker volume prune',
71  'docker volume rm',
72  'docker compose down -v',
73  'docker run without limits',
74  'git push --force',
75  'production deploy',
76  'tmux shared lanes',
77] as const
78export type HeldKind = (typeof HELD_KINDS)[number]
79
80export type Hold = { kind: string; hard: boolean; segment: string; container?: Mapped[] }
81// volumeDevices: named Docker volumes that are really a host folder (local driver, device=/path), read by the caller with docker volume inspect
82// uninspectedVolumes: named volumes docker could not be asked about; they are held as unresolved, never resolved as text
83// deployEnvKeys: names the repo's dotenv file may hold (default DEPLOY_ENV_KEYS; a test injects its own)
84// deployPins: SHA-256 list, by repo folder, of the deploy scripts a production proof may source (default DEPLOY_PINS; a test injects its own)
85// composeLimited: keys (composeKey) of the compose services whose file gives them a cpus limit, read by the caller
86export type ScratchEnv = { home?: string; tmpdir?: string; volumeDevices?: Record<string, string>; uninspectedVolumes?: string[]; composeLimited?: string[]; prodScripts?: Record<string, string>; prodWanted?: Set<string>; prodWantedEnv?: Set<string>; deployPins?: DeployPins; deployEnvKeys?: ReadonlySet<string> }
87
88const strip = (s: string) =>
89  s
90    .trim()
91    .replace(/^(?:\w+=\S*\s+)+/, '')
92    .replace(/^(?:sudo|command|time)\s+/, '')
93
94// Words a heredoc body is run as shell for: the body of `cat <<EOF` is text being written, the body of `bash <<EOF` is run.
95const SHELL_WORDS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'ssh', 'su', 'eval', 'source', '.'])
96// Commands that only show, search or send text: a deploy command inside their arguments does nothing.
97const TEXT_CARRIERS = new Set(['echo', 'printf', 'cat', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'sed', 'awk', 'head', 'tail', 'wc', 'less', 'more', 'tmux', 'screen', 'diff', 'tee'])
98// Commands that run the text they are given, so a quoted deploy command inside their arguments is real.
99const RUNS_ITS_ARGS = new Set(['ssh', 'eval', 'xargs', 'watch', 'su', 'sh', 'bash', 'zsh', 'dash', 'ksh'])
100
101const firstWord = (seg: string) => (strip(seg).replace(/^\\/, '').split(/\s+/)[0] ?? '').split('/').pop() ?? ''
102
103function tmuxInvocation(tokens: string[]): { command: string; index: number; privateSocket: boolean } {
104  let index = 1
105  let privateSocket = false
106  while (index < tokens.length) {
107    const arg = tokens[index]
108    if (arg === '-L' || arg === '-S') {
109      privateSocket = true
110      index += 2
111    } else if (/^-[LS]=?.+/.test(arg)) {
112      privateSocket = true
113      index += 1
114    } else if (arg === '-f' || arg === '-T') {
115      index += 2
116    } else if (/^-[2CluvVND]+$/.test(arg)) {
117      index += 1
118    } else if (arg.startsWith('-')) {
119      index += 1
120    } else {
121      return { command: arg, index, privateSocket }
122    }
123  }
124  return { command: '', index, privateSocket }
125}
126
127// Heredoc bodies that only write a file (cat, tee, python ... <<EOF) are not commands: drop them. A body fed to a shell is kept.
128function withoutTextHeredocs(command: string): string {
129  const lines = command.split('\n')
130  const out: string[] = []
131  for (let i = 0; i < lines.length; i += 1) {
132    out.push(lines[i])
133    const m = /<<-?\s*(['"]?)([A-Za-z_]\w*)\1/.exec(lines[i])
134    if (!m || /<<</.test(lines[i])) continue
135    const end = lines.findIndex((l, j) => j > i && l.trim() === m[2])
136    if (end < 0) continue
137    const lead = lines[i].slice(0, m.index).split(/&&|\|\||[;&|]/).pop() ?? ''
138    const after = lines[i].slice(m.index + m[0].length).replace(/\d*>&-?\d*|&>>?/g, '')
139    // a shell anywhere in the lead (`sudo bash`, `env bash`), or a pipe/and/semicolon after the marker (`cat <<EOF | bash`): the body is run
140    const plain = (w: string) => (w.replace(/^(?:\$\(|[<>]?\(|`|\{)+/, '').replace(/["'\\]/g, '').split('/').pop() ?? '')
141    const runs = (w: string) => SHELL_WORDS.has(plain(w)) || RUNS_ITS_ARGS.has(plain(w)) || WRAPPERS.has(plain(w))
142    const shellIn = (s: string) => s.split(/\s+/).some(runs) || /^(?:docker(?:\s+compose)?|docker-compose|podman|kubectl)\s+(?:exec|run)\b/.test(s.trim())
143    // `git commit -m "$(cat <<'EOF' ... EOF )"`: only a known text sink (git commit, gh pr/issue/release) takes the body as one message word; anywhere else it may be run, so it is kept
144    const textSink = /^\s*(?:\w+=\S*\s+)*(?:git(?:\s+-C\s+\S+)?\s+commit|gh\s+(?:pr|issue|release)\s+\S+)\b/.test(lead)
145    const quotedMessage = textSink && /\$\(\s*(?:cat|tee)\s*$/.test(lead) && ((lead.replace(/\\./g, '').match(/"/g) ?? []).length % 2 === 1)
146    const leadRest = quotedMessage ? lead.replace(/\$\(\s*(?:cat|tee)\s*$/, '') : lead
147    // fail closed: the body is dropped only when nothing around the marker could run it (no shell word, pipe, substitution or backtick)
148    if (shellIn(lead) || shellIn(after) || /[|;&`]|[$<>]\(/.test(after) || /[`]|[$<>]\(/.test(leadRest)) continue
149    i = end // skip the body and its delimiter line
150  }
151  return out.join('\n')
152}
153
154// The command split at shell separators (& | ; newline ( ) ` $( ), but not inside quotes: "a; b" is one word. Inside double
155// quotes, $( ) and backticks still run, so they still split. Heredoc bodies that only write a file are left out.
156export function segmentsWithSeps(command: string): Array<{ text: string; sep: string }> {
157  const text = withoutTextHeredocs(command)
158  const out: Array<{ text: string; sep: string }> = []
159  let cur = ''
160  let q: '' | "'" | '"' = ''
161  const resume: { close: string; depth: number }[] = [] // a double quote waiting for its $( ) or ` ` to close
162  const flush = (sep: string) => {
163    out.push({ text: cur, sep })
164    cur = ''
165  }
166  for (let i = 0; i < text.length; i += 1) {
167    const c = text[i]
168    if (q === "'") {
169      cur += c
170      if (c === "'") q = ''
171      continue
172    }
173    if (c === '\\') {
174      cur += c + (text[i + 1] ?? '')
175      i += 1
176      continue
177    }
178    if (q === '"') {
179      if (c === '"') {
180        q = ''
181        cur += c
182      } else if (c === '`' || (c === '$' && text[i + 1] === '(')) {
183        flush(c === '`' ? '`' : '$(')
184        resume.push({ close: c === '`' ? '`' : ')', depth: 0 })
185        q = ''
186        if (c === '$') i += 1
187      } else cur += c
188      continue
189    }
190    const top = resume.at(-1)
191    if (top) {
192      if (c === '(' && top.close === ')') top.depth += 1
193      if (c === top.close && top.depth > 0 && c === ')') {
194        top.depth -= 1
195        flush(')')
196        continue
197      }
198      if (c === top.close) {
199        flush(c)
200        resume.pop()
201        q = '"'
202        continue
203      }
204    }
205    if (c === "'" || c === '"') {
206      q = c
207      cur += c
208    } else if (c === '$' && text[i + 1] === '(') {
209      flush('$(')
210      i += 1
211    } else if ('&|;\n()`'.includes(c)) flush(c)
212    else cur += c
213  }
214  flush('')
215  return out
216}
217
218export const segmentsOf = (command: string): string[] => segmentsWithSeps(command).map(x => x.text)
219
220// A quoted piece that is one word (`"--prod"`) is an argument the shell would unquote, so it stays; a quoted message with spaces is text and goes.
221const QUOTED = /'([^']*)'|"((?:\\.|[^"\\])*)"/g
222const withoutQuoted = (seg: string) => seg.replace(QUOTED, (_m, a?: string, b?: string) => ((a ?? b ?? '') !== '' && /^\S+$/.test(a ?? b ?? '') ? (a ?? b ?? '') : ''))
223
224// Commands that run the quoted text they are given (`ssh host "a; b"`, `docker exec c "..."`): each quoted piece is a command line to judge too.
225const WRAPPERS = new Set(['env', 'nohup', 'exec', 'nice', 'ionice', 'stdbuf', 'doas', 'timeout', 'setsid', 'chrt', 'command', 'time', 'xargs'])
226// Fail closed: behind a wrapper (`env -i A=b ssh ...`, `timeout 5 bash -c ...`) we do not try to work out which word runs, so its quoted text is read as commands.
227const runsQuoted = (seg: string) =>
228  RUNS_ITS_ARGS.has(firstWord(seg)) || WRAPPERS.has(firstWord(seg)) || /^(?:docker(?:\s+compose)?|docker-compose|podman|kubectl)\s+(?:exec|run)\b/.test(strip(seg))
229const quotedPieces = (seg: string): string[] => Array.from(seg.matchAll(QUOTED), m => m[1] ?? m[2] ?? '').filter(s => s.trim() !== '')
230
231// Would this segment ship to production? Judged on what the command runs: its quoted text is data unless the command runs
232// its arguments, and a word with a "/" is a path (a folder called App--prod-lock or /srv/redeploy/prod is not a flag).
233const PROD_FLAG = /^--prod(?:uction)?(?:=.*)?$/i
234const PROD_WORD = /^(?:--[\w-]+=)?(?:--)?prod(?:uction)?$/i
235function isProdDeploy(seg: string): boolean {
236  const word = firstWord(seg)
237  if (!/^[A-Za-z0-9_.-]+$/.test(word) || TEXT_CARRIERS.has(word)) return false
238  const body = RUNS_ITS_ARGS.has(word) || /^(?:docker|kubectl)\s+(?:exec|run)\b/.test(seg) ? seg : withoutQuoted(seg)
239  // the words as the shell would unquote them: no quotes, no backslashes. A "#" is not stripped as a comment: `vercel '#' --prod` runs.
240  const words = body
241    .split(/\s+/)
242    .map(w => w.replace(/["'\\]/g, ''))
243    .filter(Boolean)
244  const args = words.filter(w => w.startsWith('-') || !w.includes('/'))
245  if (args.some(w => PROD_FLAG.test(w))) return true
246  return /redeploy/i.test(word) || args.some(w => /redeploy/i.test(w)) ? args.some(w => PROD_WORD.test(w)) : false
247}
248
249// ---- docker run -v / --mount: what a path inside the container is on this machine ----
250
251// A mount of a `docker run`: `kind` says whether its source is a folder on this machine ('host') or a Docker
252// volume ('volume': named, anonymous or tmpfs). The source is the text as written, not yet resolved.
253export type Mount = { source: string; target: string; kind: 'host' | 'volume' }
254// incomplete: the mount list may miss mounts (a compose file, --volumes-from, a flag not read), so an unlisted path is not known to be the container's own
255type Scope = { home: string; cwd?: string; vars: Map<string, string | null>; mounts?: Mount[]; incomplete?: boolean; devices: Record<string, string>; uninspected: string[]; timeout?: boolean }
256
257// One path an rm names inside a container, seen through the mounts: where it really is.
258export type Mapped =
259  | { path: string; kind: 'host'; mountAt: string; folder: string; host: string } // folder: the mount's source here; host: the path here (may hold a pattern)
260  | { path: string; kind: 'volume'; mountAt: string; volume: string } // a Docker volume, not a folder on this machine
261  | { path: string; kind: 'unresolved'; mountAt: string; source: string; why: string } // a host source that cannot be worked out
262  | { path: string; kind: 'uncovered'; why: string } // no mount covers it
263
264const newScope = (command: string, env: ScratchEnv): Scope => ({ home: env.home ?? '', vars: assignmentsOf(command, env), devices: env.volumeDevices ?? {}, uninspected: env.uninspectedVolumes ?? [] })
265
266const SUBSTITUTION = /\$\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\)|`[^`]*`/g
267const SUBST_WORD = '$CMDSUBST'
268
269// The rest of each docker run line with every $( ) and backtick substitution replaced by one unresolvable word
270function foldSubstitutionsInDockerRuns(command: string): string {
271  return command.replace(/((?:^|[\s;&|(])(?:(?:docker|podman)\s+(?:(?:compose|container)\s+)?run|docker-compose\s+run)\b)([^\n]*)/g, (_m, head: string, tail: string) =>
272    head + tail.replace(SUBSTITUTION, SUBST_WORD),
273  )
274}
275
276const DOCKER_RUN = /^(?:docker|podman)\s+(?:compose\s+|container\s+)?run\b|^docker-compose\s+run\b/
277
278// ---- a container started with no CPU cap and no timeout in front ----
279// 19 Oct: one `docker run` with neither took 14.6 of 16 cores and the machine thrashed. Held with the one-line fix.
280const DOCKER_WORDS = new Set(['docker', 'podman', 'docker-compose'])
281const baseName = (w: string) => w.split('/').pop() ?? w
282const COMPOSE_GLOBAL_VALUE = new Set(['-f', '--file', '-p', '--project-name', '--project-directory', '--profile', '--env-file', '--ansi', '--progress', '-H', '--host', '--context'])
283const DOCKER_GLOBAL_VALUE = new Set(['-H', '--host', '--context', '-c', '--config', '-l', '--log-level'])
284// a flag only caps the container when its value does: --cpus 0 and --cpu-quota -1 mean no limit, and $X is not known to be a number
285const CPU_FLAG = /^--(cpus|cpu-quota|cpuset-cpus)(?:=(.*))?$/
286const capValue = (flag: string, value: string | undefined): boolean => {
287  const v = unquote(value ?? '')
288  if (flag === 'cpus') return /^\d+(?:\.\d+)?$/.test(v) && Number(v) > 0
289  if (flag === 'cpu-quota') return /^\d+$/.test(v) && Number(v) > 0
290  return /^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(v)
291}
292const isTimeout = (w: string) => /^g?timeout$/.test(baseName(w))
293// `timeout [options] DURATION` among the words in front of what runs: the duration must be a positive number of seconds, minutes, hours
294// or days, at most a day (`timeout 0` means no limit). Stops at the first shell or docker word.
295function timeoutIn(words: string[]): boolean {
296  for (let k = 0; k < words.length; k += 1) {
297    if (isTimeout(words[k])) {
298      let j = k + 1
299      while (j < words.length && words[j].startsWith('-')) j += ['-s', '-k', '--signal', '--kill-after'].includes(words[j]) ? 2 : 1
300      const m = /^(\d+(?:\.\d+)?)([smhd]?)$/.exec(unquote(words[j] ?? ''))
301      if (!m) return false
302      const seconds = Number(m[1]) * ({ s: 1, '': 1, m: 60, h: 3600, d: 86400 } as Record<string, number>)[m[2]]
303      return seconds > 0 && seconds <= 86400
304    }
305    if (SHELL_WORDS.has(baseName(words[k])) || DOCKER_WORDS.has(baseName(words[k]))) return false
306  }
307  return false
308}
309
310export const UNLIMITED_FIX =
311  'add --cpus N (and a timeout in front), as "timeout <secs> docker run --cpus <n> --memory <m> ...", or run it through "~/.claude/scripts/docker-heavy.sh -- docker ..."'
312
313// detached: -d / --detach, so the container outlives a timeout in front of the docker command and only a cap limits it
314export type RunCall = { mode: 'run' | 'compose'; timeout: boolean; detached: boolean; capped: boolean; service?: string; image?: string; files: string[]; projectDir?: string }
315
316// the files, project directory, service and the folder the command is in: the same service in another folder is another key
317export const composeKey = (c: Pick<RunCall, 'files' | 'projectDir' | 'service'>, cwd?: string) => `${c.files.join('|')}::${c.projectDir ?? ''}::${c.service ?? ''}::${cwd ?? ''}`
318
319// A segment that starts a container with `docker run` / `docker compose run` (also podman, docker-compose), looking only at the
320// options before the image. undefined: not one, or one run through docker-heavy.sh (it adds the limits, the lock and a timeout).
321function parseRunCall(seg: string): RunCall | undefined {
322  const t = seg.split(/\s+/).filter(Boolean).map(unquote)
323  if (t.length === 0) return undefined
324  let at = 0
325  if (!DOCKER_WORDS.has(baseName(t[0]))) {
326    if (!WRAPPERS.has(baseName(t[0]))) return undefined
327    at = t.findIndex(w => DOCKER_WORDS.has(baseName(w)))
328    if (at < 0) return undefined
329  }
330  const prefix = t.slice(0, at)
331  // docker-heavy.sh adds the limits, the lock and a timeout; it is called as `docker-heavy.sh [options] -- docker ...`
332  if (prefix.some(w => baseName(w) === 'docker-heavy.sh') && t[at - 1] === '--') return undefined
333  const timeout = timeoutIn(prefix)
334  let i = at + 1
335  let mode: 'run' | 'compose'
336  const files: string[] = []
337  let projectDir: string | undefined
338  if (baseName(t[at]) === 'docker-compose') mode = 'compose'
339  else {
340    while (i < t.length && t[i].startsWith('-')) i += DOCKER_GLOBAL_VALUE.has(t[i]) ? 2 : 1
341    if (t[i] === 'compose') {
342      mode = 'compose'
343      i += 1
344    } else {
345      if (t[i] === 'container') i += 1
346      if (t[i] !== 'run') return undefined
347      mode = 'run'
348      i += 1
349    }
350  }
351  if (mode === 'compose') {
352    while (i < t.length && t[i].startsWith('-')) {
353      const w = t[i]
354      if (w === '-f' || w === '--file') {
355        files.push(t[i + 1] ?? '')
356        i += 2
357      } else if (w.startsWith('--file=')) {
358        files.push(w.slice(7))
359        i += 1
360      } else if (/^-f./.test(w)) {
361        files.push(w.slice(2))
362        i += 1
363      } else if (w === '--project-directory') {
364        projectDir = t[i + 1]
365        i += 2
366      } else if (w.startsWith('--project-directory=')) {
367        projectDir = w.slice(20)
368        i += 1
369      } else i += COMPOSE_GLOBAL_VALUE.has(w) ? 2 : 1
370    }
371    if (t[i] !== 'run') return undefined
372    i += 1
373  }
374  let capped = false
375  let detached = false
376  for (; i < t.length; i += 1) {
377    const w = t[i]
378    if (w === '--') {
379      i += 1
380      break
381    }
382    if (!w.startsWith('-')) break
383    const flag = CPU_FLAG.exec(w)
384    if (flag && capValue(flag[1], flag[2] ?? t[i + 1])) capped = true
385    if (w === '--detach' || w.startsWith('--detach=')) detached = true
386    else if (!w.startsWith('--') && w.length > 1) {
387      // grouped short flags (-itd): a d before the first flag that takes a value
388      for (const c of w.slice(1)) {
389        if (c === 'd') detached = true
390        if (SHORT_VALUE.has(c) || c === 'v') break
391      }
392    }
393    if (w.startsWith('--')) {
394      if (!w.includes('=') && RUN_VALUE_ALL.has(w)) i += 1
395    } else if (w.length === 2) {
396      if (SHORT_VALUE.has(w[1]) || w[1] === 'v') i += 1
397    } else {
398      const takes = (c: string) => SHORT_VALUE.has(c) || c === 'v'
399      if (takes(w[w.length - 1]) && !takes(w[1])) i += 1
400    }
401  }
402  return { mode, timeout, detached, capped, service: mode === 'compose' ? t[i] : undefined, image: mode === 'run' ? t[i] : undefined, files, projectDir }
403}
404
405// What an uncapped run starts: its image, or its compose service
406export const runTargetOf = (seg: string): string | undefined => {
407  const c = parseRunCall(strip(seg))
408  return c?.image ?? c?.service
409}
410
411// What a compose file says about a service's CPU: 'capped' (cpus, cpu_quota or cpuset as a direct key, or deploy.resources.limits.cpus,
412// with a positive value: a `${X}` value never counts), 'none' (a CPU key whose value is no cap, such as 0), 'absent'. Read as text:
413// anchors, `extends` and includes are not followed, so a limit set that way is 'absent' and the run stays held.
414export function composeServiceLimit(yaml: string, service: string): 'capped' | 'none' | 'absent' {
415  // text the reader cannot follow: an include, or a service that merges, extends or resets keys. Such a file is 'none', so the run is held.
416  if (/^include\s*:/m.test(yaml)) return 'none'
417  const lines = yaml.split('\n')
418  const live = (l: string) => l.trim() !== '' && !l.trim().startsWith('#')
419  const indentOf = (l: string) => l.length - l.trimStart().length
420  const top = lines.findIndex(l => live(l) && /^services\s*:\s*(#.*)?$/.test(l))
421  if (top < 0) return 'absent'
422  let svcIndent = -1
423  let start = -1
424  for (let k = top + 1; k < lines.length && start < 0; k += 1) {
425    const l = lines[k]
426    if (!live(l)) continue
427    if (indentOf(l) === 0) break
428    if (svcIndent < 0) svcIndent = indentOf(l)
429    if (indentOf(l) === svcIndent && /^["']?([^"':\s]+)["']?\s*:/.exec(l.trim())?.[1] === service) {
430      // the service must be a plain block: `web: {...}`, `web: *base` or `web: &a` hides its keys from this reader
431      if (!/^["']?[^"':\s]+["']?\s*:\s*(#.*)?$/.test(l.trim())) return 'none'
432      start = k
433    }
434  }
435  if (start < 0) return 'absent'
436  const stack: { indent: number; key: string }[] = []
437  let found = false
438  for (let k = start + 1; k < lines.length; k += 1) {
439    const l = lines[k]
440    if (!live(l)) continue
441    const indent = indentOf(l)
442    if (indent <= svcIndent) break
443    if (/<<\s*:|\bextends\s*:|!reset|!override/.test(l)) return 'none'
444    while (stack.length > 0 && stack[stack.length - 1].indent >= indent) stack.pop()
445    const m = /^\s*["']?([\w.-]+)["']?\s*:\s*(.*?)\s*(?:#.*)?$/.exec(l)
446    if (!m) continue
447    const path = [...stack.map(x => x.key), m[1]].join('.')
448    stack.push({ indent, key: m[1] })
449    if (!['cpus', 'cpu_quota', 'cpuset', 'deploy.resources.limits.cpus'].includes(path)) continue
450    // a ${VAR} value is unknown (the variable may be set elsewhere), so it never counts as a cap
451    const v = unquote(m[2])
452    found = true
453    if (path === 'cpuset' ? /^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(v) : /^\d+(?:\.\d+)?$/.test(v) && Number(v) > 0) return 'capped'
454  }
455  return found ? 'none' : 'absent'
456}
457
458export const composeServiceCapped = (yaml: string, service: string): boolean => composeServiceLimit(yaml, service) === 'capped'
459
460export type ComposeRun = { key: string; service: string; files: string[]; projectDir?: string; cwd?: string; needsCwd: boolean }
461
462// The `docker compose run` calls in a command that have no timeout in front, so the caller can read each one's compose file for a cpus limit.
463export function composeRunsOf(command: string, depth = 0, timeoutFront = false, scope: Scope = newScope(command, {})): ComposeRun[] {
464  const out: ComposeRun[] = []
465  for (const raw of segmentsOf(command)) {
466    const seg = strip(raw).replace(/^\\/, '')
467    if (seg === '') continue
468    trackCd(seg, command, scope)
469    const call = parseRunCall(seg)
470    if (call?.mode === 'compose' && call.service && ((!call.timeout && !timeoutFront) || call.detached)) {
471      const absolute = (p: string) => p.startsWith('/') || p.startsWith('~/')
472      out.push({
473        key: composeKey(call, scope.cwd),
474        service: call.service,
475        files: call.files,
476        projectDir: call.projectDir,
477        cwd: scope.cwd,
478        // a relative -f or project directory, or the default files of the folder, depend on where the shell is
479        needsCwd: call.files.length === 0 || call.files.some(f => !absolute(f)) || (call.projectDir !== undefined && !absolute(call.projectDir)),
480      })
481    }
482    const wrapped = /^(?:ba|z)?sh\s+-c\s+(.*)$/.exec(seg)
483    const front = timeoutFront || segmentTimeout(seg)
484    if (depth < 3 && wrapped) out.push(...composeRunsOf(wrapped[1].replace(/^["']|["']$/g, ''), depth + 1, front, scope))
485    else if (depth < 3 && runsQuoted(seg)) for (const piece of quotedPieces(seg)) out.push(...composeRunsOf(piece, depth + 1, front, scope))
486  }
487  return out
488}
489
490// a timeout among the words in front of what the segment runs (`timeout 600 bash -c '...'`), which then covers the quoted text it runs
491function segmentTimeout(seg: string): boolean {
492  return timeoutIn(seg.split(/\s+/).filter(Boolean))
493}
494
495// `cd /full/path` before the command gives it a known $PWD. Anything that may have run in another shell (a "(" in the
496// command, pushd, popd, a path that is not plain) leaves $PWD unknown, so a source that uses it keeps holding.
497function trackCd(seg: string, command: string, scope: Scope): void {
498  if (scope.mounts) return // inside a container its own cd says nothing about this machine
499  const m = /^(?:(cd)|pushd|popd)\b\s*(.*)$/.exec(seg)
500  if (!m) return
501  const arg = unquote(m[2].trim())
502  const dir = m[1] && arg !== '' && !/\s/.test(arg) && !withoutTextHeredocs(command).includes('(') ? resolveHostPath(arg, scope) : undefined
503  scope.cwd = dir && 'path' in dir ? dir.path : undefined
504}
505
506// A path word on this machine: ~ and $HOME, $PWD after a cd, and variables the command set to a plain value. `why` says what blocked it.
507function resolveHostPath(word: string, scope: Scope): { path: string } | { why: string } {
508  let w = unquote(word)
509  if (/`|\$\(/.test(w)) return { why: 'is built by another command when the command runs' }
510  if (w === '~' || w.startsWith('~/')) {
511    if (!scope.home) return { why: 'starts with ~ and this session does not say where home is' }
512    w = scope.home + w.slice(1)
513  } else if (w.startsWith('~')) return { why: "starts with another user's ~" }
514  let missing = ''
515  if (w.includes(SUBST_WORD)) return { why: 'is built by another command when the command runs' }
516  w = w.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g, (_m, a?: string, b?: string) => {
517    const name = (a ?? b) as string
518    const value = name === 'HOME' ? scope.home || undefined : name === 'PWD' ? scope.cwd : scope.vars.get(name)
519    if (value == null) missing = missing || name
520    return value ?? ''
521  })
522  if (missing) {
523    return {
524      why:
525        missing === 'PWD'
526          ? 'uses $PWD, which depends on the folder the shell is in, and no `cd` to a full path came before it'
527          : `goes through $${missing}, which is not set to a plain path earlier in this command (it may be empty, set elsewhere, or made by mktemp)`,
528    }
529  }
530  if (/[$`]/.test(w)) return { why: 'uses a shell expansion that is only worked out when the command runs' }
531  if (!w.startsWith('/')) {
532    if (!scope.cwd) return { why: 'is a relative path, which depends on the folder the shell is in' }
533    w = `${scope.cwd}/${w}`
534  }
535  return { path: normalizePath(w) }
536}
537
538// Split `SRC:DST:opts` at the colons that are not inside ${...}
539function splitColons(spec: string): string[] {
540  const parts: string[] = []
541  let cur = ''
542  let depth = 0
543  for (let i = 0; i < spec.length; i += 1) {
544    if (spec[i] === '$' && spec[i + 1] === '{') depth += 1
545    else if (spec[i] === '}' && depth > 0) depth -= 1
546    if (spec[i] === ':' && depth === 0) {
547      parts.push(cur)
548      cur = ''
549    } else cur += spec[i]
550  }
551  parts.push(cur)
552  return parts
553}
554
555// a source with a / ~ or $ in it, or starting with a dot (compose reads `.` and `./x` as a path), is a folder here; anything else is a volume name
556const HOSTY = /[/~$]|^\./
557
558// what docker accepts as a volume name; any other non-path source is not known to be a volume, so it is judged as a folder
559export const VOLUME_NAME = /^[A-Za-z0-9][\w.-]*$/
560const kindOf = (source: string): 'host' | 'volume' => (HOSTY.test(source) || !VOLUME_NAME.test(source) ? 'host' : 'volume')
561
562// docker run / compose run flags, so the scan stops at the image and never reads the container's own arguments as mounts
563const RUN_BOOL = new Set(['-d', '-i', '-t', '-q', '-P', '-T', '--detach', '--interactive', '--tty', '--rm', '--privileged', '--init', '--read-only', '--no-healthcheck', '--oom-kill-disable', '--publish-all', '--sig-proxy', '--disable-content-trust', '--quiet', '--no-deps', '--service-ports', '--no-TTY', '--build', '--use-aliases', '--remove-orphans', '--quiet-pull', '--help'])
564const RUN_VALUE = new Set(['-a', '-c', '-e', '-h', '-l', '-m', '-p', '-u', '-w', '--add-host', '--annotation', '--attach', '--blkio-weight', '--blkio-weight-device', '--cap-add', '--cap-drop', '--cgroup-parent', '--cgroupns', '--cidfile', '--cpu-period', '--cpu-quota', '--cpu-rt-period', '--cpu-rt-runtime', '--cpu-shares', '--cpus', '--cpuset-cpus', '--cpuset-mems', '--detach-keys', '--device', '--device-cgroup-rule', '--device-read-bps', '--device-read-iops', '--device-write-bps', '--device-write-iops', '--dns', '--dns-option', '--dns-search', '--domainname', '--entrypoint', '--env', '--env-file', '--expose', '--gpus', '--group-add', '--health-cmd', '--health-interval', '--health-retries', '--health-start-period', '--health-timeout', '--hostname', '--ip', '--ip6', '--ipc', '--isolation', '--label', '--label-file', '--link', '--link-local-ip', '--log-driver', '--log-opt', '--mac-address', '--memory', '--memory-reservation', '--memory-swap', '--memory-swappiness', '--name', '--network', '--net', '--network-alias', '--oom-score-adj', '--pid', '--pids-limit', '--platform', '--publish', '--pull', '--restart', '--runtime', '--security-opt', '--shm-size', '--stop-signal', '--stop-timeout', '--storage-opt', '--sysctl', '--tmpfs', '--ulimit', '--user', '--userns', '--uts', '--volume-driver', '--workdir', '--cap', '--entrypoint'])
565const SHORT_BOOL = new Set(['d', 'i', 't', 'q', 'P', 'T'])
566const SHORT_VALUE = new Set(['a', 'c', 'e', 'h', 'l', 'm', 'p', 'u', 'w'])
567const RUN_VALUE_ALL = new Set([...RUN_VALUE, '-v', '--volume', '--mount', '--volumes-from'])
568
569// The mounts a `docker run` / `docker compose run` gives its container: -v, --volume and --mount, in the forms docker accepts,
570// read from the options before the image only. `incomplete` says the list may miss mounts: a compose service brings its own,
571// --volumes-from and --mount forms or flags not understood are not listed.
572function parseMounts(seg: string): { mounts: Mount[]; incomplete: boolean } {
573  const t = seg.split(/\s+/).map(unquote)
574  const out: Mount[] = []
575  let incomplete = /\bcompose\b|^docker-compose\b/.test(seg.split(/\s+run\b/)[0] ?? '')
576  const volume = (spec: string) => {
577    const [first, second] = splitColons(spec)
578    if (second === undefined) {
579      if (first.startsWith('/')) out.push({ source: '', target: first, kind: 'volume' }) // anonymous volume
580      else incomplete = true
581    } else if (second.startsWith('/')) out.push({ source: first, target: second, kind: kindOf(first) })
582    else incomplete = true
583  }
584  const mount = (spec: string) => {
585    const kv = new Map(spec.split(',').map(p => [p.slice(0, p.indexOf('=')), p.slice(p.indexOf('=') + 1)] as const))
586    const type = kv.get('type') ?? kv.get('Type')
587    const source = kv.get('source') ?? kv.get('src') ?? ''
588    const target = kv.get('target') ?? kv.get('destination') ?? kv.get('dst')
589    if (!target?.startsWith('/') || (type === 'bind' && !source)) {
590      incomplete = true
591      return
592    }
593    // a volume made over a host folder with the local driver (volume-opt=device=/path) is that folder
594    const device = /device=([^,]+)/.exec(spec)?.[1]
595    if (device) out.push({ source: device, target, kind: 'host' })
596    else if (type === 'bind') out.push({ source, target, kind: 'host' })
597    else if (type === 'tmpfs') out.push({ source, target, kind: 'volume' })
598    else if (type === 'volume') out.push({ source, target, kind: source === '' ? 'volume' : kindOf(source) })
599    else out.push({ source, target, kind: kindOf(source) })
600  }
601  // the next word is this flag's value
602  const takes = (i: number, use: (v: string) => void): number => {
603    if (t[i + 1] === undefined) {
604      incomplete = true
605      return i
606    }
607    use(t[i + 1])
608    return i + 1
609  }
610  let i = t.findIndex(w => w === 'run') + 1
611  let imageSeen = false
612  for (; i < t.length; i += 1) {
613    const w = t[i]
614    if (/["']/.test(w)) incomplete = true // a quote left in a word: a value with spaces split the words, so what follows may be misread
615    if (w === '--' || !w.startsWith('-')) {
616      // the image (or the compose service) starts what the container runs; a word that is not a plausible one means the scan lost its place
617      const image = w === '--' ? t[i + 1] : w
618      if (image === undefined || !/^[\w][\w./:@-]*$/.test(image)) incomplete = true
619      imageSeen = true
620      break
621    }
622    if (w === '-v' || w === '--volume') i = takes(i, volume)
623    else if (w === '--mount') i = takes(i, mount)
624    else if (w.startsWith('--volume=')) volume(unquote(w.slice(9)))
625    else if (w.startsWith('--mount=')) mount(unquote(w.slice(8)))
626    else if (w.startsWith('--volumes-from')) {
627      incomplete = true
628      if (w === '--volumes-from') i += 1
629    } else if (w.startsWith('--')) {
630      if (RUN_BOOL.has(w) || w.includes('=')) continue
631      if (RUN_VALUE.has(w)) i += 1
632      else incomplete = true // a flag not known: whether it takes a value is a guess
633    } else if (w.length === 2) {
634      if (SHORT_VALUE.has(w[1])) i += 1
635      else if (!SHORT_BOOL.has(w[1])) incomplete = true
636    } else {
637      // grouped short flags (-it, -dv, -itv src:dst) or one with its value attached (-vsrc:dst, -eNAME=x)
638      const first = w[1]
639      if (first === 'v') volume(unquote(w.slice(2).replace(/^=/, '')))
640      else if (SHORT_VALUE.has(first)) continue
641      else {
642        const letters = [...w.slice(1)]
643        const last = letters[letters.length - 1]
644        if (!letters.slice(0, -1).every(c => SHORT_BOOL.has(c))) incomplete = true
645        else if (last === 'v') i = takes(i, volume)
646        else if (SHORT_VALUE.has(last)) i += 1
647        else if (!SHORT_BOOL.has(last)) incomplete = true
648      }
649    }
650  }
651  return { mounts: out, incomplete: incomplete || !imageSeen }
652}
653
654// The names of the Docker volumes a command mounts into a docker run, so the caller can ask docker whether one is really a host folder
655export function namedVolumesOf(command: string, depth = 0): string[] {
656  const names = new Set<string>()
657  for (const text of depth === 0 ? [command, foldSubstitutionsInDockerRuns(command)] : [command]) {
658    for (const raw of segmentsOf(text)) {
659      const seg = strip(raw).replace(/^\\/, '')
660      if (DOCKER_RUN.test(seg)) {
661        for (const m of parseMounts(seg).mounts) if (m.kind === 'volume' && m.source !== '') names.add(m.source)
662      }
663      const wrapped = /^(?:ba|z)?sh\s+-c\s+(.*)$/.exec(seg)
664      if (depth < 3 && wrapped) for (const n of namedVolumesOf(wrapped[1].replace(/^["']|["']$/g, ''), depth + 1)) names.add(n)
665      else if (depth < 3 && runsQuoted(seg)) for (const piece of quotedPieces(seg)) for (const n of namedVolumesOf(piece, depth + 1)) names.add(n)
666    }
667  }
668  return [...names]
669}
670
671// Split an rm path at its first pattern character: `base` is the folder the pattern expands in (the whole path when it has none).
672export function globBase(path: string): { base: string; glob: boolean } {
673  const g = path.search(/[*?[{]/)
674  if (g < 0) return { base: path, glob: false }
675  return { base: path.slice(0, path.lastIndexOf('/', g)) || '/', glob: true }
676}
677
678const under = (parent: string, child: string) => (parent === '/' ? child !== '/' : child.startsWith(`${parent}/`))
679
680// What each path an rm names is, given the mounts of the container it runs in. The mount with the longest target
681// holds the path; a mount sitting below the path (or below the folder a pattern expands in) is reached too, because rm
682// goes down into it.
683function mapRmTargets(targets: string[], mounts: Mount[], scope: Scope): Mapped[] {
684  const out: Mapped[] = []
685  for (const path of targets) {
686    if (/[$`]/.test(path) || !path.startsWith('/')) {
687      out.push({
688        path,
689        kind: 'uncovered',
690        why: /[$`]/.test(path)
691          ? 'the path goes through a variable the container fills in when it runs'
692          : "the path is relative to the container's working directory, which this command does not show",
693      })
694      continue
695    }
696    const p = normalizePath(path)
697    const { base } = globBase(p)
698    const at = (m: Mount) => normalizePath(m.target)
699    const cover = mounts
700      .filter(m => at(m) === base || under(at(m), base))
701      .sort((a, b) => at(b).length - at(a).length)[0]
702    const below = mounts.filter(m => under(base, at(m)))
703    const entries: Mapped[] = []
704    for (const m of [...(cover ? [cover] : []), ...below]) {
705      const mountAt = at(m)
706      const device = m.kind === 'volume' ? scope.devices[m.source] : undefined
707      if (m.kind === 'volume' && scope.uninspected.includes(m.source)) {
708        entries.push({ path, kind: 'unresolved', mountAt, source: m.source, why: 'docker could not be asked what this volume is (it may be a host folder)' })
709        continue
710      }
711      if (m.kind === 'volume' && !device) {
712        entries.push({ path, kind: 'volume', mountAt, volume: m.source })
713        continue
714      }
715      const r = resolveHostPath(device ?? m.source, scope)
716      if ('why' in r) entries.push({ path, kind: 'unresolved', mountAt, source: m.source.replace(SUBST_WORD, '$(...)'), why: r.why })
717      else {
718        const rest = m === cover ? p.slice(mountAt === '/' ? 0 : mountAt.length) : ''
719        entries.push({ path, kind: 'host', mountAt, folder: r.path, host: normalizePath(`${r.path}${rest}`) })
720      }
721    }
722    out.push(
723      ...(entries.length > 0
724        ? entries
725        : [{ path, kind: 'uncovered' as const, why: 'no -v or --mount of this command covers it, so it is a path inside the container itself (or in a volume a compose file adds)' }]),
726    )
727  }
728  return out
729}
730
731// Nothing to ask about: a Docker volume is not a folder here; a host folder is judged as a host rm would be (own scratch only);
732// a path no mount covers is the container's own, held unless it is scratch by the same text rule a host rm gets.
733function containerPathIsHarmless(m: Mapped, env: ScratchEnv, incomplete = false): boolean {
734  if (m.kind === 'volume') return true
735  if (m.kind === 'host') return isOwnScratch(m.host, new Map(), env)
736  if (m.kind === 'uncovered') return !incomplete && isOwnScratch(m.path, new Map(), env)
737  return false
738}
739
740// A lane nobody watches judges the host side: the host paths of a container rm as one host rm, or the reason it cannot.
741export function hostRmSegment(h: Hold): { segment: string } | { reason: string } {
742  if (!h.container) return { segment: h.segment }
743  const hosts: string[] = []
744  for (const m of h.container) {
745    if (m.kind === 'host') hosts.push(m.host)
746    else if (m.kind === 'unresolved') return { reason: `the mount "${m.source}:${m.mountAt}" is a host folder that ${m.why}, so what "${m.path}" deletes on this machine is unknown` }
747    else if (m.kind === 'uncovered') return { reason: `"${m.path}" inside the container: ${m.why}` }
748  }
749  return { segment: `rm -rf ${hosts.join(' ')}` }
750}
751
752// Which dangerous patterns a Bash command holds. Best effort, a net and not a
753// parser: it splits on shell separators and looks inside sh -c. `hard` ones (force push,
754// production deploy) are refused outright where nobody can be asked.
755export function classify(command: string, depth = 0, env: ScratchEnv = {}): Hold[] {
756  const holds = classifyWithEnv(command, depth, env, newScope(command, env))
757  // `docker run -v "$(pwd):/w" img sh -c 'rm ...'`: the splitter cuts the docker run in two at the substitution, so a second
758  // look at a copy with each substitution named as one unknown word finds what the cut hid. Only ever adds holds.
759  const folded = depth === 0 ? foldSubstitutionsInDockerRuns(command) : command
760  if (folded === command) return holds
761  const seen = new Set(holds.map(h => `${h.kind}\0${h.segment}`))
762  return [...holds, ...classifyWithEnv(folded, depth, env, newScope(folded, env)).filter(h => !seen.has(`${h.kind}\0${h.segment}`))]
763}
764
765// A production call counts as a read only when its forwarder script is plain and every remote command is a read.
766// The script text comes from env.prodScripts; a path not read yet is asked for through env.prodWanted and held this time. The repo's dotenv file is
767// asked for through env.prodWantedEnv instead, so the caller reduces exactly that path, and no other, to its key names.
768function prodReadOnly(raw: string, fusedErr: boolean, shape: Map<string, string> | undefined, depth: number, scope: Scope, env: ScratchEnv): boolean {
769  // depth 0 only: inside `bash -c` the commands before it are out of sight, and one of them could rewrite the script the hook just read
770  if (depth > 0 || !shape || scope.mounts) return false
771  const call = parseProdCall(raw.trim(), fusedErr)
772  if (!call) return false
773  // the script path uses only the assignments the shape check accepted, never the regex over the raw command or the inherited environment
774  const script = resolveHostPath(call.script, { ...scope, vars: shape })
775  // backstop: the path bash will open is one plain absolute word
776  if (!('path' in script) || !/^\/[\w./-]+$/.test(script.path)) return false
777  // no hidden last part either (a hidden folder such as .worktrees is fine): the forwarder is a script, never a dotfile such as the dotenv file the caller reduces to key names
778  if ((script.path.split('/').pop() ?? '').startsWith('.')) return false
779  // no `.` or `..` part, in the word or in any value it expands: the kernel follows a symlink before it folds `..`
780  const expanded = call.script.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g, (_m, a?: string, b?: string) => shape.get((a ?? b) as string) ?? '')
781  if (hasDotPart(expanded)) return false
782  const text = env.prodScripts?.[script.path]
783  if (text === undefined) {
784    env.prodWanted?.add(script.path)
785    return false
786  }
787  if (!forwarderIsPlain(text) || !remoteIsRead(call.remote)) return false
788  // the one file the forwarder sources must be a version we have reviewed
789  const deploy = deployScript(text, scope.home)
790  if (deploy === undefined) return false
791  const deployText = env.prodScripts?.[deploy.path]
792  if (deployText === undefined) {
793    env.prodWanted?.add(deploy.path)
794    return false
795  }
796  if (!deployIsPinned(deploy.repo, deployText, env.deployPins)) return false
797  // the dotenv file it loads: key names only (index.tsx keeps nothing else of the file), every one on the allowlist
798  const envPath = `${scope.home}/repos/${deploy.repo}/.env`
799  const keys = env.prodScripts?.[envPath]
800  if (keys === undefined) {
801    env.prodWantedEnv?.add(envPath)
802    return false
803  }
804  return deployEnvIsPlain(keys, env.deployEnvKeys)
805}
806
807function classifyWithEnv(command: string, depth: number, env: ScratchEnv, scope: Scope): Hold[] {
808  const holds: Hold[] = []
809  const parts = segmentsWithSeps(command)
810  for (const [index, part] of parts.entries()) {
811    const raw = part.text
812    // `2>&1` is cut at its "&": the piece ends in `2>` and the next one starts with `1`
813    const fusedErr = part.sep === '&' && /(?:^|\s)2>\s*$/.test(raw) && /^1\s*$/.test(parts[index + 1]?.text ?? '')
814    const seg = strip(raw).replace(/^\\/, '')
815    if (seg === '') continue
816    trackCd(seg, command, scope)
817    // `docker run -v SRC:DST ...`: the text it runs sees its paths through these mounts
818    const parsed = DOCKER_RUN.test(seg) ? parseMounts(seg) : undefined
819    const inner: Scope = { ...scope, mounts: parsed ? parsed.mounts : scope.mounts, incomplete: parsed ? parsed.incomplete : scope.incomplete, timeout: scope.timeout || segmentTimeout(seg) }
820    const wrapped = /^(?:ba|z)?sh\s+-c\s+(.*)$/.exec(seg)
821    if (wrapped && depth < 3) {
822      holds.push(...classifyWithEnv(wrapped[1].replace(/^["']|["']$/g, ''), depth + 1, env, inner))
823    } else if (depth < 3 && runsQuoted(seg)) {
824      for (const piece of quotedPieces(seg)) holds.push(...classifyWithEnv(piece, depth + 1, env, inner))
825    }
826    const t = seg.split(/\s+/)
827    const flags = t.filter(x => x.startsWith('-'))
828    // the words the command itself gets: a quoted message with spaces (`git commit -m "fix push -f"`) is text, not words
829    const bare = withoutQuoted(seg).split(/\s+/).filter(Boolean)
830    const add = (kind: HeldKind, hard: boolean) => holds.push({ kind, hard, segment: seg })
831
832    if (/^(?:\S*\/)?tmux$/.test(t[0])) {
833      const invocation = tmuxInvocation(t)
834      if (!invocation.privateSocket && invocation.command === 'kill-server') {
835        add('tmux shared lanes', true)
836      } else if (!invocation.privateSocket && invocation.command === 'kill-session') {
837        const args = t.slice(invocation.index + 1)
838        const targetsLanes = args.some(
839          (arg, i) => (arg === '-t' && args[i + 1] === 'lanes') || /^-t=?lanes$/.test(arg),
840        )
841        if (targetsLanes) add('tmux shared lanes', true)
842      }
843    }
844    if (/^(?:\S*\/)?rm$/.test(t[0])) {
845      const r = flags.some(f => /^-[^-]*[rR]/.test(f) || f === '--recursive')
846      const f = flags.some(f => /^-[^-]*f/.test(f) || f === '--force')
847      if (r && f && scope.mounts && (scope.mounts.length > 0 || scope.incomplete)) {
848        // inside a container that has mounts: judge each path by what it really is on this machine
849        const mapped = mapRmTargets(targetsOf(seg).map(unquote), scope.mounts, scope)
850        if (mapped.some(m => !containerPathIsHarmless(m, env, scope.incomplete))) holds.push({ kind: 'rm -rf', hard: false, segment: seg, container: mapped })
851      } else if (r && f && !ownScratchTargets(command, env, depth).some(group => group.segment === seg)) {
852        add('rm -rf', false)
853      }
854    }
855    const call = parseRunCall(seg)
856    if (call && !((call.timeout || scope.timeout) && !call.detached) && !(call.mode === 'run' ? call.capped : (env.composeLimited ?? []).includes(composeKey(call, scope.cwd)))) add('docker run without limits', false)
857    if (/^docker\s+(system|volume|image)\s+prune\b/.test(seg)) add(`docker ${t[1]} prune` as HeldKind, false)
858    if (/^docker\s+volume\s+(rm|remove)\b/.test(seg)) add('docker volume rm', false)
859    if (/^(docker\s+compose|docker-compose)\b/.test(seg) && bare.includes('down')) {
860      const after = bare.slice(bare.indexOf('down'))
861      if (after.some(x => x === '--volumes' || /^-[^-]*v/.test(x))) add('docker compose down -v', false)
862    }
863    if (/^git\b/.test(seg) && bare.includes('push')) {
864      const after = bare.slice(bare.indexOf('push'))
865      if (after.some(x => x === '-f' || x.startsWith('--force') || /^\+\S/.test(x))) add('git push --force', true)
866    }
867    if (isProdDeploy(seg) && !prodReadOnly(raw, fusedErr, prodLineShape(command, parts, index, fusedErr), depth, scope, env)) add('production deploy', true)
868  }
869  return holds
870}
871
872type OwnScratchGroup = { segment: string; targets: string[] }
873
874// Returns targets from rm -rf segments that are safe scratch locations. This
875// uses the same best-effort segmentation as classify, not a full shell parser.
876// A relative target counts only when a literal `cd <full path> &&` leads to it (see cwdTracker); the targets returned are the full paths.
877export function ownScratchTargets(command: string, env: ScratchEnv = {}, depth = 0): OwnScratchGroup[] {
878  const groups: OwnScratchGroup[] = []
879  const failed = new Set<string>() // the same words that failed once (say, with no cd before them) never pass on another line
880  const parts = segmentsWithSeps(command)
881  const cwdAt = cwdTracker(command, env)
882  let before = '' // the command up to this segment: a variable counts only if it was set before the rm that uses it
883  for (const [index, { text }] of parts.entries()) {
884    const assignments = assignmentsOf(before, env)
885    before += text + parts[index].sep
886    const cwd = cwdAt(index)
887    const seg = strip(text).replace(/^\\/, '')
888    if (seg === '') continue
889    const wrapped = /^(?:ba|z)?sh\s+-c\s+(.*)$/.exec(seg)
890    if (wrapped && depth < 3) {
891      groups.push(
892        ...ownScratchTargets(wrapped[1].replace(/^["']|["']$/g, ''), env, depth + 1).map(
893          targets => ({ segment: seg, targets }),
894        ),
895      )
896    }
897    const t = seg.split(/\s+/)
898    if (!/^(?:\S*\/)?rm$/.test(t[0])) continue
899    const flags = t.filter(x => x.startsWith('-'))
900    if (
901      !flags.some(f => /^-[^-]*[rR]/.test(f) || f === '--recursive') ||
902      !flags.some(f => /^-[^-]*f/.test(f) || f === '--force')
903    ) continue
904    const targets = t.slice(1).filter(x => !x.startsWith('-')).map(unquote)
905    // a relative word is joined to the folder a guarded cd led to; with none, it stays relative and is held
906    const full = targets.map(x => (cwd && x !== '' && !/^[/~$]/.test(x) ? `${cwd}/${x}` : x))
907    if (full.length > 0 && full.every(target => isOwnScratch(target, assignments, env))) {
908      groups.push({ segment: seg, targets: full })
909    } else failed.add(seg)
910  }
911  return groups.filter(g => !failed.has(g.segment))
912}
913
914// The folder each segment runs in, when a literal `cd <full path>` sets it. A cd counts only on a chain of && that starts a list
915// (the start, or after ; or a newline), so the later words run only if it worked: after `cd X; rm -rf a`, `cd X || ...`, a pipe,
916// a background `&`, a subshell or a substitution, the folder is unknown and a relative target keeps holding.
917function cwdTracker(command: string, env: ScratchEnv): (index: number) => string | undefined {
918  const segs = segmentsWithSeps(command)
919  let before = ''
920  // text a heredoc only writes (a python script's parens) is not shell, so it blinds nothing
921  const blind = /(?:^|[^$])\(|`|\$\(\s*(?:cd|pushd|popd)\b/.test(withoutTextHeredocs(command)) // a subshell or substitution may hold its own cd
922  const folders: Array<string | undefined> = []
923  let cwd: string | undefined
924  for (let i = 0; i < segs.length; i += 1) {
925    const prev = segs[i - 1]
926    // `a && b` splits into `a`, an empty piece between the two &, and `b`: the empty piece changes nothing
927    if (i >= 1 && prev.sep === '&' && segs[i].sep === '&' && strip(segs[i].text) === '') {
928      folders.push(cwd)
929      before += segs[i].text + segs[i].sep
930      continue
931    }
932    const andBefore = i >= 2 && prev.sep === '&' && strip(prev.text) === '' && segs[i - 2].sep === '&'
933    const startsList = i === 0 || prev.sep === ';' || prev.sep === '\n'
934    if (!andBefore) cwd = undefined // anything but && ends what the last cd promised
935    const seg = strip(segs[i].text).replace(/^\\/, '')
936    const assignments = assignmentsOf(before, env)
937    before += segs[i].text + segs[i].sep
938    folders.push(cwd)
939    const m = /^(cd|pushd|popd)\b\s*(.*)$/.exec(seg)
940    if (m) {
941      const word = unquote(m[2].trim())
942      const guarded = m[1] === 'cd' && !blind && (startsList || andBefore)
943      cwd = guarded && word !== '' && !/\s/.test(word) ? literalFolder(word, cwd, assignments, env) : undefined
944    }
945  }
946  return index => folders[index]
947}
948
949// A folder word written out in full, once ~ and the command's own literal variables are filled in; undefined for anything else.
950function literalFolder(word: string, cwd: string | undefined, assignments: Map<string, string | null>, env: ScratchEnv): string | undefined {
951  let w = word
952  if (w === '~' || w.startsWith('~/')) {
953    if (!env.home) return undefined
954    w = env.home + w.slice(1)
955  }
956  w = w.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g, (m, a?: string, b?: string) => {
957    const value = assignments.get((a ?? b) as string)
958    return typeof value === 'string' ? value : m
959  })
960  if (/[$*?[\]{}`~]/.test(w)) return undefined
961  if (!w.startsWith('/')) {
962    if (!cwd) return undefined
963    w = `${cwd}/${w}`
964  }
965  return normalizePath(w)
966}
967
968// Variables the command sets itself: a literal value, or null for one set from `mktemp` (a fresh temp folder, path unknown).
969// A value that names another variable set earlier to a literal is filled in (S=/tmp/x; P=$S/prof gives P=/tmp/x/prof); one that
970// names a variable nothing set keeps its `$`, so a target built from it stays held.
971function assignmentsOf(command: string, env: ScratchEnv): Map<string, string | null> {
972  const assignments = new Map<string, string | null>()
973  if (env.tmpdir) assignments.set('TMPDIR', env.tmpdir)
974  const mktemp = /(?:^|[;&|\n]\s*)([A-Za-z_]\w*)=\$\(\s*mktemp(?:\s+[^)]*)?\)/g
975  for (const match of command.matchAll(mktemp)) assignments.set(match[1], null)
976  const literals = /(?:^|[;&|\n]\s*)(?:export\s+)?([A-Za-z_]\w*)=("[^"]*"|'[^']*'|[^\s;&|]+)/g
977  const unsure = new Set<string>() // set twice to different things, or by mktemp and by hand: which one the rm sees depends on how the shell ran
978  for (const match of command.matchAll(literals)) {
979    if (match[2].startsWith('$(')) continue
980    const value = unquote(match[2])
981    if (assignments.has(match[1]) && assignments.get(match[1]) !== value) unsure.add(match[1])
982    assignments.set(match[1], value)
983  }
984  for (const name of unsure) assignments.delete(name)
985  for (let pass = 0; pass < 5; pass += 1) {
986    let changed = false
987    for (const [name, value] of assignments) {
988      if (typeof value !== 'string' || !value.includes('$')) continue
989      const next = value.replace(/\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))/g, (m, a?: string, b?: string) => {
990        const ref = (a ?? b) as string
991        const other = ref === name ? undefined : assignments.get(ref)
992        return typeof other === 'string' && !other.includes('$') ? other : m
993      })
994      if (next !== value) {
995        assignments.set(name, next)
996        changed = true
997      }
998    }
999    if (!changed) break
1000  }
1001  return assignments
1002}
1003
1004export const unquote = (value: string) => value.replace(/^(["'])(.*)\1$/, '$2')
1005
1006function isOwnScratch(
1007  input: string,
1008  assignments: Map<string, string | null>,
1009  env: ScratchEnv,
1010): boolean {
1011  if (!input) return false
1012  let path = input
1013  const variable = /^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))(\/.*)?$/.exec(path)
1014  if (variable ? /[*?[\]{}]/.test(variable[3] ?? '') : /[*?[\]{}]/.test(input)) {
1015    return false
1016  }
1017  if (variable) {
1018    const name = variable[1] ?? variable[2]
1019    if (!assignments.has(name)) return false
1020    const value = assignments.get(name)
1021    if (value === null) {
1022      const suffix = normalizePath((variable[3] ?? '').replace(/^\//, ''))
1023      return !suffix.startsWith('../') && suffix !== '..' && !suffix.startsWith('/')
1024    }
1025    if (value === undefined) return false
1026    path = `${value}${variable[3] ?? ''}`
1027  } else if (path.startsWith('$')) {
1028    return false
1029  }
1030
1031  if (path === '~' || path.startsWith('~/')) path = `${env.home ?? '~'}${path.slice(1)}`
1032  else if (path.startsWith('~')) return false
1033  if (/[$*?[\]{}]/.test(path)) return false
1034  const normalized = normalizePath(path)
1035
1036  const cacheNames = new Set([
1037    '__pycache__',
1038    '.pytest_cache',
1039    '.mypy_cache',
1040    '.ruff_cache',
1041    '.expo',
1042    '.turbo',
1043  ])
1044  const parts = normalized.split('/').filter(Boolean)
1045  // A cache name directly in home is user state, not scratch (~/.expo holds the Expo login).
1046  const parent = `${normalized.startsWith('/') ? '/' : ''}${parts.slice(0, -1).join('/')}`
1047  const homeLevel = parent === '~' || (env.home !== undefined && parent === normalizePath(env.home))
1048  if (
1049    (!homeLevel && cacheNames.has(parts.at(-1) ?? '')) ||
1050    (parts.at(-2) === 'node_modules' && parts.at(-1) === '.cache')
1051  ) return true
1052
1053  const tmpRoots = ['/tmp', env.tmpdir ? normalizePath(env.tmpdir) : undefined].filter(
1054    (root): root is string => Boolean(root),
1055  )
1056  if (normalized.startsWith('/') && tmpRoots.some(
1057    root => normalized !== root && normalized.startsWith(`${root}/`),
1058  )) return true
1059
1060  const laneRoot = `${normalizePath(`${env.home ?? '~'}/.claude/state/lanes`)}/`
1061  return normalized.startsWith(laneRoot) && normalized.slice(laneRoot.length).split('/').filter(Boolean).length >= 2
1062}
1063
1064function normalizePath(path: string): string {
1065  const absolute = path.startsWith('/')
1066  const parts: string[] = []
1067  for (const part of path.split('/')) {
1068    if (!part || part === '.') continue
1069    if (part === '..' && parts.length > 0 && parts.at(-1) !== '..') parts.pop()
1070    else if (part === '..' && !absolute) parts.push(part)
1071    else if (part !== '..') parts.push(part)
1072  }
1073  return `${absolute ? '/' : ''}${parts.join('/')}` || (absolute ? '/' : '.')
1074}
1075
1076// Non-flag words after the command word: what an rm names.
1077export function targetsOf(segment: string): string[] {
1078  return segment.split(/\s+/).slice(1).filter(x => !x.startsWith('-'))
1079}
1080
1081// In plain words: what a held command does, and why it is held. Shown in the "Run it?" question
1082// and in every refusal, so nobody has to decode `rm -rf` from the log.
1083export function explain(hold: Hold): { what: string; why: string } {
1084  const vars = [...hold.segment.matchAll(/\$\{?([A-Za-z_]\w*)/g)].map(m => m[1])
1085  switch (hold.kind) {
1086    case 'rm -rf':
1087      if (hold.container) {
1088        return {
1089          what: 'deletes files inside a Docker container; a path under a mounted host folder is deleted on this machine too, with no undo',
1090          why: 'a mount ties the container path to a real folder here, and the held command does not say which until the mount is read',
1091        }
1092      }
1093      return {
1094        what: 'deletes the named files and folders and everything inside them, without asking for each one',
1095        why:
1096          vars.length > 0
1097            ? `there is no undo, and the path goes through $${vars[0]}: if $${vars[0]} is empty or unset the path collapses (for example "$${vars[0]}/build" becomes "/build") and the wrong place is deleted`
1098            : 'there is no undo, and a wrong or empty path deletes far more than meant',
1099      }
1100    case 'docker system prune':
1101    case 'docker image prune':
1102      return {
1103        what: 'deletes every unused Docker container, network and image on this machine',
1104        why: 'one Docker engine is shared by every project here, and another project may need what it removes',
1105      }
1106    case 'docker volume prune':
1107      return {
1108        what: 'deletes every Docker volume no running container uses (volumes hold databases and uploads)',
1109        why: 'the data in a deleted volume cannot be brought back',
1110      }
1111    case 'docker volume rm':
1112      return { what: 'deletes the named Docker volumes and the data in them', why: 'the data cannot be brought back' }
1113    case 'docker compose down -v':
1114      return {
1115        what: 'stops the compose stack and deletes its volumes (its database and uploads)',
1116        why: 'the data in a deleted volume cannot be brought back',
1117      }
1118    case 'docker run without limits':
1119      return {
1120        what: 'starts a container with no CPU cap and no timeout in front, so it can take every core and keep them',
1121        why: 'on 19 Oct one such container took 14.6 of 16 cores and the machine stopped answering',
1122      }
1123    case 'git push --force':
1124      return {
1125        what: "overwrites the branch on the remote with this machine's history",
1126        why: 'commits other people or machines pushed can be lost',
1127      }
1128    case 'production deploy':
1129      return { what: 'ships to the live production site', why: 'production changes wait for the agreed window' }
1130    case 'tmux shared lanes':
1131      return hold.segment.includes('kill-server')
1132        ? {
1133            what: "closes every lane window (the tmux session 'lanes'), with no undo; it also closes every other session and window on the default tmux server",
1134            why: 'all lanes share the default tmux server, so resetting one server closes every lane',
1135          }
1136        : {
1137            what: "closes every lane window (the tmux session 'lanes'), with no undo",
1138            why: 'all lanes share this tmux session, so ending it closes every lane',
1139          }
1140    default:
1141      return { what: hold.kind, why: 'it is on the held list' }
1142  }
1143}
1144
1145export type LaneEnv = { home: string; hand?: string; tmpdir?: string }
1146
1147// A lane (AFA_LANE=1) is not asked "Run it?" about a hold whose fix can be named: the refusal says the fix and the lane runs the
1148// corrected command. A hold with no fix here keeps the dialog. Only a relative path in an rm and a docker run without limits have one.
1149export function laneFix(hold: Hold): string | undefined {
1150  if (hold.kind === 'docker run without limits') return `Fix: ${UNLIMITED_FIX}. Then run it again.`
1151  if (hold.kind === 'rm -rf' && !hold.container && targetsOf(hold.segment).map(unquote).some(x => x !== '' && !/^[/~$]/.test(x))) {
1152    return 'Fix: use the full absolute path, written out in full (for "cd /a/b && rm -rf c" write "rm -rf /a/b/c"): a relative name depends on the folder the shell is in, which the guard cannot confirm. Then run it again.'
1153  }
1154  return undefined
1155}
1156
1157// A lane nobody watches (AFA_LANE_UNATTENDED=1, set by lane.sh) may delete only inside: its own hand-off
1158// folder (AFA_LANE_HAND) or a worktree under ~/repos/.worktrees. The path must be written out in full: no
1159// variable, no pattern, no relative path, no `..`. This check is on the words only; a symlink inside an
1160// allowed folder that points elsewhere is caught by realPathVerdict, which index.tsx runs on the resolved paths.
1161export function unattendedRoots(env: LaneEnv): string[] {
1162  const hand = env.hand ? normalizePath(env.hand) : undefined
1163  return [hand, `${normalizePath(env.home)}/repos/.worktrees`].filter((r): r is string => Boolean(r))
1164}
1165
1166// The full paths an rm names, once the words check passed: what index.tsx hands to realpath.
1167export function unattendedRmPaths(segment: string, env: LaneEnv): string[] {
1168  const home = normalizePath(env.home)
1169  return targetsOf(segment)
1170    .map(unquote)
1171    .map(t => normalizePath(t === '~' || t.startsWith('~/') ? `${home}${t.slice(1)}` : t))
1172}
1173
1174// `real` maps each named path to what realpath says it is; `roots` are the allowed folders, themselves resolved.
1175// A path that cannot be resolved (empty) is refused, so a failing realpath never opens the door.
1176export function realPathVerdict(
1177  real: Array<{ path: string; real: string }>,
1178  roots: string[],
1179): { ok: true } | { ok: false; reason: string } {
1180  for (const r of real) {
1181    if (!r.real) return { ok: false, reason: `"${r.path}" could not be resolved to its real location, so the delete is refused` }
1182    if (!roots.some(root => r.real !== root && r.real.startsWith(`${root}/`))) {
1183      return {
1184        ok: false,
1185        reason: `"${r.path}" really points to ${r.real} (through a link), which is outside this lane's own folder and its worktree`,
1186      }
1187    }
1188  }
1189  return { ok: true }
1190}
1191
1192export function unattendedRmVerdict(segment: string, env: LaneEnv): { ok: true } | { ok: false; reason: string } {
1193  const targets = targetsOf(segment).map(unquote)
1194  const hand = env.hand ? normalizePath(env.hand) : undefined
1195  const home = normalizePath(env.home)
1196  const where = [
1197    hand ? `this lane's own folder (${hand})` : null,
1198    `a worktree under ${home}/repos/.worktrees`,
1199  ].filter(Boolean).join(', ')
1200  const refuse = (target: string, why: string) => ({
src/prodread.ts 510 lines
1// A command that ships to production is held. One exception is checked here, by reading what will run: a --prod call of a forwarder
2// script (rexec.sh) whose script does nothing but pass the command on, and whose every remote command is a read (drush status, a
3// SELECT, composer audit, a curl GET ...). Nothing here trusts a label: a command the reader does not recognise word for word is
4// not a read, and the caller keeps holding it.
5
6export type Word = { v: string; quote: 'none' | 'single' | 'double' | 'mixed' }
7
8type Redirects = { errToOut?: boolean }
9
10// The words of a command line, with quotes taken off. Returns undefined at anything it will not judge: a backslash outside quotes,
11// a substitution, a subshell, a redirect other than the three that only discard or merge output, a "#" comment. `remote` is the
12// text a remote shell will run (no unquoted "$" at all); the local line may use $VAR in a word, which the caller resolves.
13// With `fusedErr`, a last word `2>` stands for `2>&1` (the splitter cut the line at the "&"; the caller checked what followed).
14function tokenize(text: string, remote: boolean, fusedErr = false): { commands: Word[][]; ops: string[] } | undefined {
15  const commands: Word[][] = [[]]
16  const ops: string[] = []
17  let word: Word | undefined
18  let i = 0
19  const endWord = () => {
20    if (word) commands[commands.length - 1].push(word)
21    word = undefined
22  }
23  const endCommand = (op: string) => {
24    endWord()
25    ops.push(op)
26    commands.push([])
27  }
28  const REDIRECTS = ['2>&1', '2>/dev/null', '>/dev/null', '1>/dev/null']
29  while (i < text.length) {
30    const c = text[i]
31    if (!word && /[ \t]/.test(c)) {
32      i += 1
33      continue
34    }
35    if (!word) {
36      const rest = text.slice(i)
37      const redirect = REDIRECTS.find(r => rest.startsWith(r) && (rest.length === r.length || /[\s;&|]/.test(rest[r.length])))
38      if (redirect) {
39        i += redirect.length
40        continue
41      }
42      if (fusedErr && /^2>\s*$/.test(rest)) {
43        i = text.length
44        continue
45      }
46    }
47    if (c === "'" || c === '"') {
48      const piece = c
49      let j = i + 1
50      let value = ''
51      for (; j < text.length && text[j] !== piece; j += 1) {
52        if (piece === "'") value += text[j]
53        else if (text[j] === '\\') {
54          if (text[j + 1] !== '"' && text[j + 1] !== '\\') return undefined
55          value += text[j + 1]
56          j += 1
57        } else if (text[j] === '$' || text[j] === '`') return undefined
58        else value += text[j]
59      }
60      if (j >= text.length) return undefined
61      const kind = piece === "'" ? 'single' : 'double'
62      word = word ? { v: word.v + value, quote: word.quote === kind ? kind : 'mixed' } : { v: value, quote: kind }
63      i = j + 1
64      continue
65    }
66    if (c === '\\' || c === '`' || c === '(' || c === ')' || c === '<' || c === '>') return undefined
67    if (c === '$' && (remote || !/[A-Za-z_{]/.test(text[i + 1] ?? ''))) return undefined
68    if (c === '#' && !word) return undefined
69    if (c === ';' || c === '\n') {
70      endCommand(';')
71      i += 1
72      continue
73    }
74    if (c === '&') {
75      if (text[i + 1] !== '&') return undefined
76      endCommand('&&')
77      i += 2
78      continue
79    }
80    if (c === '|') {
81      const op = text[i + 1] === '|' ? '||' : '|'
82      endCommand(op)
83      i += op.length
84      continue
85    }
86    if (/[ \t]/.test(c)) {
87      endWord()
88      i += 1
89      continue
90    }
91    word = word ? { v: word.v + c, quote: word.quote === 'none' ? 'none' : 'mixed' } : { v: c, quote: 'none' }
92    i += 1
93  }
94  endWord()
95  return { commands: commands.filter(c => c.length > 0), ops }
96}
97
98// ---- the local line: [STACK_NAME=x] [timeout N] [bash|sh] SCRIPT --prod 'REMOTE' [USER] ----
99
100export type ProdCall = { script: string; remote: string; user?: string }
101
102export function parseProdCall(raw: string, fusedErr: boolean): ProdCall | undefined {
103  const t = tokenize(raw, false, fusedErr)
104  if (!t || t.commands.length !== 1) return undefined
105  let w = t.commands[0]
106  while (w.length > 0 && /^[A-Za-z_]\w*=/.test(w[0].v)) {
107    if (!/^STACK_NAME=[\w-]+$/.test(w[0].v)) return undefined
108    w = w.slice(1)
109  }
110  if (w[0]?.v === 'timeout' && w[0].quote === 'none') {
111    let j = 1
112    while (w[j]?.v.startsWith('-')) j += ['-s', '-k', '--signal', '--kill-after'].includes(w[j].v) ? 2 : 1
113    if (!/^\d+[smh]?$/.test(w[j]?.v ?? '')) return undefined
114    w = w.slice(j + 1)
115  }
116  if (w[0] && (w[0].v === 'bash' || w[0].v === 'sh') && w[0].quote === 'none') w = w.slice(1)
117  const [script, flag, remote, user, ...extra] = w
118  if (!script || !flag || !remote || extra.length > 0) return undefined
119  if (!/^--prod(?:uction)?$/.test(flag.v) || flag.quote !== 'none') return undefined
120  if (remote.quote !== 'single' && remote.quote !== 'double') return undefined
121  if (user && !/^(?:\d+|www-data|root)$/.test(user.v)) return undefined
122  return { script: script.v, remote: remote.v, user: user?.v }
123}
124
125// ---- the whole command line around the call ----
126// The hook reads the forwarder before the command runs, so nothing else in the command may touch that file or run beside it:
127// only plain assignments or `cd /abs/path` before the call (joined by ; newline or &&), then the call, then optionally 2>&1,
128// then optionally ONE pipe into tail/head with a number. Anything else is held.
129
130type Piece = { text: string; sep: string }
131
132// A value is one plain word: no space (the unquoted `$SP` in the call would split on it), no `~` (bash expands it in an assignment, the map would not), no `$`, glob or redirect characters.
133const ASSIGN = /^([A-Za-z_]\w*)=([\w./:,@%+=-]*|'[\w./:,@%+=-]*'|"[\w./:,@%+=-]*")$/
134// Only these names may be set before the call: bash gives many other names a meaning of their own (readonly, recomputed, or `$_`), and a value stored here would then differ from what bash holds.
135const ASSIGN_OK = /^(?:SP|L|DIR|SCRIPTS|STACK_NAME)$/
136const CD_ABS = /^cd\s+\/[\w./-]*$/
137
138// bash keeps CR, NBSP and other odd characters inside a word where JS .trim() drops them, so the hook and the shell would read different lines.
139// Anything but printable ASCII, tab and newline refuses the exception.
140export const PLAIN_ASCII = /^[\x20-\x7e\t\n]*$/
141// a `.` or `..` part is followed by the kernel through a symlink before it is folded, which a text tidy-up cannot know
142export const hasDotPart = (path: string) => path.split('/').some(part => part === '.' || part === '..')
143const TAIL_HEAD = /^(?:tail|head)(?:\s+-n\s*\d+|\s+-\d+)?$/
144
145const blank = (p: Piece | undefined) => p !== undefined && p.text.trim() === ''
146const lineEnd = (sep: string) => sep === '' || sep === '\n' || sep === ';'
147
148// Returns the plain assignments before the call (the only variables the script path may use), or undefined when the line is not the plain shape.
149// A `<<` anywhere refuses it: the splitter drops heredoc bodies it takes for text, and the shell would not see the line the same way.
150export function prodLineShape(command: string, parts: Piece[], index: number, fusedErr: boolean): Map<string, string> | undefined {
151  if (command.includes('<<') || !PLAIN_ASCII.test(command)) return undefined
152  const vars = new Map<string, string>()
153  const ok = lineShape(parts, index, fusedErr, vars)
154  return ok ? vars : undefined
155}
156
157function lineShape(parts: Piece[], index: number, fusedErr: boolean, vars: Map<string, string>): boolean {
158  for (let i = 0; i < index; i += 1) {
159    const { text, sep } = parts[i]
160    const t = text.trim()
161    if (t === '') {
162      // a blank line, or the second "&" of "&&" (checked where the first one is)
163      if (sep === ';' || sep === '\n') continue
164      if (sep === '&' && i > 0 && parts[i - 1].sep === '&' && !blank(parts[i - 1])) continue
165      return false
166    }
167    const a = ASSIGN.exec(t)
168    if (!(a ? ASSIGN_OK.test(a[1]) : CD_ABS.test(t) && !hasDotPart(t.slice(2).trim()))) return false
169    if (a) vars.set(a[1], a[2].replace(/^(['"])(.*)\1$/, '$2'))
170    if (sep === '&') {
171      if (!(blank(parts[i + 1]) && parts[i + 1].sep === '&')) return false // a lone & puts it in the background
172    } else if (sep !== ';' && sep !== '\n') return false
173  }
174  let last = index
175  if (fusedErr) {
176    if (parts[index + 1]?.text.trim() !== '1') return false // `2>&1` and nothing else: other words would reach the script
177    last = index + 1
178  }
179  let sep = parts[last].sep
180  let k = last + 1
181  if (sep === '|') {
182    const next = parts[k]
183    if (!next || !TAIL_HEAD.test(next.text.trim())) return false
184    sep = next.sep
185    k += 1
186  }
187  if (!lineEnd(sep)) return false
188  return parts.slice(k).every(p => blank(p) && (p.sep === '' || p.sep === '\n'))
189}
190
191// ---- the forwarder script: every line must be one of these, so it only passes its second argument on ----
192
193const FORWARDER_LINES: RegExp[] = [
194  /^#(?!!).*$/,
195  /^set -[euo]+(?: pipefail)?$/,
196  /^T="\$1"; CMD="\$2"; U="\$\{3-82\}"$/,
197  /^T="\$1"; CMD="\$2"; U="\$\{3:-82\}"$/,
198  /^cd (?:~|\$HOME)\/repos\/[\w-]+ \|\| exit 1$/,
199  /^source scripts\/portainer-deploy\.sh "\$T"$/,
200  /^auth >\/dev\/null 2>&1 \|\| \{ echo "auth failed"; exit 1; \}$/,
201  /^cid="\$\(find_service_container "\$\{STACK_NAME\}_php"\)"$/,
202  /^\[ -n "\$cid" \] \|\| \{ echo "no php container for \$STACK_NAME"; exit 1; \}$/,
203  /^echo "\[rexec\] stack=\$STACK_NAME portainer=\$PORTAINER_URL" >&2$/,
204  /^container_exec "\$cid" "\$CMD" "\$U"$/,
205]
206
207const SHEBANGS = new Set(['#!/usr/bin/env bash', '#!/bin/bash'])
208
209// the lines both the plain check and the deploy-script lookup read, so they cannot disagree about which line is the cd
210const forwarderLines = (text: string): string[] => text.split('\n').map(l => l.trim()).filter(Boolean)
211
212export function forwarderIsPlain(text: string): boolean {
213  if (!PLAIN_ASCII.test(text)) return false
214  // a `#!` line is the interpreter when the script is run without `bash` in front, so line 1 may name only bash; later `#!` lines are not comments we trust
215  const first = text.split('\n')[0]
216  if (first.startsWith('#!') && !SHEBANGS.has(first)) return false
217  // no indented line: the real forwarders have none, and one would be read differently by a line match and by a person
218  if (text.split('\n').some(l => /^\s/.test(l))) return false
219  const lines = forwarderLines(text)
220  if (lines.length === 0 || lines.length > 40) return false
221  // the repo's own portainer-deploy.sh line is the only file it may source; any other `source` or `.` runs code we did not read
222  if (lines.some(l => /^(?:source|\.)\s/.test(l) && l !== 'source scripts/portainer-deploy.sh "$T"')) return false
223  if (lines.filter(l => l.startsWith('source ')).length > 1) return false
224  if (!lines.every(l => (l.startsWith('#!') ? l === first : FORWARDER_LINES.some(r => r.test(l))))) return false
225  // the cd that picks the repo must come before the source line, and stop the script when it fails
226  if (lines.filter(l => l.startsWith('cd ')).length !== 1) return false
227  const cdAt = lines.findIndex(l => l.startsWith('cd '))
228  const srcAt = lines.findIndex(l => l.startsWith('source '))
229  if (srcAt >= 0 && !(cdAt >= 0 && cdAt < srcAt)) return false
230  // exactly one thing runs in the container, and it is the second argument
231  return lines.filter(l => l.startsWith('container_exec ')).length === 1
232}
233
234// ---- the remote commands: each must be a read ----
235
236// The remote environment words a read may set, each with the values it may take: HOME and COMPOSER_HOME only to the two scratch folders
237// (they decide where a tool keeps its cache and which config it loads), the rest to a plain name.
238const ENV_OK: Record<string, RegExp> = {
239  HOME: /^\/tmp$/,
240  COMPOSER_HOME: /^\/tmp\/composer$/,
241  TZ: /^[A-Za-z_/+-]{1,40}$/,
242  LANG: /^(?:C|C\.UTF-8|en_US\.UTF-8)$/,
243  LC_ALL: /^(?:C|C\.UTF-8|en_US\.UTF-8)$/,
244}
245const PLAIN = /^[\w./:,@%+=-]*$/
246
247const PLAIN_READERS = new Set(['echo', 'printf', 'true', 'pwd', 'ls', 'cat', 'head', 'tail', 'grep', 'egrep', 'fgrep', 'cut', 'wc', 'tr', 'stat', 'du', 'df', 'test', '[', 'uname', 'whoami', 'id', 'basename', 'dirname', 'readlink', 'realpath'])
248
249const DRUSH_SUBCOMMANDS = new Set(['status', 'st', 'core:status', 'core-status', 'state:get', 'sget', 'watchdog:show', 'ws', 'wd-show', 'pm:list', 'pml', 'pm-list', 'pm:security', 'config:get', 'cget', 'config:status', 'cst', 'core:requirements', 'requirements', 'sqlq', 'sql:query', 'sql-query', 'version'])
250const DRUSH_GLOBAL = /^(?:--no-ansi|--ansi|-v|-vv|-vvv|--verbose|--quiet|-q|--uri=[\w.:/-]+)$/
251const DRUSH_OPTION = /^--(?:format|fields|field|filter|severity|count|type|status|uri|package|extra-sort|limit|offset)=[\w .,:*@/-]*$|^--(?:pipe|full|no-ansi|ansi|extended|detail)$/
252const SQL_READ = /^\s*(?:select|show|describe|desc|explain\s+select)\b/i
253const SQL_BAD = /\b(?:into|outfile|dumpfile|for\s+update|lock\s+in\s+share|sleep|benchmark|get_lock|release_lock|load_file|call|set|handler|delete|update|insert|replace|merge|truncate|alter|drop|create|grant|revoke|analyze|optimize|repair|lock|unlock|nextval|setval|lo_export|lo_import|master_pos_wait|sys_exec|sys_eval|pg_\w+)\b|;|--|\/\*|#/i
254
255const COMPOSER_SUBCOMMANDS = new Set(['outdated', 'audit', 'show', 'diff', 'licenses', 'why', 'why-not', 'depends', 'prohibits', 'validate', 'status', '--version', 'about'])
256const COMPOSER_OPTION = /^(?:--(?:direct|no-ansi|ansi|locked|no-dev|minor-only|patch-only|major-only|strict|no-interaction|quiet|installed|outdated|self|tree|latest|name-only|path|platform|available|all|abandoned=(?:report|ignore|fail)|format=(?:json|text|summary|plain)|no-check-publish|no-check-all|no-plugins|no-scripts)|-(?:o|D|m|a|i|t|l|N|s|v|vv|vvv))$/
257
258const CURL_FLAG = /^(?:-[sSfLkvigI]+|--silent|--show-error|--fail|--location|--insecure|--head|--include|--compressed|--globoff)$/
259// each option that takes a value, and what the value may be: a write-out format is %{name} pieces and plain text only (no %output{file}, no @file),
260// a header or agent has no @ (curl reads a file for @), a time or count is a number
261const CURL_VALUE: Record<string, RegExp> = {
262  '-w': /^(?:%\{[a-z_]+\}|[\w .:/\\,-])*$/,
263  '--write-out': /^(?:%\{[a-z_]+\}|[\w .:/\\,-])*$/,
264  '-H': /^[^@\n\r]*$/,
265  '--header': /^[^@\n\r]*$/,
266  '-A': /^[^@\n\r]*$/,
267  '--user-agent': /^[^@\n\r]*$/,
268  '-m': /^\d+(?:\.\d+)?$/,
269  '--max-time': /^\d+(?:\.\d+)?$/,
270  '--connect-timeout': /^\d+(?:\.\d+)?$/,
271  '--retry': /^\d+$/,
272}
273
274const findIsRead = (args: string[]) => !args.some(a => /^-(?:exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/.test(a))
275
276function drushIsRead(args: Word[]): boolean {
277  let k = 0
278  while (k < args.length && DRUSH_GLOBAL.test(args[k].v)) k += 1
279  const sub = args[k]?.v
280  if (!sub || !DRUSH_SUBCOMMANDS.has(sub)) return false
281  const rest = args.slice(k + 1)
282  const isSql = sub === 'sqlq' || sub === 'sql:query' || sub === 'sql-query'
283  let sql = 0
284  for (const a of rest) {
285    if (a.v.startsWith('-')) {
286      if (!DRUSH_OPTION.test(a.v)) return false
287    } else if (isSql) {
288      sql += 1
289      if (!SQL_READ.test(a.v) || SQL_BAD.test(a.v)) return false
290    } else if (!PLAIN.test(a.v)) return false
291  }
292  return !isSql || sql === 1
293}
294
295function composerIsRead(args: Word[]): boolean {
296  let k = 0
297  while (k < args.length && /^(?:--no-ansi|--ansi|-n|--no-interaction|-q|--quiet)$/.test(args[k].v)) k += 1
298  if (args[k]?.v === '-d' || args[k]?.v === '--working-dir') {
299    if (args[k + 1]?.v !== '/var/www/html') return false
300    k += 2
301  }
302  const sub = args[k]?.v
303  if (!sub || !COMPOSER_SUBCOMMANDS.has(sub)) return false
304  return args.slice(k + 1).every(a => (a.v.startsWith('-') ? COMPOSER_OPTION.test(a.v) : PLAIN.test(a.v)))
305}
306
307function curlIsRead(args: Word[]): boolean {
308  let urls = 0
309  for (let k = 0; k < args.length; k += 1) {
310    const a = args[k].v
311    if (CURL_FLAG.test(a)) continue
312    if (Object.hasOwn(CURL_VALUE, a)) {
313      const val = args[k + 1]
314      if (!val || !CURL_VALUE[a].test(val.v)) return false
315      k += 1
316      continue
317    }
318    if (a === '-o' || a === '--output') {
319      if (args[k + 1]?.v !== '/dev/null') return false
320      k += 1
321      continue
322    }
323    if (a.startsWith('-')) return false
324    if (!/^https?:\/\/[\w.:/?&=%+,@~-]+$/.test(a)) return false
325    urls += 1
326  }
327  return urls >= 1
328}
329
330function phpIsRead(args: Word[]): boolean {
331  if (args.length === 1) return ['-v', '-m', '-i', '--version', '--ini'].includes(args[0].v)
332  if (args.length === 2 && args[0].v === '-r') {
333    return /^echo\s+(?:PHP_[A-Z_]+|'[\w .:-]*'|"[\w .:-]*")(?:\s*,\s*(?:PHP_[A-Z_]+|'[\w .:-]*'|"[\w .:-]*"))*\s*;?$/.test(args[1].v)
334  }
335  return false
336}
337
338// date shows the time; -s, --set and a bare number (which sets it) are not allowed. -d takes a plain value, +FORMAT is the output shape.
339function dateIsRead(args: Word[]): boolean {
340  for (let k = 0; k < args.length; k += 1) {
341    const a = args[k].v
342    if (/^(?:-u|-I|-R|--utc|--universal|--rfc-email|--iso-8601(?:=[a-z]+)?)$/.test(a)) continue
343    if (a === '-d' || a === '--date') {
344      if (!/^[\w :+.-]+$/.test(args[k + 1]?.v ?? '')) return false
345      k += 1
346      continue
347    }
348    if (/^--date=[\w :+.-]+$/.test(a)) continue
349    if (a.startsWith('+')) continue
350    return false
351  }
352  return true
353}
354
355function commandIsRead(words: Word[]): boolean {
356  let w = words
357  while (w.length > 0 && /^[A-Za-z_]\w*=/.test(w[0].v) && w[0].quote === 'none') {
358    const m = /^([A-Za-z_]\w*)=(.*)$/.exec(w[0].v) as RegExpExecArray
359    if (!Object.hasOwn(ENV_OK, m[1]) || !ENV_OK[m[1]].test(m[2])) return false
360    w = w.slice(1)
361  }
362  if (w.length === 0) return true
363  const [head, ...args] = w
364  if (head.quote !== 'none') return false
365  const name = head.v.split('/').pop() as string
366  if (head.v.includes('/') && !/^(?:\.\/)?(?:[\w.-]+\/)*(?:drush|composer)$/.test(head.v)) return false
367  if (!/^[A-Za-z][\w.:[-]*$|^\[$/.test(name)) return false
368  switch (name) {
369    case 'cd':
370      return args.length === 1 && PLAIN.test(args[0].v)
371    case 'drush':
372      return drushIsRead(args)
373    case 'composer':
374      return composerIsRead(args)
375    case 'curl':
376      return curlIsRead(args)
377    case 'php':
378      return phpIsRead(args)
379    case 'find':
380      return findIsRead(args.map(a => a.v))
381    case 'date':
382      return dateIsRead(args)
383    case 'sort':
384      return args.every(a => (a.v.startsWith('-') ? /^-[nrukfdhbsgiMV]+$/.test(a.v) : PLAIN.test(a.v) || a.quote !== 'none') && !/^-o|--output/.test(a.v))
385    case 'uniq':
386      return args.every(a => /^-[cdiuf]+$/.test(a.v))
387    default:
388      return PLAIN_READERS.has(name)
389  }
390}
391
392// True only when every command in the remote line is a recognised read.
393export function remoteIsRead(remote: string): boolean {
394  const t = tokenize(remote, true)
395  if (!t || t.commands.length === 0) return false
396  return t.commands.every(commandIsRead)
397}
398
399
400// ---- the one file the forwarder sources: pinned by SHA-256 ----
401
402// The repo folder the forwarder cd's into (`cd ~/repos/NAME || exit 1`, the only cd line) and the deploy script it then sources.
403export function deployScript(forwarder: string, home: string): { repo: string; path: string } | undefined {
404  if (!home.startsWith('/') || hasDotPart(home)) return undefined
405  const cds = forwarderLines(forwarder).filter(l => l.startsWith('cd '))
406  const m = cds.length === 1 ? /^cd (?:~|\$HOME)\/repos\/([\w-]+) \|\| exit 1$/.exec(cds[0]) : null
407  return m ? { repo: m[1], path: `${home}/repos/${m[1]}/scripts/portainer-deploy.sh` } : undefined
408}
409
410// SHA-256 (hex) of the UTF-8 bytes of a text; undefined for text that is not valid Unicode.
411export function sha256Hex(text: string): string | undefined {
412  let bytes: number[]
413  try {
414    bytes = Array.from(unescape(encodeURIComponent(text)), c => c.charCodeAt(0))
415  } catch {
416    return undefined
417  }
418  const K = [
419    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
420    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
421    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
422    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
423  ]
424  const h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
425  const bitLen = bytes.length * 8
426  bytes.push(0x80)
427  while (bytes.length % 64 !== 56) bytes.push(0)
428  for (let i = 7; i >= 0; i -= 1) bytes.push(i >= 4 ? 0 : (bitLen >>> (i * 8)) & 0xff)
429  const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n))
430  const w = new Array<number>(64)
431  for (let off = 0; off < bytes.length; off += 64) {
432    for (let i = 0; i < 16; i += 1) w[i] = ((bytes[off + 4 * i] << 24) | (bytes[off + 4 * i + 1] << 16) | (bytes[off + 4 * i + 2] << 8) | bytes[off + 4 * i + 3]) | 0
433    for (let i = 16; i < 64; i += 1) {
434      const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3)
435      const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10)
436      w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0
437    }
438    let [a, b, c, d, e, f, g, hh] = h
439    for (let i = 0; i < 64; i += 1) {
440      const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0
441      const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0
442      hh = g
443      g = f
444      f = e
445      e = (d + t1) | 0
446      d = c
447      c = b
448      b = a
449      a = (t1 + t2) | 0
450    }
451    h[0] = (h[0] + a) | 0
452    h[1] = (h[1] + b) | 0
453    h[2] = (h[2] + c) | 0
454    h[3] = (h[3] + d) | 0
455    h[4] = (h[4] + e) | 0
456    h[5] = (h[5] + f) | 0
457    h[6] = (h[6] + g) | 0
458    h[7] = (h[7] + hh) | 0
459  }
460  return h.map(x => (x >>> 0).toString(16).padStart(8, '0')).join('')
461}
462
463// SHA-256 of the scripts/portainer-deploy.sh versions a production proof may source, by the repo folder they live in. Only a folder listed here counts:
464// a lane can make a folder of its own under ~/repos with a copy of a pinned script beside files we have not read. A different copy, or a pinned copy in
465// another folder, keeps the command held. The list changes only by a reviewed PR; when a repo's script changes, so does this.
466// Eduity is not listed: its script has no BASH_SOURCE guard (sourcing it runs its action dispatch), takes REPO_ROOT from $0 (the forwarder's scratch
467// folder) and defines neither find_service_container nor container_exec. It gets a pin after it has a source guard and the helpers.
468export type DeployPins = Record<string, readonly string[]>
469export const DEPLOY_PINS: DeployPins = {
470  'Chattanooga-Digital': ['3224c8b19ee7e7f9e0edf30b16c789a7a45eaf71422ef20843127f5077e8f527'], // main (aed358a)
471}
472
473export const deployIsPinned = (repo: string, text: string, pins: DeployPins = DEPLOY_PINS): boolean => {
474  const h = sha256Hex(text)
475  return h !== undefined && Object.prototype.hasOwnProperty.call(pins, repo) && pins[repo].includes(h)
476}
477
478// ---- the dotenv file the pinned script loads ----
479// portainer-deploy.sh's load_env exports every KEY=value line of the repo's dotenv file that the caller has not set, so a key such as PYTHONPATH,
480// LD_PRELOAD, BASH_ENV or PORTAINER_URL_OVERRIDE would reach the python3 and curl it runs while it holds the production login. The hook reads the key
481// NAMES only (envKeyLines keeps what is before the first `=` and drops the values at once; nothing else of the file is held or shown) and allows a read
482// only when every key is one of these. An allowlist: a new key keeps proofs held until a reviewed PR adds it. Values are not checked, so a changed
483// value of an allowed key (a Portainer address) is outside this check.
484export const DEPLOY_ENV_KEYS: ReadonlySet<string> = new Set([
485  'PROJECT_NAME', 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_ROOT_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DRIVER',
486  'DRUPAL_ADMIN_USER', 'DRUPAL_ADMIN_PASS', 'DRUPAL_CMS_TAG', 'MARIADB_TAG', 'NGINX_TAG', 'NGINX_VHOST_PRESET', 'DRUPAL_PORT',
487  'GITHUB_BACKUP_TOKEN', 'GITHUB_REPO', 'GREG_PASSWORD', 'SMTP_PASSWORD',
488  'PORTAINER_URL', 'PORTAINER_USER', 'PORTAINER_PASSWORD', 'PORTAINER_ENDPOINT_ID',
489  'PORTAINER_PROD_URL', 'PORTAINER_PROD_USER', 'PORTAINER_PROD_PASSWORD', 'PORTAINER_PROD_ENDPOINT_ID', 'PORTAINER_GIT_TOKEN_FILE',
490  'UPTIMEROBOT_API_KEY', 'DRUPAL_GITLAB_TOKEN', 'DRUPAL_ORG_USER', 'DRUPAL_ORG_PASS',
491  'GREG_NEXTCLOUD_STAGING_URL', 'GREG_NEXTCLOUD_STAGING_USER', 'GREG_NEXTCLOUD_STAGING_PASS',
492  'NEXTCLOUD_PROD_URL', 'NEXTCLOUD_PROD_USER', 'NEXTCLOUD_PROD_PASS', 'NEXTCLOUD_PROD_APP_PASSWORD',
493])
494
495// The key part of each line load_env would look at (blank lines and lines starting with `#` are skipped as it skips them), values dropped.
496export const envKeyLines = (text: string): string =>
497  text
498    .split('\n')
499    .filter(l => l !== '' && !l.startsWith('#'))
500    .map(l => {
501      const at = l.indexOf('=')
502      return at < 0 ? l : l.slice(0, at)
503    })
504    .join('\n')
505
506// Strict on purpose: a key part that is not exactly an allowed name (spaces, a CR, a non-ASCII character, nothing before the `=`) is held, though
507// load_env would skip it, so the hook never has to agree with bash about what counts as a name.
508export const deployEnvIsPlain = (keyLines: string, allowed: ReadonlySet<string> = DEPLOY_ENV_KEYS): boolean =>
509  keyLines.split('\n').every(k => k === '' || allowed.has(k))
510
src/touches.ts 330 lines
1// What a held command would touch. Every prompt and every refusal carries these lines, for every rule:
2// real things (a path with its size, a branch and remote, containers, volumes, the service) or, when the
3// words cannot say, "can't tell what this touches: <why>". Never nothing, never a fragment of code.
4//
5// Read-only probes only. `Probe` is the part of the engine this needs (the same $.fs / $.process calls),
6// so a test hands in a fake with the same shape. Every async function here takes it first, spelled `$`.
7
8import { UNLIMITED_FIX, globBase, runTargetOf, targetsOf, unquote } from './lib'
9import type { Hold, Mapped } from './lib'
10
11export type Probe = {
12  fs: {
13    stat(path: string): Promise<{ kind: string; size: number }> // throws when the path is not there
14    list(path: string): Promise<unknown[]>
15    read(path: string): Promise<unknown>
16    exists(path: string): Promise<boolean>
17  }
18  process: {
19    run(argv: string[], opts: { timeoutMs: number }): Promise<{ exitCode: number; stdout: string }>
20  }
21}
22
23export const cantTell = (why: string) => `can't tell what this touches: ${why}`
24
25const MAX_LISTED = 8
26const DOCKER_DOWN = 'docker did not answer (is the Docker engine running?)'
27const SAFE_WORD = /^[A-Za-z0-9][\w.\/~:@+=-]*$/
28
29const clip = (lines: string[], n: number) =>
30  lines.length > n ? [...lines.slice(0, n), `... ${lines.length - n} more not listed`] : lines
31
32const outLines = (out: string) =>
33  out
34    .split('\n')
35    .map(l => l.trim())
36    .filter(Boolean)
37
38// stdout of a read-only program, or null when it failed or is not there
39async function ran($: Probe, argv: string[]): Promise<string | null> {
40  try {
41    const r = await $.process.run(argv, { timeoutMs: 10_000 })
42    return r.exitCode === 0 ? r.stdout : null
43  } catch {
44    return null
45  }
46}
47
48// One path an rm names, as the words can say it
49async function rmTargetLine($: Probe, raw: string, home: string): Promise<string> {
50  const path = raw.replace(/^~(?=\/|$)/, home)
51  const variable = /\$\{?([A-Za-z_]\w*)/.exec(path)
52  if (variable || /[`$]/.test(path)) {
53    const why = variable
54      ? `the path goes through $${variable[1]}, which is only read when the command runs`
55      : 'the path is built by another command when it runs'
56    return `${path}: ${cantTell(why)}`
57  }
58  if (/[*?[\]{}]/.test(path)) return `${path}: ${cantTell('the pattern only expands when the command runs')}`
59  try {
60    const st = await $.fs.stat(path)
61    if (st.kind === 'directory') {
62      let inside = ', everything inside removed'
63      try {
64        inside = `, ${(await $.fs.list(path)).length} entries at the top level, all removed`
65      } catch {
66        // the size and the words are still true
67      }
68      return `${path} (dir, ${st.size} bytes${inside})`
69    }
70    return `${path} (${st.kind}, ${st.size} bytes)`
71  } catch {
72    return `${path} (not found)`
73  }
74}
75
76async function rmLines($: Probe, segment: string, home: string): Promise<string[]> {
77  const all = targetsOf(segment).map(unquote)
78  if (all.length === 0) {
79    return [cantTell('rm names no path here (it may be given its paths by another command)')]
80  }
81  const out: string[] = []
82  for (const raw of all.slice(0, MAX_LISTED)) out.push(await rmTargetLine($, raw, home))
83  if (all.length > MAX_LISTED) out.push(`... ${all.length - MAX_LISTED} more targets not listed`)
84  return out
85}
86
87const tilde = (path: string, home: string) => (home && (path === home || path.startsWith(`${home}/`)) ? `~${path.slice(home.length)}` : path)
88
89// An rm inside `docker run -v ...`: each path shown through its mount, as the folder it is on this machine
90async function containerLines($: Probe, mapped: Mapped[], home: string): Promise<string[]> {
91  const out: string[] = []
92  for (const m of mapped.slice(0, MAX_LISTED)) {
93    if (m.kind === 'volume') {
94      out.push(`${m.path}: ${m.mountAt} is ${m.volume ? `the Docker volume "${m.volume}"` : 'a Docker volume made for this container'}, not a folder on this machine`)
95    } else if (m.kind === 'unresolved') {
96      out.push(`${m.path}: ${cantTell(`${m.mountAt} is mounted from "${m.source}", a host folder that ${m.why}`)}`)
97    } else if (m.kind === 'uncovered') {
98      out.push(`${m.path}: ${cantTell(m.why)}`)
99    } else {
100      const { base, glob } = globBase(m.host)
101      const folder = `${m.mountAt} is ${tilde(m.folder, home)} on this machine (a host folder mounted into the container)`
102      if (glob) {
103        const dir = await rmTargetLine($, base, home)
104        out.push(`${m.path}: ${folder}; the pattern removes what matches inside ${tilde(dir, home)}`)
105      } else out.push(`${m.path}: ${folder}; ${tilde(await rmTargetLine($, m.host, home), home)}`)
106    }
107  }
108  if (mapped.length > MAX_LISTED) out.push(`... ${mapped.length - MAX_LISTED} more targets not listed`)
109  return out
110}
111
112async function dockerPruneLines($: Probe, hold: Hold): Promise<string[]> {
113  const df = await ran($, ['docker', 'system', 'df'])
114  if (df === null) return [cantTell(DOCKER_DOWN)]
115  const out: string[] = []
116  if (hold.kind === 'docker volume prune') {
117    const vols = await ran($, ['docker', 'volume', 'ls', '--filter', 'dangling=true', '--format', '{{.Name}}'])
118    if (vols === null) return [cantTell(DOCKER_DOWN)]
119    const names = outLines(vols)
120    out.push(names.length > 0 ? 'unused volumes that would go:' : 'unused volumes that would go: none found right now')
121    out.push(...clip(names, 10).map(n => `  ${n}`))
122    return out
123  }
124  if (hold.kind === 'docker system prune') {
125    const stopped = await ran($, ['docker', 'ps', '-a', '--filter', 'status=exited', '--format', '{{.Names}} ({{.Image}})'])
126    const names = outLines(stopped ?? '')
127    out.push(names.length > 0 ? 'stopped containers that would go:' : 'stopped containers that would go: none found right now')
128    out.push(...clip(names, 10).map(n => `  ${n}`))
129  } else {
130    const every = /\s(-a|--all)\b/.test(hold.segment)
131    const filter = every ? [] : ['--filter', 'dangling=true']
132    const imgs = await ran($, ['docker', 'image', 'ls', ...filter, '--format', '{{.Repository}}:{{.Tag}} ({{.Size}})'])
133    const names = outLines(imgs ?? '')
134    out.push(every ? 'images on this machine (every unused one goes):' : 'untagged images that would go:')
135    out.push(...(names.length > 0 ? clip(names, 10).map(n => `  ${n}`) : ['  none found right now']))
136  }
137  out.push('disk use now:', ...clip(outLines(df), 6).map(l => `  ${l}`))
138  return out
139}
140
141async function volumeRmLines($: Probe, segment: string): Promise<string[]> {
142  const t = segment.split(/\s+/)
143  const at = t.findIndex(x => x === 'rm' || x === 'remove')
144  const names = t.slice(at + 1).filter(x => !x.startsWith('-')).map(unquote)
145  if (names.length === 0) return [cantTell('no volume name is given here (another command may supply it)')]
146  const have = await ran($, ['docker', 'volume', 'ls', '--format', '{{.Name}}'])
147  if (have === null) return [cantTell(DOCKER_DOWN)]
148  const exists = new Set(outLines(have))
149  return clip(
150    names.map(n =>
151      /[$`*?]/.test(n)
152        ? `${n}: ${cantTell('the name is built when the command runs')}`
153        : `${n} (${exists.has(n) ? 'volume exists, its data goes' : 'volume not found'})`,
154    ),
155    MAX_LISTED,
156  )
157}
158
159async function composeDownLines($: Probe, segment: string): Promise<string[]> {
160  const t = segment.split(/\s+/)
161  const flags: string[] = []
162  for (let i = 0; i < t.length; i += 1) {
163    const next = t[i + 1] ? unquote(t[i + 1]) : ''
164    if ((t[i] === '-f' || t[i] === '--file' || t[i] === '-p' || t[i] === '--project-name') && SAFE_WORD.test(next)) {
165      flags.push(t[i], next)
166    }
167  }
168  const named = await ran($, ['docker', 'compose', ...flags, 'config', '--volumes'])
169  const names = outLines(named ?? '')
170  if (names.length === 0) {
171    return [cantTell("the compose file here could not be read (docker compose config --volumes gave nothing), so the stack's volumes are unknown")]
172  }
173  return ['volumes this stack declares (deleted with it, with their data):', ...clip(names, 10).map(n => `  ${n}`)]
174}
175
176// host and path only: a remote address can carry a token in its user part, and that part is cut
177const hostOf = (url: string): string => {
178  const web = /^[a-z+]+:\/\/(?:[^@/]*@)?([^/?#]+)([^?#]*)/i.exec(url)
179  if (web) return `${web[1]}${web[2]}`
180  const scp = /^(?:[^@/\s]+@)?([^:/\s]+):(.+)$/.exec(url)
181  return scp ? `${scp[1]}/${scp[2]}` : ''
182}
183
184// What an uncapped run would take: the container it starts, and the one-line fix (the same words the refusal to a lane carries)
185function unlimitedLines(segment: string): string[] {
186  const target = runTargetOf(segment)
187  return [
188    `container from ${target ? `image or service ${target}` : 'an image the words do not name'}: no --cpus or compose cpus limit and no timeout, so it can use every core on this machine`,
189    `fix: ${UNLIMITED_FIX}`,
190  ]
191}
192
193async function forcePushLines($: Probe, segment: string): Promise<string[]> {
194  const t = segment.split(/\s+/)
195  const after = t.slice(t.indexOf('push') + 1)
196  const words = after.filter(x => !x.startsWith('-')).map(unquote)
197  const current = ((await ran($, ['git', 'branch', '--show-current'])) ?? '').trim()
198  let remote = words[0]
199  if (!remote && SAFE_WORD.test(current)) {
200    remote = ((await ran($, ['git', 'config', '--get', `branch.${current}.remote`])) ?? '').trim() || undefined
201  }
202  const refs = words.slice(1).map(w => w.replace(/^\+/, '').split(':').pop() || w)
203  let branch = refs.length > 0 ? refs.join(', ') : current
204  if (after.includes('--all')) branch = 'every local branch (--all)'
205  else if (after.includes('--mirror')) branch = 'every ref on the remote (--mirror)'
206  if (!branch) return [cantTell('no branch is named and this folder is on a detached HEAD')]
207  if (!remote) return [`branch ${branch}; ${cantTell('no remote is named and none is set for this branch')}`]
208  const isAddress = remote.includes(':') || remote.includes('/')
209  const url = isAddress ? remote : SAFE_WORD.test(remote) ? ((await ran($, ['git', 'remote', 'get-url', remote])) ?? '').trim() : ''
210  const where = hostOf(url)
211  return [
212    `branch ${branch} on remote ${isAddress ? '(given as an address)' : remote} (${where || 'its address could not be read here'}); commits there that this machine lacks are lost`,
213  ]
214}
215
216const DEPLOY_TOOLS: Record<string, string> = {
217  vercel: 'Vercel (the project linked to the current folder)',
218  netlify: 'Netlify (the site linked to the current folder)',
219  wrangler: 'Cloudflare Workers/Pages (the project in the wrangler config)',
220  firebase: 'Firebase Hosting (the project in .firebaserc)',
221  fly: 'Fly.io (the app named in fly.toml)',
222  flyctl: 'Fly.io (the app named in fly.toml)',
223  heroku: 'Heroku (the app set for this folder)',
224  railway: 'Railway (the service linked to this folder)',
225  supabase: 'Supabase (the project linked to this folder)',
226  eas: 'Expo EAS (store builds and updates)',
227  kubectl: 'a Kubernetes cluster (the current context)',
228  terraform: 'infrastructure managed by Terraform',
229  aws: 'AWS (the active profile)',
230  gcloud: 'Google Cloud (the active project)',
231  az: 'Azure (the active subscription)',
232  serverless: 'AWS through Serverless',
233  sls: 'AWS through Serverless',
234}
235
236async function deployLines($: Probe, segment: string): Promise<string[]> {
237  const t = segment.split(/\s+/)
238  const tool = (t[0] ?? '').split('/').pop() ?? ''
239  const hosts = [...segment.matchAll(/https?:\/\/([^\s/"']+)/g)].map(m => m[1])
240  const flag = /--prod(?:uction)?\b/.exec(segment)?.[0] ?? 'redeploy aimed at prod'
241  const named = hosts.length > 0 ? `; host named: ${hosts.join(', ')}` : ''
242  if (DEPLOY_TOOLS[tool]) return [`service: ${DEPLOY_TOOLS[tool]}; target: production (${flag})${named}`]
243  if (['npm', 'pnpm', 'yarn', 'npx', 'bun'].includes(tool)) {
244    const script = t.slice(1).find(x => !x.startsWith('-') && x !== 'run')
245    let pkg = ''
246    try {
247      pkg = (await $.fs.exists('package.json')) ? String(await $.fs.read('package.json')) : ''
248    } catch {
249      pkg = ''
250    }
251    const body = /"scripts"\s*:\s*\{([^}]*)\}/s.exec(pkg)?.[1] ?? ''
252    const line = script ? new RegExp(`"${script.replace(/[^\w-]/g, '')}"\\s*:\\s*"([^"]*)"`).exec(body)?.[1] : undefined
253    if (line) {
254      const inner = DEPLOY_TOOLS[(line.trim().split(/\s+/)[0] ?? '').split('/').pop() ?? '']
255      const service = inner ? `service: ${inner}` : cantTell(`the script "${script}" runs "${line.slice(0, 80)}", which is not a deploy tool I know`)
256      return [`script "${script}" in this folder's package.json runs: ${line.slice(0, 200)}; ${service}; target: production (${flag})`]
257    }
258    return [cantTell(`${tool} runs a project script${script ? ` ("${script}")` : ''} and package.json here does not show what it ships to`)]
259  }
260  if (hosts.length > 0) return [`host named in the command: ${hosts.join(', ')}; target: production (${flag})`]
261  return [cantTell(`"${tool.slice(0, 40)}" is not a deploy tool I know and the command names no host, so the live site it ships to is unknown`)]
262}
263
264// One entry per rule `classify` can raise, with commands that raise it. A test walks this table, and a second
265// test fails when `classify` or `explain` names a kind that is missing here: a new rule cannot ship undescribed.
266export const RULE_SAMPLES: Record<string, string[]> = {
267  'rm -rf': ['rm -rf /home/t/build /home/t/missing', 'rm -rf "$BUILD_DIR"/old', 'rm -rf dist/*', 'rm -rf'],
268  'docker system prune': ['docker system prune -af'],
269  'docker image prune': ['docker image prune -a', 'docker image prune'],
270  'docker volume prune': ['docker volume prune -f'],
271  'docker volume rm': ['docker volume rm pgdata cache', 'docker volume rm'],
272  'docker compose down -v': ['docker compose down -v', 'docker compose -f ci.yml -p demo down --volumes'],
273  'docker run without limits': ['docker run --rm ada-stair-generator-site-tools', 'docker compose run --rm app make test', 'docker-compose -f ci.yml run web npm test'],
274  'git push --force': ['git push --force origin main', 'git push -f', 'git push origin +feat/x'],
275  'production deploy': ['vercel --prod', 'npm run deploy --production', 'redeploy prod now', 'mystery-tool --prod'],
276  'tmux shared lanes': [
277    'tmux kill-server',
278    'tmux kill-session -t lanes',
279    'tmux kill-session -tlanes',
280    'tmux kill-session -t=lanes',
281  ],
282}
283
284// The lines for one hold: the command, then what it would touch. Never just the command.
285export async function touches($: Probe, hold: Hold, home: string): Promise<string> {
286  const cut = hold.segment.length > 300 ? ' ... (cut, full command is longer)' : ''
287  const head = hold.kind + ': ' + hold.segment.slice(0, 300) + cut
288  let lines: string[]
289  try {
290    switch (hold.kind) {
291      case 'rm -rf':
292        lines = hold.container ? await containerLines($, hold.container, home) : await rmLines($, hold.segment, home)
293        break
294      case 'docker system prune':
295      case 'docker image prune':
296      case 'docker volume prune':
297        lines = await dockerPruneLines($, hold)
298        break
299      case 'docker volume rm':
300        lines = await volumeRmLines($, hold.segment)
301        break
302      case 'docker compose down -v':
303        lines = await composeDownLines($, hold.segment)
304        break
305      case 'docker run without limits':
306        lines = unlimitedLines(hold.segment)
307        break
308      case 'git push --force':
309        lines = await forcePushLines($, hold.segment)
310        break
311      case 'production deploy':
312        lines = await deployLines($, hold.segment)
313        break
314      case 'tmux shared lanes':
315        lines = [
316          hold.segment.includes('kill-server')
317            ? "closes every lane window (the tmux session 'lanes'), with no undo; also closes every other session and window on the default tmux server"
318            : "closes every lane window (the tmux session 'lanes'), with no undo",
319        ]
320        break
321      default:
322        lines = [cantTell('"' + hold.kind + '" is a held rule that has no description of its targets yet')]
323    }
324  } catch {
325    lines = [cantTell('looking it up failed')]
326  }
327  if (lines.length === 0) lines = [cantTell('nothing could be read about it')]
328  return [head, ...lines.map(l => (l.startsWith(' ') ? l : '  ' + l))].join('\n')
329}
330
src/state.d.ts 13 lines
1export type AfaModsBand = { lanes: number; inbox: number; client: number }
2
3declare module 'claude-code' {
4  interface PluginState {
5    'afa-mods': {
6      isHub: boolean
7      prepRan: boolean
8      percent: number | null
9      band: AfaModsBand
10    }
11  }
12}
13