SLOPSHOPPER

so-hud

See Session Orchestrator status, warnings and session beacons in Claude Code ($.so contract v1), with protection gates for secret-printing commands, rule…

bandguardcommandtoaststatusprocess
★ 52v0.2.0MITupdated 2026-10-23Kanevry/session-orchestrator/mods/so-hud
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · so-hud
› 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 so-hud: [so-hud] Schutz-Hook fehlgeschlagen; der Aufruf läuft nicht. ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /profile ⎿ so-hud: Profil: ausgewogen (Vorgabe, noch nicht gewählt) ⎿ so-hud: Regel-Fallen abgelehnt, Kollision fragt. ⎿ so-hud: Auf jedem Profil: Secrets ausgeben wird abgelehnt, Außenwirkung wird zweimal bestätigt (interaktiv). ⎿ so-hud: Wechseln: im Band über dem Prompt (locker, ausgewogen, streng) oder in /config, Eintrag strictness von so-hud. Profil: ausgewogen (Vorgabe, noch nicht gewählt) Regel-Fallen abgelehnt, Kollision fragt. Auf jedem Profil: Secrets ausgeben wird abgelehnt, Außenwirkung wird zweimal bestätigt (interaktiv). [ locker ] [ ausgewogen ] [ streng ] [ Schließen ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Profil: ausgewogen (Vorgabe, noch nicht gewählt) Regel-Fallen abgelehnt, Kollision fragt. Auf jedem Profil: Secrets ausgeben wird abgelehnt, Außenwirkung wird zweimal bestätigt (interaktiv). [ locker ] [ ausgewogen ] [ streng ] [ Schließen ] ⟨Claude Code's own drawing⟩
README

so-hud 0.2.0

A native Session Orchestrator display for Claude Code (package A, #1508): a status line for the running session, a warning band when something needs attention, and one beacon file per session that other sessions can read through $.so.beacons(). The status line shows how many peer sessions are running (from the session registry). Since 0.2.0 it also checks tool calls before they run (#1551, see Protection gates).

Requirements

  • Claude Code with mod support; tested with 2.1.296. Claude Code only — Codex, Cursor and Pi do not load this mod.
  • Node.js 24 or later.
  • Session Orchestrator from the release that ships this mod or later, as the plugin or as a checkout set through soRoot: the mod reads all state through its scripts/so-hud.mjs, which earlier releases do not have.

Install

/plugin marketplace add Kanevry/session-orchestrator
/plugin install so-hud@kanevry

The mod finds the Session Orchestrator installation in this order: the soRoot setting (an absolute path), then the path cached from an earlier lookup, then a root registered with node scripts/so-hud.mjs --register-root inside that installation, then claude plugin list --json. The first hit is cached, so after a move only soRoot replaces it. None of these install actions is run by the development tests. For a local checkout you can also load this directory directly with claude --plugin-dir ./mods/so-hud.

Settings: strictness is locker (relaxed), ausgewogen (balanced, the default) or streng (strict); it is shown in the status line, returned by $.so.profile() and decides how the protection gates react. Until one is chosen, a band above the prompt shows the current profile with one button per profile (no hotkeys: a digit typed into an empty prompt would press one); a press saves it in this mod's strictness row of /config, used by every new session. /profile shows the profile and its effect without a model turn and opens the band, with Schließen to hide it for the session (#1552). The profile steers only these gates, not Session Orchestrator's own guards. soRoot is optional.

Upgrading from 0.1.0: 0.1.0 only displayed state; 0.2.0 adds the protection gates, so outward actions such as push, merge, release and publish ask for two confirmations within 30 seconds, and commands that would print a secret are refused. /plugin install uses scope user by default, and an update at that scope changes every Claude Code session on the host at once, including lead sessions that merge through the API on the owner's word. Set strictness per host first (0.1.0 already has the row in /config), try 0.2.0 in one session (claude --plugin-dir ./mods/so-hud, or an install at project scope), and only then update the user-scope install: docs/mods.md § Upgrading from 0.1.0 with scope user.

What it does

Session Orchestrator state comes only from scripts/so-hud.mjs, called as --json --repo-root <cwd> --session-id <raw-uuid> every 15 seconds with a 3-second timeout. With --session-id the collector counts the session's agents beside its own session.lock, which can sit in another checkout than the cwd (#1730). A collector older than #1730 rejects the flag with exit 2; the mod then calls it without the flag for the rest of the session. STATE.md, locks, dispatch and events are never changed. The mod writes only its own beacon file, its install-path cache, the receipt lines in aktionen.jsonl (see below), and, when a profile is picked in the band, its own strictness row in /config and the store key profile-chosen. Without a Session Orchestrator root it asks claude plugin list at most once every 5 minutes.

The status line says nicht eingerichtet for a part that is not set up (no Session Orchestrator installation found, no vault-integration block) and noch kein Lauf for an enabled vault mirror that never ran; a repository where no session has written events yet is not shown as teilweise gemessen.

$.so.version() is 1; snapshot() and beacons() are asynchronous engine calls (await); profile() returns locker, ausgewogen or streng. A cold snapshot is null; an old one keeps its measurement time and carries age_ms; after a failed refresh it is kept and marked degraded.

Language: the status texts and the texts of the protection gates are German. An English text table is prepared but not selectable yet, because JSON v1 has no field for the owner's language.

Beacons: the $.fs API of this Claude Code build offers no rename, chmod or unlink, so hooks/beacon-io.mjs is called through $.process.run with argv and JSON on stdin: temporary file plus rename, mode 0600, beacon directory 0700, at most 4 KB. hud/ and hud/beacons/ must be real directories owned by the user, not symlinks, checked through an O_NOFOLLOW handle; where Node has no O_NOFOLLOW (native Windows) an lstat check stands in, and a link swapped in between check and chmod would be followed. Removing a beacon follows no symlink. The helper's parent PID stands for the starting engine process; that mapping still has to be confirmed in a real engine host. Foreign beacons are validated; one older than 120 seconds whose PID cannot be shown to be alive becomes state unknown. tool.check: ask means handing the decision on (also in auto mode), not proof that a dialog was shown.

Protection gates

Before a shell command (Bash, Monitor, PowerShell) or a file edit runs, so-hud checks it, and it checks tool results before they reach the model (#1551). This is a behaviour change against 0.1.0: outward actions now ask twice by default, secret-printing commands are refused, and on the default profile ausgewogen rule traps such as git add -A are refused too.

  • SEC-008 traps (commands that would print a secret, such as cat .env, a bare env, echo $TOKEN, docker inspect without --format, a token in curl arguments or in a curl URL) are refused on every profile; the refusal names the safe replacement command.
  • Rule traps (git add ./-A/--all, claude -p without env -u ANTHROPIC_API_KEY, ${PIPESTATUS[, grep -c … || echo 0) show a toast on locker and are refused on ausgewogen and streng.
  • Outward actions (push to main/master, force, tags or delete; merge; release; publish; production deploy) are held wherever a surface is attached (terminal, desktop, IDE, phone) until the owner confirms twice within 30 seconds; declining, closing the dialog or letting the time run out refuses the call. Only a plain push of a feature branch runs without a question (#1569): git push [-u] origin feat/x, HEAD or a bare git push; exact options; every earlier command on the line a local git call from an allowlist (fetch with no option and no :: word, log/show/diff with display options only — --output, --ext-diff, --textconv, --upload-pack ask), so any earlier command that is not git (npm test && git push origin feat/x), and any earlier output redirection other than onto exactly /dev/null or between stdout and stderr (git log … >> .git/config, also on cd, an assignment or exec), makes every push form ask; after add, commit, status, diff, fetch or checkout -- <paths> on the line, only when so-hud measured that none of the hooks those steps can fire exists (a hook file of that name, in husky v9 the user's .husky/<name>, or a hook.* config entry for that event; see docs/mods.md § Limits) and the step ran in the push's own folder as written (git -C ../b commit && git push … asks; in a husky repository with a .husky/pre-commit, git commit … && git push … on one line asks); behind any git call, only when that call ran in the push's own folder as written and every key of the repository's own git config is on an allowlist (core.fsmonitor, diff.external, filters, textconv, core.sshCommand, credential.helper, include.path and any other key ask, and so does any submodule or embedded repository in the index, #1573); no earlier step that changes the branch, git config or the folder; harmless variable names only; a remote defined in git config; and the standard push configuration (push.*, remote.<r>.push, remote.<r>.mirror, push remotes and submodule.recurse are read). Lowercase head, --no-verify and every other shape ask. A run with no surface at all (a plain claude -p) cannot ask: so-hud writes a receipt and lets the call run, and there merges, releases, publishes and deploys are checked by no Session Orchestrator gate.
  • Collision guard: an edit of a file in the declared wave scope of another live Session Orchestrator session in the same working copy gives a toast on locker, a question on ausgewogen and a refusal on streng. Sessions that do not run Session Orchestrator are invisible to it.
  • Secret shield: a token in a tool result reaches the model as [<kind> entfernt · sha256:<12 hex>], with a toast to rotate it.

Every decision on an outward action appends one receipt line per held action, and every asked collision one line, to ~/.config/session-orchestrator/hud/aktionen.jsonl (0600, append-only, a regular file with one link); it carries the SHA-256 of JSON.stringify([tool, command]) — [tool, file path] for a collision — never the command. If the gate itself fails, the call is refused, except on locker for calls that are neither outward nor SEC-008. The gates are a hurdle, not the authority: pre-push hook, destructive-command guard and CI stay authoritative where they exist. Profiles, receipt fields, the full list of checked commands and the limits: docs/mods.md.

Limits

  • A status without a session or wave binding is not attributed to the current wave.
  • Dispatch records do not always carry agent type or model; those fields stay null.
  • Peer scope is unknown when either scope source is missing or the scope signals have gaps.
  • Events are read only from the last 512 KB, reported as events:tail-only. There is no complete history.

Checks

npx vitest --run tests/so-hud in the Session Orchestrator repo (CI job test). The CI job mods:plugin runs claude plugin validate --strict --json and claude plugin test for every mod. Engine integration separately with claude plugin test mods/so-hud; under Claude Code 2.1.296 the kit tests pass. tsconfig.json follows the header of the type file; the engine creates .claude-plugin/types when it loads the mod. No rollout, no commands from later packages and no second Session Orchestrator state.

Source 5 files
hooks/register.tsx 671 lines
1import type { EngineInterface, Register } from 'claude-code'
2import type { SoBeacon, SoProfile, SoSnapshot } from '../types/index'
3import { ageBeacon, completeState, configHooksFire, displayText, findings, fireableHooks, holdsProfile, PROFILES, profileLines, profileOf, profileText, statusText, validId, validateBeacon } from './logic'
4import { CD_SCRIPT, classifyAllOutward, collisionVerdict, findCollisions, findTraps, GITLINKS_SCRIPT, gitlinksFromRun, hasSecret, KIND_LABEL, plainSourceRefs, pushDestinations, pushNeedsConfirm, pushRemote, pushSources, redactDeep, redactText, REPO_CONFIG_READ, repoConfigEntries, trapVerdict, UNKNOWN_DIR, type Outward, type PushConfig, type PushFacts, type RepoConfig, type SecretHit } from './rules'
5
6// Only these closures cross helper boundaries; the engine table never does.
7type IO = {
8  run: EngineInterface['process']['run']
9  read: (path: string) => Promise<string>
10  list: EngineInterface['fs']['list']
11  now: EngineInterface['clock']['now']
12  env: () => ReturnType<EngineInterface['env']['get']>
13  storeGet: EngineInterface['store']['get']
14  storeSet: EngineInterface['store']['set']
15  sessionId: EngineInterface['session']['id']
16  cwd: EngineInterface['session']['cwd']
17  model: EngineInterface['session']['model']
18  usage: EngineInterface['session']['usage']
19  pluginRoot: () => string
20}
21
22// `tool` and `text` form the hashed vector (ADR-009 "Klick-Provenienz" of lead-session-orchestrator): the tool name stands where a CLI program would.
23type Receipt = { aktion: 'aussenwirkung' | 'kollision'; tool: string; text: string; art: string }
24type Assessed = { hit: Outward; cwd: string | null; facts: PushFacts | null; needs: boolean }
25
26const CONFIRM_WINDOW_MS = 30_000
27// Ceiling for retrying `claude plugin list` without a Session Orchestrator root (F13): an install made mid-session shows
28// within 5 minutes, `so-hud.mjs --register-root` at the next refresh (that file is read every time). Revisit if 5 minutes is too slow.
29const PLUGIN_LIST_RETRY_MS = 5 * 60_000
30const STEP_ONE = ['Weiter zur Bestätigung', 'Ablehnen'] as const
31const STEP_TWO = ['Jetzt genau einmal ausführen', 'Ablehnen'] as const
32// Tools whose `command` is a shell line: traps, outward classification and receipts apply to each.
33const COMMAND_TOOLS: ReadonlySet<string> = new Set(['Bash', 'Monitor', 'PowerShell'])
34// The push configuration nobody set: the most permissive one pushNeedsConfirm accepts (#1569).
35const UNSET_PUSH_CONFIG: PushConfig = { push: [], remotePush: [], remoteMirror: null, remotePushDefault: null, branchPushRemote: null, submoduleRecurse: null }
36// A repository with no key set (#1573): the most permissive repoConfig pushNeedsConfirm accepts.
37const NO_REPO_CONFIG: RepoConfig = []
38// Lists the hooks folder one name per line, prints nothing when no such path exists, and exits 2 when something
39// other than a folder is there. The folder is passed as an argument, never as source.
40const HOOKS_SCRIPT = `d="$1"; if [ -d "$d" ]; then ls -A -- "$d/"; elif [ -e "$d" ] || [ -L "$d" ]; then exit 2; fi`
41// husky v9 (#1574): core.hooksPath is `<dir>/_`, each `_/<name>` a generated stub sourcing `_/h`, and `h` runs the user's
42// `<dir>/<name>` when that file exists, else exits 0 before anything else runs. Verifies `h` starts with that exact
43// prefix and every named stub is byte-for-byte husky's (trailing newlines aside): exit 0 when both hold, 4 when either
44// differs (not recognisably husky), anything else when a read failed. Folder, stub, prefix and names are arguments.
45const HUSKY_SCRIPT = `d="$1"; stub="$2"; prefix="$3"; shift 3; h=$(cat -- "$d/h") || exit 3; case "$h" in "$prefix"*) ;; *) exit 4 ;; esac; for n in "$@"; do if [ -e "$d/$n" ] || [ -L "$d/$n" ]; then s=$(cat -- "$d/$n") || exit 3; [ "$s" = "$stub" ] || exit 4; fi; done`
46// What husky 9.1 writes (node_modules/husky/index.js and its `husky` file, measured 9.1.7); another version asks.
47const HUSKY_STUB = '#!/usr/bin/env sh\n. "$(dirname "$0")/h"'
48const HUSKY_H_PREFIX = '#!/usr/bin/env sh\n[ "$HUSKY" = "2" ] && set -x\nn=$(basename "$0")\ns=$(dirname "$(dirname "$0")")/$n\n\n[ ! -f "$s" ] && exit 0\n'
49// The raw session id the collector accepts for --session-id (#1730): the same form as UUID_RE in
50// scripts/lib/session-id.mjs (version 1-8, RFC variant). Any other id is not passed on, so it cannot read as an
51// older collector and switch the flag off.
52const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
53
54// The mod's lib has no DOM types; Web Crypto and TextEncoder are globals in the mod engine (as in rules.ts).
55type WebGlobals = {
56  crypto: { subtle: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> } }
57  TextEncoder: new () => { encode(input: string): Uint8Array }
58}
59async function sha256(text: string): Promise<string> {
60  const { crypto, TextEncoder } = globalThis as unknown as WebGlobals
61  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
62  return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('')
63}
64
65export const register: Register = (on, options) => {
66  let io: IO
67  let current: SoSnapshot | null = null
68  let own: SoBeacon | null = null
69  let interactive = false
70  let refreshing = false
71  let sessionIdFlag = true
72  let ending = false
73  let cancel: (() => void) | undefined
74  let beaconWrites: Promise<unknown> = Promise.resolve()
75  const problems = new Set<string>()
76  // Calls already passed downstream; a repeated id never runs twice. One entry per tool call — a session's
77  // few thousand calls stay small; revisit if sessions ever run unbounded.
78  const passed = new Set<string>()
79  // What the gate read off a call before anything could fail, for its `.catch` (dropped once the call settles).
80  const classes = new Map<string, { outward: boolean; sec008: boolean }>()
81  const profile: SoProfile = profileOf(options.strictness)
82  // Profile band (#1552). Closure state, because $.state refuses writes while a render hook draws. `chosen` stays
83  // null until session.start has read it, so a chosen profile never flashes the band; `opened` is /profile's.
84  let chosen: boolean | null = null
85  let opened = false
86  // "Schließen" hides the band for this session only; it returns at the next session start while nothing is chosen.
87  let dismissed = false
88  let choosing = false
89  // When root() last asked `claude plugin list`; a miss is never stored, so without this every 15-second refresh spawned it.
90  let pluginListAt: number | null = null
91  const helper = async (io: IO, action: string, id = '', input: unknown = null) => {
92    const result = await io.run(['node', `${io.pluginRoot()}/hooks/beacon-io.mjs`, action, id], { stdin: JSON.stringify(input), timeoutMs: 3000 })
93    if (result.exitCode !== 0) throw new Error('beacon-io')
94    return JSON.parse(result.stdout) as unknown
95  }
96  const snapshot = async (io: IO): Promise<SoSnapshot | null> => current ? {
97    ...current, age_ms: Math.max(0, await io.now() - Date.parse(current.measured_at)),
98    degraded: [...new Set([...current.degraded, ...problems])],
99  } : null
100  const root = async (io: IO): Promise<string | null> => {
101    if (typeof options.soRoot === 'string' && options.soRoot.startsWith('/')) {
102      await io.storeSet('so-root', options.soRoot)
103      return options.soRoot
104    }
105    const cached = await io.storeGet('so-root')
106    if (typeof cached === 'string' && cached.startsWith('/')) return cached
107    const home = await io.env()
108    let found: string | null = null
109    if (home) {
110      try { const p = (await io.read(`${home}/.config/session-orchestrator/hud/so-root`)).trim(); if (p.startsWith('/')) found = p } catch { /* try installed plugins */ }
111    }
112    // At most one `claude plugin list` per PLUGIN_LIST_RETRY_MS while no root is found, whatever its outcome.
113    const now = found ? null : await io.now()
114    if (now !== null && (pluginListAt === null || now - pluginListAt >= PLUGIN_LIST_RETRY_MS)) {
115      pluginListAt = now
116      const result = await io.run(['claude', 'plugin', 'list', '--json'], { timeoutMs: 3000 })
117      if (result.exitCode === 0) {
118        const data = JSON.parse(result.stdout)
119        const rows: unknown[] = Array.isArray(data) ? data : Array.isArray(data.plugins) ? data.plugins : []
120        for (const row of rows) {
121          const p = row as { name?: string; id?: string; installPath?: string }
122          if ((p.name ?? p.id ?? '').split('@')[0] === 'session-orchestrator' && p.installPath?.startsWith('/')) { found = p.installPath; break }
123        }
124      }
125    }
126    if (found) await io.storeSet('so-root', found)
127    return found
128  }
129  const write = async (io: IO, change: Partial<SoBeacon> = {}) => {
130    if (ending || !own) return
131    const now = new Date(await io.now()).toISOString()
132    if (ending || !own) return
133    own = { ...own, ...change, seit: change.zustand && change.zustand !== own.zustand ? now : own.seit, aktualisiert_at: now }
134    const value = { ...own }
135    beaconWrites = beaconWrites.catch(() => undefined).then(() => helper(io, 'write', value.session_id, value))
136    await beaconWrites.catch(() => { problems.add('beacon-write-failed') })
137  }
138  const readBeacons = async (io: IO): Promise<SoBeacon[]> => {
139    const home = await io.env()
140    if (!home) return []
141    const dir = `${home}/.config/session-orchestrator/hud/beacons`
142    const entries = await io.list(dir).catch(() => [])
143    const beacons: SoBeacon[] = []
144    for (const f of entries) {
145      if (f.kind !== 'file' || f.isLink || f.size > 4096 || !f.name.endsWith('.json')) continue
146      try { const b: unknown = JSON.parse(await io.read(`${dir}/${f.name}`)); if (validateBeacon(b) && f.name === `${b.session_id}.json`) beacons.push(b) } catch { /* skip unreadable */ }
147    }
148    const alive = await helper(io, 'alive', '', beacons.map(b => b.pid)).catch(() => []) as number[]
149    const now = await io.now()
150    return beacons.map(b => ageBeacon(b, now, b.pid !== null && alive.includes(b.pid)))
151  }
152  const refresh = async (io: IO) => {
153    if (refreshing || ending) return
154    refreshing = true
155    try {
156      const soRoot = await root(io)
157      if (!soRoot) throw new Error('not-configured')
158      // #1730: the session's agents are read beside its own lock, which need not be the cwd's checkout. A collector
159      // older than #1730 refuses the unknown flag with the usage exit 2: then it is dropped for the rest of the session.
160      const argv = ['node', `${soRoot}/scripts/so-hud.mjs`, '--json', '--repo-root', await io.cwd()]
161      const sid = await io.sessionId()
162      const withId = sessionIdFlag && UUID_RE.test(sid)
163      let result = await io.run(withId ? [...argv, '--session-id', sid] : argv, { timeoutMs: 3000 })
164      if (withId && result.exitCode === 2) {
165        sessionIdFlag = false
166        result = await io.run(argv, { timeoutMs: 3000 })
167      }
168      if (result.exitCode !== 0) throw new Error('collector-failed')
169      const value = JSON.parse(result.stdout) as SoSnapshot
170      if (value.schema_version !== 1 || !Number.isFinite(Date.parse(value.measured_at)) || !value.wave || !value.state || !value.gate || !value.vault || !Array.isArray(value.peers) || !Array.isArray(value.degraded)) throw new Error('invalid-snapshot')
171      current = value
172      for (const reason of ['not-configured', 'refresh-failed', 'collector-failed', 'invalid-snapshot']) problems.delete(reason)
173    } catch (error) {
174      for (const reason of ['not-configured', 'refresh-failed', 'collector-failed', 'invalid-snapshot']) problems.delete(reason)
175      const reason = error instanceof Error ? error.message : ''
176      problems.add(['not-configured', 'collector-failed', 'invalid-snapshot'].includes(reason) ? reason : 'refresh-failed')
177    }
178    finally { refreshing = false }
179    try {
180      const usage = await io.usage()
181      await write(io, { kontext_prozent: usage.context.percent ?? null, welle: current?.wave.number ?? null })
182    } catch { problems.add('usage-unavailable') }
183  }
184
185  // ---- Protection gates (#1551): host reads for one call ----------------------------
186  const resolveCwd = async (io: IO, dir: string | null): Promise<string | null> => {
187    const sessionCwd = await io.cwd()
188    if (dir === null) return sessionCwd
189    // A folder the rules could not pin down asks without relying on how the host resolves the sentinel.
190    if (dir === UNKNOWN_DIR || dir.startsWith(`${UNKNOWN_DIR}/`)) return null
191    const ran = await io.run(['bash', '-c', CD_SCRIPT, 'so-hud', dir], { cwd: sessionCwd, timeoutMs: 5000 })
192    const out = ran.exitCode === 0 ? ran.stdout.trim() : ''
193    return out.startsWith('/') ? out : null
194  }
195  const pushFacts = async (io: IO, hit: Outward, cwd: string): Promise<PushFacts> => {
196    const git = async (args: string[]) => {
197      const ran = await io.run(['git', ...args], { cwd, timeoutMs: 5000 })
198      const out = ran.exitCode === 0 ? ran.stdout.trim() : ''
199      return { ok: ran.exitCode === 0, value: out === '' ? null : out }
200    }
201    const current = (await git(['rev-parse', '--abbrev-ref', 'HEAD'])).value
202    const upstream = (await git(['rev-parse', '--abbrev-ref', '@{u}'])).value
203    const remote = current !== null && current !== 'HEAD' ? (await git(['config', `branch.${current}.remote`])).value : null
204    const target = pushRemote(hit, remote)
205    // Config-defined remotes only: `git remote get-url` also answers a legacy .git/remotes/<name> file, whose `Push:` line
206    // can send a branch to main without any `remote.<name>.push` the configuration read below could see (#1569).
207    const remoteUrlKnown = !target.startsWith('-') && (await git(['config', '--get', `remote.${target}.url`])).value !== null
208    const dsts = pushDestinations(hit, current, upstream, target)
209    let tagRefs: string[] | null = null
210    if (dsts !== null) {
211      tagRefs = []
212      for (const dst of dsts) if ((await git(['rev-parse', '--verify', '--quiet', `refs/tags/${dst}`])).ok) tagRefs.push(dst)
213    }
214    const facts: PushFacts = { current, upstream, remote, remoteUrlKnown, tagRefs, pushConfig: null }
215    // Each later fact as measured, or else its most permissive value: what a fact decides is judged with the rest clean.
216    const clean = (): PushFacts => ({ hooks: false, repoConfig: NO_REPO_CONFIG, gitlinks: false, sourceRefs: plainSourceRefs(hit), ...facts })
217    // Read only what decides: a push that asks with nothing configured and no hooks asks whatever is there.
218    if (!pushNeedsConfirm(hit, { ...clean(), pushConfig: UNSET_PUSH_CONFIG })) {
219      facts.pushConfig = await pushConfig(io, cwd, target, current)
220      // #1570: each named source as git resolves it — a symbolic ref or a `refs/<name>` must not stand in for the branch.
221      if (!pushNeedsConfirm(hit, clean()) && pushNeedsConfirm(hit, { ...clean(), sourceRefs: undefined })) {
222        const sourceRefs: (string | null)[] = []
223        for (const src of pushSources(hit)) sourceRefs.push((await git(['rev-parse', '--symbolic-full-name', src])).value)
224        facts.sourceRefs = sourceRefs
225      }
226      // Each of the rest only where it decides: the push runs with it clean and asks with it unread.
227      if (!pushNeedsConfirm(hit, clean()) && pushNeedsConfirm(hit, { ...clean(), hooks: undefined })) facts.hooks = await hooksFact(io, cwd, hit.gitBefore)
228      // The repository's keys (#1573): only a push behind a git step reads them.
229      if (!pushNeedsConfirm(hit, clean()) && pushNeedsConfirm(hit, { ...clean(), repoConfig: undefined })) facts.repoConfig = await repoConfig(io, cwd)
230      // …and whether a step can walk into a submodule or embedded repository (#1573 review). Order matters: the count
231      // runs `git ls-files`, which itself runs a configured core.fsmonitor, so it must come after repoConfig — a
232      // program-carrying fsmonitor makes clean() ask there and this read is skipped. Pinned by schutz.test.ts.
233      if (!pushNeedsConfirm(hit, clean()) && pushNeedsConfirm(hit, { ...clean(), gitlinks: undefined })) facts.gitlinks = await gitlinksFact(io, cwd)
234    }
235    return facts
236  }
237  /** Whether the push folder's index holds a gitlink; null when the count failed (asks). */
238  const gitlinksFact = async (io: IO, cwd: string): Promise<boolean | null> => {
239    const ran = await io.run(['bash', '-c', GITLINKS_SCRIPT, 'so-hud-gitlinks'], { cwd, timeoutMs: 5000 })
240    return ran.isStdoutTruncated ? null : gitlinksFromRun(ran.exitCode, ran.stdout)
241  }
242  /** Every configured key with its scope (#1573), one `git config` call; null when it fails, warns or does not parse (asks). */
243  const repoConfig = async (io: IO, cwd: string): Promise<RepoConfig | null> => {
244    const ran = await io.run(['git', ...REPO_CONFIG_READ], { cwd, timeoutMs: 5000 })
245    if (ran.exitCode !== 0 || ran.isStdoutTruncated || ran.stderr !== '') return null
246    return repoConfigEntries(ran.stdout)
247  }
248  /**
249   * Whether a git step earlier on the line may run a hook that moves HEAD or the push configuration (MR !133), judged
250   * only on the hook names those steps can fire (#1574, {@link fireableHooks}; an unmapped step: any name):
251   * true when a hook defined in config runs on one of them, or the effective hooks folder (`git rev-parse --git-path
252   * hooks`, which follows core.hooksPath) holds a file of that name (or `<name>.<ext>`, `*.sample` aside). In a
253   * husky v9 folder ({@link HUSKY_SCRIPT}) a stub counts only when the user's `<dir>/<name>` beside `_` exists.
254   * false only when all of that was measured absent; null when any read failed or did not parse. Measured in the
255   * push's folder, so a step run in another repo (`cd ../b && git commit && cd - && git push`) is judged by this
256   * repo's hooks; revisit if that form shows up.
257   */
258  const hooksFact = async (io: IO, cwd: string, steps: readonly string[] | undefined): Promise<boolean | null> => {
259    const names = fireableHooks(steps)
260    const hooksPath = await io.run(['git', 'config', '--get', 'core.hooksPath'], { cwd, timeoutMs: 5000 })
261    const hooksPathSet = hooksPath.exitCode === 0 && hooksPath.stdout.trim() !== ''
262    if (!hooksPathSet && (hooksPath.exitCode !== 1 || hooksPath.stdout !== '' || hooksPath.stderr !== '')) return null
263    // Hooks defined in config (`hook.<name>.command` + `.event`, any level, includes followed) run like a file in the
264    // folder (measured, git 2.56). Exit 1 with nothing printed is none set.
265    const configured = await io.run(['git', 'config', '--null', '--get-regexp', '^hook\\.'], { cwd, timeoutMs: 5000 })
266    if (configured.stderr !== '' || configured.isStdoutTruncated) return null
267    if (configured.exitCode === 0 && configured.stdout !== '') {
268      const fires = configHooksFire(configured.stdout, names)
269      if (fires !== false) return fires
270    } else if (configured.exitCode !== 1 || configured.stdout !== '') return null
271    // `.git/hooks`, core.hooksPath, or the common folder's in a worktree; a relative path is relative to cwd, where the listing runs.
272    const where = await io.run(['git', 'rev-parse', '--git-path', 'hooks'], { cwd, timeoutMs: 5000 })
273    const dir = where.exitCode === 0 && !where.isStdoutTruncated ? where.stdout.replace(/\n$/, '') : ''
274    if (dir === '') return null
275    const list = async (folder: string): Promise<string[] | null> => {
276      const listed = await io.run(['bash', '-c', HOOKS_SCRIPT, 'so-hud-hooks', folder], { cwd, timeoutMs: 5000 })
277      // A name holding a newline splits, but its last part ends as the name does, so it still counts.
278      return listed.exitCode !== 0 || listed.isStdoutTruncated ? null : listed.stdout.split('\n').filter(name => name !== '')
279    }
280    const entries = await list(dir)
281    if (entries === null) return null
282    const wanted = names === null ? null : [...names]
283    // Case-insensitive: on APFS or NTFS git runs `PRE-COMMIT` as pre-commit, and husky's `[ -f ]` finds `.husky/Pre-Commit`.
284    // On a case-sensitive filesystem this over-counts, which only asks (fail-closed).
285    const fires = (name: string): boolean => {
286      const lower = name.toLowerCase()
287      return !lower.endsWith('.sample') && (wanted === null || wanted.some(n => lower === n || lower.startsWith(`${n}.`)))
288    }
289    const hooks = entries.filter(fires)
290    const folder = dir.replace(/\/+$/, '')
291    const husky = hooksPathSet && (folder === '_' || folder.endsWith('/_')) && entries.includes('h')
292    if (!husky || wanted === null || hooks.length === 0) return hooks.length > 0
293    // husky: a `<name>.<ext>` beside the stubs is no husky file; a stub is checked, then the user's file beside `_`.
294    const stubs = wanted.filter(n => entries.includes(n))
295    if (hooks.length > stubs.length) return true
296    const verified = await io.run(['bash', '-c', HUSKY_SCRIPT, 'so-hud-husky', folder, HUSKY_STUB, HUSKY_H_PREFIX, ...stubs], { cwd, timeoutMs: 5000 })
297    if (verified.exitCode === 4) return true
298    if (verified.exitCode !== 0) return null
299    // `h` runs `$(dirname "$(dirname "$0")")/<name>`: the folder above `_`, taken as written, as `dirname` does.
300    const user = await list(folder === '_' ? '.' : folder.slice(0, -2) || '/')
301    return user === null ? null : user.some(name => stubs.includes(name.toLowerCase()))
302  }
303  /** The push configuration (#1569 P2), each key read with `git config --null`; null when any read failed. */
304  const pushConfig = async (io: IO, cwd: string, target: string, current: string | null): Promise<PushConfig | null> => {
305    // The entries of one read: [] for unset (exit 1, nothing printed), null for any other failure.
306    const read = async (args: string[]): Promise<string[] | null> => {
307      const ran = await io.run(['git', 'config', '--null', ...args], { cwd, timeoutMs: 5000 })
308      if (ran.isStdoutTruncated) return null
309      if (ran.exitCode === 1 && ran.stdout === '' && ran.stderr === '') return []
310      return ran.exitCode === 0 && ran.stdout.endsWith('\0') ? ran.stdout.slice(0, -1).split('\0') : null
311    }
312    // A key read with --get: one entry, or none when unset; undefined when the output does not parse.
313    const one = (entries: string[] | null): string | null | undefined => entries === null || entries.length > 1 ? undefined : entries[0] ?? null
314    const push = await read(['--get-regexp', '^push\\.'])
315    const remotePush = await read(['--get-all', `remote.${target}.push`])
316    const remoteMirror = one(await read(['--type=bool', '--get', `remote.${target}.mirror`]))
317    const remotePushDefault = one(await read(['--get', 'remote.pushDefault']))
318    const branchPushRemote = current === null || current === 'HEAD' ? null : one(await read(['--get', `branch.${current}.pushRemote`]))
319    const submoduleRecurse = one(await read(['--type=bool', '--get', 'submodule.recurse']))
320    if (push === null || remotePush === null || remoteMirror === undefined || remotePushDefault === undefined || branchPushRemote === undefined || submoduleRecurse === undefined) return null
321    // `key\nvalue`, or the key alone when it was written without `=`.
322    const entries = push.map(entry => entry.includes('\n') ? [entry.slice(0, entry.indexOf('\n')), entry.slice(entry.indexOf('\n') + 1)] as const : [entry, null] as const)
323    return { push: entries, remotePush, remoteMirror, remotePushDefault, branchPushRemote, submoduleRecurse }
324  }
325  const assess = async (io: IO, hit: Outward): Promise<Assessed> => {
326    let cwd: string | null = null
327    let facts: PushFacts | null = null
328    try {
329      cwd = await resolveCwd(io, hit.dir)
330      if (hit.kind === 'push' && cwd !== null) facts = await pushFacts(io, hit, cwd)
331    } catch { facts = null } // a failed measurement only ever asks (fail-closed)
332    return { hit, cwd, facts, needs: hit.kind !== 'push' || facts === null || pushNeedsConfirm(hit, facts) }
333  }
334  // The commits a push sends, measured — never guessed. Only a single destination that is the branch
335  // checked out has a known source (HEAD); every other shape says it could not be measured.
336  const effect = async (io: IO, a: Assessed): Promise<string[]> => {
337    const head = `${KIND_LABEL[a.hit.kind]}: ${displayText(a.hit.label)}`
338    if (a.hit.kind !== 'push') return [head]
339    const unmeasured = [head, 'Ausgehende Commits: nicht messbar']
340    if (a.cwd === null || a.facts === null || a.hit.args.some(arg => !arg.startsWith('-') && arg.includes(':'))) return unmeasured
341    const remote = pushRemote(a.hit, a.facts.remote)
342    const dsts = pushDestinations(a.hit, a.facts.current, a.facts.upstream, remote)
343    if (dsts?.length !== 1 || dsts[0] !== a.facts.current || remote.startsWith('-')) return unmeasured
344    const ran = await io.run(['git', 'log', '--oneline', '-n', '10', `${remote}/${dsts[0]}..HEAD`], { cwd: a.cwd, timeoutMs: 5000 }).catch(() => null)
345    if (ran?.exitCode !== 0) return unmeasured
346    const lines = ran.stdout.split('\n').map(line => line.trim()).filter(Boolean)
347    return [head, `Ausgehende Commits nach ${remote}/${dsts[0]}: ${lines.length === 0 ? 'keine' : lines.length}`, ...lines.map(line => `  ${displayText(line)}`)]
348  }
349  /** Appends one receipt; false when it could not be written. Never throws: a write failure must not deny or re-run. */
350  const receipt = async (io: IO, r: Receipt, ergebnis: 'ausgefuehrt' | 'abgelehnt' | 'verfallen' | 'ohne-zeichenflaeche', exit: number | null): Promise<boolean> => {
351    try {
352      const sessionId = await io.sessionId()
353      await helper(io, 'aktion', sessionId, { zeit: new Date(await io.now()).toISOString(), session_id: sessionId, vorgang: 'pane-aktion',
354        aktion: r.aktion, argv_sha256: await sha256(JSON.stringify([r.tool, r.text])), exit, profil: profile, ergebnis, art: r.art })
355      return true
356    } catch {
357      problems.add('receipt-failed')
358      return false
359    }
360  }
361
362  const initialize = async (io: IO, cwd: string) => {
363    ending = false
364    const id = await io.sessionId()
365    if (own?.session_id !== id) current = null
366    if (validId(id)) {
367      const now = new Date(await io.now()).toISOString()
368      const identity = await helper(io, 'identity').catch(() => null) as { pid: number } | null
369      own = { schema_version: 1, session_id: id, name: null, repo_name: cwd.split('/').at(-1) ?? null, branch: null,
370        pid: identity?.pid ?? null, zustand: 'unbekannt', seit: now, warte_grund: null, heuristisch: false,
371        kontext_prozent: null, letzter_request_at: null, modell: await io.model().catch(() => null), welle: null, aktualisiert_at: now }
372    }
373    await refresh(io)
374  }
375
376  // Register the whole chain before any engine call. engine.create is post-order, never caught.
377  on('engine.create', async (_$, e, next) => {
378    const beneath = await next(e)
379    io = {
380      run: (argv, init) => beneath.process.run(argv, init),
381      read: (path) => beneath.fs.read(path),
382      list: (path) => beneath.fs.list(path),
383      now: () => beneath.clock.now(),
384      env: () => beneath.env.get('HOME'),
385      storeGet: (key) => beneath.store.get(key),
386      storeSet: (key, value) => beneath.store.set(key, value),
387      sessionId: () => beneath.session.id(),
388      cwd: () => beneath.session.cwd(),
389      model: () => beneath.session.model(),
390      usage: () => beneath.session.usage(),
391      pluginRoot: () => beneath.plugin.root,
392    }
393    return { ...beneath, so: { version: () => 1 as const, snapshot: () => snapshot(io), beacons: () => readBeacons(io), profile: () => profile } }
394  })
395  on('session.start', async ($, e, next) => {
396    interactive = e.isInteractive
397    // Band and /profile need no Session Orchestrator root, collector or vault (F13), so they come before initialize.
398    await $.command.register({ name: 'profile', description: 'so-hud: Profil zeigen und wechseln (locker, ausgewogen, streng)', immediate: true })
399      .catch(() => { try { $.ui.toast('[so-hud] /profile ließ sich nicht anlegen; Profil in /config wechseln.', { timeoutMs: 8000 }) } catch { /* best effort */ } })
400    // Chosen = this mod stored a choice, or any settings source holds one (also set in /config by hand). A failed read shows the band.
401    try { chosen = await $.store.get('profile-chosen') === true || holdsProfile(await $.settings.read(), $.plugin.name) }
402    catch { chosen = false }
403    dismissed = false
404    if (interactive) $.ui.invalidate('ui.render')
405    await initialize(io, e.cwd)
406    const updateUI = async () => {
407      if (interactive && !ending) {
408        $.ui.status(statusText(await snapshot(io), profile, 'de', [...problems]))
409        $.ui.invalidate('ui.render')
410      }
411    }
412    await updateUI()
413    cancel?.()
414    const timer = $.clock.every(15_000, async () => {
415      try { await refresh(io); await updateUI() }
416      catch { problems.add('refresh-failed') }
417    })
418    cancel = () => timer.cancel()
419    return next(e)
420  }).catch(($, e, next) => next(e))
421  on('turn.start', async ($, e, next) => {
422    if (ending || !own || own.session_id !== await io.sessionId()) {
423      await initialize(io, await io.cwd())
424      const updateUI = async () => {
425        if (interactive && !ending) {
426          $.ui.status(statusText(await snapshot(io), profile, 'de', [...problems]))
427          $.ui.invalidate('ui.render')
428        }
429      }
430      await updateUI()
431      cancel?.()
432      const timer = $.clock.every(15_000, async () => {
433        try { await refresh(io); await updateUI() }
434        catch { problems.add('refresh-failed') }
435      })
436      cancel = () => timer.cancel()
437    }
438    await write(io, { zustand: 'arbeitet', warte_grund: null, heuristisch: false, letzter_request_at: new Date(await io.now()).toISOString() })
439    return next(e)
440  }).catch(($, e, next) => next(e))
441  on('turn.complete', async ($, e, next) => {
442    if (!e.agentId) await write(io, completeState(e.answer))
443    return next(e)
444  }).catch(($, e, next) => next(e))
445  // The protection gate (#1551). Registered before the beacon hook: a plugin's registrations nest in order,
446  // first outermost, so a deny here never reaches the beacon and a confirmed call runs through it once.
447  on('tool.call', async ($, e, next) => {
448    const id = e.tool_use_id
449    if (passed.has(id)) return { deny: '[so-hud] Dieser Aufruf wurde bereits weitergereicht und läuft nicht erneut.' }
450    const args = e as unknown as Record<string, unknown>
451    const command = COMMAND_TOOLS.has(e.tool) && typeof args.command === 'string' ? args.command : null
452    const traps = command === null ? [] : findTraps(command)
453    const outward = command === null ? [] : classifyAllOutward(command)
454    classes.set(id, { outward: outward.length > 0, sec008: traps.some(trap => trap.klasse === 'sec008') })
455    const done = <T,>(value: T): T => { classes.delete(id); return value }
456    const toast = (text: string) => { try { $.ui.toast(text, { timeoutMs: 8000 }) } catch { /* best effort, never a deny */ } }
457    type Ergebnis = Parameters<typeof receipt>[2]
458    const record = async (list: readonly Receipt[], ergebnis: Ergebnis, exit: number | null) => {
459      let ok = true
460      for (const r of list) ok = await receipt(io, r, ergebnis, exit) && ok
461      if (!ok) toast('[so-hud] Aktionsbeleg ließ sich nicht schreiben.')
462    }
463    const after: Receipt[] = []
464    // Who can be asked is decided per call: an SDK host or an attached app draws although the session started
465    // non-interactive. Only a run with no surface at all (plain -p) has nobody to ask. A failing read throws
466    // into the gate's `.catch`, which refuses (fail-closed).
467    let askable: boolean | null = null
468    const canAsk = async () => {
469      if (askable === null) askable = interactive || (await $.session.surfaces()).length > 0
470      return askable
471    }
472
473    // Traps the rules name (SEC-008 refuses on every profile).
474    const verdict = trapVerdict(traps, profile)
475    if (verdict.aktion === 'ablehnen') return done({ deny: verdict.text })
476    if (verdict.aktion === 'warnen') toast(verdict.text)
477
478    // Actions with an effect outside (F9): two steps inside the held call, never deny-and-rerun.
479    if (command !== null && outward.length > 0) {
480      const measure = async () => {
481        const all: Assessed[] = []
482        for (const hit of outward) all.push(await assess(io, hit))
483        const needing = all.filter(a => a.needs)
484        const effects: string[][] = []
485        for (const a of needing) effects.push(await effect(io, a))
486        return { needing, effects, key: JSON.stringify([all.map(a => [a.needs, a.cwd, a.facts]), effects]) }
487      }
488      const { needing, effects, key } = await measure()
489      const receipts = needing.map(a => ({ aktion: 'aussenwirkung' as const, tool: e.tool, text: command, art: a.hit.kind }))
490      if (needing.length > 0 && !await canAsk()) {
491        // No surface to confirm on: the CLI's own gates decide; the mod only records.
492        await record(receipts, 'ohne-zeichenflaeche', null)
493      } else if (needing.length > 0) {
494        const labels = [...new Set(needing.map(a => KIND_LABEL[a.hit.kind]))].join(' + ')
495        const lines = [`Befehl: ${displayText(await redactText(command, []), 300)}`]
496        needing.forEach((a, i) => lines.push(`Ordner: ${displayText(a.cwd ?? 'nicht auflösbar', 300)}`, ...effects[i] ?? []))
497        const decline = async (ergebnis: 'abgelehnt' | 'verfallen', text: string) => {
498          await record(receipts, ergebnis, null)
499          return done({ deny: text })
500        }
501        const refused = `[so-hud] Der Owner hat ${labels} abgelehnt; nichts ausgeführt. Denselben Aufruf nicht erneut versuchen.`
502        const first = await $.ui.ask([...lines, `${labels} freigeben?`].join('\n'), { options: [...STEP_ONE], header: 'Außenwirkung' }).catch(() => null)
503        if (first !== STEP_ONE[0]) return decline('abgelehnt', refused)
504        const firstAt = await io.now()
505        // Step two shows the facts measured again; a push whose facts moved since step one is not confirmed on old ones.
506        const again = await measure()
507        if (again.key !== key) return decline('abgelehnt', '[so-hud] Stand hat sich geändert; neu bestätigen. Nichts ausgeführt.')
508        const second = await $.ui.ask([...again.effects.flat(), `${labels} jetzt genau einmal ausführen?`].join('\n'), { options: [...STEP_TWO], header: 'Bestätigen' }).catch(() => null)
509        if (await io.now() - firstAt > CONFIRM_WINDOW_MS) return decline('verfallen', '[so-hud] Bestätigung verfallen; nichts ausgeführt.')
510        if (second !== STEP_TWO[0]) return decline('abgelehnt', refused)
511        after.push(...receipts)
512      }
513    }
514
515    // Collisions with a peer's wave scope (F8), on the cached snapshot only: no process start here.
516    const filePath = ['Edit', 'Write', 'NotebookEdit'].includes(e.tool)
517      ? typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : null : null
518    if (filePath !== null && current !== null) {
519      const { hits } = findCollisions({ filePath, repoRoot: current.repo.root, ownSessionId: await io.sessionId(), peers: current.peers })
520      const collision = collisionVerdict(hits, profile)
521      if (collision.aktion === 'ablehnen') return done({ deny: collision.text })
522      if (collision.aktion === 'warnen') toast(collision.text)
523      if (collision.aktion === 'fragen') {
524        const r: Receipt = { aktion: 'kollision', tool: e.tool, text: filePath, art: e.tool.toLowerCase() }
525        const asking = await canAsk()
526        const answer = asking ? await $.ui.ask(`${collision.text}\nTrotzdem in ${displayText(filePath)} schreiben?`, { options: [...collision.optionen], header: 'Kollision' }).catch(() => null) : null
527        if (answer === 'Trotzdem') after.push(r)
528        else {
529          if (!asking) {
530            const who = [...new Set(hits.map(hit => hit.session_id))].join(', ')
531            return done({ deny: `[so-hud] Kollision mit ${who} und niemand zum Fragen da (kopfloser Lauf); nichts geschrieben.` })
532          }
533          await record([r], 'abgelehnt', null)
534          const sid = (await io.sessionId()).slice(0, 8)
535          return done({ deny: answer === 'Worktree vorschlagen'
536            ? `${collision.text}\nNichts geschrieben. Vorschlag: git -C ${current.repo.root} worktree add ${current.repo.root}-${sid} -b wt/${sid} — dort weiterarbeiten.`
537            : `${collision.text}\n[so-hud] Abgebrochen; nichts geschrieben. Nicht erneut versuchen, ohne den Owner zu fragen.` })
538        }
539      }
540    }
541
542    passed.add(id)
543    const ran = await next(e)
544    if (after.length > 0) {
545      const outcome = ran.deny !== undefined ? 'abgelehnt' : 'ausgefuehrt'
546      const code = (ran.result as { exitCode?: unknown } | undefined)?.exitCode
547      const exit = ran.deny !== undefined ? null : typeof code === 'number' && Number.isSafeInteger(code) ? code : ran.isError === true ? 1 : 0
548      await record(after, outcome, exit)
549    }
550    if (ran.deny !== undefined) return done(ran)
551
552    // Secret shield (SEC-008): what reaches the model never carries a token.
553    // Both channels are checked: a hook's own `{ result }` carries no `text`, and an empty or clean `text` says
554    // nothing about `result` — either may be what the model reads.
555    const serialized = JSON.stringify(ran.result ?? null)
556    if (!hasSecret(ran.text ?? '') && !hasSecret(serialized)) return done(ran)
557    const hits: SecretHit[] = []
558    const kinds = () => [...new Set(hits.map(hit => hit.name))].join(', ')
559    if (ran.isError === true) {
560      const text = await redactText(ran.text || serialized, hits)
561      toast(`[so-hud] Secret in der Ausgabe geschwärzt (${kinds()}); rotieren.`)
562      return done({ deny: `[so-hud] Fehlerausgabe enthielt ein Secret und ist geschwärzt:\n${text}` })
563    }
564    const result = await redactDeep(ran.result, hits) as typeof ran.result
565    const text = ran.text === undefined ? {} : { text: await redactText(ran.text, hits) }
566    toast(`[so-hud] Secret in der Ausgabe geschwärzt (${kinds()}); rotieren.`)
567    return done({ result, ...text, context: [`[so-hud] Die Ausgabe enthielt ein Secret (${kinds()}) und ist geschwärzt. Den Wert nicht erneut ausgeben; den Owner auf Rotation hinweisen.`] })
568  }).catch(($, e) => {
569    const id = e.tool_use_id
570    const seen = classes.get(id)
571    classes.delete(id)
572    if (passed.has(id)) return { deny: '[so-hud] Ausgabe zurückgehalten (Fehler im Schutz-Hook).' }
573    if (profile === 'locker' && seen !== undefined && !seen.outward && !seen.sec008) {
574      try { $.ui.toast('[so-hud] Schutz-Hook fehlgeschlagen; der Aufruf läuft ungeprüft (Profil locker).', { timeoutMs: 8000 }) } catch { /* best effort */ }
575      return undefined
576    }
577    return { deny: '[so-hud] Schutz-Hook fehlgeschlagen; der Aufruf läuft nicht.' }
578  })
579  // The engine refuses a second unmatched registration of one event; this match-all matcher (every tool name)
580  // lets the beacon hook stand beneath the gate. The gate itself stays unmatched, so no call can slip past it.
581  on('tool.call', { tool: /^/ }, async ($, e, next) => {
582    if (e.agentId) return next(e)
583    if (e.tool === 'AskUserQuestion') await write(io, { zustand: 'wartet', warte_grund: 'dialog', heuristisch: false })
584    else if (own?.warte_grund === 'freigabe') await write(io, { zustand: 'arbeitet', warte_grund: null, heuristisch: false })
585    const result = await next(e)
586    // No telemetry error can cause this tool to execute twice.
587    await write(io, { zustand: 'arbeitet', warte_grund: null, heuristisch: false }).catch(() => { problems.add('beacon-write-failed') })
588    return result
589  }).catch(($, e, next) => next(e))
590  on('tool.check', async ($, e, next) => {
591    const result = await next(e)
592    if (result.decision === 'ask' && !e.agentId && e.tool_use_id && e.tool !== 'AskUserQuestion') await write(io, { zustand: 'wartet', warte_grund: 'freigabe', heuristisch: false }).catch(() => { problems.add('beacon-write-failed') })
593    return result
594  }).catch(($, e, next) => next(e))
595  on('session.end', async ($, e, next) => {
596    ending = true
597    cancel?.()
598    await beaconWrites.catch(() => undefined)
599    if (own) await helper(io, 'remove', own.session_id).catch(() => { problems.add('beacon-remove-failed') })
600    own = null
601    return next(e)
602  }).catch(($, e, next) => next(e))
603  // /profile (#1552): answered here without next, so it runs no model turn and adds no `context`; the `text` row is stored
604  // in the transcript, so the model reads it on its next turn.
605  on('command.run', { command: 'profile' }, async ($) => {
606    opened = true
607    try { $.ui.invalidate('ui.render') } catch { /* nothing drawn to refresh (claude -p) */ }
608    return { text: profileText(profile, chosen === true) }
609  })
610  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
611    if (e.props.hasSurvey) return next(e)
612    const below = await next(e)
613    let lines: string[] = []
614    try {
615      const usage = await io.usage()
616      lines = findings(await snapshot(io), usage.context, own?.letzter_request_at ?? null, await io.now(), [...problems])
617    } catch { /* the profile band still draws */ }
618    const showProfile = opened || (chosen === false && !dismissed)
619    if (!lines.length && !showProfile) return below
620    const { Box, Text, Button } = $.ui.resolve(e)
621    const toast = (text: string) => { try { $.ui.toast(text, { timeoutMs: 8000 }) } catch { /* best effort */ } }
622    // Persists through the /config row of this plugin's strictness field; a successful set reloads the plugin.
623    const choose = async (value: SoProfile) => {
624      if (choosing) return
625      choosing = true
626      // The flag is written before $.config.set: a successful set reloads the plugin, so this instance may
627      // never run past it, and the default profile may leave no setting holdsProfile can see. Every path
628      // that stores nothing puts the flag back as it was.
629      let before: unknown
630      const restore = async () => {
631        try { await (before === undefined ? $.store.delete('profile-chosen') : $.store.set('profile-chosen', before)) } catch { /* best effort */ }
632      }
633      try {
634        before = await $.store.get('profile-chosen').catch(() => undefined)
635        await $.store.set('profile-chosen', true).catch(() => undefined)
636        const name = $.plugin.name
637        const row = (await $.config.list()).find(r => r.key === `${name}.strictness` || (r.provider.plugin === name && r.key.endsWith('.strictness')))
638        if (!row) {
639          await restore()
640          return toast('[so-hud] Profil nicht gespeichert: /config hat keinen Eintrag strictness von so-hud.')
641        }
642        const set = await $.config.set({ key: row.key, value })
643        if (set.deny !== undefined) {
644          await restore()
645          return toast(`[so-hud] Profil nicht gespeichert: ${displayText(set.deny)}`)
646        }
647        chosen = true
648        opened = false
649        toast(`[so-hud] Profil ${value} gespeichert (/config).`)
650      } catch {
651        await restore()
652        toast('[so-hud] Profil nicht gespeichert (Fehler beim Schreiben).')
653      }
654      finally {
655        choosing = false
656        try { $.ui.invalidate('ui.render') } catch { /* instance already reloaded */ }
657      }
658    }
659    // No hotkeys on the profile buttons: a bare digit typed into an empty prompt presses a band Button, and a
660    // letter can take another mod's band hotkey — either would change the host-wide profile by accident.
661    const band = showProfile ? <Box flexDirection="column">
662      {profileLines(profile, chosen === true).map((line, i) => <Text key={`profil-zeile-${i}`} dimColor={i > 0}>{line}</Text>)}
663      <Box gap={2}>
664        {PROFILES.map(p => <Button key={`profil-${p}`} label={p} variant={p === profile ? 'primary' : undefined} onPress={() => void choose(p)} />)}
665        {opened ? <Button key="profil-schliessen" label="Schließen" role="dismiss" onPress={() => { opened = false; dismissed = true; $.ui.invalidate('ui.render') }} /> : null}
666      </Box>
667    </Box> : null
668    return <Box flexDirection="column">{band}{lines.length ? <Text color="yellow">{lines.join(' · ')}</Text> : null}{below}</Box>
669  }).catch(($, e, next) => next(e))
670}
671
hooks/logic.ts 183 lines
1import type { SoBeacon, SoProfile, SoSnapshot } from '../types/index'
2
3export function ownerQuestion(answer: string): boolean {
4  let fence: string | null = null
5  const plain = answer.split('\n').filter(line => {
6    const mark = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1]
7    if (mark) {
8      if (!fence) fence = mark
9      else if (mark[0] === fence[0] && mark.length >= fence.length) fence = null
10      return false
11    }
12    return fence === null
13  }).join('\n').trim()
14  return plain.endsWith('?') || /weiter mit|soll ich|welche option|freigabe für/i.test(plain.slice(-400))
15}
16export const tables = {
17  de: { red: 'rot', error: 'Fehler', off: 'aus', partial: 'teilweise gemessen', setup: 'nicht eingerichtet', norun: 'noch kein Lauf', measurement: 'Messung fehlgeschlagen', mirror: 'Vault-Spiegel fehlgeschlagen', peer: 'Peer im selben Working Copy', scope: 'Peer ohne bekannten Scope im selben Working Copy', context: 'Kontext', cold: 'Cache kalt' },
18  en: { red: 'red', error: 'error', off: 'off', partial: 'partially measured', setup: 'not configured', norun: 'no run yet', measurement: 'Measurement failed', mirror: 'Vault mirror failed', peer: 'Peer in the same working copy', scope: 'Peer with unknown scope in the same working copy', context: 'Context', cold: 'Cache cold' },
19} as const
20/** Bound each displayed field; replace terminal controls and line separators. */
21export function displayText(value: unknown, limit = 120): string {
22  const plain = String(value ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ')
23  return plain.length <= limit ? plain : `${plain.slice(0, limit - 1)}…`
24}
25const measurementProblems = new Set(['refresh-failed', 'collector-failed', 'invalid-snapshot'])
26function measurementFailure(problems: readonly string[]): string[] {
27  return problems.filter(p => measurementProblems.has(p))
28}
29export function time(at: string | null): string {
30  if (!at || !Number.isFinite(Date.parse(at))) return '?'
31  const d = new Date(at)
32  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
33}
34export function statusText(s: SoSnapshot | null, profile: SoProfile, language: keyof typeof tables = 'de', problems: readonly string[] = []): string {
35  const t = tables[language]
36  if (!s) {
37    const failed = measurementFailure(problems)
38    return displayText(`SO ${failed.length ? `${t.measurement} (${failed.join(', ')})` : t.setup} · ${profile}`)
39  }
40  const g = s.gate.last
41  const vault = s.vault
42  const bad = vault.last_run && (vault.last_run.aborted || (vault.last_run.failed ?? 0) > 0)
43  // enabled null has two causes: no vault-integration block (not configured) or an unreadable CLAUDE.md/AGENTS.md (unknown).
44  const vaultUnset = s.degraded.includes('config:unreadable') ? '?' : t.setup
45  // Enabled but never mirrored is a state, not an unknown; '?' stays for a run whose time does not parse.
46  const vaultOn = vault.last_run === null ? t.norun : time(vault.last_run?.at ?? null)
47  // A repo where no session ever wrote events is fresh, not partially measured (F13): nothing is missing there.
48  const partial = s.degraded.some(d => d !== 'events:absent')
49  return displayText([s.state.session_type, s.wave.number !== null ? `W${s.wave.number}/${s.state.total_waves ?? '?'}` : null,
50    s.wave.role, agentsText(s.agents),
51    g ? `Gate ${g.passed === true ? 'ok' : g.passed === false ? t.red : '?'} ${time(g.at)}` : null,
52    `${s.degraded.some(d => /discovery|registry/.test(d)) ? '?' : s.peers.length} Peer`, `Vault ${vault.enabled === false ? t.off : bad ? t.error : vault.enabled === true ? vaultOn : vaultUnset}`, profile,
53    partial ? t.partial : null].filter(Boolean).map(value => displayText(value)).join(' · '), 800)
54}
55/**
56 * The running agents of this session from the collector's live map (#1580, #1633): a number is measured, `null`
57 * is unknown (`? Agents`, a map older than the session says nothing). Shown not at all without a session
58 * (`no-session`: nothing to count for) or from a collector before #1580 that sends no `running` — never as 0.
59 */
60function agentsText(agents: SoSnapshot['agents'] | undefined): string | null {
61  const running = agents?.running
62  if (running === undefined || agents?.stale_reason === 'no-session') return null
63  const decayed = agents?.decayed
64  // Agents without a Stop past 24 h (a parallel collector change): counted apart, shown only when there are some.
65  const stale = typeof decayed === 'number' && Number.isSafeInteger(decayed) && decayed > 0 ? ` (+${decayed} ?)` : ''
66  return `${typeof running === 'number' && Number.isSafeInteger(running) && running >= 0 ? running : '?'} Agents${stale}`
67}
68export function findings(s: SoSnapshot | null, context: { percent?: number; tokens?: number }, lastRequest: string | null, now: number, problems: readonly string[] = []): string[] {
69  const failed = measurementFailure(problems)
70  const out: string[] = failed.length ? [`${tables.de.measurement}: ${failed.join(', ')}`] : []
71  if (s?.gate.last?.passed === false) out.push(`Gate rot: ${s.gate.last.variant ?? '?'} ${s.gate.last.check_failed === true ? 'check_failed' : s.gate.last.exit_code ?? '?'}`)
72  if (s?.peers.some(p => p.gleiches_working_copy)) out.push(s.peers.some(p => p.gleiches_working_copy && p.scope_paths === null) ? tables.de.scope : tables.de.peer)
73  if (s?.vault.enabled && s.vault.last_run && (s.vault.last_run.aborted || (s.vault.last_run.failed ?? 0) > 0)) out.push(`${tables.de.mirror}: ${s.vault.last_run.aborted ?? s.vault.last_run.failed}`)
74  if ((context.percent ?? -1) >= 80) out.push(`Kontext ${context.percent} %`)
75  if (lastRequest && now - Date.parse(lastRequest) >= 3_600_000 && (context.tokens ?? 0) >= 100_000) out.push(tables.de.cold)
76  return out.map(value => displayText(value))
77}
78export const validId = (v: unknown): v is string => typeof v === 'string' && /^[a-zA-Z0-9_-]{1,200}$/.test(v)
79export function validateBeacon(v: unknown): v is SoBeacon {
80  if (!v || typeof v !== 'object') return false
81  const b = v as SoBeacon
82  const date = (s: unknown) => typeof s === 'string' && Number.isFinite(Date.parse(s))
83  const nullableString = (s: unknown) => s === null || typeof s === 'string'
84  return b.schema_version === 1 && validId(b.session_id) && ['arbeitet', 'wartet', 'bereit', 'blockiert', 'unbekannt'].includes(b.zustand)
85    && date(b.seit) && date(b.aktualisiert_at) && (b.letzter_request_at === null || date(b.letzter_request_at))
86    && [b.name, b.repo_name, b.branch, b.modell].every(nullableString)
87    && (b.pid === null || Number.isSafeInteger(b.pid) && b.pid > 0)
88    && (b.welle === null || Number.isSafeInteger(b.welle) && b.welle > 0)
89    && (b.kontext_prozent === null || Number.isFinite(b.kontext_prozent) && b.kontext_prozent >= 0 && b.kontext_prozent <= 100)
90    && typeof b.heuristisch === 'boolean' && [null, 'dialog', 'freigabe', 'frage'].includes(b.warte_grund)
91    && (b.zustand === 'wartet' ? b.warte_grund !== null : b.warte_grund === null)
92    && b.heuristisch === (b.warte_grund === 'frage')
93}
94export function ageBeacon(b: SoBeacon, now: number, alive: boolean): SoBeacon {
95  return now - Date.parse(b.aktualisiert_at) > 120_000 && !alive
96    ? { ...b, zustand: 'unbekannt', warte_grund: null, heuristisch: false } : b
97}
98export function completeState(answer: string): Pick<SoBeacon, 'zustand' | 'warte_grund' | 'heuristisch'> {
99  return ownerQuestion(answer) ? { zustand: 'wartet', warte_grund: 'frage', heuristisch: true } : { zustand: 'bereit', warte_grund: null, heuristisch: false }
100}
101
102// ---- Which hooks the git steps before a push can fire (#1574 proposal 3) ----
103// Per step as rules.ts records it (`gitStep`), the hook names githooks(5) of git 2.56 lists for that command.
104// A ref update fires reference-transaction, an index write post-index-change; commit and fetch end in
105// `gc --auto` (pre-auto-gc); a step that reads the index may query a core.fsmonitor hook. Options a step may carry
106// are not seen here (`commit --amend` → post-rewrite, `--no-verify` skips pre-commit), so each entry is the union.
107const FIREABLE_HOOKS: ReadonlyMap<string, readonly string[]> = new Map<string, readonly string[]>([
108  ['add', ['post-index-change', 'fsmonitor-watchman']],
109  ['status', ['post-index-change', 'fsmonitor-watchman']],
110  ['diff', ['post-index-change', 'fsmonitor-watchman']],
111  ['ls-files', ['fsmonitor-watchman']],
112  ['commit', ['pre-commit', 'prepare-commit-msg', 'commit-msg', 'post-commit', 'post-rewrite', 'reference-transaction', 'post-index-change', 'pre-auto-gc', 'fsmonitor-watchman']],
113  ['fetch', ['reference-transaction', 'pre-auto-gc']],
114  ['checkout -- <paths>', ['post-checkout', 'post-index-change', 'fsmonitor-watchman']],
115  ...['log', 'show', 'log [signature]', 'show [signature]', 'rev-parse', 'branch --show-current', 'tag --list'].map((step): [string, readonly string[]] => [step, []]),
116])
117
118/**
119 * The hook names the git steps earlier on a push's line can fire; null when any step is not in the map, which
120 * means any hook may run (fail-closed). Steps outside rules.ts's LOCAL_GIT already ask there, so they need no entry.
121 */
122export function fireableHooks(steps: readonly string[] | undefined): ReadonlySet<string> | null {
123  const names = new Set<string>()
124  for (const step of steps ?? []) {
125    const fired = FIREABLE_HOOKS.get(step)
126    if (fired === undefined) return null
127    for (const name of fired) names.add(name)
128  }
129  return names
130}
131
132/**
133 * Whether a hook defined in config (`git config --null --get-regexp ^hook\.` output) runs on one of `names`
134 * (null: on any event): a `hook.<friendly-name>.event` naming one of them, or a friendly name that is one.
135 * `.enabled` is not honoured (a disabled hook still counts). null when the output does not parse or holds a
136 * `hook.*` key git 2.56 does not document (asks).
137 */
138export function configHooksFire(output: string, names: ReadonlySet<string> | null): boolean | null {
139  if (!output.endsWith('\0')) return null
140  let fires = false
141  for (const entry of output.slice(0, -1).split('\0')) {
142    const cut = entry.indexOf('\n')
143    const key = cut === -1 ? entry : entry.slice(0, cut)
144    if (key === 'hook.jobs') continue
145    const parts = /^hook\.(.+)\.(command|event|enabled|parallel|jobs)$/.exec(key)
146    if (!parts) return null
147    const [, friendly = '', variable] = parts
148    if (cut === -1 && (variable === 'event' || variable === 'command')) return null
149    const value = entry.slice(cut + 1).trim().toLowerCase()
150    if (variable === 'event' && value !== '' && (names === null || names.has(value))) fires = true
151    if (variable === 'command' && (names === null || names.has(friendly.toLowerCase()))) fires = true
152  }
153  return fires
154}
155
156// ---- Profile band and /profile (#1552). SSOT of the effects: docs/mods.md § Profiles. ----
157export const PROFILES: readonly SoProfile[] = ['locker', 'ausgewogen', 'streng']
158const PROFILE_EFFECT: Record<SoProfile, string> = {
159  locker: 'Regel-Fallen und Kollisionen nur Warnung.',
160  ausgewogen: 'Regel-Fallen abgelehnt, Kollision fragt.',
161  streng: 'Regel-Fallen und Kollisionen abgelehnt.',
162}
163const PROFILE_ALWAYS = 'Auf jedem Profil: Secrets ausgeben wird abgelehnt, Außenwirkung wird zweimal bestätigt (interaktiv).'
164/** Any value outside the three profiles falls back to the default `ausgewogen`, as the engine does for a stored value outside `options`. */
165export function profileOf(value: unknown): SoProfile {
166  return value === 'locker' || value === 'streng' ? value : 'ausgewogen'
167}
168/** The band's lines: the profile (marked when it is only the default), what it loosens or locks, what holds on every profile. */
169export function profileLines(profile: SoProfile, chosen: boolean): string[] {
170  return [`Profil: ${profile}${chosen ? '' : ' (Vorgabe, noch nicht gewählt)'}`, PROFILE_EFFECT[profile], PROFILE_ALWAYS]
171}
172/** /profile's output: readable alone in `claude -p "/profile"`, where no band is drawn. */
173export function profileText(profile: SoProfile, chosen: boolean): string {
174  return [...profileLines(profile, chosen), `Wechseln: im Band über dem Prompt (${PROFILES.join(', ')}) oder in /config, Eintrag strictness von so-hud.`].join('\n')
175}
176/** Whether settings hold an explicit strictness for this plugin under `pluginConfigs[<plugin>[@<marketplace>]].options`. */
177export function holdsProfile(settings: unknown, plugin: string): boolean {
178  const configs: unknown = (settings as { pluginConfigs?: unknown } | null)?.pluginConfigs
179  if (!configs || typeof configs !== 'object') return false
180  return Object.entries(configs).some(([key, entry]) => key.split('@')[0] === plugin
181    && (PROFILES as readonly unknown[]).includes((entry as { options?: { strictness?: unknown } } | null)?.options?.strictness))
182}
183
hooks/rules.ts 2999 lines
1// The pure half of the so-hud protection gates (#1551): reading a shell command, a tool's output
2// and a peer's scope. Nothing here touches `$`, the engine or node:, so every rule runs inside the
3// mod engine and is testable on its own. Ported from an internal mod; only its general rules are
4// carried over.
5
6import { scanHeredocs, type HeredocStage } from './heredoc-scan'
7
8// ---- Reading a shell command ------------------------------------------------
9
10// One part of a shell word: a double-quoted run, a single-quoted run, a backslash escape, plain text,
11// or a quote that never closes (kept as written).
12const WORD_PART = /"((?:[^"\\]|\\.)*)"|'([^']*)'|\\(.)|([^"'\\]+)|(["'\\])/gs
13
14/** A shell word with its quotes and escapes removed, as the shell passes it on: `"HEAD:ma"in` is `HEAD:main`. */
15function dequote(word: string): string {
16  return word.replace(WORD_PART, (_m: string, dq?: string, sq?: string, esc?: string, plain?: string, lone?: string) =>
17    dq !== undefined ? dq.replace(/\\(["\\$`])/g, '$1') : (sq ?? esc ?? plain ?? lone ?? ''))
18}
19
20/**
21 * Splits one segment into shell words: each word is a run of `"…"`, `'…'` and unquoted characters
22 * joined together, quotes and escapes removed. Good enough to read flags and paths.
23 */
24export function tokenize(text: string): string[] {
25  return rawWords(text).map(dequote)
26}
27
28/** The shell words of a segment as written, quotes and escapes kept. */
29function rawWords(text: string): string[] {
30  return [...text.matchAll(/(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\]+|["'\\])+/gs)].map(m => m[0])
31}
32
33// An output redirection or descriptor copy as written: `2>&1`, `>/dev/null`, `&>>log`, `<&3`, or an
34// operator alone (`>`, `2>`, `&>`) whose target is the next word. Input redirections (`< .env`) stay
35// words: the file they name is read by the command.
36const REDIRECT = /^(?:(?:\d+|&)?>[>|&]?|\d*<&)(.*)$/s
37// An input redirection as written: `<file`, `0< in`, `<>file`, a here-string `<<<word`, a heredoc's
38// `<<EOF` / `<<-EOF`. Only the outward reader drops them (`</dev/null git push` is `git push`); a
39// trap still reads the file a command is fed (`cat < .env`).
40const IN_REDIRECT = /^\d*(?:<<<|<<-?|<>|<)(.*)$/s
41
42/**
43 * The raw words without their output redirections — and, when `input`, their input redirections:
44 * the shell removes them before the command sees its words, so `git 2>/dev/null push` is `git push`.
45 * Checked before quote removal, so a quoted `">"` stays an argument; `>(…)` and `<(…)` (process
46 * substitution) stay words too.
47 */
48function dropRedirections(raw: readonly string[], input: boolean): string[] {
49  const out: string[] = []
50  for (let i = 0; i < raw.length; i += 1) {
51    const word = raw[i] ?? ''
52    const target = REDIRECT.exec(word)?.[1] ?? (input ? IN_REDIRECT.exec(word)?.[1] : undefined)
53    if (target === undefined || target.startsWith('(')) out.push(word)
54    else if (target === '') i += 1
55  }
56  return out
57}
58
59// Where a redirection or process substitution starts after its `<` or `>`, longest form first.
60const REDIRECT_OP = /<<<|<<-?|<>|<&|<\(|<|>\(|>>|>&|>\||>/y
61// The characters that end a redirection target unquoted in every shell; also where the next one may
62// start. An unquoted `&` inside a target starts `&>` (a lone one already ended the segment): `x&>y`.
63const TARGET_END = /[<>()&]/g
64const ANGLE = /[<>]/g
65
66/** The word with every quoted run and backslash escape blanked to `_`, same length: what is left is unquoted. */
67function maskQuoted(word: string): string {
68  return word.replace(WORD_PART, (m: string, _dq?: string, _sq?: string, _esc?: string, plain?: string) => (plain === undefined ? '_'.repeat(m.length) : m))
69}
70
71/**
72 * Whether an output redirection writes nothing: `>`, `>>` or `&>` (any descriptor) onto exactly
73 * `/dev/null`, or `>&` copying stdout or stderr onto the other. Every other form, target or descriptor
74 * (`>&3`, `3>&1`, `&>>`, `<>`, `<&`, `>|`, a quoted or `$` target) counts as a write.
75 */
76function harmlessOutput(op: string, fd: string, target: string): boolean {
77  if (op === '>' || op === '>>' || op === '&>') return target === '/dev/null'
78  return op === '>&' && (fd === '' || fd === '1' || fd === '2') && (target === '1' || target === '2')
79}
80
81/**
82 * Whether a segment carries an output redirection that may write a file (#1569, MR !133): `git log
83 * --format=… >> .git/config` wrote the push configuration the facts never saw. Read quote-aware over the
84 * same words as {@link readCommand}, also where the reader keeps the word (`--short>>.git/config`), so a
85 * quoted `"a > b"` is no redirection. Input redirections (`<`, `N<`, `<<`, `<<<`) and process
86 * substitutions (`<(…)`, `>(…)`, read by {@link gitInSubstitution}) write nothing here. One pass per word.
87 */
88function writesOutput(segment: string): boolean {
89  // An operator whose target is the next word: `> .git/HEAD`. `in` skips that word, `out` judges it.
90  let pending: { kind: 'in' | 'out'; op: string; fd: string } | null = null
91  for (const word of rawWords(stripGroup(segment))) {
92    const masked = maskQuoted(word)
93    let at = 0
94    // The target runs to the next unquoted `<`, `>`, `(`, `)` or `&`: `/dev/null)` closes a `$(…)`.
95    const targetEnd = (from: number): number => {
96      TARGET_END.lastIndex = from
97      return TARGET_END.exec(masked)?.index ?? word.length
98    }
99    if (pending !== null) {
100      at = targetEnd(0)
101      if (pending.kind === 'out' && !harmlessOutput(pending.op, pending.fd, word.slice(0, at))) return true
102      pending = null
103    }
104    for (;;) {
105      ANGLE.lastIndex = at
106      const angle = ANGLE.exec(masked)?.index
107      if (angle === undefined) break
108      REDIRECT_OP.lastIndex = angle
109      let op = REDIRECT_OP.exec(masked)?.[0] ?? ''
110      let opEnd = angle + op.length
111      if (op === '<(' || op === '>(') {
112        at = opEnd
113        continue
114      }
115      // `&>` / `&>>`: the `&` belongs to the operator; otherwise the digits in front are its descriptor.
116      let fd = ''
117      if (op.startsWith('>') && masked[angle - 1] === '&') op = `&${op}`
118      else {
119        let start = angle
120        while (start > at && /\d/.test(masked[start - 1] ?? '')) start -= 1
121        fd = masked.slice(start, angle)
122      }
123      if (op === '&>' && masked[opEnd] === '>') {
124        op = '&>>'
125        opEnd += 1
126      }
127      const kind = op.startsWith('<') && op !== '<>' && op !== '<&' ? 'in' : 'out'
128      if (opEnd >= word.length) {
129        pending = { kind, op, fd }
130        break
131      }
132      at = targetEnd(opEnd)
133      if (kind === 'out' && !harmlessOutput(op, fd, word.slice(opEnd, at))) return true
134    }
135  }
136  // An output operator with no target left (`git log >`, cut at a `|`): fail-closed.
137  return pending?.kind === 'out'
138}
139
140/** The words of a segment as the command receives them: redirections dropped (input ones when `input`), quotes removed. */
141function argWords(text: string, input = false): string[] {
142  return dropRedirections(rawWords(text), input).map(dequote)
143}
144
145// Words that can come before the real command without changing what it does. `eval` with unquoted
146// words runs exactly those words; its quoted form is read by {@link extractInner}. `if`, `while`,
147// `until` and `elif` run their condition as a command, `then`, `do` and `else` their body.
148const PREFIXES = new Set(['command', 'exec', 'nohup', 'time', 'if', 'elif', 'while', 'until', 'then', 'do', 'else', '!', 'eval'])
149
150// The options of the transparent prefixes and runners that take a separate value.
151const ENV_VALUED = new Set(['-u', '--unset'])
152const SUDO_VALUED = new Set(['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U', '-T', '--user', '--group', '--host', '--prompt', '--close-from', '--chdir', '--role', '--type', '--other-user', '--command-timeout'])
153const NICE_VALUED = new Set(['-n', '--adjustment'])
154const TIMEOUT_VALUED = new Set(['-s', '--signal', '-k', '--kill-after'])
155const RUNNER_VALUED = new Set(['-p', '--package'])
156// caffeinate's -t <seconds> and -w <pid>, also as the last letter of a group (`-it 5`).
157const CAFFEINATE_VALUED = /^-[a-z]*[tw]$/
158
159// A variable assignment word: `NAME=value`, `NAME+=value`, and an array element `NAME[i]=value` (zsh: `HOME[1,-1]=x`
160// rewrites HOME, #1571); group 1 is the name.
161const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)(?:\[[^\]]*\])?\+?=/
162
163/**
164 * A segment without the `(`/`{` in front and the `)`/`}` behind it. Trimmed by hand: `\s*[)}]+$`
165 * retried from every blank of a long run, quadratic on attacker-controlled length.
166 */
167function stripGroup(segment: string): string {
168  const text = segment.trim().replace(/^[({]+\s*/, '')
169  let end = text.length
170  while (end > 0 && (text[end - 1] === ')' || text[end - 1] === '}')) end -= 1
171  return end === text.length ? text : text.slice(0, end).trimEnd()
172}
173
174/**
175 * The command a segment runs, read with an index (a `shift()` per word was quadratic: 535 ms for 50k
176 * characters of `npx -y`): its words with redirections, leading `VAR=x`, `env -u X`, `sudo`, `nice`,
177 * `timeout`, `caffeinate`, the prefixes above and a runner's own options removed, and the names those
178 * leading assignments set. `input` also drops input redirections (the outward reader).
179 */
180function readCommand(segment: string, input: boolean): { words: string[]; assigned: string[] } {
181  const words = argWords(stripGroup(segment), input)
182  const assigned: string[] = []
183  let i = 0
184  // Skips options (and, for those `valued` names, their value) up to the first word that is none, or past `--`.
185  // `env -u NAME` / `--unset=NAME` removes NAME for the command: recorded like an assignment (`env -u HOME git push`).
186  const skipOptions = (valued: ReadonlySet<string> | RegExp, unsets = false): void => {
187    while ((words[i] ?? '').startsWith('-')) {
188      const option = words[i] ?? ''
189      i += 1
190      if (option === '--') break
191      if (unsets && option.startsWith('--unset=')) assigned.push(option.slice('--unset='.length))
192      else if (unsets && /^-u./.test(option)) assigned.push(option.slice(2))
193      if (valued instanceof RegExp ? valued.test(option) : valued.has(option)) {
194        if (unsets) assigned.push(words[i] ?? '')
195        i += 1
196      }
197    }
198  }
199  for (;;) {
200    const word = words[i]
201    if (word === undefined) break
202    const assignment = ASSIGNMENT.exec(word)
203    if (assignment !== null || PREFIXES.has(word)) {
204      if (assignment !== null) assigned.push(assignment[1] ?? '')
205      i += 1
206      continue
207    }
208    if (word === 'env' || word === 'sudo' || word === 'nice') {
209      i += 1
210      skipOptions(word === 'env' ? ENV_VALUED : word === 'sudo' ? SUDO_VALUED : NICE_VALUED, word === 'env')
211      continue
212    }
213    if (word === 'timeout' || word === 'gtimeout') {
214      i += 1
215      skipOptions(TIMEOUT_VALUED)
216      i += 1 // the duration
217      continue
218    }
219    if (word === 'caffeinate') {
220      i += 1
221      skipOptions(CAFFEINATE_VALUED)
222      continue
223    }
224    break
225  }
226  // npx vercel, npx --yes npm publish, pnpm dlx vercel, npm exec -- changeset: the tool is the next
227  // word after the runner's own options.
228  if (words[i] === 'npx' || words[i] === 'bunx') {
229    i += 1
230    skipOptions(RUNNER_VALUED)
231  } else if ((words[i] === 'pnpm' && (words[i + 1] === 'dlx' || words[i + 1] === 'exec')) || (words[i] === 'npm' && (words[i + 1] === 'exec' || words[i + 1] === 'x'))) {
232    i += 2
233    skipOptions(RUNNER_VALUED)
234  }
235  return { words: words.slice(i), assigned }
236}
237
238/** The words of one segment, redirections, leading `VAR=x`, `env -u X`, `sudo`, `nice`, `timeout`, `caffeinate` and the prefixes above removed. */
239export function commandWords(segment: string): string[] {
240  return readCommand(segment, false).words
241}
242
243/** `\` + newline removed, as the shell does before it reads words: `git \<LF>push` is `git push`. */
244function joinContinuations(command: string): string {
245  return command.replace(/\\\r?\n/g, '')
246}
247
248// ---- What the shell never runs: comments and data heredocs (#1572, #1574) -----
249
250// The characters after which an unquoted `#` starts a comment (the start of a word).
251const WORD_BREAK = /[\s;&|()<>]/
252// A heredoc operator and its delimiter: `<<EOF`, `<<-EOF`, `<< 'EOF'`, `<<"EOF"`, `<<\EOF`. Group 1 is `-`, groups
253// 2 and 3 a single- or double-quoted delimiter, group 4 a backslash-quoted one, group 5 an unquoted one.
254const HEREDOC_OP = /<<(-?)[ \t]*(?:(?:'([A-Za-z_][\w.-]*)'|"([A-Za-z_][\w.-]*)")|\\([A-Za-z_][\w.-]*)|([A-Za-z_][\w.-]*))/y
255// `$(cat <<'EOF'` up to the end of its line: a substitution whose only command is `cat` reading a heredoc with a quoted delimiter.
256const CAT_HEREDOC = /\$\([ \t]*cat[ \t]+<<(-?)[ \t]*(?:'([A-Za-z_][\w.-]*)'|"([A-Za-z_][\w.-]*)")[ \t]*\n/y
257// What may follow a heredoc operator on its own line for the body to stay data: words, `>`, `&&`, `||`, `;`, `&` and
258// simple quotes — no `|` into another command, no second heredoc, no `$`, backtick or backslash.
259const HEREDOC_REST = /^(?:[^'"`$\\|<\n]|'[^'\n]*'|"[^"\\$`\n]*"|\|\|)*$/
260// A `${name}` that nests nothing; any other `${` stops the view like `$(`.
261const PLAIN_BRACE = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/y
262// Heredocs whose closing line was not found before the view gives up (each miss reads to the end of the line).
263const MAX_HEREDOC_MISSES = 4
264// An `eval` word: what it is given is parsed again as shell code, so nothing quoted behind it is text.
265const EVAL_WORD = /(?:^|[\s;&|(){}])eval(?=\s)/
266
267/**
268 * Whether the command a heredoc or `$(cat <<'EOF' …)` feeds treats it as text: `cat` printing it (no file
269 * written), `git commit` (its message), or a forge's issue/merge-request/pull-request command (a body). Never a
270 * shell, an interpreter, `gh api` (a GraphQL body) or anything else (#1574: `bash <<'EOF'` still runs its body).
271 */
272function readsAsText(words: readonly string[], writes: boolean): boolean {
273  const [first, ...args] = words
274  const cmd = baseName(first ?? '')
275  if (cmd === 'cat') return !writes && args.every(arg => arg === '-')
276  if (cmd === 'git') {
277    const git = readGit(args, null)
278    return git.sub === 'commit' && git.config.length === 0
279  }
280  return (cmd === 'gh' || cmd === 'glab') && (args[0] === 'issue' || args[0] === 'mr' || args[0] === 'pr')
281}
282
283/**
284 * Whether the body of a heredoc with an unquoted delimiter runs nothing: no backtick, `$(`, `$((`, `$[` or `${…}` other
285 * than `${name}` — a plain `$name` only expands. (A quoted delimiter keeps every body literal.)
286 */
287function inertBody(body: string): boolean {
288  return !/`|\$[([]|\$\{(?![A-Za-z_][A-Za-z0-9_]*\})/.test(body)
289}
290
291/** The index just past the closing line of a heredoc whose body starts at `from`, or -1 (`tabs`: `<<-`, leading tabs stripped). */
292function heredocEnd(line: string, from: number, delimiter: string, tabs: boolean): number {
293  let at = from
294  while (at <= line.length) {
295    const nl = line.indexOf('\n', at)
296    const end = nl === -1 ? line.length : nl
297    const text = line.slice(at, end)
298    if ((tabs ? text.replace(/^\t+/, '') : text) === delimiter) return end
299    if (nl === -1) return -1
300    at = nl + 1
301  }
302  return -1
303}
304
305/**
306 * The line as the shell runs it, for every reader below: each comment removed, and each heredoc that is only text
307 * replaced by the word `<_` (an input redirection the readers drop), its body and closing line removed — so a commit
308 * message, an issue body or a comment that mentions `git push` is no command, and `git commit -m "$(cat <<'EOF' …
309 * EOF)"` (Claude Code's own recipe) is one git step, not a `cat` before the push (#1574). A heredoc is text only with
310 * a quoted delimiter (or an unquoted one with an {@link inertBody}) and a reader per
311 * {@link readsAsText}; `$(cat <<'EOF' … EOF)` only inside double quotes, its closing `)` right after the closing line.
312 * Read with the quote tracking of {@link scanLine}: from the first newline inside a quote or construct that nests its
313 * own quoting (`$(`, a backtick, `${…}` other than `${name}`, `$'`, `<(`, `>(`, a heredoc that is not text) the rest
314 * is kept as written — over-reading only asks. A `#` starts a comment at the start of a word outside quotes: a push
315 * between `# bash -c '` and `# '` runs (#1572 E1).
316 */
317function dataView(line: string): string {
318  const out: string[] = []
319  let quote: '"' | "'" | null = null
320  let segStart = 0
321  let misses = 0
322  let copied = 0
323  let consumerAt = -1
324  let consumerText = false
325  const flush = (to: number): void => {
326    if (to > copied) out.push(line.slice(copied, to))
327    copied = to
328  }
329  for (let i = 0; i < line.length; i += 1) {
330    const ch = line[i] ?? ''
331    if (quote === "'") {
332      if (ch === "'") quote = null
333      else if (ch === '\n') break
334      continue
335    }
336    if (ch === '\\') {
337      i += 1
338      continue
339    }
340    if (ch === '\n' && quote !== null) break
341    if (ch === '`') break
342    if (ch === '$') {
343      const next = line[i + 1]
344      if (next === '{') {
345        PLAIN_BRACE.lastIndex = i
346        if (!PLAIN_BRACE.test(line)) break
347        i = PLAIN_BRACE.lastIndex - 1
348        continue
349      }
350      if (next === "'") break
351      if (next !== '(') continue
352      CAT_HEREDOC.lastIndex = i
353      const cat = CAT_HEREDOC.exec(line)
354      const delimiter = cat?.[2] ?? cat?.[3]
355      if (cat === null || delimiter === undefined || quote !== '"' || misses >= MAX_HEREDOC_MISSES) break
356      const end = heredocEnd(line, CAT_HEREDOC.lastIndex, delimiter, cat[1] === '-')
357      const close = end === -1 ? null : /^\s*\)/.exec(line.slice(end, end + 64))
358      if (close === null) {
359        misses += 1
360        break
361      }
362      // Judged once per segment: many substitutions in one quoted word would re-read its growing prefix (quadratic).
363      if (consumerAt !== segStart) {
364        const prefix = line.slice(segStart, i)
365        const consumer = readCommand(prefix, true).words
366        consumerAt = segStart
367        // `eval git commit -m "$(cat …)"` parses the message again as shell code.
368        consumerText = readsAsText(consumer, false) && baseName(consumer[0] ?? '') !== 'cat' && !EVAL_WORD.test(prefix)
369      }
370      if (!consumerText) break
371      flush(i)
372      out.push('_')
373      copied = end + close[0].length
374      i = copied - 1
375      continue
376    }
377    if (quote === '"') {
378      if (ch === '"') quote = null
379      continue
380    }
381    if (ch === '"' || ch === "'") quote = ch
382    else if ((ch === '<' || ch === '>') && line[i + 1] === '(') break
383    else if (ch === '#' && (i === 0 || WORD_BREAK.test(line[i - 1] ?? ''))) {
384      flush(i)
385      const nl = line.indexOf('\n', i)
386      copied = nl === -1 ? line.length : nl
387      i = copied - 1
388    } else if (ch === '<' && line[i + 1] === '<' && line[i + 2] === '<') i += 2
389    else if (ch === '<' && line[i + 1] === '<') {
390      HEREDOC_OP.lastIndex = i
391      const op = HEREDOC_OP.exec(line)
392      const delimiter = op?.[2] ?? op?.[3] ?? op?.[4] ?? op?.[5]
393      if (op === null || delimiter === undefined || misses >= MAX_HEREDOC_MISSES) break
394      const opEnd = HEREDOC_OP.lastIndex
395      const nl = line.indexOf('\n', opEnd)
396      const rest = line.slice(opEnd, nl === -1 ? line.length : nl)
397      if (nl === -1 || !HEREDOC_REST.test(rest)) break
398      const end = heredocEnd(line, nl + 1, delimiter, op[1] === '-')
399      if (end === -1) {
400        misses += 1
401        break
402      }
403      const reader = `${line.slice(segStart, i)} ${rest}`
404      const body = line.slice(nl + 1, end)
405      const literal = op[5] === undefined || inertBody(body)
406      if (!literal || !readsAsText(readCommand(reader, true).words, writesOutput(reader))) break
407      flush(i)
408      out.push(`<_${rest}`)
409      copied = end
410      i = end - 1
411    } else if (ch === ';' || ch === '&' || ch === '|' || ch === '\n' || ch === '(' || ch === ')') segStart = i + 1
412  }
413  flush(line.length)
414  return out.join('')
415}
416
417/**
418 * One pass over a line. `marked` is the line with each background `&` turned into `;`, same length: a
419 * lone `&` ends a command like `;` does (`true & git push`). Not `&&`, `&>`, `>&`, `<&` or `|&`, and
420 * not after a backslash or inside quotes, where `&` is a character (`curl "…?a=1&b=2"`, a commit
421 * message) — but only while the quote tracking is certain. It stops being certain (`doubt`) at the
422 * first newline inside an open quote (a heredoc body or a multi-line string: which of the two, this
423 * cannot tell, and resetting the quote there flipped parity on the next line, so `"msg<NL>x=1"; git
424 * status & git switch main` hid the `&`) and at the first construct that nests its own quoting or is
425 * no shell word: `$(`, `${`, `$'`, a backtick, `<(`, `>(`, `<<`. From there every lone `&` is cut,
426 * quoted or not: over-reading finds more commands, never fewer.
427 * `unsure[i]` is 1 where position `i` may sit inside a quote — or after doubt began, or after an
428 * unquoted `(` or `{` (a group: a `cd` there may not reach what follows); `unsure[length]` is the state
429 * at the end.
430 */
431function scanLine(line: string): { marked: string; unsure: Uint8Array } {
432  const out: string[] = new Array<string>(line.length)
433  const unsure = new Uint8Array(line.length + 1)
434  let quote: string | null = null
435  let doubt = false
436  let group = false
437  for (let i = 0; i < line.length; i += 1) {
438    const ch = line[i] ?? ''
439    const next = line[i + 1] ?? ''
440    if (!doubt && ((ch === '$' && (next === '(' || next === '{' || next === "'")) || ch === '`' || ((ch === '<' || ch === '>') && next === '(') || (ch === '<' && next === '<') || (ch === '\n' && quote !== null))) doubt = true
441    unsure[i] = doubt || group || quote !== null ? 1 : 0
442    out[i] = ch
443    if (ch === '&' && (quote === null || doubt) && !/[&<>|]/.test(line[i - 1] ?? '') && !/[&>]/.test(next)) out[i] = ';'
444    else if (quote === "'") {
445      if (ch === "'") quote = null
446    } else if (ch === '\\') {
447      i += 1
448      if (i < line.length) {
449        out[i] = line[i] ?? ''
450        unsure[i] = unsure[i - 1] ?? 1
451      }
452    } else if (quote === '"') {
453      if (ch === '"') quote = null
454    } else if (ch === '"' || ch === "'") quote = ch
455    else if (ch === '(' || ch === '{') group = true
456  }
457  unsure[line.length] = doubt || group || quote !== null ? 1 : 0
458  return { marked: out.join(''), unsure }
459}
460
461/** The line with each background `&` turned into `;` ({@link scanLine}). */
462function markBackground(line: string): string {
463  return scanLine(line).marked
464}
465
466// Where splitSegments cuts: `&&`, `||`, `|` and `|&`, `;`, newlines (a background `&` is a `;` by then).
467const SEPARATOR = /&&|\|\||\|&?|;|\n/g
468
469/** The command line cut at `&&`, `||`, `;`, `&`, `|`, `|&` and newlines. Quotes are honoured for `&` only: detection only. */
470export function splitSegments(command: string): string[] {
471  return markBackground(joinContinuations(command)).split(SEPARATOR)
472}
473
474// A separator as written; '' is the start or end of the line.
475type Sep = '' | '&&' | '||' | '|' | '|&' | ';' | '\n' | '&'
476// The separators that end an and-or list (`a && b || c`): what follows runs whatever the list returned.
477const LIST_END: ReadonlySet<Sep> = new Set<Sep>([';', '\n', '&'])
478const PIPE: ReadonlySet<Sep> = new Set<Sep>(['|', '|&'])
479
480/**
481 * A segment as {@link splitSegments} cuts it, with the separators around it. `sure`: at neither end can
482 * it sit inside a quote, after doubt began, or inside a group ({@link scanLine}) — so it is a command
483 * of its own in this shell, not a piece of a string a separator inside quotes cut out. `start`: its index in the line.
484 */
485type Seg = { text: string; before: Sep; after: Sep; sure: boolean; start: number }
486
487function segmentsOf(command: string): Seg[] {
488  const line = joinContinuations(command)
489  const { marked, unsure } = scanLine(line)
490  const segs: Seg[] = []
491  let start = 0
492  let before: Sep = ''
493  const push = (end: number, after: Sep): void => {
494    segs.push({ text: line.slice(start, end), before, after, sure: unsure[start] === 0 && unsure[end] === 0, start })
495  }
496  for (const m of marked.matchAll(SEPARATOR)) {
497    const sep = (m[0] === ';' && line[m.index] === '&' ? '&' : m[0]) as Sep
498    push(m.index, sep)
499    start = m.index + m[0].length
500    before = sep
501  }
502  push(line.length, '')
503  return segs
504}
505
506/** The pipelines of a command line, each a list of its stages. */
507export function splitPipelines(command: string): string[][] {
508  return markBackground(joinContinuations(command)).split(/&&|\|\||;|\n/).map(pipeline => pipeline.split(/\|&?/))
509}
510
511// A quoted command line run by another shell (`bash -c "…"`, `sh -lc '…'`), by a runner's shell mode
512// (`npx -c '…'`, `pnpm exec -c '…'`) or by `eval "…"`. Its separators sit inside quotes, which
513// splitSegments does not honour, so it is cut out first and read as a command line of its own.
514// The shell runs one word after `-c` (the rest become $0, $1, …); `eval` joins all its words. A word
515// that starts with `-` (`bash -c -- "…"`) or a shell this cannot cut is left whole: {@link unreadableOutward} reads it.
516const SHELL_WORD = String.raw`(?:"(?:[^"\\]|\\.)*"|'[^']*'|\\.|[^\s"'\\;&|()<>]+)+`
517const INNER_SOURCE = String.raw`(?<![\w./-])(?:(?:(?:bash|sh|zsh|dash|ksh)\s+(?:-[-\w]+\s+)*?-(?=[A-Za-z]*c)[A-Za-z]+|(?:npx|bunx|pnpm\s+(?:dlx|exec)|npm\s+(?:exec|x))\s+(?:-[-\w=]+\s+)*?(?:-c|--call|--shell-mode))\s+(?!-)(${SHELL_WORD})|eval((?:[ \t]+${SHELL_WORD})+))`
518const INNER = new RegExp(INNER_SOURCE, 'g')
519const INNER_AT = new RegExp(INNER_SOURCE, 'y')
520const INNER_WORD = /^__SOHUD_INNER_(\d+)__$/
521// Nesting deeper than this is read without cutting, so its words still split (and over-detect).
522const MAX_DEPTH = 3
523
524// `expanded`: the part of the inner line the OUTER shell expands before running it — all of an `eval`, and the
525// double-quoted or bare parts of a `-c` word (a single-quoted `$x` is read by the child, which has no unexported x).
526type Inner = { command: string; sameShell: boolean; expanded: string }
527
528/** The line with each inner command line replaced by a placeholder word, and those command lines. */
529function extractInner(line: string, depth: number): { text: string; inners: Inner[] } {
530  const inners: Inner[] = []
531  if (depth >= MAX_DEPTH) return { text: line, inners }
532  const text = line.replace(INNER, (_match: string, shellWord?: string, evalWords?: string) => {
533    if (shellWord !== undefined) {
534      const expanded = shellWord.replace(/"(?:[^"\\]|\\.)*"|'[^']*'|\\./g, part => (part.startsWith("'") ? '' : part))
535      inners.push({ command: dequote(shellWord), sameShell: false, expanded })
536    } else {
537      const command = tokenize(evalWords ?? '').join(' ')
538      inners.push({ command, sameShell: true, expanded: command })
539    }
540    return ` __SOHUD_INNER_${inners.length - 1}__ `
541  })
542  return { text, inners }
543}
544
545/** The inner command line a segment runs, when its first word is a placeholder. */
546function innerAt(word: string, inners: readonly Inner[]): Inner | null {
547  const m = INNER_WORD.exec(word)
548  return m ? (inners[Number(m[1])] ?? null) : null
549}
550
551function baseName(word: string): string {
552  return word.replace(/^\\/, '').split('/').pop() ?? word
553}
554
555/** A folder a later `cd arg` moves to, given the folder so far (null = the session folder). */
556function joinDir(dir: string | null, arg: string | undefined): string {
557  if (arg === undefined || arg === '~' || arg.startsWith('/') || arg.startsWith('~/')) {
558    return arg ?? '~'
559  }
560  return dir ? `${dir}/${arg}` : arg
561}
562
563/** The positional arguments, skipping each option and, for the options in `valued`, its value. */
564export function positionals(args: readonly string[], valued: ReadonlySet<string>): string[] {
565  const out: string[] = []
566  for (let i = 0; i < args.length; i += 1) {
567    const arg = args[i] ?? ''
568    if (arg === '--') {
569      out.push(...args.slice(i + 1))
570      break
571    }
572    if (arg.startsWith('-') && arg !== '-') {
573      if (valued.has(arg)) i += 1
574      continue
575    }
576    out.push(arg)
577  }
578  return out
579}
580
581/** The value of `--name value`, `--name=value` or `-n value`, or undefined. */
582export function optionValue(args: readonly string[], ...names: string[]): string | undefined {
583  for (let i = 0; i < args.length; i += 1) {
584    const arg = args[i] ?? ''
585    for (const name of names) {
586      if (arg === name) return args[i + 1]
587      if (arg.startsWith(`${name}=`)) return arg.slice(name.length + 1)
588    }
589  }
590  return undefined
591}
592
593// ---- Actions with an effect outside this machine -----------------------------
594
595export type OutwardKind = 'push' | 'merge' | 'publish' | 'deploy' | 'release'
596
597export const KIND_LABEL: Record<OutwardKind, string> = {
598  push: 'Push',
599  merge: 'Merge',
600  publish: 'Paket veröffentlichen',
601  deploy: 'Produktiv-Deploy',
602  release: 'Release',
603}
604
605export type Outward = {
606  kind: OutwardKind
607  /** The detected action. */
608  label: string
609  /** The command's own words after the subcommand. */
610  args: string[]
611  /**
612   * Where a `cd` earlier on the line moved to; null means the session folder. A `cd`, `pushd` or
613   * `popd` whose effect on this command is not certain — inside `( )`, `{ }` or quotes, in a pipeline
614   * stage, after `||` or followed by one before the command, ending a background list, behind a
615   * prefix (`if`, `then`, `command`, `VAR=x`), after `&&` in an earlier list, an option or `-`/`+N` —
616   * makes it {@link UNKNOWN_DIR} (or a folder below it), which resolves to no folder, so the push asks.
617   */
618  dir: string | null
619  /** For merges and releases: which forge CLI. */
620  forge?: 'glab' | 'gh'
621  /** For publishes and deploys: which tool. */
622  tool?: string
623  /**
624   * For pushes: every git invocation earlier on the line as a step ({@link gitStep}), child shells and
625   * command substitutions included: any of them may have moved what the facts measured. A git step run
626   * in a folder other than {@link dir}, or in an unknown one, is recorded as `<step> [other folder]`: its
627   * hooks and its configuration are not the ones {@link PushFacts.hooks} and {@link PushFacts.repoConfig}
628   * measured (`git -C ../b diff` runs ../b's `diff.external`, #1573 review).
629   */
630  gitBefore?: string[]
631  /**
632   * For pushes: some earlier command on the line is not a git call — in this shell, a child shell or a
633   * command substitution (`gh pr checkout 5 && …`, `./switch.sh; …`, `x=$(./x)`) — so it may have moved
634   * HEAD or written the push configuration (`printf … >> .git/config`): every push form behind it asks.
635   * `cd`/`pushd`/`popd` (read as {@link dir}) and a bare assignment (`x=1`) run no command and do not set it.
636   * Also set by an earlier output redirection on any segment, git steps included ({@link writesOutput}):
637   * `git log --format=… >> .git/config`, `cd . > .git/HEAD`, `exec 3>>.git/config`.
638   */
639  otherBefore?: true
640  /**
641   * For pushes: an earlier `git commit` on the line signs explicitly (`-S`, `-S<key>`, `--gpg-sign`, a short
642   * option bundle holding `S`; the last of these and `--no-gpg-sign` wins), so it runs `gpg.program` whatever
643   * `commit.gpgSign` says ({@link repoConfigStandard}). `tag -s` and `merge -S` are no local step.
644   */
645  signsBefore?: true
646  /**
647   * For pushes: git configuration the push runs with that the measured facts did not see — each
648   * `-c` / `--config-env` entry as written (`key=value`), `--git-dir` / `--work-tree` / `--namespace`
649   * as `--option=value`, every other global option as written, the names of `GIT_CONFIG*` /
650   * `GIT_DIR`-style variables anywhere on the line, and the name of every variable assigned, exported,
651   * declared or unset on the line (in front of the push or as a statement) that is not
652   * {@link HARMLESS_VAR} (`HOME=x` moves the config git reads), plus `source`/`.`/`alias`/`hash` as written.
653   */
654  gitConfig?: string[]
655  /** For pushes: the destination is not read from git's own words (an unreadable line, a forge API ref write): always asks. */
656  opaque?: true
657}
658
659// stepDirs: the folder each git step of gitBefore ran in, by its index.
660type WalkState = { dir: string | null; gitBefore: string[]; stepDirs: Map<number, string | null>; otherBefore: boolean; signs: boolean; gitEnv: Set<string> }
661
662// Variables that route a push past what the facts measured: extra config, another repository.
663const GIT_ENV = /(?<![\w])(GIT_(?:CONFIG\w*|DIR|WORK_TREE|NAMESPACE|COMMON_DIR))=/g
664
665/**
666 * The folder a push gets when a `cd` before it may or may not have run ({@link Outward.dir}): a path
667 * below `/dev/null`, a device and never a directory, so `cd` into it (or into any folder below it)
668 * fails on every system and the wiring resolves no folder — the push asks.
669 */
670export const UNKNOWN_DIR = '/dev/null/so-hud-unknown-folder'
671
672/**
673 * The variable names an assignment before a push may set without asking — an allowlist (#1569 M2a):
674 * a single lowercase letter, or a name an agent's one-liner uses to hold a value. bash gives no
675 * lowercase name a meaning; none of these is a zsh special parameter (zshparam(1), zsh/parameter —
676 * `path`, `cdpath`, `commands`, `aliases` are, and stay out), and none is read by git, ssh or curl.
677 * Also one or two uppercase characters (`D`, `WT`, `L1`, `TZ`): agents hold paths in them, and no
678 * shell gives such a name a meaning (measured 2026-10-12: zsh 5.9 `${(k)parameters}`, 185 names, and
679 * bash `compgen -v` hold none matching `^[A-Z][A-Z0-9]?$`); `TZ` only changes how times print. A later
680 * `$D` after `cd` or in the push's own words is not read by the rules and asks on its own.
681 * Everything else asks: `HOME`, `XDG_*`, `GIT_*`, `PATH`, `PREFIX`, `CDPATH`, `BASH_ENV` … change
682 * which config git reads, which git runs, or where `cd` goes.
683 */
684const HARMLESS_VAR = /^(?:[a-z]|rc|out|msg|sha|ref|head|base|branch|res|ok|tmp|[A-Z][A-Z0-9]?)$/
685// Statements that set or remove variables by name, and those that change how the shell finds a command.
686const DECLARERS = new Set(['export', 'declare', 'typeset', 'local', 'readonly', 'unset', 'let'])
687// Builtins that set the variables they name without `=` (#1571): `read -r GIT_CONFIG_COUNT … <<< "…"`, `printf -v HOME`,
688// `mapfile`/`readarray`, `getopts`, zsh `vared`. Every word that starts like a name counts (a prompt word too: that only asks).
689const NAME_SETTERS = new Set(['read', 'printf', 'mapfile', 'readarray', 'getopts', 'vared'])
690const SHELL_STATE = new Set(['source', '.', 'alias', 'hash'])
691
692/**
693 * Every action with an effect outside, one per segment: `git push origin feat && git push origin main`
694 * holds two, and a skippable first one must not let the second run (review R1, gate-host). Command
695 * lines run by `bash -c`, `sh -c`, `zsh -c`, `eval` and a runner's `-c` are read too, up to depth 3;
696 * a line this cannot read adds one fail-closed hit from {@link unreadableOutward}.
697 */
698export function classifyAllOutward(command: string): Outward[] {
699  const hits: Outward[] = []
700  const line = dataView(joinContinuations(command))
701  walkOutward(line, 0, { dir: null, gitBefore: [], stepDirs: new Map(), otherBefore: false, signs: false, gitEnv: new Set() }, hits)
702  const kind = unreadKind(line) ?? unformedKind(line, 0)
703  if (kind !== null) hits.push({ kind, label: UNREADABLE_LABEL, args: [], dir: null, opaque: true })
704  return hits
705}
706
707// ---- The fail-closed fallback: an outward word no hit was formed for (#1570) ---
708
709// Commands that never run what they are given: their words are data (`echo "… git push …"`, `grep -rn publish`).
710// Not here: `sed` (GNU `e`), `awk` (`system()`), `find` (`-ok`), `xargs`, any shell or interpreter, and every
711// command not listed — an allowlist, so a wrapper this does not know (`flock`, `stdbuf`, `doas`) is read as code.
712const DATA_COMMANDS = new Set(['echo', 'printf', 'cat', 'grep', 'egrep', 'fgrep', 'rg', 'head', 'tail', 'wc', 'ls', 'sort', 'uniq', 'cut', 'tr', 'diff', 'cmp', 'less', 'more', 'file', 'stat', 'du', 'df', 'test', '[', '[[', ':', 'true', 'false', 'sleep', 'wait', 'date', 'pwd', 'which', 'type', 'whence', 'mkdir', 'touch', 'rm', 'rmdir', 'cp', 'mv', 'ln', 'chmod', 'basename', 'dirname', 'realpath', 'readlink', 'jq', 'yq', 'column', 'nl', 'fold', 'cd', 'pushd', 'popd', 'export', 'declare', 'typeset', 'local', 'readonly', 'unset', 'set', 'shift', 'return', 'exit', 'break', 'continue', 'ps', 'pgrep', 'pkill', 'kill', 'lsof'])
713// Commands that read a pipe as data and never run it; a pipe into anything else (`| sh`, `| awk`, `| sed`) runs its input.
714const PIPE_DATA = new Set(['cat', 'grep', 'egrep', 'fgrep', 'rg', 'head', 'tail', 'wc', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'jq', 'yq', 'tee', 'column', 'nl', 'fold', 'diff', 'cmp', 'base64', 'shasum', 'sha256sum', 'md5', 'od', 'xxd', 'hexdump', 'strings'])
715// The forge subcommands whose words are titles, bodies and filters; `merge`, `release create` and `api` writes are read as hits.
716const FORGE_TEXT = new Set(['issue', 'mr', 'pr', 'api', 'label', 'search', 'browse', 'status', 'auth', 'config'])
717const FORGE_READ_ACTIONS = new Set(['view', 'list', 'download', 'status', 'watch', 'trace', 'get', 'clone'])
718// The tools whose outward subcommands the classifier knows exactly: a `--dry-run` of theirs, and any vercel call that is
719// no production deploy, was read and judged.
720const OUTWARD_TOOLS = new Set(['npm', 'pnpm', 'yarn', 'cargo', 'changeset', 'vercel', 'supabase', 'fly', 'flyctl', 'railway'])
721// Interpreters whose inline code (`node -e "…"`, `python3 - <<'EOF'`) reaches git only through a process API: without
722// one of {@link SPAWN_API} on the line, their code is data to the fallback (an analysis script that mentions `git push`).
723// Ceiling: a process API spelled so this does not match (`require('child' + '_process')`), or a module the code loads.
724const GATED_INTERPRETERS = new Set(['node', 'deno', 'bun', 'tsx', 'python', 'python3', 'osascript', 'perl', 'ruby'])
725// perl and ruby also run a backtick string, and a backtick is ordinary text to node (a template literal).
726const BACKTICK_RUNNERS = new Set(['perl', 'ruby'])
727const SPAWN_API = /\bsystem\s*\(|\bqx\b|\bpopen\b|\bOpen3\b|%x[({[]|child_process|\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync|fork)\s*\(|\bexeca\b|\$`|\bBun\.(?:spawn|\$)|\bDeno\.(?:run|Command)|\bzx\b|\bsubprocess\b|\bos\.(?:system|popen|exec|spawn|posix_spawn)|\bpty\b|\bplumbum\b|\bpexpect\b|do shell script/
728
729// What a command word from a variable may hide behind it: an outward subcommand whose tool is unreadable (`${X}t push`).
730const OUTWARD_SUBWORDS = new Set(['push', 'publish', 'merge', 'accept', 'deploy', 'promote', 'rollback', 'up', '--prod'])
731
732// git subcommands that run a shell command given as an argument (`git rebase -x "…"`, `git submodule foreach '…'`): their
733// words are code, not judged.
734const GIT_RUNS_SHELL = new Set(['rebase', 'bisect', 'submodule', 'filter-branch', 'difftool', 'mergetool'])
735
736/** Whether the classifier read this command and judged it, so its words need no second look ({@link unformedKind}). */
737function judged(cmd: string, args: string[]): boolean {
738  if (classifyWords(cmd, args, null) !== null || cmd === 'git-push') return true
739  if (cmd === 'git') return !GIT_RUNS_SHELL.has(readGit(args, null).sub ?? '')
740  if (cmd === 'gh' || cmd === 'glab' || /^glab-[a-z0-9-]+$/.test(cmd)) {
741    return FORGE_TEXT.has(args[0] ?? '') || FORGE_READ_ACTIONS.has(args[1] ?? '')
742  }
743  if (!OUTWARD_TOOLS.has(cmd)) return false
744  // `npm help publish`, `npm i publish-x`: a subcommand the publish reader rules out.
745  const pm = (cmd === 'npm' || cmd === 'pnpm' || cmd === 'yarn') && PM_NOT_PUBLISHING.has(positionals(args, PM_VALUED)[0] ?? '')
746  return cmd === 'vercel' || pm || isDryRun(args, PM_VALUED, false)
747}
748
749/** The segment with each inner command line put back where its placeholder stands. */
750function withInners(text: string, inners: readonly Inner[]): string {
751  return text.replace(/__SOHUD_INNER_(\d+)__/g, (m: string, n: string) => inners[Number(n)]?.command ?? m)
752}
753
754/**
755 * The fail-closed fallback after the walker (#1570): the outward kind of the first segment that names an outward
756 * action ({@link classKindIn}) but formed no hit and was not judged ({@link judged}); null when there is none. A
757 * denylist of spellings does not converge (each review found new wrappers: `time -p`, `flock … bash -c`, `nohup --`,
758 * `sh <<<'…'`, `python3 -c`, `case x in a|x)`), so this asks for every segment it cannot account for instead. Not read
759 * as code: a segment whose command is in {@link DATA_COMMANDS} (unless its output is piped into a command outside
760 * {@link PIPE_DATA}: `echo git push origin main | sh`), one with no command (`msg="deploy"`), and what {@link dataView}
761 * removed. A placeholder of a cut-out `bash -c '…'` that is not the first word (`flock /tmp/l bash -c "…"`) counts
762 * as code; a first-word one is read as its own line. Inline code of a {@link GATED_INTERPRETERS} interpreter counts
763 * only on a line with a process API ({@link SPAWN_API}). A git subcommand from a variable (`git ${X}sh`) always asks,
764 * a command word from one asks when its subcommand is an outward word ({@link OUTWARD_SUBWORDS}: `${X}t push`).
765 */
766function unformedKind(line: string, depth: number): OutwardKind | null {
767  const { text, inners } = extractInner(line, depth)
768  const joined = joinContinuations(text)
769  const segs = segmentsOf(joined)
770  const spawns = SPAWN_API.test(joined)
771  const openers = quoteOpeners(joined, spawns)
772  const words = segs.map(seg => readCommand(seg.text, true).words)
773  // Per segment, the first segment from it on whose cut is outside every quote (or not followed): where its command ends.
774  const realEnd = new Int32Array(segs.length)
775  for (let j = segs.length - 1; j >= 0; j -= 1) {
776    const cut = openers[(segs[j]?.start ?? 0) + (segs[j]?.text.length ?? 0)] ?? UNKNOWN_QUOTE
777    realEnd[j] = cut < 0 || j === segs.length - 1 ? j : (realEnd[j + 1] ?? j)
778  }
779  // The segment holding index `at` (the last one starting at or before it).
780  const segAt = (at: number): number => {
781    let lo = 0
782    let hi = segs.length - 1
783    while (lo < hi) {
784      const mid = (lo + hi + 1) >> 1
785      if ((segs[mid]?.start ?? 0) <= at) lo = mid
786      else hi = mid - 1
787    }
788    return lo
789  }
790  for (let k = 0; k < segs.length; k += 1) {
791    const seg = segs[k]
792    if (seg === undefined) continue
793    const opener = openers[seg.start] ?? UNKNOWN_QUOTE
794    if (opener === HEREDOC_DATA) continue
795    // A segment cut out of a quoted word (a commit body's line, `-m "a; b"`) is that word's command's argument —
796    // unless an `eval` parses that word again.
797    const quotedIn = opener >= 0 ? segAt(opener) : k
798    const owner = EVAL_WORD.test(segs[quotedIn]?.text ?? '') ? k : quotedIn
799    const [first, ...args] = words[owner] ?? []
800    if (first === undefined) continue
801    const inner = innerAt(first, inners)
802    if (inner !== null) {
803      if (owner !== k) continue
804      const kind = unformedKind(inner.command, depth + 1)
805      if (kind !== null) return kind
806      continue
807    }
808    const cmd = baseName(first)
809    if (owner === k && cmd === 'git' && (readGit(args, null).sub ?? '').includes('$')) return 'push'
810    if (judged(cmd, args)) continue
811    // The command ends at the first cut outside its quotes: a `|` inside `grep -E "a|b"` is no pipe.
812    const last = realEnd[owner] ?? owner
813    const next = words[last + 1] ?? []
814    const piped = PIPE.has(segs[last]?.after ?? '') && !PIPE_DATA.has(baseName(next[0] ?? '')) && !judged(baseName(next[0] ?? ''), next.slice(1))
815    if (DATA_COMMANDS.has(cmd) && !piped) continue
816    if (GATED_INTERPRETERS.has(cmd) && !spawns && !(BACKTICK_RUNNERS.has(cmd) && joined.includes('`'))) continue
817    const code = withInners(seg.text, inners)
818    const kind = classKindIn(code)
819    if (kind !== null) return kind
820    if (owner === k && first.includes('$') && args.slice(0, 2).some(word => OUTWARD_SUBWORDS.has(word))) return 'push'
821  }
822  return null
823}
824
825// A command that may run a file written earlier on the line, in command position (line start or after `;`, `&`, `|`,
826// `(`, `{`, a newline, `then`/`do`): a shell or interpreter, `source`/`.`, `exec`, `xargs`, or a path like `./x`, `/tmp/x.sh`.
827const RUNS_FILE = /(?:^|[;&|(){}\n]|\b(?:then|do|else)\s)\s*(?:sudo\s+|env\s+|nohup\s+|exec\s+)*(sh|bash|zsh|dash|ksh|fish|source|\.|python3?|node|deno|bun|tsx|perl|ruby|exec|xargs|\.{0,2}\/\S+)(?=[\s;&|()]|$)/g
828
829/**
830 * Whether a line may run a file it wrote ({@link RUNS_FILE}): a runner that is no {@link GATED_INTERPRETERS} one, or a
831 * gated one on a line that can start a process (`spawns`) — `cat > x.mjs <<'EOF' … EOF; node x.mjs` with no process API
832 * runs no git.
833 */
834function runsWrittenFile(line: string, spawns: boolean): boolean {
835  for (const m of line.matchAll(RUNS_FILE)) {
836    const runner = m[1] ?? ''
837    if (spawns || !GATED_INTERPRETERS.has(runner) || (BACKTICK_RUNNERS.has(runner) && line.includes('`'))) return true
838  }
839  return false
840}
841
842// Values of {@link quoteOpeners} that are no index: outside every quote, not followed (after a construct that nests its
843// own quoting), and inside the body of a heredoc read as text.
844const NO_QUOTE = -1
845const UNKNOWN_QUOTE = -2
846const HEREDOC_DATA = -3
847
848/**
849 * Per index of `line`: where the quote it sits inside opened, {@link NO_QUOTE}, {@link HEREDOC_DATA} inside the body of
850 * a heredoc with a literal body that `cat` or `tee` reads (also into a file, on a line that runs no file
851 * ({@link runsWrittenFile}): the walker still reads those lines, this only keeps the fallback from asking for them) or a
852 * {@link GATED_INTERPRETERS} one does on a line without `spawns`,
853 * or {@link UNKNOWN_QUOTE} from the first construct whose quoting this does not follow (a backtick, `${…}` other than
854 * `${name}`, `$'`, `<(`, `>(`, any other heredoc). Quotes are followed
855 * across newlines (a multi-line commit message is one word) and into `$(…)`, whose body starts unquoted and whose `)`
856 * restores the quote around it; a `case` or a comment inside it stops the tracking (their `)` would end it early). Every
857 * `$(…)` body is read by {@link unreadRegions} as well. One pass.
858 */
859function quoteOpeners(line: string, spawns: boolean): Int32Array {
860  const owner = new Int32Array(line.length + 1).fill(UNKNOWN_QUOTE)
861  let quote: '"' | "'" | null = null
862  let opened = NO_QUOTE
863  let segStart = 0
864  // One frame per open `$(`: the quote around it, and the plain `(` opened inside it, so its `)` is found.
865  const frames: { quote: '"' | "'" | null; opened: number; parens: number }[] = []
866  let i = 0
867  const here = (): number => (quote === null ? NO_QUOTE : opened)
868  for (; i < line.length; i += 1) {
869    const ch = line[i] ?? ''
870    owner[i] = here()
871    if (quote === "'") {
872      if (ch === "'") quote = null
873      continue
874    }
875    if (ch === '\\') {
876      i += 1
877      if (i < line.length) owner[i] = here()
878      continue
879    }
880    if (ch === '`') break
881    if (ch === '$') {
882      const next = line[i + 1]
883      if (next === "'") break
884      if (next === '(') {
885        frames.push({ quote, opened, parens: 0 })
886        quote = null
887        owner[i + 1] = NO_QUOTE
888        i += 1
889        segStart = i + 1
890      } else if (next === '{') {
891        PLAIN_BRACE.lastIndex = i
892        if (!PLAIN_BRACE.test(line)) break
893      }
894      continue
895    }
896    if (quote === '"') {
897      if (ch === '"') quote = null
898      continue
899    }
900    const frame = frames.at(-1)
901    // Inside `$(…)` a `case` pattern's `)` or a comment's `)` would end the frame early and shift the quotes after it.
902    if (frame !== undefined && (i === 0 || WORD_BREAK.test(line[i - 1] ?? '')) && (ch === '#' || /^case(?=[\s;&|()<>]|$)/.test(line.slice(i, i + 5)))) break
903    if (ch === '"' || ch === "'") {
904      quote = ch
905      opened = i
906    } else if ((ch === '<' || ch === '>') && line[i + 1] === '(') break
907    else if (ch === '(' && frame !== undefined) frame.parens += 1
908    else if (ch === ')' && frame !== undefined && frame.parens > 0) frame.parens -= 1
909    else if (ch === ')' && frame !== undefined) {
910      frames.pop()
911      quote = frame.quote
912      opened = frame.opened
913      owner[i] = here()
914    } else if (ch === '<' && line[i + 1] === '<' && line[i + 2] === '<') {
915      owner[i + 1] = NO_QUOTE
916      owner[i + 2] = NO_QUOTE
917      i += 2
918    } else if (ch === '<' && line[i + 1] === '<') {
919      HEREDOC_OP.lastIndex = i
920      const op = HEREDOC_OP.exec(line)
921      const delimiter = op?.[2] ?? op?.[3] ?? op?.[4] ?? op?.[5]
922      const nl = line.indexOf('\n', HEREDOC_OP.lastIndex)
923      if (op === null || delimiter === undefined || nl === -1) break
924      const rest = line.slice(HEREDOC_OP.lastIndex, nl)
925      const end = HEREDOC_REST.test(rest) ? heredocEnd(line, nl + 1, delimiter, op[1] === '-') : -1
926      if (end === -1) break
927      const readerText = `${line.slice(segStart, i)} ${rest}`
928      const reader = readCommand(readerText, true).words
929      const tool = baseName(reader[0] ?? '')
930      const literal = op[5] === undefined || inertBody(line.slice(nl + 1, end))
931      // A body `cat`/`tee` writes to a file is code when the line may run a file (`cat > f <<'EOF' … EOF; sh f`).
932      const written = (tool === 'cat' || tool === 'tee') && !runsWrittenFile(line, spawns)
933      if (!literal || !(written || readsAsText(reader, writesOutput(readerText)) || (GATED_INTERPRETERS.has(tool) && !spawns && !(BACKTICK_RUNNERS.has(tool) && line.includes('`'))))) break
934      owner.fill(NO_QUOTE, i, nl + 1)
935      owner.fill(HEREDOC_DATA, nl + 1, end)
936      i = end - 1
937    } else if (ch === ';' || ch === '&' || ch === '|' || ch === '\n' || ch === '(' || ch === ')') segStart = i + 1
938  }
939  if (i >= line.length) owner[line.length] = here()
940  return owner
941}
942
943// ---- Shapes this parser does not read (fail-closed) --------------------------
944
945const UNREADABLE_LABEL = 'nicht lesbare Befehlsform'
946
947// Constructs whose effect the word reader above cannot see. Each is judged on the segment it sits in.
948const UNREAD_CONSTRUCTS = [
949  /\bxargs\b/g,
950  /\bssh\s/g,
951  /\bwatch\s/g,
952  // The lookbehind anchors the name at a word start: without it the engine retries from every
953  // character of a long word, quadratic (1524 ms on 50k chars, Lead review of !132).
954  /(?<![\w.-])[\w.-]+\s*\(\)\s*\{/g,
955  /\bfunction\s+[\w.-]+/g,
956  /\/(?:bash|sh|zsh|dash|ksh|env)(?=\s)/g,
957  /\$'/g,
958  /\balias\./gi,
959]
960// Constructs of a head and a later tail in the same run (no `;`, `&`, `|` or newline between):
961// `find … -exec`, `env … -S`, `case … in`. Matched as two linear scans ({@link headsWithTail}): as one
962// regex `head[^\n;&|]*tail` each head re-scanned the run to its end, quadratic (`env -i` ×N).
963const UNREAD_PAIRS: readonly (readonly [head: RegExp, tail: RegExp])[] = [
964  [/\bfind\b/g, /\s-exec(?:dir)?\b/g],
965  [/\benv\b/g, /\s(?:-[A-Za-z]*S|--split-string)/g],
966  [/\bcase\b/g, /\bin\b/g],
967]
968// A shell given a command with -c — a shell name followed by whitespace, and later in the same run
969// without `;`, `&` or `|` a word of letters holding `c` (`-c`, `-lc`) — unreadable when INNER cannot
970// cut it at the same place. Matched as two linear scans ({@link shellCStarts}): as one regex with a
971// lazy word run it retried from every shell name to the run's end, 680 ms for 10k `bash ` words.
972const SHELL_NAME = /(?<![\w./-])(?:bash|sh|zsh|dash|ksh)(?=\s)/g
973// `-(?=[A-Za-z]*c)[A-Za-z]+` is `-[A-Za-z]*c[A-Za-z]*` without its quadratic backtracking on a long word.
974const C_OPTION = /\s-(?=[A-Za-z]*c)[A-Za-z]+(?=\s|$)/g
975
976/** The `[start, end)` of each run of the line between the characters `cut` matches. */
977function runsOf(line: string, cut: RegExp): Span[] {
978  const runs: Span[] = []
979  let start = 0
980  for (const m of line.matchAll(cut)) {
981    runs.push([start, m.index])
982    start = m.index + 1
983  }
984  runs.push([start, line.length])
985  return runs
986}
987
988/** The start of each `head` match with a `tail` match starting at or after its end in the same run: two linear scans. */
989function headsWithTail(line: string, runs: readonly Span[], head: RegExp, tail: RegExp): number[] {
990  const lastTail = new Map<number, number>()
991  for (const m of line.matchAll(tail)) lastTail.set(spanIndexAt(runs, m.index), m.index)
992  const starts: number[] = []
993  for (const m of line.matchAll(head)) {
994    const t = lastTail.get(spanIndexAt(runs, m.index))
995    if (t !== undefined && t >= m.index + m[0].length) starts.push(m.index)
996  }
997  return starts
998}
999
1000/** Where a shell is given `-c`: a SHELL_NAME with a C_OPTION after it and no `;`, `&` or `|` between. */
1001function shellCStarts(line: string): number[] {
1002  return headsWithTail(line, runsOf(line, /[;&|]/g), SHELL_NAME, C_OPTION)
1003}
1004
1005type Span = [start: number, end: number]
1006
1007/** The `[start, end)` of every segment of the line, cut at the separators splitSegments cuts at, in order. */
1008function segmentSpans(line: string): Span[] {
1009  const spans: Span[] = []
1010  let start = 0
1011  for (const m of markBackground(line).matchAll(SEPARATOR)) {
1012    spans.push([start, m.index])
1013    start = m.index + m[0].length
1014  }
1015  spans.push([start, line.length])
1016  return spans
1017}
1018
1019/** The index in `spans` of the segment holding `index` (binary search: the last segment starting at or before it). */
1020function spanIndexAt(spans: readonly Span[], index: number): number {
1021  let lo = 0
1022  let hi = spans.length - 1
1023  while (lo < hi) {
1024    const mid = (lo + hi + 1) >> 1
1025    if ((spans[mid]?.[0] ?? 0) <= index) lo = mid
1026    else hi = mid - 1
1027  }
1028  return lo
1029}
1030
1031/**
1032 * The `[start, end)` body of every `$(…)` (parentheses balanced, quotes not honoured) and after every
1033 * backtick (to the next one), each to the end of the line when unclosed. One pass with a stack, so a
1034 * line of 25,000 unclosed `$(` costs no more than one of plain words.
1035 */
1036function substitutionSpans(line: string): Span[] {
1037  const spans: Span[] = []
1038  // Per open parenthesis: the index in `spans` of the `$(` it opened, or -1 for a plain `(`.
1039  const open: number[] = []
1040  let lastTick = -1
1041  for (let i = 0; i < line.length; i += 1) {
1042    const ch = line[i]
1043    if (ch === '$' && line[i + 1] === '(') {
1044      open.push(spans.push([i + 2, line.length]) - 1)
1045      i += 1
1046    } else if (ch === '(') open.push(-1)
1047    else if (ch === ')') {
1048      const k = open.pop()
1049      const span = k === undefined || k === -1 ? undefined : spans[k]
1050      if (span !== undefined) span[1] = i
1051    } else if (ch === '`') {
1052      const prev = lastTick === -1 ? undefined : spans[lastTick]
1053      if (prev !== undefined) prev[1] = i
1054      lastTick = spans.push([i + 1, line.length]) - 1
1055    }
1056  }
1057  return spans
1058}
1059
1060/** The spans merged where they overlap or touch, sorted. */
1061function mergeSpans(spans: Span[]): Span[] {
1062  const merged: Span[] = []
1063  for (const [start, end] of [...spans].sort((a, b) => a[0] - b[0])) {
1064    const last = merged.at(-1)
1065    if (last !== undefined && start <= last[1]) last[1] = Math.max(last[1], end)
1066    else merged.push([start, end])
1067  }
1068  return merged
1069}
1070
1071/** The text with `$'…'` escapes decoded and every quote and backslash dropped, so `pu"sh"` and `$'\x70ush'` read as `push`. */
1072function normalizeWords(text: string): string {
1073  return text
1074    .replace(/\$'((?:[^'\\]|\\.)*)'/g, (_m: string, body: string) =>
1075      body.replace(/\\x([0-9a-fA-F]{1,2})|\\u([0-9a-fA-F]{1,4})|\\([0-7]{1,3})|\\(.)/g, (_e: string, hex?: string, uni?: string, oct?: string, ch?: string) =>
1076        hex !== undefined ? String.fromCharCode(parseInt(hex, 16)) : uni !== undefined ? String.fromCharCode(parseInt(uni, 16)) : oct !== undefined ? String.fromCharCode(parseInt(oct, 8)) : (ch ?? '')))
1077    .replace(/["'\\]/g, '')
1078}
1079
1080/** The outward kind a piece of unread text names, or null — wide on purpose: any `deploy` or `publish`, any forge `merge`/`release`. */
1081function outwardWordIn(text: string): OutwardKind | null {
1082  const t = normalizeWords(text)
1083  const forge = /\b(?:gh|glab)\b/.test(t)
1084  if (/\bgit\b/.test(t) && /\bpush\b/.test(t)) return 'push'
1085  if (/\bpublish\b/.test(t)) return 'publish'
1086  if (forge && /\b(?:merge|accept)\b/.test(t)) return 'merge'
1087  if (/\bdeploy\b/.test(t) || /--prod(?:uction)?\b/.test(t)) return 'deploy'
1088  if (forge && /\brelease\b/.test(t)) return 'release'
1089  return classKindIn(text)
1090}
1091
1092// The words of unread text, split at blanks and at shell and code punctuation: `os.system(git push)` gives `git`, `push`;
1093// `args.push(x)` stays one word, so a JS `.push(` next to a `git` word is no push.
1094const CODE_WORD = /[^\s()[\]{}<>;|&,`]+/g
1095// git's global options that take the next word as their value (`git -C dir push`).
1096const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path', '--attr-source'])
1097const FORGE_VALUED = new Set(['-R', '--repo'])
1098const NONE_VALUED: ReadonlySet<string> = new Set()
1099
1100/**
1101 * The outward kind of the first action the classifier holds ({@link classifyWords}) that a piece of unread text spells
1102 * as a tool word with its action word in subcommand position, options skipped — or null. `git [options] push`,
1103 * `git-push`; `gh|glab [options] mr|pr merge|accept`, `… release create`, `… api` with a method or field and a ref, branch or
1104 * merge path; npm/pnpm/yarn/changeset/cargo with a later `publish` word; vercel/vc with `--prod`, `--production`,
1105 * `promote` or `rollback`; `supabase db push`, `supabase db reset … --linked`, `supabase migration up … --linked`;
1106 * `fly deploy`; `railway up` (#1572 E3/E4). A piece holding `--dry-run` names no publish or supabase write. Linear: one
1107 * pass over the words, a later word looked up by its last index.
1108 */
1109function classKindIn(text: string): OutwardKind | null {
1110  const plain = normalizeWords(text)
1111  const words = plain.match(CODE_WORD) ?? []
1112  const last = new Map<string, number>()
1113  words.forEach((word, i) => last.set(word, i))
1114  const later = (i: number, ...names: string[]): boolean => names.some(name => (last.get(name) ?? -1) > i)
1115  const dry = last.has('--dry-run')
1116  // Judged for the whole piece, once: a slice per `api` word was quadratic on `gh api gh api …`.
1117  // An API call writes only with a method or a field (`gh api repos/o/r/git/refs/heads/main` alone reads).
1118  const apiWrites = /(?:^|\s)(?:-X\s*|--method[=\s]+)(?:POST|PUT|PATCH|DELETE)\b|(?:^|\s)(?:-[fF]|--(?:raw-)?field|--input)(?:[=\s]|\S)/i.test(plain)
1119  const refWrite = apiWrites && /refs\/heads\/|\bbranch=/.test(plain)
1120  const mergePath = apiWrites && /\/merges?\b/.test(plain)
1121  // The index of the first word from `j` that is no option (a valued option skips its value too).
1122  const skip = (j: number, valued: ReadonlySet<string>): number => {
1123    let k = j
1124    while ((words[k] ?? '').startsWith('-')) k += valued.has(words[k] ?? '') ? 2 : 1
1125    return k
1126  }
1127  for (let i = 0; i < words.length; i += 1) {
1128    const tool = baseName(words[i] ?? '')
1129    if (tool === 'git-push') return 'push'
1130    if (tool === 'git' && words[skip(i + 1, GIT_VALUED)] === 'push') return 'push'
1131    if (tool === 'gh' || tool === 'glab') {
1132      const j = skip(i + 1, FORGE_VALUED)
1133      const [sub, action] = [words[j], words[j + 1]]
1134      if ((sub === 'mr' || sub === 'pr') && (action === 'merge' || action === 'accept')) return 'merge'
1135      if (sub === 'release' && action === 'create') return 'release'
1136      if (sub === 'api' && refWrite) return 'push'
1137      if (sub === 'api' && mergePath) return 'merge'
1138    }
1139    if (['npm', 'pnpm', 'yarn', 'changeset', 'cargo'].includes(tool) && later(i, 'publish') && !dry) return 'publish'
1140    if ((tool === 'vercel' || tool === 'vc') && later(i, '--prod', '--production', 'promote', 'rollback')) return 'deploy'
1141    if (tool === 'supabase' && !dry) {
1142      const j = skip(i + 1, NONE_VALUED)
1143      const [sub, action] = [words[j], words[j + 1]]
1144      if (sub === 'db' && (action === 'push' || (action === 'reset' && later(j, '--linked')))) return 'deploy'
1145      if (sub === 'migration' && action === 'up' && later(j, '--linked')) return 'deploy'
1146    }
1147    if ((tool === 'fly' || tool === 'flyctl') && words[skip(i + 1, NONE_VALUED)] === 'deploy') return 'deploy'
1148    if (tool === 'railway' && words[skip(i + 1, NONE_VALUED)] === 'up') return 'deploy'
1149  }
1150  return null
1151}
1152
1153/**
1154 * The pieces of a line this parser does not read: each construct's segment, a substitution's segment
1155 * joined with its body, and the whole line for a `$var` command. Each segment is read once however
1156 * many constructs it holds, and a substitution's segment and body, with every span overlapping them,
1157 * form one contiguous piece — a superset of reading each pair on its own, in linear time (a construct
1158 * per match over the whole line was quadratic: 317 ms at 8k characters of `$(`, about 12 s at 50k).
1159 */
1160function unreadRegions(line: string): string[] {
1161  const regions: string[] = []
1162  const segments = segmentSpans(line)
1163  const constructSegments = new Set<number>()
1164  for (const re of UNREAD_CONSTRUCTS) for (const m of line.matchAll(re)) constructSegments.add(spanIndexAt(segments, m.index))
1165  const runs = runsOf(line, /[\n;&|]/g)
1166  for (const [head, tail] of UNREAD_PAIRS) for (const at of headsWithTail(line, runs, head, tail)) constructSegments.add(spanIndexAt(segments, at))
1167  for (const at of shellCStarts(line)) {
1168    INNER_AT.lastIndex = at
1169    if (!INNER_AT.test(line)) constructSegments.add(spanIndexAt(segments, at))
1170  }
1171  for (const k of constructSegments) {
1172    const span = segments[k]
1173    if (span !== undefined) regions.push(line.slice(...span))
1174  }
1175  const bodies = substitutionSpans(line)
1176  const owners = new Set<number>()
1177  for (const [start] of bodies) owners.add(spanIndexAt(segments, start - 1))
1178  const pieces = [...bodies]
1179  for (const k of owners) {
1180    const span = segments[k]
1181    if (span !== undefined) pieces.push(span)
1182  }
1183  for (const [start, end] of mergeSpans(pieces)) regions.push(line.slice(start, end))
1184  // `p=push; git $p origin main`: a command or git subcommand from a variable is set anywhere on the
1185  // line, so the whole line is read — once (once per such segment re-read the line, quadratic).
1186  const expanded = (word: string | undefined) => word !== undefined && word.includes('$') && !word.startsWith('$(')
1187  for (const segment of splitSegments(line)) {
1188    const [first, ...args] = readCommand(segment, true).words
1189    if (expanded(first) || (baseName(first ?? '') === 'git' && expanded(readGit(args, null).sub))) {
1190      regions.push(line)
1191      break
1192    }
1193  }
1194  return regions
1195}
1196
1197/**
1198 * One fail-closed hit for a line holding a construct this parser does not read (`$(…)`, a backtick,
1199 * `xargs`, `find -exec`, `ssh`, `env -S`, `watch`, a function, `case`, a shell by path or one `-c`
1200 * cannot be cut from, `$'…'`, a git alias, a command from a variable) whose unread part names an
hooks/heredoc-scan.ts 395 lines
1// ---- Heredoc bodies the shell expands (#1696) ---------------------------------
2//
3// One pass over a command text with an explicit state machine (quotes, `$'…'`, `${…}`, `$(…)`, backticks,
4// arithmetic, comments) and a queue of the heredoc operators read on the current line. At a newline that the
5// shell reads as a command terminator, the queued bodies follow in order; each body line is read once, so the
6// whole scan is linear in the text. The scanner judges nothing itself: `secretIn` names the secret a body line
7// expands, `prints` says whether the stage a heredoc feeds reaches the transcript — both supplied by rules.ts.
8
9/** A stage of a pipeline as the scanner cut it: `[start, end)` in the text, -1 while open; `pipe`: the stage after `|`. */
10type Stage = { start: number; end: number; pipe: Stage | null; cuts: Array<[number, number]>; verdict: boolean | undefined }
11
12type Pending = { delimiter: string; quoted: boolean; tabs: boolean; stage: Stage; nested: boolean }
13
14/** What a stage feeds: its text without the heredoc operators, and the next stage (`null`: unreadable, `undefined`: none). */
15export type HeredocStage = { text: string | null; next: string | null | undefined; nested: boolean }
16
17export type HeredocFinding =
18  | { kind: 'body'; name: string; delimiter: string }
19  | { kind: 'fail-closed'; reason: 'unbalanced' | 'too-many' | 'no-delimiter' | 'unreadable' }
20
21// Frames of the state machine. `code` frames read commands and heredoc operators; the others only quoting.
22type Frame = 'root' | 'subst' | 'paren' | 'procsub' | 'tick' | 'dq' | 'brace' | 'dqbrace' | 'arith' | 'bracket'
23
24// Heredoc operators queued on one line before the bodies are read. Real commands use one or two; past the cap the
25// line is not read (the operator count was the lever of the reverted attempt's quadratic run) — fail-closed.
26// NAMED CEILING (BV-004): 16; revisit if a legitimate command needs more heredocs on one line.
27const MAX_PENDING = 16
28// The characters after which an unquoted `#` starts a comment (the start of a word).
29const WORD_BREAK = /[\s;&|()<>]/
30// Where an unquoted heredoc delimiter word ends. Not `\r`: the shell keeps it in the word, so `<<EOF` on a CRLF line
31// closes only at `EOF\r` — ending the word there too keeps the body from running past the shell's closing line.
32const WORD_END = /[ \t\n;&|<>()]/
33
34// Reserved words after which the next word is a command again (`if x; then case …`).
35const COMMAND_WORDS: ReadonlySet<string> = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time'])
36
37const CODE: ReadonlySet<Frame> = new Set(['root', 'subst', 'paren', 'procsub', 'tick'])
38// Frames whose output a command reads instead of the transcript seeing it directly: judged as printing (fail-closed).
39const CAPTURED: ReadonlySet<Frame> = new Set(['subst', 'procsub', 'tick'])
40
41/**
42 * Reads every heredoc in `text` and returns the first one whose body expands a secret while its stage prints
43 * (`prints`), or a fail-closed finding: an unbalanced quote or construct at the end of the text, more than
44 * {@link MAX_PENDING} operators on one line, or an operator without a delimiter word. A quoted delimiter
45 * (`<<'EOF'`, `<<"EOF"`, `<<\EOF`, any quote in the word) keeps its body literal and is never a finding. Whether a
46 * fail-closed finding matters (a secret named anywhere in the text) is the caller's call. Stops at the first finding.
47 */
48export function scanHeredocs(
49  text: string,
50  secretIn: (line: string) => string | undefined,
51  prints: (stage: HeredocStage) => boolean,
52): HeredocFinding | null {
53  const frames: Frame[] = ['root']
54  // One open stage per code frame, parallel to `frames` (null for quoting frames).
55  const stages: Array<Stage | null> = [newStage(0)]
56  let pending: Pending[] = []
57  // Per frame: `(`/`[` inside arithmetic, `{` inside a brace, open `case` words inside a code frame.
58  const depth: number[] = [0]
59  const n = text.length
60  // The `)` that ended the last case pattern: the word after it is a command (`a) case y in …`), unlike after `$(x)`.
61  let patternClose = -1
62
63  const top = (): Frame => frames[frames.length - 1] ?? 'root'
64  const push = (frame: Frame, at: number): void => {
65    frames.push(frame)
66    stages.push(CODE.has(frame) ? newStage(at) : null)
67    depth.push(0)
68  }
69  const pop = (at: number): void => {
70    const stage = stages[stages.length - 1]
71    if (stage !== null && stage !== undefined && stage.end === -1) stage.end = at
72    frames.pop()
73    stages.pop()
74    depth.pop()
75  }
76  // Ends the open stage of the current code frame at `at`; a pipe links it to the stage that starts at `from`.
77  const cut = (at: number, from: number, pipe: boolean): void => {
78    const stage = stages[stages.length - 1]
79    if (stage === null || stage === undefined) return
80    stage.end = at
81    const next = newStage(from)
82    if (pipe) stage.pipe = next
83    stages[stages.length - 1] = next
84  }
85  const nested = (): boolean => frames.some(frame => CAPTURED.has(frame))
86
87  for (let i = 0; i < n; i += 1) {
88    const ch = text[i] ?? ''
89    const next = text[i + 1] ?? ''
90    const frame = top()
91
92    if (frame === 'dq' || frame === 'dqbrace' || frame === 'brace') {
93      if (ch === '\\') i += 1
94      else if (frame === 'dq' && ch === '"') pop(i)
95      else if (frame !== 'dq' && ch === '}') pop(i)
96      // A raw `{` inside `${…}` (`"${x:-{}"`): the shells disagree on which `}` closes it — fail-closed (#1696 M2).
97      // A nested `${` opens its own frame through openDollar.
98      else if (frame !== 'dq' && ch === '{') return { kind: 'fail-closed', reason: 'unreadable' }
99      else if (frame !== 'dq' && ch === '"') push('dq', i)
100      else if (frame === 'brace' && ch === "'") {
101        const close = text.indexOf("'", i + 1)
102        if (close === -1) return { kind: 'fail-closed', reason: 'unbalanced' }
103        i = close
104      } else if (ch === '$' || ch === '`') i = openDollar(i, frame === 'brace' ? 'brace' : 'dqbrace')
105      continue
106    }
107    if (frame === 'arith' || frame === 'bracket') {
108      const [open, close] = frame === 'arith' ? ['(', ')'] : ['[', ']']
109      const d = depth[depth.length - 1] ?? 0
110      // A newline, or `$((`/`((` closed by `) )` instead of `))`, is a command in a subshell, not arithmetic: the
111      // shells run `$((cat <<EOF … ) )` (#1696 M1) — fail-closed rather than reading its heredoc as arithmetic.
112      if (ch === '\n') return { kind: 'fail-closed', reason: 'unreadable' }
113      if (ch === open) depth[depth.length - 1] = d + 1
114      else if (ch === close && d > 0) depth[depth.length - 1] = d - 1
115      else if (ch === close) {
116        if (frame === 'arith' && next !== ')') return { kind: 'fail-closed', reason: 'unreadable' }
117        if (frame === 'arith') i += 1
118        pop(i)
119      }
120      continue
121    }
122
123    // A code frame.
124    if (ch === '\\') {
125      i += 1
126      continue
127    }
128    if (ch === "'") {
129      const close = text.indexOf("'", i + 1)
130      if (close === -1) return { kind: 'fail-closed', reason: 'unbalanced' }
131      i = close
132      continue
133    }
134    if (ch === '"') {
135      push('dq', i)
136      continue
137    }
138    if (ch === '$' || ch === '`') {
139      if (ch === '`' && frame === 'tick') pop(i)
140      else i = openDollar(i, 'code')
141      continue
142    }
143    if (ch === '#' && (i === 0 || WORD_BREAK.test(text[i - 1] ?? ''))) {
144      const nl = text.indexOf('\n', i)
145      i = (nl === -1 ? n : nl) - 1
146      continue
147    }
148    if (ch === '<' && next === '<' && text[i + 2] === '<') {
149      i += 2
150      continue
151    }
152    if (ch === '<' && next === '<') {
153      const op = readOperator(i + 2)
154      if (op === null) return { kind: 'fail-closed', reason: 'no-delimiter' }
155      if (op === 'unbalanced') return { kind: 'fail-closed', reason: 'unbalanced' }
156      const stage = stages[stages.length - 1] ?? newStage(i)
157      stage.cuts.push([i, op.end])
158      pending.push({ delimiter: op.delimiter, quoted: op.quoted, tabs: op.tabs, stage, nested: nested() })
159      if (pending.length > MAX_PENDING) return { kind: 'fail-closed', reason: 'too-many' }
160      i = op.end - 1
161      continue
162    }
163    if ((ch === '<' || ch === '>') && next === '(') {
164      push('procsub', i + 2)
165      i += 1
166      continue
167    }
168    if (ch === '(' && next === '(') {
169      push('arith', i)
170      i += 1
171      continue
172    }
173    if (ch === '(') {
174      cut(i, i + 1, false)
175      push('paren', i + 1)
176      continue
177    }
178    if ((ch === 'c' || ch === 'e') && (i === 0 || WORD_BREAK.test(text[i - 1] ?? '')) && commandPosition(i)) {
179      // In a code frame the depth counts open `case` words: the `)` after a pattern closes no `$(` (#1696:
180      // `"$(case x in x) cat <<A;; esac …)"` read the `)` as the end and the heredoc as quoted text). Only in
181      // command position: `echo esac` is an argument and closes nothing (M3).
182      const word = /^(?:case|esac)(?=[ \t\n;&|<>()]|$)/.exec(text.slice(i, i + 5))?.[0]
183      const d = depth[depth.length - 1] ?? 0
184      if (word === 'case') depth[depth.length - 1] = d + 1
185      else if (word === 'esac' && d > 0) depth[depth.length - 1] = d - 1
186      if (word !== undefined) i += 3
187      continue
188    }
189    if (ch === ')') {
190      if ((depth[depth.length - 1] ?? 0) > 0) patternClose = i
191      else if (frame === 'subst' || frame === 'paren' || frame === 'procsub') pop(i)
192      continue
193    }
194    if (ch === '|') {
195      if (next === '|') {
196        cut(i, i + 2, false)
197        i += 1
198      } else {
199        cut(i, i + (next === '&' ? 2 : 1), true)
200        if (next === '&') i += 1
201      }
202      continue
203    }
204    if (ch === ';' || ch === '&') {
205      // `&&`, `;;`, a lone `&` end the command; `&>` / `>&` / `<&` are redirections, read with the stage.
206      if (ch === '&' && (next === '>' || text[i - 1] === '>' || text[i - 1] === '<')) continue
207      const width = next === ch ? 2 : 1
208      cut(i, i + width, false)
209      i += width - 1
210      continue
211    }
212    if (ch === '\n') {
213      cut(i, i + 1, false)
214      if (pending.length === 0) continue
215      const found = readBodies(i + 1)
216      if (typeof found !== 'number') return found
217      pending = []
218      // The bodies end at `found`, the start of the next command line; the code frame is unchanged.
219      const stage = stages[stages.length - 1]
220      if (stage !== null && stage !== undefined) stage.start = found
221      i = found - 1
222    }
223  }
224  // Operators on the last line with no newline after them have no body.
225  return frames.length === 1 ? null : { kind: 'fail-closed', reason: 'unbalanced' }
226
227  /**
228   * Whether the word at `at` stands where a command starts: at the text start, after `;`, `&`, `|`, `(`, `{`, a
229   * backtick, a newline or the `)` of a case pattern, or after a reserved word that takes a command (`then`, `do`, …). Reads back over the
230   * blanks and the one word before `at` only, so every character is read back at most once (linear).
231   */
232  function commandPosition(at: number): boolean {
233    let p = at - 1
234    while (p >= 0 && (text[p] === ' ' || text[p] === '\t')) p -= 1
235    if (p < 0 || p === patternClose || /[;&|({`\n]/.test(text[p] ?? '')) return true
236    let w = p
237    while (w >= 0 && /[a-z!]/.test(text[w] ?? '')) w -= 1
238    if (w >= 0 && !/[\s;&|({`]/.test(text[w] ?? '')) return false
239    return COMMAND_WORDS.has(text.slice(w + 1, p + 1))
240  }
241
242  /** Opens the construct a `$` or backtick at `at` starts; returns the index the loop continues from. */
243  function openDollar(at: number, context: 'code' | 'brace' | 'dqbrace'): number {
244    const ch = text[at]
245    const next = text[at + 1]
246    if (ch === '`') {
247      push('tick', at + 1)
248      return at
249    }
250    if (next === '(' && text[at + 2] === '(') {
251      push('arith', at)
252      return at + 2
253    }
254    if (next === '(') {
255      push('subst', at + 2)
256      return at + 1
257    }
258    if (next === '[') {
259      push('bracket', at)
260      return at + 1
261    }
262    if (next === '{') {
263      push(context === 'code' || context === 'brace' ? 'brace' : 'dqbrace', at)
264      return at + 1
265    }
266    if (next === "'" && context !== 'dqbrace') {
267      // `$'…'`: a backslash escapes the next character, `\'` included.
268      for (let j = at + 2; j < n; j += 1) {
269        if (text[j] === '\\') j += 1
270        else if (text[j] === "'") return j
271      }
272      return n
273    }
274    return at
275  }
276
277  /** The delimiter word after `<<` at `from`; null when there is none, 'unbalanced' for an open quote in it. */
278  function readOperator(from: number): { delimiter: string; quoted: boolean; tabs: boolean; end: number } | null | 'unbalanced' {
279    let j = from
280    const tabs = text[j] === '-'
281    if (tabs) j += 1
282    while (text[j] === ' ' || text[j] === '\t') j += 1
283    const parts: string[] = []
284    let quoted = false
285    for (; j < n; j += 1) {
286      const c = text[j] ?? ''
287      if (WORD_END.test(c)) break
288      // A substitution in the delimiter word (`<<$(x)`): the shells take it literally, this reading would end the
289      // word at its `(` — fail-closed instead of guessing (#1696 M4).
290      if ((c === '$' && text[j + 1] === '(') || c === '`') return null
291      if (c === '\\') {
292        // `\` + newline continues the line and quotes nothing: `<<EO\<LF>F` is the unquoted delimiter EOF.
293        if (text[j + 1] !== '\n') {
294          quoted = true
295          parts.push(text[j + 1] ?? '')
296        }
297        j += 1
298      } else if (c === "'" || c === '"') {
299        quoted = true
300        let k = j + 1
301        for (; k < n && text[k] !== c; k += 1) {
302          if (c === '"' && text[k] === '\\') k += 1
303        }
304        if (k >= n) return 'unbalanced'
305        parts.push(text.slice(j + 1, k))
306        j = k
307      } else parts.push(c)
308    }
309    const delimiter = parts.join('')
310    return delimiter === '' && !quoted ? null : { delimiter, quoted, tabs, end: j }
311  }
312
313  /**
314   * Reads the queued bodies from `from` in order: each runs to its closing line or to the end of the text. Returns
315   * the index past the last closing line, or the first finding. Each stage is judged at most once (its verdict is
316   * kept), so many heredocs feeding one stage cost one judgement.
317   */
318  function readBodies(from: number): number | HeredocFinding {
319    let at = from
320    for (const doc of pending) {
321      let hit = false
322      let closed = false
323      // An unquoted body joins a line that ends in an odd run of `\` with the next one, as the shell does: neither
324      // `foo\` + `EOF` closes the body nor does `$T_TO\` + `KEN` hide the name. A quoted body keeps every line.
325      let carried = ''
326      // Whether the current physical line continues an earlier one: `carried` alone cannot tell, because a continued
327      // line that was only `\` leaves it empty (#1696 R2: `<<-EOF`, `\`, `<tab>EOF` does not close in zsh).
328      let continued = false
329      while (at <= n) {
330        const nl = text.indexOf('\n', at)
331        const end = nl === -1 ? n : nl
332        let physical = text.slice(at, end)
333        at = nl === -1 ? n + 1 : nl + 1
334        // `<<-` strips the tabs at the start of the logical line only: a continued line keeps its own (#1696 M5).
335        if (doc.tabs && !continued) physical = physical.replace(/^\t+/, '')
336        if (!doc.quoted && nl !== -1 && oddSlashes(physical)) {
337          carried += physical.slice(0, -1)
338          continued = true
339          continue
340        }
341        const line = carried + physical
342        carried = ''
343        continued = false
344        if (line === doc.delimiter) {
345          closed = true
346          break
347        }
348        if (hit) continue
349        const name = secretIn(line)
350        if (name === undefined) continue
351        hit = true
352        if (!doc.quoted && judge(doc)) return { kind: 'body', name, delimiter: doc.delimiter }
353      }
354      // A literal body that never closes swallowed the rest of the text unread: if the shell closed it where this
355      // reading did not (a delimiter told apart differently), a secret behind it went unseen — fail-closed.
356      if (doc.quoted && hit && !closed) return { kind: 'fail-closed', reason: 'unbalanced' }
357    }
358    return Math.min(at, n)
359  }
360
361  function judge(doc: Pending): boolean {
362    const { stage } = doc
363    if (stage.verdict === undefined) {
364      const pipe = stage.pipe
365      stage.verdict = prints({
366        text: stage.end === -1 ? null : stageText(stage),
367        next: pipe === null ? undefined : pipe.end === -1 ? null : stageText(pipe),
368        nested: doc.nested,
369      })
370    }
371    return stage.verdict
372  }
373
374  function stageText(stage: Stage): string {
375    let out = ''
376    let from = stage.start
377    for (const [a, b] of stage.cuts) {
378      out += `${text.slice(from, a)} `
379      from = b
380    }
381    return out + text.slice(from, stage.end)
382  }
383}
384
385/** Whether a line ends in an odd run of backslashes (the last one escapes the newline). */
386function oddSlashes(line: string): boolean {
387  let count = 0
388  for (let j = line.length - 1; j >= 0 && line[j] === '\\'; j -= 1) count += 1
389  return count % 2 === 1
390}
391
392function newStage(start: number): Stage {
393  return { start, end: -1, pipe: null, cuts: [], verdict: undefined }
394}
395
types/index.d.ts 37 lines
1/** Standalone public wire contract; null means unmeasured. Engine nouns are asynchronous. */
2export type SoProfile = 'locker' | 'ausgewogen' | 'streng'
3export type SoState = 'arbeitet' | 'wartet' | 'bereit' | 'blockiert' | 'unbekannt'
4export interface SoBeacon {
5  schema_version: 1; session_id: string; name: string | null; repo_name: string | null
6  branch: string | null; pid: number | null; zustand: SoState; seit: string
7  warte_grund: 'dialog' | 'freigabe' | 'frage' | null; heuristisch: boolean
8  kontext_prozent: number | null; letzter_request_at: string | null; modell: string | null
9  welle: number | null; aktualisiert_at: string
10}
11export interface SoSnapshot {
12  schema_version: 1; measured_at: string; age_ms: number
13  repo: { root: string; name: string }
14  lock: { session_id: string | null; live: boolean; last_heartbeat: string | null } | null
15  session: { session_id: string; semantic_session_id: string | null } | null
16  wave: { running: boolean | null; number: number | null; role: string | null; agents_total: number | null; source: string | null }
17  agents: { entries: { id: string; typ: string | null; modellfamilie: string | null; status: string | null; tokens: null; letzter_request_at: null; quelle: string }[]; source: string | null; at: string | null; degraded: unknown
18    /** Running agents of this session; null when unknown (see stale_reason). Absent from collectors before #1580. */
19    running?: number | null
20    /** Why `running` is null: 'no-session', 'cache-unverifiable', 'no-session-start' or 'older-than-session'; null when measured. */
21    stale_reason?: string | null
22    /** Agents still running without a Stop past 24 h, counted apart from `running`; absent from older collectors. */
23    decayed?: number | null }
24  state: { status: string | null; session_type: string | null; current_wave: number | null; total_waves: number | null }
25  gate: { last: { variant: string | null; passed: boolean | null; check_failed: boolean | null; exit_code: number | null; at: string | null } | null; last_green_sha: string | null }
26  peers: { session_id: string; branch: string | null; status: string | null; current_wave: number | null; last_heartbeat: string | null; gleiches_working_copy: boolean; scope_paths: string[] | null }[]
27  vault: { enabled: boolean | null; mode: string | null; last_run: { at: string | null; created: number | null; updated: number | null; failed: number | null; aborted: string | null } | null; board: { action: string | null; at: string | null } | null }
28  degraded: string[]
29}
30export interface So {
31  version(): 1
32  snapshot(): Promise<SoSnapshot | null>
33  beacons(): Promise<SoBeacon[]>
34  profile(): SoProfile
35}
36declare module 'claude-code' { interface EngineInterface { so: So } }
37