SLOPSHOPPER

agentic-qe-fleet

PACTS-based agentic quality engineering fleet — 11 specialized QE agents, sublinear coverage analysis, chaos/resilience testing, and TDD skills for Claude Code

guardcommandtoast
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agentic-qe-fleet
› 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(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /aqe-mod ⎿ agentic-qe-fleet: /aqe-mod status guard mode, counts for this session and all sessions, the last refusal ⎿ agentic-qe-fleet: /aqe-mod check <command> would the guard refuse this shell command? (nothing runs) ⎿ agentic-qe-fleet: /aqe-mod fleet AQE data files present and AQE MCP tools connected ⎿ agentic-qe-fleet: /aqe-mod gate what is known about the last quality gate ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

agentic-qe-fleet

PACTS-based agentic quality engineering fleet for Claude Code. This is a slim starter bundle of the AQE platform. It has 11 specialized QE agents, 9 core skills, 9 slash commands, and the agentic-qe MCP server, pinned to the plugin version.

Install

In one step (Claude Code 2.1.275 or later):

/plugin install agentic-qe-fleet --marketplace proffesor-for-testing/agentic-qe

Or add the marketplace first:

/plugin marketplace add proffesor-for-testing/agentic-qe
/plugin install agentic-qe-fleet@agentic-qe

The install registers the MCP server plugin:agentic-qe-fleet:agentic-qe, which runs npx -y agentic-qe@<plugin version> mcp. You don't need to run claude mcp add. Check it with claude mcp list.

Options (userConfig)

Set these with /plugin configure agentic-qe-fleet@agentic-qe, or pass --config KEY=VALUE to claude plugin install. Every option has a default, so the server starts even if you leave them unset.

OptionSetsDefaultEffect
llm_providerAQE_LLM_PROVIDERempty (auto)Pins the LLM provider, e.g. claude-code, claude, openrouter or ollama. If it's empty, the provider comes from llm-config.json or env auto-detection.
max_budget_usdAQE_MAX_BUDGET_USD0 (no cap)Per-run spend cap for metered providers.
memory_backendAQE_MEMORY_BACKENDhybridhybrid saves learning to .agentic-qe/memory.db. memory is database-free mode: same features, but nothing is written under .agentic-qe/.

What's Included

Agents (11)

Agents are routed by cognitive load: heavy reasoning runs on Opus, focused execution on Sonnet.

AgentModelPurpose
qe-test-architectopusAI-powered test generation with sublinear optimization
qe-fleet-commanderopusFleet lifecycle and workload distribution
qe-security-scanneropusSAST/DAST/dependency/secrets scanning
qe-chaos-engineeropusControlled fault injection and resilience testing
qe-regression-analyzeropusIntelligent test selection and change-impact scoring
qe-requirements-validatoropusTestability analysis and BDD scenario generation
qe-coverage-specialistsonnetO(log n) sublinear coverage analysis with risk-weighted gap detection
qe-flaky-huntersonnetFlaky test detection and auto-stabilization
qe-performance-testersonnetLoad, stress, endurance, regression detection
qe-quality-gatesonnetQuality gate enforcement with policy validation
qe-tdd-specialistsonnetRed-Green-Refactor (London + Chicago schools)

Skills (9)

Each skill has a trust tier and a scoped allowed-tools list with no wildcards.

  • Tier 3: full eval infrastructure (eval YAML, JSON schema and validator).
  • Tier 2: tested, but without an eval.

The bundle leaves out tier-1 (untested) skills, per AQE trust-tier policy.

SkillTrust tierMCP tools
qe-test-generation3test_generate_enhanced
qe-coverage-analysis3coverage_analyze_sublinear, qe_coverage_gaps
qe-test-execution3test_execute_parallel
qe-chaos-resilience3chaos_test
qe-quality-assessment3quality_assess
chaos-engineering-resilience3— (methodology guide)
mutation-testing3— (Stryker integration)
risk-based-testing3— (read-only analysis)
tdd-london-chicago2— (TDD school comparison)

MCP tool names. A server that comes from this plugin exposes its tools as mcp__plugin_agentic-qe-fleet_agentic-qe__<tool>. A project set up with aqe init registers the server under the name agentic-qe, which gives mcp__agentic-qe__<tool>. Each skill lists both forms in allowed-tools, so it works with either setup. See ADR-0001.

Commands (9)

/aqe-analyze, /aqe-benchmark, /aqe-chaos, /aqe-costs, /aqe-execute, /aqe-fleet-status, /aqe-generate, /aqe-optimize, /aqe-report

Requires

  • Node.js >= 22.13.0, with npx on PATH. The MCP server runs through npx.
  • Network access the first time the server starts, so npx can fetch the pinned agentic-qe package. After that it uses the npm cache.
  • No other plugin. The plugin ships its own MCP server.

Compatibility

  • Versioning: the plugin version always equals the agentic-qe npm package version, and .mcp.json pins the server to that exact version (agentic-qe@<version>, never @latest). The release flow bumps all of these together: npm version runs scripts/sync-plugin-versions.cjs.
  • Coexisting with aqe init: a project that has both the plugin and aqe init runs two agentic-qe server processes, one under each name. Both work. To keep only one, disable the plugin in that project or remove agentic-qe from the project .mcp.json.
  • Verification: bash plugins/agentic-qe-fleet/scripts/smoke.sh is the contract.

Namespace coordination

The fleet uses the AQE memory namespaces below. They are database identifiers, not filesystem paths, and other plugins MUST NOT shadow them.

  • aqe/v3/domains/<domain>/*: per-domain data, for example:
  • aqe/v3/domains/test-generation/patterns/
  • aqe/v3/domains/coverage-analysis/metrics/
  • aqe/v3/domains/test-execution/flaky/
  • aqe/v3/domains/security-compliance/scans/
  • aqe/v3/queen/*: fleet coordination (aqe/v3/queen/fleet/, aqe/v3/queen/tasks/).

With memory_backend=hybrid, they persist to .agentic-qe/memory.db in the project. With memory_backend=memory, they last only for the server process.

Test locally

claude --plugin-dir ./plugins/agentic-qe-fleet

Then run, for example, /aqe-fleet-status.

Verification

claude plugin validate plugins/agentic-qe-fleet
bash plugins/agentic-qe-fleet/scripts/smoke.sh     # or: npm run plugin:smoke
# Expected: "PASS: agentic-qe-fleet contract holds"
node scripts/sync-plugin-versions.cjs --check      # plugin versions == package.json

Architecture Decisions

As a mod (Claude Code >= 2.1.287)

The plugin ships a hooks module, aqe-mod (hooks/hooks.json -> hooks/register.ts), which loads with the plugin by default.

  • Learning-data guard (on by default). It refuses Bash, Monitor, PowerShell, Write, Edit and NotebookEdit calls that would destroy AQE's learning data:
  • rm, mv, cp/install/ln over, truncate, shred, dd, tee, gzip, sed -i or a > redirect on .agentic-qe/*.db (and -wal, -shm, *.rvf)
  • rm -rf .agentic-qe (also as .agentic*), find ... -delete/-exec that can reach it, git clean -x
  • sqlite3 with DROP, DELETE FROM, TRUNCATE, ALTER TABLE ... DROP or .restore on a store, and .backup/.save/.output/.once onto one
  • node -e, python3 -c, perl, ruby and similar scripts that name the data and delete, move or overwrite it
  • PowerShell Remove-Item, Move-Item, Set-Content, Out-File and similar on those files
  • Write/Edit on those files

The guard reads commands the way the shell does. It follows bash -c/-lc, eval, heredocs, pipes (find ... | xargs rm), $(...), keywords (then, do, !, coproc), brace expansion (memory.db{,-wal}), ANSI-C quoting ($'\x2eagentic-qe'), variables, cd .agentic-qe and git -C. It also refuses find that deletes .agentic-qe by name or path (unless -pruned or negated), and a directory copy that lands in it (cp -r backup/.agentic-qe ./, rsync -a backup/ .agentic-qe/). SQL is checked only in a sqlite3 command, and code only in an interpreter command, so grep -rn "DROP TABLE" src next to ls .agentic-qe passes.

These pass: reads and backups (cp .agentic-qe/memory.db .agentic-qe/memory.db.bak-$(date +%s), cp ... .agentic-qe/memory-backup-20261009.db, SELECT, PRAGMA integrity_check, .backup /tmp/x.db, sqlite3 -readonly, file:...?mode=ro), copies from the store in scripts (shutil.copy('.agentic-qe/memory.db', '/tmp/x.db'): the destination decides), and rm -rf .agentic-qe/tmp or rm .agentic-qe/*.log. The guard only refuses and never loosens anything. Set the plugin option guardMode to enforce (default), notify or off.

When it cannot tell, it refuses. The guard does not run the shell, so anything it cannot resolve counts as possibly the store:

  • An unset or unknown $NAME, ${...} or $@ in a path reads as * (rm -f .agentic-qe/$DB_FILE is refused). ${X:-word} reads as word or *.
  • A $(...) or backtick reads as what its command may print. Naming the store (rm "$(printf .agentic-qe)/memory.db") yields those paths. Listing files that may include it ($(find . -name '*.db'), $(ls -A), $(git ls-files -o)), or printing something the guard cannot know ($(cat list), $(... | base64 -d)), yields the store itself. Only known-harmless output ($(date +%s), $(pwd), $(find . -name '*.tmp'), $(which tool), $(npm config get cache)) reads as plain *. $(git status ...) and $(< file) may print the store. A find is judged on everything it prints, every -o branch included. The same holds for DB=$(...), arrays (arr=($(...)), arr+=("$f"), "${arr[@]}", slices "${arr[@]:1}"), mapfile/readarray, for f in $(...), ... | xargs rm, echo "$dbs" | xargs rm, here-strings (xargs rm <<< "$dbs", done <<< "$(find ...)") and while read f; ... done < <(...). A prefix assignment is an environment binding the nested shell sees (D=.agentic-qe bash -c 'rm -rf $D'). An unknown prefix may be empty, so "$X.agentic-qe" and $(true).agentic-qe name the store. bash -c or eval of a script that is wholly an unknown expansion (bash -c "$(... | base64 -d)", eval "$CMD") is refused; eval "$(ssh-agent -s)" and similar shell-setup generators pass.
  • A glob may match anything it could match: bracket expressions with POSIX classes ([[:alpha:]]) match any character, an extglob group (@(qe)) reads as *, and after shopt/GLOBIGNORE on the line, * also matches dot names.
  • find that deletes from ., .., ~, $HOME or any unresolved root is refused when it can reach a data file. An exclusion counts only in two forms, never with -depth: a branch that is exactly -name .agentic-qe -prune or -path ./.agentic-qe[/*] -prune, followed by -o and an -exec (never -delete: BSD find reads -delete as -d, which turns -prune off), or -not -path './.agentic-qe/*' as a condition of the deleting branch itself. A positive -path narrows only when it is literal: -path '*proj*' may match a store at any depth. Every -exec is read past wrappers (-exec sudo rm, -exec git rm). A shell's -c text is judged as if it ran on the store, a SQLite client on its SQL, and a copy only when the found file is its destination, so -exec grep -l rm {} \; and -exec cp {} /tmp/backup/ \; pass.
  • Past its read limits, text that names .agentic-qe is refused: brace expansion beyond 256 results, words over 2 KiB, or braces nested over 32 deep (each brace group reads as *); 256 expansions of one word; $(...) or bash -c nested deeper than the guard follows; scripts with more string literals than it reads.

Decisions and limits:

  • Refused in enforce mode on purpose: the CLAUDE.md restore flow (cp memory.db.bak-X .agentic-qe/memory.db, then removing -wal/-shm). To restore, ask the user to run it, or set guardMode to notify or off for that step.
  • Every .agentic-qe is protected, fixtures included: rm -rf /tmp/fixture/.agentic-qe is refused in enforce mode. A hook cannot resolve globs (/tmp/*/.agentic-qe), $-expansions or symlinks (/tmp/link pointing at the project), so it cannot tell a throwaway fixture from a project that lives under a temp directory. To clean fixtures, set guardMode to notify or off for that step, or ask the user.
  • Size and nesting limits: a shell command over 256 KiB is refused unread, and text nested more than 8 $(...) deep is refused when it names .agentic-qe. If the guard itself fails or runs out of time on a call, that call is refused (enforce mode).
  • SQL: DROP, DELETE FROM, TRUNCATE, ALTER ... DROP and UPDATE (which can overwrite every row: UPDATE ... SET content = NULL) are refused against a store. INSERT passes. SQL the guard cannot read is refused too: .read file, sqlite3 db < file.sql, or a heredoc whose end is not in the command. VACUUM INTO a store, sqlite-utils commands that change a store, litecli without -e, and destructive SQL handed to any other client are refused. sqlite3 -readonly and file:...?mode=ro pass.
  • Backup names: a file whose name contains backup or a .bak/-bak part (memory-backup-1.db, memory.bak.db) is a copy, not the store. Tools may write and remove it.
  • git clean -x -e: an exclude passes only if it keeps every data file (-e .agentic-qe, or -e '*.db*' -e '*.rvf'). -e '*.db' alone still lets git delete -wal/-shm/*.rvf, so it is refused.
  • PowerShell: a pipeline whose earlier stage names the store or lists recursively from where it may be (gci .agentic-qe .db | ri, Get-ChildItem -Recurse -Filter .db | Remove-Item) is refused at the destroying stage. Invoke-Expression/iex, & { ... } script blocks, Start-Process ... -ArgumentList (comma lists included), pwsh -c/powershell -Command (from either tool) and wsl <cmd> are read like the command they run, and New-Item -Force over a store is refused. Variables and splats are followed ($p = '.agentic-qe'; Remove-Item $p, $a = @{Path='.agentic-qe'}; Remove-Item @a, foreach ($d in $dbs)); an unknown $var reads as *, and iex or a .NET delete on one is refused. A -Force/-Hidden listing feeds a recursive Remove-Item, and any listing after sl .agentic-qe feeds a delete. $x += ... appends, a (...)/@(...)/$(...) argument is read as a stage of its own (Remove-Item (gci -r -Filter *.db)), $db.Delete()/.MoveTo() on a variable that holds the store is refused, and -OutVariable binds the stage's output. A Where-Object filter narrows what is fed on only when it is a pure conjunction (no -or, -xor, -not, !, -ne, -notlike, -notmatch) with a positive literal -eq/-like on Name or Extension that cannot match a store file (Where-Object Extension -eq '.tmp', { $_.Extension -eq '.tmp' -and $_.Length -gt 0 }).
  • What the guard cannot see: a script file it is not shown (python3 cleanup.py, make clean, npm run clean), paths assembled at run time ('.agentic' + '-qe'), and symlinks pointing into .agentic-qe. tar -x -C .agentic-qe and unzip -d .agentic-qe are refused, but an archive extracted elsewhere that happens to contain .agentic-qe is not. It is a guard against mistakes, not a sandbox.
  • /aqe-mod: status, check <command> (a dry run of the guard's verdict), fleet (the learning-data files present and the AQE MCP tools connected), gate. Anything only the AQE MCP server knows is reported as unknown, never estimated. status prints a this session: line, an all sessions: line (with the time counting began) and the last refusal (when, which tool, blocked or flagged, and the guard's reason).
  • Console status. Writes .claude-flow/aqe-mod/status.json for the ruflo console's Mods section. When ruflo-mods is loaded, it also adds an aqe segment to ruflo's status bar. The file is version: 1:
  • modVersion is the plugin version. hooks/version.ts is generated by scripts/sync-plugin-versions.cjs (the npm version hook), and --check fails if it drifts.
  • calls, blocked, flagged and startedMs count this session only, as before.
  • totals: {calls, blocked, flagged, since} count every session in the project. A new session loads them from the file it finds, and every write re-reads the file first, so sessions running side by side add to the totals instead of overwriting each other. If the file is missing or corrupt, the totals start from zero. Status-file I/O never blocks or allows a tool call. A file written by 3.15.1 or earlier has no totals, so its counters seed them.
  • lastRefusal: {atMs, tool, outcome, reason} is the most recent refusal from any session. outcome is blocked, or flagged in notify mode. reason is the guard's reason with its fixed back-up advice dropped, control and bidi characters removed, and operands redacted, then cut to 200 characters. A path keeps only its .agentic-qe/... part, or becomes <path>. A backticked expression becomes ` <expr> . The verb stays, for example aqe-mod refused this: rm on .agentic-qe/memory.db. `. The command itself is never stored.
  • Read back from the file, a time later than now plus one day is dropped. So is a lastRefusal whose reason does not start with aqe-mod refused this: .
  • lastDenied (the console's refusal class) is set once any session has refused something.
  • The ruflo console reads the top-level fields. totals and lastRefusal are additive, and today's console ignores them.
  • The mod never reads or writes the status file through a symbolic link. Before every read and write it checks .claude-flow, .claude-flow/aqe-mod and status.json with $.fs.stat. If any of them is a link, or is not a folder or a regular file where one is expected, it skips the file and leaves the link as it is. /aqe-mod status then says status file: not written: .... $.fs has no write that refuses to follow a link and no rename, so a link swapped in between the check and the write is not caught.

To reset the totals, delete status.json between sessions.

Tests: claude plugin test plugins/agentic-qe-fleet and bash plugins/agentic-qe-fleet/scripts/smoke-mod.sh.

Source 19 files
hooks/register.ts 185 lines
1import type { Hook, Register } from 'claude-code'
2
3import { answer, type DataFile } from './command'
4import { fallbackVerdict, isGuarded, judge, SUFFIX } from './guard'
5import { readOptions, type GuardMode } from './options'
6import { cleanReason, type Counts, countsOf, mergeSaved, MOD_NAME, newStats, noSaved, parseSaved, type Saved, segmentText, STATUS_DIR, STATUS_PATH, statusText, type Stats, toolName, ZERO } from './status'
7
8type Dollar = Parameters<Hook<'session.start'>>[0]
9
10/** The status file and the folders above it under the project root, outermost first. */
11const PARTS: readonly (readonly [string, 'dir' | 'file'])[] = [
12  ['.claude-flow', 'dir'],
13  [STATUS_DIR, 'dir'],
14  [STATUS_PATH, 'file'],
15]
16
17const missing = (err: unknown): boolean => /ENOENT|no such file|not found|does not exist/i.test(String((err as { message?: unknown })?.message ?? err))
18
19/**
20 * Why the status file must not be touched, or undefined when it may be: a
21 * symbolic link anywhere from `.claude-flow` down, or something other than a
22 * folder or a regular file where one is expected. A missing part is fine (the
23 * write creates it); a part that cannot be checked is not. Never follows a
24 * link, never removes one.
25 *
26 * `$.fs` has no no-follow write or rename, so a link swapped in between this
27 * check and the read or write that follows is not caught (a short window).
28 */
29async function statusBlocked($: Dollar, root: string): Promise<string | undefined> {
30  for (const [rel, kind] of PARTS) {
31    let st: { kind: string; isLink: boolean }
32    try {
33      st = await $.fs.stat(`${root}/${rel}`)
34    } catch (err) {
35      if (missing(err)) continue // not there yet: the write creates it; the parts below are still checked
36      return `${rel} could not be checked`
37    }
38    if (st.isLink) return `${rel} is a symbolic link (never followed)`
39    if (st.kind !== kind) return `${rel} is not a ${kind === 'dir' ? 'folder' : 'regular file'}`
40  }
41  return undefined
42}
43
44/** What the status file carries across sessions, or null when it is missing, unreadable or unsafe to read. */
45async function readSaved($: Dollar, root: string, nowMs: number): Promise<Saved | null> {
46  try {
47    if ((await statusBlocked($, root)) !== undefined) return null
48    return parseSaved(await $.fs.read(`${root}/${STATUS_PATH}`), nowMs)
49  } catch {
50    return null
51  }
52}
53
54/** Writes the status file unless it is unsafe; returns why it was not written, or undefined when it was. */
55async function writeStatus($: Dollar, root: string, text: string): Promise<string | undefined> {
56  const blocked = await statusBlocked($, root)
57  if (blocked !== undefined) return blocked
58  await $.fs.write(`${root}/${STATUS_PATH}`, text)
59  return undefined
60}
61
62/**
63 * One session of the mod: its mode, its counters, the project root, the segment last drawn,
64 * the cross-session totals as last written (`saved`) and the session counts already in them (`written`).
65 */
66type Session = { readonly mode: GuardMode; readonly stats: Stats; root?: string; segment?: string; saved: Saved; written: Counts; unavailable?: string }
67
68/**
69 * Writes the console's status file; a failure only costs the console a row. The totals are
70 * re-read first, so sessions running side by side add to them rather than overwrite each other;
71 * a missing or corrupt file falls back to what this session last wrote (zero at the start).
72 * A status file reached through a symbolic link is neither read nor written (statusfile.ts).
73 */
74async function flush($: Dollar, s: Session): Promise<void> {
75  if (s.root === undefined) return
76  try {
77    const now = await $.clock.now()
78    const saved = mergeSaved((await readSaved($, s.root, now)) ?? s.saved, s.stats, s.written)
79    s.unavailable = await writeStatus($, s.root, statusText(s.stats, s.mode, now, saved))
80    if (s.unavailable === undefined) {
81      s.saved = saved
82      s.written = countsOf(s.stats)
83    }
84  } catch {
85    /* the status file is a courtesy */
86  }
87  const text = segmentText(s.stats, s.mode)
88  if (text === s.segment) return
89  try {
90    await $.ruflo.segment({ id: 'aqe', text })
91    s.segment = text
92  } catch {
93    /* ruflo-mods is not seated: no status-bar segment */
94  }
95}
96
97async function aqeDir($: Dollar, root: string | undefined): Promise<readonly DataFile[] | null> {
98  if (root === undefined) return null
99  const dir = `${root}/.agentic-qe`
100  if (!(await $.fs.exists(dir))) return null
101  return (await $.fs.list(dir)).filter(f => f.kind === 'file').map(f => ({ name: f.name, size: f.size, mtimeMs: f.mtimeMs }))
102}
103
104/**
105 * agentic-qe as a mod (aqe-mod): a tighten-only guard for AQE's irreplaceable
106 * learning data, `/aqe-mod`, and the status file the ruflo console reads.
107 * Everything goes through `$`; no network, no process, no MCP calls.
108 */
109export const register: Register = (on, options) => {
110  const s: Session = { mode: readOptions(options).mode, stats: newStats(), saved: noSaved(), written: { ...ZERO } }
111
112  on('session.start', async ($, e, next) => {
113    const result = await next(e)
114    try {
115      s.root = (await $.session.root()) as string | undefined
116      s.stats.startedMs = await $.clock.now()
117    } catch {
118      /* no root: no status file, the guard still runs */
119    }
120    try {
121      await $.command.register({ name: MOD_NAME, description: 'AQE mod: status, check <command>, fleet, gate' })
122    } catch {
123      /* a name taken by another plugin must not stop the guard */
124    }
125    await flush($, s)
126    return result
127  })
128
129  // Tighten-only: a deny or the event unchanged; never a rewrite, never an allow over another hook.
130  on('tool.call', async ($, e, next) => {
131    if (s.mode === 'off' || !isGuarded(e.tool)) return next(e)
132    s.stats.calls++
133    const refusal = judge(e.tool, e, { root: s.root })
134    if (refusal === undefined) return next(e)
135    s.stats.lastDenied = refusal.cls
136    try {
137      // The reason, cut short and without its fixed advice; never the command (#924).
138      const outcome = s.mode === 'enforce' ? 'blocked' : 'flagged'
139      s.stats.lastRefusal = { atMs: await $.clock.now(), tool: toolName(e.tool), outcome, reason: cleanReason(refusal.reason, SUFFIX) }
140    } catch {
141      /* no clock: the counters still move */
142    }
143    if (s.mode === 'enforce') {
144      s.stats.blocked++
145      await flush($, s)
146      return { deny: refusal.reason }
147    }
148    s.stats.flagged++
149    try {
150      $.ui.toast('aqe-mod (notify): this call would delete or overwrite .agentic-qe learning data')
151    } catch {
152      /* a refused toast changes nothing */
153    }
154    await flush($, s)
155    return next(e)
156  }).catch(($, e, next) => {
157    // Fail closed: a guard that threw or overran refuses the call; a re-entry beneath its own
158    // `$` call is judged once (see fallbackVerdict).
159    const verdict = fallbackVerdict(s.mode, e.tool, e, next.called, next.error.kind, { root: s.root })
160    return verdict ?? next(e)
161  })
162
163  on('turn.complete', async ($, e, next) => {
164    const result = await next(e)
165    await flush($, s)
166    return result
167  })
168
169  /** `/aqe-mod`, answered here: read-only verbs, no model turn. */
170  on('command.run', { command: 'aqe-mod' }, async ($, e) => {
171    const args = typeof e.args === 'string' ? e.args : ''
172    await flush($, s)
173    const text = await answer(args, {
174      mode: s.mode,
175      stats: s.stats,
176      saved: mergeSaved(s.saved, s.stats, s.written),
177      unavailable: s.unavailable,
178      tools: async () => (await $.tool.list()).map(t => t.name),
179      aqeDir: () => aqeDir($, s.root),
180      root: s.root,
181    })
182    return { text }
183  })
184}
185
hooks/command.ts 124 lines
1import { judgeBash } from './guard'
2import type { GuardMode } from './options'
3import { DATA_FILE } from './paths'
4import { type Counts, type LastRefusal, mergeSaved, noSaved, type Saved, STATUS_PATH, type Stats, ZERO } from './status'
5
6/** A learning-data file as `$.fs.list` reports it. */
7export type DataFile = { readonly name: string; readonly size: number; readonly mtimeMs: number }
8
9/**
10 * What `/aqe-mod` reads: all of it local and cheap. Anything only the AQE MCP
11 * server knows (the last gate verdict, live fleet health, pattern counts) is
12 * reported as unknown, never estimated: this sandboxed mod does not call MCP.
13 */
14export type CommandDeps = {
15  readonly mode: GuardMode
16  readonly stats: Stats
17  /** The totals across sessions, this one included, and the last refusal of any session. */
18  readonly saved?: Saved
19  /** Why the status file was last neither read nor written (a symbolic link on its path), if it was not. */
20  readonly unavailable?: string
21  /** Names of the tools connected now. */
22  readonly tools: () => Promise<readonly string[]>
23  /** The entries of `<root>/.agentic-qe`, or null when it is missing or unreadable. */
24  readonly aqeDir: () => Promise<readonly DataFile[] | null>
25  /** The project root, when known: `check` then judges exactly as the guard does. */
26  readonly root?: string
27}
28
29const HELP = [
30  '/aqe-mod status          guard mode, counts for this session and all sessions, the last refusal',
31  '/aqe-mod check <command> would the guard refuse this shell command? (nothing runs)',
32  '/aqe-mod fleet           AQE data files present and AQE MCP tools connected',
33  '/aqe-mod gate            what is known about the last quality gate',
34].join('\n')
35
36/** AQE's MCP tools, by server name (`mcp__agentic-qe__*`, or the plugin-scoped `mcp__plugin_agentic-qe-fleet_...__*`). */
37export const isAqeTool = (name: string): boolean => /^mcp__(plugin_agentic-qe[^_]*_)?[^_]*agentic[-_]qe[^_]*__/i.test(name)
38
39const kb = (n: number) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`)
40
41async function aqeToolCount(deps: CommandDeps): Promise<string> {
42  try {
43    const n = (await deps.tools()).filter(isAqeTool).length
44    return n === 0 ? 'AQE MCP tools connected: none (is the agentic-qe MCP server running?)' : `AQE MCP tools connected: ${n}`
45  } catch {
46    return 'AQE MCP tools connected: unknown (the tool list was not readable)'
47  }
48}
49
50const counts = (c: Counts): string => `${c.calls} call${c.calls === 1 ? '' : 's'} checked · ${c.blocked} blocked · ${c.flagged} flagged`
51/** An ISO time, or `unknown` for a time no Date can hold (never throws). */
52export const iso = (ms: number): string => {
53  const d = new Date(ms)
54  return Number.isFinite(d.getTime()) ? d.toISOString() : 'unknown'
55}
56
57function refusalLine(r: LastRefusal | undefined, denied: Stats['lastDenied']): string {
58  if (r === undefined) return denied === undefined ? 'last refusal: none' : `last refusal: ${denied} (this session)`
59  const what = r.outcome === 'flagged' ? 'flagged (notify: it ran)' : 'blocked'
60  return `last refusal: ${iso(r.atMs)} · ${r.tool} · ${what} · ${r.reason}`
61}
62
63function status(deps: CommandDeps): string {
64  const { mode, stats } = deps
65  const saved = deps.saved ?? mergeSaved(noSaved(), stats, ZERO)
66  const since = saved.totals.since === undefined ? '' : ` (since ${iso(saved.totals.since)})`
67  const line =
68    mode === 'enforce'
69      ? 'guard: enforce (refuses destructive operations on .agentic-qe learning data)'
70      : mode === 'notify'
71        ? 'guard: notify (allows, but warns on destructive operations on .agentic-qe learning data)'
72        : 'guard: off (nothing is checked)'
73  return [
74    line,
75    `this session: ${counts(stats)}`,
76    `all sessions: ${counts(saved.totals)}${since}`,
77    refusalLine(saved.lastRefusal, stats.lastDenied),
78    deps.unavailable === undefined ? `status file: ${STATUS_PATH}` : `status file: not written: ${deps.unavailable}`,
79  ].join('\n')
80}
81
82function check(command: string, root: string | undefined): string {
83  if (command === '') return 'Usage: /aqe-mod check <shell command>'
84  const r = judgeBash(command, { root })
85  return r === undefined ? 'allowed: the guard would let this run.' : `refused: ${r.reason}`
86}
87
88async function fleet(deps: CommandDeps): Promise<string> {
89  let files: readonly DataFile[] | null
90  try {
91    files = await deps.aqeDir()
92  } catch {
93    files = null
94  }
95  const data = (files ?? []).filter(f => DATA_FILE.test(f.name))
96  const lines =
97    files === null
98      ? ['.agentic-qe: not found in this project (run `aqe init`)']
99      : data.length === 0
100        ? ['.agentic-qe: present, no learning-data files yet']
101        : ['.agentic-qe learning data:', ...data.map(f => `  ${f.name}  ${kb(f.size)}  modified ${new Date(f.mtimeMs).toISOString()}`)]
102  return [...lines, await aqeToolCount(deps), 'fleet health: unknown here (ask the fleet_status MCP tool or run /aqe-fleet-status)'].join('\n')
103}
104
105async function gate(deps: CommandDeps): Promise<string> {
106  return [
107    'last quality-gate verdict: unknown (it is held by the AQE MCP server; this mod does not call MCP)',
108    await aqeToolCount(deps),
109    'to evaluate one: the quality_assess MCP tool, or /aqe-report',
110  ].join('\n')
111}
112
113/** `/aqe-mod`, answered locally: no model turn, and nothing it says is estimated. */
114export async function answer(args: string, deps: CommandDeps): Promise<string> {
115  const trimmed = args.trim()
116  const [verb = '', ...rest] = trimmed.split(/\s+/)
117  if (verb === '' || verb === 'help') return HELP
118  if (verb === 'status') return status(deps)
119  if (verb === 'check') return check(trimmed.slice(verb.length).trim(), deps.root)
120  if (verb === 'fleet') return fleet(deps)
121  if (verb === 'gate') return gate(deps)
122  return `Unknown: ${verb.slice(0, 40)}${rest.length > 0 ? ' …' : ''}\n${HELP}`
123}
124
hooks/guard.ts 204 lines
1/**
2 * The learning-data guard: decides whether one tool call would destroy or
3 * overwrite AQE's irreplaceable learning data (the CLAUDE.md "Data Protection"
4 * rule, made mechanical).
5 *
6 * Pure and synchronous: no `$`, no I/O, no imports outside this folder, so it
7 * runs unchanged in the sandbox, under `claude plugin test` and under vitest.
8 *
9 * Tighten-only by construction: `judge` returns a refusal reason or undefined.
10 * It never rewrites a call and never allows something another hook refused.
11 *
12 * Reads and backups pass: `cp .agentic-qe/memory.db x.bak`, `sqlite3 ... "SELECT ..."`,
13 * `PRAGMA integrity_check`, `.backup /tmp/x`, `ls`, `du`.
14 *
15 * The rules live by concern: shell.ts reads the command line, verbs.ts and
16 * writers.ts judge each command, find.ts judges find, producers.ts decides what
17 * substitutions and pipelines may yield, scripts.ts judges sqlite3 and
18 * interpreter one-liners, powershell.ts the PowerShell tool, paths.ts says what
19 * is learning data.
20 */
21import { expandVars, isData, textNamesData, WORD_BUDGET, type Ctx, type GuardScope } from './context'
22import { protectedKind } from './paths'
23import type { GuardMode } from './options'
24import { judgePowerShell } from './powershell'
25import { substitutionAlts } from './producers'
26import { parse } from './shell'
27import { judgeSegment } from './verbs'
28
29export type { GuardScope } from './context'
30export { segments, words } from './shell'
31
32/** A refusal: the reason shown to the model, and the console's fixed class for it. */
33export type Refusal = { readonly reason: string; readonly cls: 'destructive' }
34
35/** The tools whose input the guard reads; every other tool passes untouched. */
36export const GUARDED_TOOLS = ['Bash', 'Monitor', 'PowerShell', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'] as const
37
38const PREFIX = 'aqe-mod refused this: '
39/** The fixed advice every refusal ends with; the status file drops it from the reason it keeps. */
40export const SUFFIX = ' AQE learning data (.agentic-qe/*.db, -wal, -shm, *.rvf) is irreplaceable. Back it up with `cp .agentic-qe/memory.db .agentic-qe/memory.db.bak-$(date +%s)` and ask the user to run this themselves, or set the plugin option guardMode to notify/off.'
41
42const refuse = (what: string): Refusal => ({ reason: `${PREFIX}${what}.${SUFFIX}`, cls: 'destructive' })
43
44const field = (input: unknown, key: string): string => {
45  const v = typeof input === 'object' && input !== null ? (input as Record<string, unknown>)[key] : undefined
46  return typeof v === 'string' ? v : ''
47}
48
49/** The longest shell command the guard reads (256 KiB); a longer one is refused unread. */
50export const MAX_COMMAND = 256 * 1024
51
52/** Nesting past this (`bash -c "bash -c ..."`) is refused when the line names learning data at all. */
53const MAX_DEPTH = 6
54
55/** Judges one shell command line under `ctx`; the recursion behind `bash -c`, `eval`, heredocs and `.shell`. */
56function bashWhat(command: string, ctx: Ctx): string | undefined {
57  if (command.trim() === '') return undefined
58  // Past the depth the guard follows, the text is not read piecemeal: naming the store at all is enough.
59  if (ctx.depth > MAX_DEPTH) return ctx.mentionsData || /agentic/i.test(command) || textNamesData(command, ctx) ? 'a command nested too deeply to read names learning data' : undefined
60  // `shopt -s dotglob`/`GLOBIGNORE` make `*` match dot names: from here on, globs may reach `.agentic-qe`.
61  if (/\bshopt\b|GLOBIGNORE/.test(command)) ctx.dotglob = true
62  const segs = parse(command)
63  if (!ctx.mentionsData)
64    ctx.mentionsData = segs.some(s => s.words.some(w => isData(w, ctx)) || s.redirects.some(r => isData(r.target, ctx)) || (s.stdin !== '' && textNamesData(s.stdin, ctx)))
65  // `done < <(find ...)`: what the process substitution prints is what `read` receives, earlier on the line.
66  // `done <<< "$(find ...)"` or `done <<< "$dbs"`: a here-string feeds `read` the same way. The line's
67  // earlier assignments (`dbs=$(find ...)`) are not bound yet here, so they are replayed, once, on a copy.
68  const replay = segs.some(s => (s.hereStrings ?? []).length > 0) ? new Map(ctx.vars) : undefined
69  for (const s of segs) {
70    for (const w of replay === undefined ? [] : (s.hereStrings ?? [])) {
71      const named = expandVars(w, replay as Map<string, readonly string[]>, WORD_BUDGET, inner => ctx.subst(inner, ctx)).filter(v => isData(v, ctx))
72      if (named.length > 0) {
73        ctx.readFed = [...new Set([...(ctx.readFed ?? []), ...named, '*'])]
74        ctx.mentionsData = true
75      }
76    }
77    if (replay !== undefined) for (const w of s.words) assignOn(replay, w, ctx)
78    for (const r of s.redirects) {
79      if (r.op !== '<' || !r.target.startsWith('<(')) continue
80      const alts = ctx.subst(r.target.slice(2, r.target.endsWith(')') ? -1 : undefined), ctx)
81      if (alts.length > 1) {
82        ctx.readFed = alts
83        ctx.mentionsData = true
84      }
85    }
86  }
87  const inner: Ctx = { ...ctx, depth: ctx.depth + 1 }
88  for (const seg of segs) {
89    const what = judgeSegment(seg, inner)
90    // `cd`, variables and mentions inside a nested shell carry on in the line that holds it.
91    ctx.inAqe = inner.inAqe
92    ctx.mentionsData = ctx.mentionsData || inner.mentionsData
93    ctx.dotglob = ctx.dotglob || inner.dotglob
94    ctx.readFed = ctx.readFed ?? inner.readFed
95    if (what !== undefined) return what
96  }
97  return undefined
98}
99
100/** Applies one `NAME=value` word to a variable map (the here-string replay). */
101function assignOn(vars: Map<string, readonly string[]>, word: string, ctx: Ctx): void {
102  const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(word)
103  if (m !== null) vars.set(m[1] as string, expandVars(m[2] as string, vars, WORD_BUDGET, inner => ctx.subst(inner, ctx)))
104}
105
106const newCtx = (scope: GuardScope | undefined): Ctx => ({
107  inAqe: false,
108  mentionsData: false,
109  dotglob: false,
110  root: scope?.root,
111  vars: new Map(),
112  depth: 0,
113  bash: (command, ctx) => bashWhat(command, { ...ctx }),
114  subst: cachedSubst(),
115  readFed: undefined,
116  pwsh: (command, ctx) => judgePowerShell(command, { ...ctx }),
117})
118
119/** `substitutionAlts`, remembered per inner text for one call (a word may repeat a substitution). */
120function cachedSubst(): Ctx['subst'] {
121  const seen = new Map<string, readonly string[]>()
122  return (inner, ctx) => {
123    const key = `${ctx.inAqe ? 1 : 0}${ctx.dotglob ? 1 : 0}${inner}`
124    const hit = seen.get(key)
125    if (hit !== undefined) return hit
126    const alts = substitutionAlts(inner, ctx)
127    seen.set(key, alts)
128    return alts
129  }
130}
131
132/** The refusal for one shell command line, or undefined to let it run. */
133export function judgeBash(command: string, scope?: GuardScope): Refusal | undefined {
134  const what = bashWhat(command, newCtx(scope))
135  return what === undefined ? undefined : refuse(what)
136}
137
138/** The refusal for one PowerShell command line, or undefined. */
139export function judgePwsh(command: string, scope?: GuardScope): Refusal | undefined {
140  if (command.trim() === '') return undefined
141  const what = judgePowerShell(command, newCtx(scope))
142  return what === undefined ? undefined : refuse(what)
143}
144
145/** The refusal for a file tool writing to a learning-data file, or undefined. */
146export function judgeFileTool(path: string): Refusal | undefined {
147  const k = protectedKind(path)
148  return k === 'file' || k === 'glob' ? refuse(`a file tool writes to ${path}`) : undefined
149}
150
151/** True for the tools the guard reads. */
152export const isGuarded = (tool: string): boolean => (GUARDED_TOOLS as readonly string[]).includes(tool)
153
154/**
155 * The guard's verdict on one tool call (`input` the call's fields), or undefined to let it run.
156 * `scope.root` (the project root) only widens what is refused (`find /root -name '*.db' -delete`);
157 * every `.agentic-qe` path is protected with or without it.
158 */
159export function judge(tool: string, input: unknown, scope?: GuardScope): Refusal | undefined {
160  if (tool === 'Bash' || tool === 'Monitor' || tool === 'PowerShell') {
161    const command = field(input, 'command')
162    // Past this size the reader's cost is no longer small and bounded: refuse rather than judge.
163    if (command.length > MAX_COMMAND) return refuse(`a ${Math.round(command.length / 1024)} KiB command is too long for the guard to read`)
164    return tool === 'PowerShell' ? judgePwsh(command, scope) : judgeBash(command, scope)
165  }
166  if (tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit') return judgeFileTool(field(input, 'file_path'))
167  if (tool === 'NotebookEdit') return judgeFileTool(field(input, 'notebook_path'))
168  return undefined
169}
170
171/** The refusal the `.catch` handler gives when the guard's own check throws. */
172export const GUARD_FAILED = 'aqe-mod: the learning-data guard failed on this call, so it was refused.'
173
174/** Why the `tool.call` hook's `.catch` handler was asked (the engine's `next.error.kind`). */
175export type FailureKind = 'throw' | 'timeout' | 're-entry'
176
177/**
178 * The `tool.call` hook's `.catch` decision, or undefined to run `next(e)`.
179 * - `next` already ran (`called`): its settled result is replayed.
180 * - The hook threw or overran its budget before deciding: in enforce mode the
181 *   call is refused outright. The judge is not run again: whatever made it
182 *   throw or run slow would do so twice.
183 * - A re-entry (the call rose beneath the guard's own `$` call, so the hook did
184 *   not run): enforce mode judges it once, and refuses it when that throws.
185 * notify and off never refuse here.
186 */
187export function fallbackVerdict(
188  mode: GuardMode,
189  tool: string,
190  input: unknown,
191  called: boolean,
192  kind: FailureKind,
193  scope?: GuardScope,
194): { readonly deny: string } | undefined {
195  if (called || mode !== 'enforce' || !isGuarded(tool)) return undefined
196  if (kind !== 're-entry') return { deny: GUARD_FAILED }
197  try {
198    const refusal = judge(tool, input, scope)
199    return refusal === undefined ? undefined : { deny: refusal.reason }
200  } catch {
201    return { deny: GUARD_FAILED }
202  }
203}
204
hooks/options.ts 27 lines
1import type { PluginOptions } from 'claude-code'
2
3/**
4 * The guard's mode. `enforce` (default): refuse. `notify`: let the call run,
5 * toast and count it. `off`: read nothing.
6 */
7export type GuardMode = 'off' | 'notify' | 'enforce'
8export const GUARD_MODES: readonly GuardMode[] = ['off', 'notify', 'enforce']
9
10/** The plugin's `userConfig`, validated: a missing or unknown value is the default, enforce. */
11export type ModOptions = { readonly mode: GuardMode }
12
13/** The userConfig key this mod reads. */
14export const OPTION_KEY = 'guardMode'
15
16/** `on`/`true` read as enforce and `false` as off, so a boolean-style setting still means what it says. */
17export function asMode(value: unknown): GuardMode | undefined {
18  if (value === true || value === 'on' || value === 'true') return 'enforce'
19  if (value === false || value === 'false') return 'off'
20  return GUARD_MODES.find(m => m === value)
21}
22
23export function readOptions(options: PluginOptions | Readonly<Record<string, unknown>> | undefined): ModOptions {
24  const o = (options ?? {}) as Readonly<Record<string, unknown>>
25  return { mode: asMode(o[OPTION_KEY]) ?? 'enforce' }
26}
27
hooks/status.ts 211 lines
1import type { GuardMode } from './options'
2import { MOD_VERSION } from './version'
3
4export { MOD_VERSION }
5
6/**
7 * The status file the ruflo console's Mods section reads (ADR-446; contract in
8 * ruflo-console hooks/data/mods.ts): `.claude-flow/<name>-mod/status.json`,
9 * `version: 1`, at most 8 KB, stale after 6 hours without a write. The console
10 * reads the top-level counters; `totals` and `lastRefusal` are additive fields
11 * it ignores, kept so a refusal outlives the session that made it (#924).
12 */
13export const MOD_NAME = 'aqe-mod'
14export const STATUS_DIR = `.claude-flow/${MOD_NAME}`
15export const STATUS_PATH = `${STATUS_DIR}/status.json`
16/** The console's folder rule; the smoke script and tests hold the name to it. */
17export const STATUS_DIR_RULE = /^[a-z0-9][a-z0-9-]{0,40}-mod$/
18export const STATUS_MAX_BYTES = 8192
19/** One line (at most 120 characters) for the console row. */
20export const SUMMARY = 'Guards AQE learning data (.agentic-qe/*.db, -wal, -shm, *.rvf) from rm, overwrite, truncate and DROP/DELETE'
21/** The most characters of a refusal reason kept in the file. */
22export const REASON_MAX = 200
23
24/** What the guard did with a call it would refuse: refused it (enforce) or let it run with a warning (notify). */
25export type Outcome = 'blocked' | 'flagged'
26
27/** The most recent refusal: when, which tool, and the guard's reason, cut short. Never the command itself. */
28export type LastRefusal = { atMs: number; tool: string; outcome: Outcome; reason: string }
29
30/** Counters for this session. `calls`: tool calls the guard read; `blocked`: refused; `flagged`: would have refused (notify). */
31export type Stats = { calls: number; blocked: number; flagged: number; lastDenied?: 'destructive'; startedMs?: number; lastRefusal?: LastRefusal }
32
33export const newStats = (): Stats => ({ calls: 0, blocked: 0, flagged: 0 })
34
35/** The three counters, as a session or the totals hold them. */
36export type Counts = { calls: number; blocked: number; flagged: number }
37
38export const ZERO: Counts = { calls: 0, blocked: 0, flagged: 0 }
39export const countsOf = (c: Counts): Counts => ({ calls: c.calls, blocked: c.blocked, flagged: c.flagged })
40
41/** Counts across every session in this project, and when counting began. */
42export type Totals = Counts & { since?: number }
43
44/** What the file carries across sessions. */
45export type Saved = { totals: Totals; lastRefusal?: LastRefusal }
46
47export const noSaved = (): Saved => ({ totals: { ...ZERO } })
48
49/** What the file holds. Counts and fixed classes, plus the last refusal's reason cut to REASON_MAX: never a command. */
50export type StatusPayload = {
51  version: 1
52  modVersion: string
53  summary: string
54  guard: boolean
55  mode: GuardMode
56  calls: number
57  blocked: number
58  flagged: number
59  lastDenied?: 'destructive'
60  startedMs?: number
61  updatedMs: number
62  totals: Totals
63  lastRefusal?: LastRefusal
64}
65
66const CEILING = Number.MAX_SAFE_INTEGER
67const DAY_MS = 86_400_000
68const whole = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(Math.floor(v), CEILING) : undefined)
69/** A time read from the file: kept only within [0, now + 1 day], else missing (a planted far-future time must not stick). */
70const instant = (v: unknown, nowMs: number): number | undefined => {
71  const t = whole(v)
72  return t !== undefined && t <= nowMs + DAY_MS ? t : undefined
73}
74const record = (v: unknown): Record<string, unknown> | undefined => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined)
75const TOOL = /^[A-Za-z0-9_.-]{1,64}$/
76/** C0/C1 controls, and the bidi and zero-width marks that could disguise text (ADR-450 T2). */
77const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g
78
79/** A tool name fit for the file: the name itself when plain, else `other`. */
80export const toolName = (tool: unknown): string => (typeof tool === 'string' && TOOL.test(tool) ? tool : 'other')
81
82/** Every reason the guard's `judge` gives starts with this; a stored reason that does not is dropped. */
83export const REASON_PREFIX = 'aqe-mod refused this: '
84/** A backticked span kept as written: a verb and its flags (`rm`, `xargs rm -c`, `.backup`, `Remove-Item -Force`). */
85const VERB = /^(?=.{1,40}$)[A-Za-z0-9 ._+-]+(\/-[a-z]+)?$/
86/** A word that is an operand: a path, an expansion, a quote, a glob, or a data file. */
87const OPERAND = /[/\\~$="(){}*?[\]]|^'|agentic|\.(db|rvf)$|-(wal|shm)$/i
88/** The guard's own prose that has slashes: SQL keyword lists (`DROP/DELETE`, `UPDATE/.restore`). */
89const PROSE = /^[A-Z]+(\/(\.[a-z]+|[A-Z]+))+$/
90const STORE = /\.agentic-qe(?=[/\\]|$)/i
91
92/** An operand as the file may keep it: its `.agentic-qe/...` suffix when it has one, else `<path>`. */
93function operand(word: string): string {
94  const m = STORE.exec(word)
95  return m === null ? '<path>' : word.slice(m.index).replace(/\\/g, '/')
96}
97
98/**
99 * The reason without operands that could carry a secret (a path such as
100 * `/home/u/<token>/.agentic-qe`): a backticked expression becomes `<expr>`,
101 * any other operand its `.agentic-qe/...` suffix or `<path>`. The verb and what
102 * was refused stay.
103 */
104export function redactReason(text: string): string {
105  return text
106    .split(/(`[^`]*`)/)
107    .map((part, i) => {
108      if (i % 2 === 1) return VERB.test(part.slice(1, -1)) ? part : '`<expr>`'
109      return part.replace(/\S+/g, word => {
110        const m = /^(\(*)(.*?)([.,;:)]*)$/.exec(word) as RegExpExecArray
111        const core = m[2] as string
112        return core !== '' && OPERAND.test(core) && !PROSE.test(core) ?`${m[1] as string}${operand(core)}${m[3] as string}` : word
113      })
114    })
115    .join('')
116}
117
118/**
119 * A refusal reason fit for the file: `advice` (the guard's fixed back-up-first
120 * suffix) dropped, control and bidi characters removed, whitespace collapsed,
121 * operands redacted (redactReason), and cut to REASON_MAX characters.
122 */
123export function cleanReason(reason: unknown, advice = ''): string {
124  let text = typeof reason === 'string' ? reason : ''
125  if (advice !== '' && text.endsWith(advice)) text = text.slice(0, -advice.length)
126  text = redactReason(text.replace(UNSAFE, ' ').replace(/\s+/g, ' ').trim())
127  return text.length <= REASON_MAX ? text : `${text.slice(0, REASON_MAX - 1)}…`
128}
129
130function refusalOf(v: unknown, nowMs: number): LastRefusal | undefined {
131  const r = record(v)
132  const atMs = instant(r?.atMs, nowMs)
133  if (r === undefined || atMs === undefined || typeof r.reason !== 'string') return undefined
134  const reason = cleanReason(r.reason)
135  if (!reason.startsWith(REASON_PREFIX)) return undefined
136  const outcome: Outcome = r.outcome === 'flagged' ? 'flagged' : 'blocked'
137  return { atMs, tool: toolName(r.tool), outcome, reason }
138}
139
140/**
141 * What an earlier status file carried across sessions, or null when it is
142 * missing, too large, not JSON or not version 1. A file from before #924 has
143 * no `totals`: its session counters seed them. A time past `nowMs` + 1 day is
144 * dropped, and so is a last refusal whose reason is not the guard's.
145 */
146export function parseSaved(text: unknown, nowMs: number): Saved | null {
147  if (typeof text !== 'string' || text.length > STATUS_MAX_BYTES) return null
148  let value: Record<string, unknown> | undefined
149  try {
150    value = record(JSON.parse(text))
151  } catch {
152    return null
153  }
154  if (value === undefined || value.version !== 1) return null
155  const from = record(value.totals) ?? value
156  const since = instant(record(value.totals) === undefined ? value.startedMs : from.since, nowMs)
157  const lastRefusal = refusalOf(value.lastRefusal, nowMs)
158  return {
159    totals: { calls: whole(from.calls) ?? 0, blocked: whole(from.blocked) ?? 0, flagged: whole(from.flagged) ?? 0, ...(since !== undefined && { since }) },
160    ...(lastRefusal !== undefined && { lastRefusal }),
161  }
162}
163
164const add = (a: number, b: number): number => Math.min(a + Math.max(b, 0), CEILING)
165
166/**
167 * `prior` (what the file holds now, other sessions included) plus this
168 * session's counts not yet written (`stats` less `written`), and the newer of
169 * the two last refusals.
170 */
171export function mergeSaved(prior: Saved, stats: Stats, written: Counts): Saved {
172  const since = prior.totals.since ?? stats.startedMs
173  const mine = stats.lastRefusal
174  const theirs = prior.lastRefusal
175  const lastRefusal = mine === undefined ? theirs : theirs === undefined || mine.atMs >= theirs.atMs ? mine : theirs
176  return {
177    totals: {
178      calls: add(prior.totals.calls, stats.calls - written.calls),
179      blocked: add(prior.totals.blocked, stats.blocked - written.blocked),
180      flagged: add(prior.totals.flagged, stats.flagged - written.flagged),
181      ...(since !== undefined && { since }),
182    },
183    ...(lastRefusal !== undefined && { lastRefusal }),
184  }
185}
186
187export function statusPayload(stats: Stats, mode: GuardMode, nowMs: number, saved: Saved = mergeSaved(noSaved(), stats, ZERO)): StatusPayload {
188  const denied = stats.lastDenied ?? (saved.lastRefusal !== undefined ? 'destructive' : undefined)
189  return {
190    version: 1,
191    modVersion: MOD_VERSION,
192    summary: SUMMARY,
193    guard: mode === 'enforce',
194    mode,
195    calls: stats.calls,
196    blocked: stats.blocked,
197    flagged: stats.flagged,
198    ...(denied !== undefined && { lastDenied: denied }),
199    ...(stats.startedMs !== undefined && { startedMs: stats.startedMs }),
200    updatedMs: nowMs,
201    totals: saved.totals,
202    ...(saved.lastRefusal !== undefined && { lastRefusal: saved.lastRefusal }),
203  }
204}
205
206export const statusText = (stats: Stats, mode: GuardMode, nowMs: number, saved?: Saved): string => `${JSON.stringify(statusPayload(stats, mode, nowMs, saved), null, 2)}\n`
207
208/** The ruflo status-bar segment's text (ruflo cuts it to 48 characters). */
209export const segmentText = (stats: Stats, mode: GuardMode): string =>
210  mode === 'off' ? 'aqe guard off' : `aqe ${mode}${stats.blocked > 0 ? ` · ${stats.blocked} blocked` : ''}${stats.flagged > 0 ? ` · ${stats.flagged} flagged` : ''}`
211
hooks/paths.ts 126 lines
1/**
2 * Which paths are AQE's irreplaceable learning data.
3 *
4 * Pure: no `$`. Shared by the guard (hooks/guard.ts), the `/aqe-mod fleet`
5 * verb and the tests.
6 *
7 * Protected, case-insensitively, anywhere in a path:
8 * - the `.agentic-qe` directory itself (deleting or moving it loses everything),
9 *   including a glob component that could match it (`.agentic*`, `.[a]gentic-qe`, `.*`);
10 * - a direct child of `.agentic-qe/` named `*.db`, `*.db-wal`, `*.db-shm`,
11 *   `*.db-journal` or `*.rvf` (memory.db and its WAL/SHM, brain/pattern stores);
12 * - a glob directly under `.agentic-qe/` that could match one of those.
13 *
14 * Not protected: backups (`memory.db.bak-<ts>` does not end in `.db`, and a
15 * name containing `backup` or a `.bak`/`-bak` part is a copy, not the store),
16 * subdirectories (`.agentic-qe/agents/`), config, logs.
17 *
18 * Every `.agentic-qe` is protected wherever it lives, `/tmp/...` included: a
19 * pure check cannot resolve globs, `$`-expansions or symlinks, so it cannot
20 * tell a throwaway fixture from a project that lives under a temp directory.
21 */
22import { globMatch } from './glob'
23
24/** A learning-data file's name: what the CLAUDE.md Data Protection rule guards. */
25export const DATA_FILE = /\.(db(-wal|-shm|-journal)?|rvf)$/i
26
27/** A backup's name (`memory-backup-20261009.db`, `memory.bak.db`, `x-bak-1.db`): a copy the guard lets tools write and remove. */
28export const BACKUP_NAME = /backup|(^|[._-])bak([._-]|\d|$)/i
29
30/** Names a glob is tried against to decide whether it could reach learning data. */
31const SAMPLES = ['memory.db', 'memory.db-wal', 'memory.db-shm', 'memory.db-journal', 'brain.rvf', 'patterns.rvf', 'x.db']
32
33const AQE = '.agentic-qe'
34
35export type ProtectedKind = 'dir' | 'file' | 'glob'
36
37/** The longest word read as a path; a longer one is judged by whether it mentions the store at all. */
38export const MAX_PATH = 4096
39
40/**
41 * Collapses `\`, `//`, `/./`, `a/../` and a leading `./`, so `.agentic-qe/./memory.db`,
42 * `x/../.agentic-qe/memory.db` and `./memory.db` read plainly. `./` alone reads as `.`.
43 */
44export function normalisePath(raw: string): string {
45  const p = raw.replace(/\\/g, '/').replace(/\/{2,}/g, '/')
46  const parts: string[] = []
47  for (const part of p.split('/')) {
48    if (part === '.' && parts.length > 0) continue
49    if (part === '..' && parts.length > 0 && parts[parts.length - 1] !== '..' && parts[parts.length - 1] !== '' && parts[parts.length - 1] !== '.') {
50      parts.pop()
51      continue
52    }
53    parts.push(part)
54  }
55  while (parts.length > 1 && parts[0] === '.') parts.shift()
56  const out = parts.join('/')
57  return out === '' && p.startsWith('.') ? '.' : out
58}
59
60export const hasGlob = (s: string): boolean => /[*?[]/.test(s)
61
62/** Whether a glob matches a name (linear; see glob.ts). */
63export const globMatches = (glob: string, name: string): boolean => globMatch(glob, name)
64
65/** Whether a glob (a file-name pattern, no directory part) could match a learning-data file. */
66export const globReachesData = (glob: string): boolean => SAMPLES.some(name => globMatches(glob, name))
67
68/**
69 * Whether one path component names the `.agentic-qe` directory: literally (after
70 * a `--db=` or `file:` style prefix), or as a glob the shell would expand to it.
71 * A glob only reaches a dot-directory when it starts with `.` or a bracket.
72 */
73function namesAqe(component: string, dotglob: boolean): boolean {
74  // A `--db=` or `file:` prefix, never one reaching into a glob (`.agentic-q[[:alpha:]]`).
75  const c = component.replace(/^[^*?[]*[=:]/, '')
76  if (c.toLowerCase() === AQE) return true
77  // Leading `*`s are often an unknown expansion that may be empty (`"$X.agentic-qe"`, `$(true).agentic-qe`).
78  if (/^\*+\./.test(c) && globMatches(c.replace(/^\*+/, ''), AQE)) return true
79  return hasGlob(c) && (dotglob || c.startsWith('.') || c.startsWith('[')) && globMatches(c, AQE)
80}
81
82/** The index of the first component naming `.agentic-qe`, or -1. */
83const aqeIndex = (parts: readonly string[], dotglob = false): number => parts.findIndex(p => namesAqe(p, dotglob))
84
85/**
86 * How a path touches learning data, or undefined when it does not.
87 * `inAqe`: the command already changed into `.agentic-qe`, so a bare `memory.db` is the store.
88 * `dotglob`: the line may have set `shopt -s dotglob`/`GLOBIGNORE`, so `*` also matches dot names.
89 */
90export function protectedKind(raw: string, inAqe = false, dotglob = false): ProtectedKind | undefined {
91  // Outside `.agentic-qe`, a path can only reach it by naming it or by a glob: a cheap exit for every other word.
92  if (!inAqe && !/agentic|[*?[]/i.test(raw)) return undefined
93  // No real path is this long: read it as a glob that may reach the store when it could name it.
94  if (raw.length > MAX_PATH) return inAqe || /agentic/i.test(raw) ? 'glob' : undefined
95  const path = normalisePath(stripUri(raw.trim()))
96  if (path === '') return undefined
97  const parts = path.split('/')
98  const at = aqeIndex(parts, dotglob)
99  let rest: string
100  if (at === -1) {
101    if (!inAqe || path.includes('/')) return undefined
102    rest = path
103  } else {
104    rest = parts.slice(at + 1).join('/')
105  }
106  if (rest === '' || rest === '.') return 'dir'
107  // Only direct children are the stores; `.agentic-qe/agents/x.db` is someone's fixture.
108  if (rest.includes('/')) return undefined
109  if (hasGlob(rest)) return globReachesData(rest) ? 'glob' : undefined
110  return DATA_FILE.test(rest) && !BACKUP_NAME.test(rest) ? 'file' : undefined
111}
112
113/** A `file:` URI's path without its `?query`/`#fragment` (`file:.agentic-qe/memory.db?mode=rw`). */
114export const stripUri = (raw: string): string => (/^file:/i.test(raw) ? raw.replace(/[?#].*$/s, '') : raw)
115
116/** The last path component. */
117export const baseName = (p: string): string => {
118  if (!/[\\/]/.test(p)) return p
119  const parts = normalisePath(p).split('/').filter(s => s !== '')
120  return parts[parts.length - 1] ?? ''
121}
122
123/** True when a path names something under `.agentic-qe` at any depth (for `find` roots and `rsync --delete`). */
124export const underAqe = (raw: string, inAqe = false): boolean =>
125  aqeIndex(normalisePath(raw.trim()).split('/')) !== -1 || (inAqe && (raw === '.' || raw === './' || !raw.startsWith('/')))
126
hooks/context.ts 181 lines
1/**
2 * What the guard knows while it reads one command line: where the command has
3 * changed into, the variables it has set, the project root, and how to judge a
4 * nested shell command. Pure: no `$`.
5 */
6import { MAX_PATH, protectedKind, type ProtectedKind } from './paths'
7import { expandBraces, unmask, type Segment } from './shell'
8
9/** Where the guard is judging: the project root, when the session knows it (so `find /abs/root ...` is read as from above `.agentic-qe`). */
10export type GuardScope = { readonly root?: string }
11
12export type Ctx = {
13  /** The command has changed into `.agentic-qe` (`cd .agentic-qe`, `git -C .agentic-qe`). */
14  inAqe: boolean
15  /** Some word of the whole line names learning data (for `xargs rm`, `| sh`, `while read`). */
16  mentionsData: boolean
17  /** The line may change globbing (`shopt`, `GLOBIGNORE`): `*` may then match `.agentic-qe`. */
18  dotglob: boolean
19  readonly root: string | undefined
20  /** Shell variables the line set (`F=...`, `for f in ...`, `read f`), each to the values it can hold. */
21  readonly vars: Map<string, readonly string[]>
22  /** How deep in `bash -c`/`eval`/heredoc nesting this line is. */
23  readonly depth: number
24  /** Judges a nested shell command line (`bash -c "..."`, `.shell ...`) under this context. */
25  readonly bash: (command: string, ctx: Ctx) => string | undefined
26  /** What a `$(...)`/backtick substitution may expand to (producers.ts), cached per inner text. */
27  readonly subst: (inner: string, ctx: Ctx) => readonly string[]
28  /** What `read` receives from a `< <(...)` on the line, when that may be the store. */
29  readFed: readonly string[] | undefined
30  /** Judges a PowerShell command line (`pwsh -c ...` from the Bash tool) under this context. */
31  readonly pwsh: (command: string, ctx: Ctx) => string | undefined
32}
33
34/** How a word touches learning data under this context, or undefined. */
35export const kindOf = (word: string, ctx: Ctx): ProtectedKind | undefined => protectedKind(word.replace(EXTGLOB, '*'), ctx.inAqe, ctx.dotglob)
36
37/** An extglob group (`@(qe)`, `!(x)`, `+(a|b)`): read as `*`, which it may match. */
38const EXTGLOB = /[@!+*?]\([^()]*\)/g
39
40export const isData = (w: string, ctx: Ctx): boolean => kindOf(w, ctx) !== undefined
41
42export const isDataFileOrGlob = (w: string, ctx: Ctx): boolean => {
43  const k = kindOf(w, ctx)
44  return k === 'file' || k === 'glob'
45}
46
47/** Results one word may expand to before its expansions are read as `*` instead. */
48export const WORD_BUDGET = 256
49
50/** A `$` expansion's alternatives: one of these values stands in its place. */
51type Unit = readonly string[]
52
53/** The index of the bracket closing the one at `open` (`(`/`{`), or -1. */
54function matching(w: string, open: number, o: string, c: string): number {
55  let depth = 0
56  for (let i = open; i < w.length; i++) {
57    if (w[i] === o) depth++
58    else if (w[i] === c && --depth === 0) return i
59  }
60  return -1
61}
62
63/** `${...}`'s alternatives: a known variable's values, a default word or `*`; anything unmodelled is `*`. */
64function braceParam(inner: string, vars: ReadonlyMap<string, readonly string[]>, depth: number): Unit {
65  const name = /^[A-Za-z_][A-Za-z0-9_]*$/.test(inner) ? inner : undefined
66  if (name !== undefined) return vars.get(name) ?? ['*']
67  // `${arr[@]}`, `${arr[*]}`, `${arr[0]}`, slices `${arr[@]:1}`: the array's values (an array binding holds every element).
68  const element = /^([A-Za-z_][A-Za-z0-9_]*)\[[^\]]*\](:[^}]*)?$/.exec(inner)
69  if (element !== null) return vars.get(element[1] as string) ?? ['*']
70  const op = /^([A-Za-z_][A-Za-z0-9_]*)(:?[-=?+])(.*)$/s.exec(inner)
71  if (op === null || depth > 8) return ['*']
72  const known = vars.get(op[1] as string)
73  const word = loose(op[3] as string, depth + 1)
74  if ((op[2] as string).endsWith('+')) return [word, '']
75  return [...(known ?? []), word, '*']
76}
77
78/** Resolves a substitution's inner text to what it may expand to; without one, every substitution is `*`. */
79export type Subst = (inner: string) => readonly string[]
80
81/** Splits a word into literal text and `$` expansions (unknown ones as `*`). */
82function units(word: string, vars: ReadonlyMap<string, readonly string[]>, depth = 0, subst?: Subst): Array<string | Unit> {
83  const out: Array<string | Unit> = []
84  let lit = ''
85  for (let i = 0; i < word.length; i++) {
86    const c = word[i] as string
87    const n = word[i + 1]
88    let unit: Unit | undefined
89    let end = i
90    if (c === '`') {
91      const close = word.indexOf('`', i + 1)
92      end = close === -1 ? word.length - 1 : close
93      unit = subst === undefined ? ['*'] : subst(word.slice(i + 1, end))
94    } else if (c === '$' && n === '(') {
95      const close = matching(word, i + 1, '(', ')')
96      end = close === -1 ? word.length - 1 : close
97      unit = subst === undefined ? ['*'] : subst(word.slice(i + 2, close === -1 ? word.length : close))
98    } else if (c === '$' && n === '{') {
99      const close = matching(word, i + 1, '{', '}')
100      end = close === -1 ? word.length - 1 : close
101      unit = braceParam(word.slice(i + 2, close === -1 ? word.length : close), vars, depth)
102    } else if (c === '$' && n !== undefined && /[A-Za-z_]/.test(n)) {
103      const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(word.slice(i + 1, i + 257)) as RegExpExecArray
104      end = i + m[0].length
105      unit = vars.get(m[0]) ?? ['*']
106    } else if (c === '$' && n !== undefined && /[0-9@*#?$!-]/.test(n)) {
107      end = i + 1
108      unit = ['*']
109    }
110    if (unit === undefined) lit += c
111    else {
112      if (lit !== '') out.push(lit)
113      lit = ''
114      out.push(unit)
115      i = end
116    }
117  }
118  if (lit !== '') out.push(lit)
119  return out
120}
121
122/** A word with every `$` expansion read as `*`: what it can always match. */
123const loose = (word: string, depth = 0): string =>
124  units(word, new Map(), depth)
125    .map(u => (typeof u === 'string' ? u : '*'))
126    .join('')
127
128/**
129 * A word as the shell may expand it: each known variable by the values it can
130 * hold, every other `$NAME`, `${...}`, `$@`, `$(...)` and backtick as `*`
131 * (unknown text can be anything), `${X:-w}` as `w` or `*`. Past `budget`
132 * results the whole word is read loose, every expansion as `*`.
133 */
134export function expandVars(word: string, vars: ReadonlyMap<string, readonly string[]>, budget = WORD_BUDGET, subst?: Subst): string[] {
135  if (!word.includes('$') && !word.includes('`')) return [word]
136  const parts = units(word, vars, 0, subst)
137  let count = 1
138  let length = 0
139  for (const p of parts) {
140    if (typeof p === 'string') length += p.length
141    else {
142      count *= Math.max(1, p.length)
143      // A loop, not Math.max(...spread): a unit may hold more values than the call stack takes.
144      length += p.reduce((m, v) => Math.max(m, v.length), 0)
145    }
146  }
147  // Too many results, or too long: read loose, but keep any alternative that names the store as a word of its own.
148  if (count > budget || length > MAX_PATH) {
149    const named = parts.flatMap(p => (typeof p === 'string' ? [] : p.filter(v => /agentic/i.test(v))))
150    return [loose(word), ...new Set(named)]
151  }
152  let out = ['']
153  for (const p of parts) out = typeof p === 'string' ? out.map(o => o + p) : out.flatMap(o => p.map(v => o + v))
154  return out
155}
156
157/** A segment's words as the shell expands them: braces (unquoted ones only), then `$` expansions. */
158export function expandWords(seg: Segment, ctx: Ctx): string[] {
159  // Most words hold nothing to expand: no `$`, backtick or brace.
160  if (!seg.words.some(w => /[$`{]/.test(w))) return [...seg.words]
161  return seg.words.flatMap((w, i) => {
162    const ex = seg.expandable[i] ?? w
163    const braced = ex.includes('{') ? expandBraces(ex).map(unmask) : [w]
164    const budget = Math.max(1, Math.floor(WORD_BUDGET / braced.length))
165    return braced.flatMap(b => expandVars(b, ctx.vars, budget, inner => ctx.subst(inner, ctx)))
166  })
167}
168
169/**
170 * Words inside a script or SQL text that could be paths: split at quotes,
171 * whitespace and punctuation, so `rmSync('.agentic-qe', {...})`,
172 * `os.path.join('.agentic-qe','memory.db')` and `'${root}/.agentic-qe/memory.db'` each yield the path.
173 */
174export const pathTokens = (text: string): string[] => text.split(/[\s'"`,;(){}+<>|&=$]+/).filter(t => t !== '')
175
176/** Whether a script or SQL text names learning data (the directory counts). */
177export const textNamesData = (text: string, ctx: Ctx): boolean => pathTokens(text).some(t => isData(t, ctx))
178
179/** Whether a script or SQL text names a learning-data file or glob (the directory alone does not). */
180export const textNamesDataFile = (text: string, ctx: Ctx): boolean => pathTokens(text).some(t => isDataFileOrGlob(t, ctx))
181
hooks/powershell.ts 253 lines
1/**
2 * The guard's reading of a PowerShell tool command: Remove-Item, Move-Item,
3 * Copy-Item, Set-Content, New-Item -Force and friends (and their aliases) on
4 * learning data, `>` redirects, .NET file APIs, `cmd /c`, `Start-Process`,
5 * `Invoke-Expression`/`iex` and `& { ... }` script blocks, and pipelines where
6 * an earlier stage lists the store (`gci .agentic-qe *.db | Remove-Item`).
7 * Anything else in a stage (sqlite3, git, python -c, ...) is read by the
8 * shell rules. Pure: no `$`.
9 */
10import { holdsAqe } from './commands'
11import { isData, isDataFileOrGlob, kindOf, textNamesData, type Ctx } from './context'
12import { DATA_FILE, baseName, globMatches, globReachesData, underAqe } from './paths'
13import { assignment, foreachOf, hasUnknownVar, rhsValues, substitute, type PsVars } from './psvars'
14
15const DELETE = new Set(['remove-item', 'rm', 'del', 'erase', 'rd', 'rmdir', 'ri'])
16const MOVE = new Set(['move-item', 'mv', 'move', 'mi'])
17const COPY = new Set(['copy-item', 'cp', 'copy', 'cpi', 'cpp'])
18const RENAME = new Set(['rename-item', 'ren', 'rni'])
19const WRITE = new Set(['set-content', 'sc', 'clear-content', 'clc', 'out-file', 'add-content', 'ac', 'tee-object', 'tee'])
20const CREATE = new Set(['new-item', 'ni'])
21const CD = new Set(['cd', 'set-location', 'sl', 'chdir', 'pushd', 'push-location'])
22const LIST = new Set(['get-childitem', 'gci', 'ls', 'dir'])
23const EXPR = new Set(['invoke-expression', 'iex'])
24const START = new Set(['start-process', 'saps', 'start'])
25const PWSH = /^(pwsh|powershell)(\.exe)?$/
26/** A downstream stage that destroys what is piped to it. */
27const CONSUMES = /(^|[\s{;(])(remove-item|ri|rm|del|erase|rd|rmdir|move-item|mv|move|mi|clear-content|clc|set-content|sc|rename-item|ren|rni)(?=$|[\s;})])|\.delete\s*\(/i
28/** .NET file APIs that delete, move or overwrite. */
29const DOTNET = /\[(System\.)?IO\.(File|Directory|FileInfo|DirectoryInfo)\]::(Delete|Move|Copy|Replace|WriteAll\w*|AppendAll\w*|Create\w*|Open\w*)\b|\.Delete\s*\(/i
30/** Names and extensions of the store's files and directory, for literal Where-Object filters. */
31const STORE_NAMES = ['memory.db', 'memory.db-wal', 'memory.db-shm', 'memory.db-journal', 'brain.rvf', '.agentic-qe']
32const STORE_EXTENSIONS = ['.db', '.db-wal', '.db-shm', '.db-journal', '.rvf', '.agentic-qe']
33/** A `(...)`, `@(...)` or `$(...)` group inside a stage (one level of nesting). */
34const GROUP = /[@$]?\(((?:[^()]|\([^()]*\))*)\)/g
35/** `$x.Delete(...)` / `$x.MoveTo(...)` on a variable. */
36const METHOD_ON_VAR = /\$\{?([A-Za-z_]\w*)\}?\.(delete|moveto)\s*\(/gi
37
38/**
39 * Whether a stage is a Where-Object filter that cannot pass a store file: a pure conjunction
40 * (no `-or`, `-xor`, `-not`, `!`, `-ne`, `-notlike`, `-notmatch`) with at least one positive
41 * literal `-eq`/`-like` on Name or Extension that cannot match a store file or `.agentic-qe`
42 * (`Where-Object Extension -eq '.tmp'`, `{ $_.Extension -eq '.tmp' -and $_.Length -gt 0 }`).
43 */
44function narrowsAwayFromStore(stage: string): boolean {
45  if (!/^\s*(where-object|where|\?)(\s|\{|$)/i.test(stage)) return false
46  if (/-[ic]?(or|xor|not|ne|notlike|notmatch)\b|!/i.test(stage)) return false
47  // A literal: single-quoted (where `$` is literal), or double-quoted without `$` (no expansion).
48  const tests = /(?:\$_\.)?\b(name|extension)\s+-[ic]?(eq|like)\s+(?:'([^']*)'|"([^"$]*)")/gi
49  for (const m of stage.matchAll(tests)) {
50    const candidates = (m[1] as string).toLowerCase() === 'name' ? STORE_NAMES : STORE_EXTENSIONS
51    const literal = (m[3] ?? m[4]) as string
52    const misses = (m[2] as string).toLowerCase() === 'eq' ? candidates.every(c => c.toLowerCase() !== literal.toLowerCase()) : candidates.every(c => !globMatches(literal, c))
53    if (misses) return true
54  }
55  return false
56}
57
58/** How deep `iex`, `& { }` and `Start-Process` text is followed before naming the store at all is refused. */
59const MAX_DEPTH = 6
60
61/** Splits at top-level separators (outside quotes, braces and parentheses; backtick escapes). */
62function splitTop(command: string, at: (c: string, next: string | undefined) => boolean): string[] {
63  const out: string[] = []
64  let cur = ''
65  let quote: string | undefined
66  let depth = 0
67  for (let i = 0; i < command.length; i++) {
68    const c = command[i] as string
69    if (quote !== undefined) {
70      if (c === quote) quote = undefined
71      cur += c
72    } else if (c === '`') {
73      cur += command[i + 1] ?? ''
74      i++
75    } else if (c === "'" || c === '"') {
76      quote = c
77      cur += c
78    } else if (c === '{' || c === '(') {
79      depth++
80      cur += c
81    } else if (c === '}' || c === ')') {
82      depth = Math.max(0, depth - 1)
83      cur += c
84    } else if (depth === 0 && at(c, command[i + 1])) {
85      if (command[i + 1] === c) i++
86      out.push(cur)
87      cur = ''
88    } else cur += c
89  }
90  out.push(cur)
91  return out.map(s => s.trim()).filter(s => s !== '')
92}
93
94const statements = (command: string): string[] => splitTop(command, (c, n) => c === ';' || c === '\n' || (c === '&' && n === '&') || (c === '|' && n === '|'))
95const stages = (statement: string): string[] => splitTop(statement, (c, n) => c === '|' && n !== '|')
96
97/** Words of one stage, quotes and grouping parentheses removed, backslashes kept (they are path separators here). */
98const psWords = (seg: string): string[] =>
99  [...seg.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/g)]
100    .map(m => m[1] ?? m[2] ?? m[3] ?? '')
101    .map(w => w.replace(/^-\w+:(?=.)/, '').replace(/^[@$]?\(+|\)+$/g, ''))
102
103/** Redirect targets (`>`, `>>`, `*>`, `2>`). */
104const psRedirects = (seg: string): string[] => [...seg.matchAll(/(?:^|[^-])[*\d]?>{1,2}\s*(['"]?)([^\s'"]+)\1/g)].map(m => m[2] ?? '')
105
106/** The value of a named parameter (`-Destination X`, `-Path X`), case-insensitively. */
107function param(ws: readonly string[], ...names: string[]): string | undefined {
108  const i = ws.findIndex(w => names.some(n => w.toLowerCase() === `-${n}`))
109  return i === -1 ? undefined : ws[i + 1]
110}
111
112/** Whether a switch is given, by any unambiguous prefix PowerShell accepts (`-r`, `-rec`, `-Recurse`). */
113const hasSwitch = (ws: readonly string[], name: string, min: number): boolean =>
114  ws.some(w => w.startsWith('-') && w.length - 1 >= min && name.startsWith(w.slice(1).toLowerCase()))
115
116/** Operands: words that are not `-Param` names (a parameter's value counts as an operand). */
117const operands = (ws: readonly string[]): string[] => ws.filter(w => !/^-[A-Za-z]/.test(w))
118
119/** The verb of a stage (past a leading `&`/`.` call operator) and its argument words. */
120function verbOf(seg: string): { verb: string; args: string[] } {
121  const ws = psWords(seg)
122  const call = ws[0] === '&' || ws[0] === '.'
123  return { verb: baseName(call ? (ws[1] ?? '') : (ws[0] ?? '')).toLowerCase(), args: call ? ws.slice(2) : ws.slice(1) }
124}
125
126/**
127 * Whether a stage hands the store to the next one: it names it; it lists recursively from
128 * where it may be; it lists hidden items (`-Force`, `-Hidden`) for a recursive delete; or it
129 * lists inside `.agentic-qe` (after `sl .agentic-qe`).
130 */
131function feedsStore(seg: string, ctx: Ctx, recursiveConsumer = false): boolean {
132  if (textNamesData(seg.replace(/\\/g, '/'), ctx)) return true
133  const { verb, args } = verbOf(seg)
134  if (!LIST.has(verb)) return false
135  const hidden = hasSwitch(args, 'force', 2) || hasSwitch(args, 'hidden', 2)
136  if (!hasSwitch(args, 'recurse', 1) && !(hidden && recursiveConsumer) && !ctx.inAqe) return false
137  const ops = operands(args)
138  // The listing root: -Path, or the first operand unless it is a bare pattern (`ls -r *.db` lists from here).
139  const first = ops[0]
140  const path = param(args, 'path', 'literalpath') ?? (first !== undefined && !(/[*?]/.test(first) && !/[\\/]/.test(first)) ? first : undefined)
141  if (path !== undefined && !holdsAqe(path.replace(/\\/g, '/'), ctx) && !underAqe(path.replace(/\\/g, '/'), ctx.inAqe)) return false
142  const patterns = [param(args, 'filter'), param(args, 'include'), ...ops.filter(o => o !== path)].filter((p): p is string => p !== undefined)
143  return patterns.length === 0 || patterns.some(p => globReachesData(baseName(p)) || globMatches(baseName(p), '.agentic-qe'))
144}
145
146function judgePsSegment(seg: string, ctx: Ctx, depth: number): string | undefined {
147  const redirect = psRedirects(seg).find(t => isDataFileOrGlob(t, ctx))
148  if (redirect !== undefined) return `a PowerShell redirect overwrites ${redirect}`
149  // A .NET file API on the store, or on an argument the guard cannot resolve (an unknown `$p`, read as `*`).
150  if (DOTNET.test(seg) && (textNamesData(seg.replace(/\\/g, '/'), ctx) || /\(\s*['"]?\*/.test(seg))) return 'a .NET file API deletes or overwrites AQE learning data'
151  // A script block (`& { ... }`, `ForEach-Object { ... }`) is read as PowerShell of its own.
152  for (const block of seg.matchAll(/\{([^{}]*)\}/g)) {
153    const what = judgePowerShell(block[1] ?? '', ctx, depth + 1)
154    if (what !== undefined) return what
155  }
156  const { verb, args } = verbOf(seg)
157  const ops = operands(args)
158  if (CD.has(verb)) {
159    const t = ops[0]
160    if (t !== undefined) ctx.inAqe = underAqe(t, ctx.inAqe) && !t.startsWith('..')
161    return undefined
162  }
163  if (verb === 'cmd' || verb === 'cmd.exe') {
164    const c = args.findIndex(a => /^\/[ck]$/i.test(a))
165    return c === -1 ? undefined : judgePowerShell(args.slice(c + 1).join(' '), ctx, depth + 1)
166  }
167  if (EXPR.has(verb)) return judgePowerShell(ops.join(' '), ctx, depth + 1)
168  if (START.has(verb)) {
169    // `-ArgumentList '/c','rd','/s','/q','.agentic-qe'` is a comma list; `'-Command ...'` one string.
170    const listed = /-(?:argumentlist|args)\s+((?:(?:'[^']*'|"[^"]*"|[^\s,'"]+)\s*,\s*)*(?:'[^']*'|"[^"]*"|[^\s,'"]+))/i.exec(seg)?.[1]
171    const list = listed === undefined ? ops.slice(1).join(' ') : listed.split(/\s*,\s*/).map(a => a.replace(/^(['"])([\s\S]*)\1$/, '$2')).join(' ')
172    const file = param(args, 'filepath') ?? ops[0] ?? ''
173    return judgePowerShell(`${file} ${list}`, ctx, depth + 1)
174  }
175  if (PWSH.test(verb)) {
176    const c = args.findIndex(a => /^-(c|command|encodedcommand|ec|e)$/i.test(a))
177    if (c === -1) return undefined
178    if (/^-(encodedcommand|ec|e)$/i.test(args[c] as string)) return `\`${verb} -EncodedCommand\` runs a script the guard cannot read`
179    return judgePowerShell(args.slice(c + 1).join(' '), ctx, depth + 1)
180  }
181  if (DELETE.has(verb)) {
182    const hit = ops.find(a => isData(a, ctx))
183    if (hit !== undefined) return `\`${verb}\` on ${hit}`
184    return textNamesData(seg.replace(/\\/g, '/'), ctx) ? `\`${verb}\` on what names AQE learning data` : undefined
185  }
186  if (MOVE.has(verb) || RENAME.has(verb)) {
187    const dest = param(args, 'destination', 'newname') ?? (ops.length > 1 ? ops[ops.length - 1] : undefined)
188    const src = ops.filter(o => o !== dest)
189    const moved = src.find(a => isData(a, ctx))
190    if (moved !== undefined) return `\`${verb}\` moves ${moved} away`
191    return dest !== undefined && isDataFileOrGlob(dest, ctx) ? `\`${verb}\` overwrites ${dest}` : undefined
192  }
193  if (COPY.has(verb)) {
194    const dest = param(args, 'destination') ?? ops[ops.length - 1]
195    if (dest === undefined || ops.length < 2) return undefined
196    const k = kindOf(dest, ctx)
197    const src = ops.filter(o => o !== dest)
198    if (k === 'file' || k === 'glob' || (k === 'dir' && src.some(s => DATA_FILE.test(baseName(s))))) return `\`${verb}\` overwrites ${dest}`
199    return undefined
200  }
201  if (WRITE.has(verb)) {
202    const target = param(args, 'path', 'literalpath', 'filepath') ?? ops.find(o => isDataFileOrGlob(o, ctx)) ?? ops[0]
203    return target !== undefined && isDataFileOrGlob(target, ctx) ? `\`${verb}\` writes ${target}` : undefined
204  }
205  // New-Item -Force replaces an existing file with an empty one.
206  if (CREATE.has(verb) && hasSwitch(args, 'force', 2)) {
207    const hit = ops.find(o => isDataFileOrGlob(o, ctx))
208    return hit === undefined ? undefined : `\`${verb} -Force\` replaces ${hit}`
209  }
210  // Not a PowerShell file cmdlet: read it as a shell command (sqlite3, git, python -c, bash -c ...).
211  return ctx.bash(seg.replace(/\\/g, '/'), ctx)
212}
213
214/** The refusal reason for a PowerShell command line, or undefined. Variables bound on the line are read through. */
215export function judgePowerShell(command: string, ctx: Ctx, depth = 0, vars: PsVars = new Map()): string | undefined {
216  if (depth > MAX_DEPTH) return /agentic/i.test(command) ? 'PowerShell nested too deeply to read names learning data' : undefined
217  for (const raw of statements(command)) {
218    // `iex` of text holding a variable the guard cannot resolve: it cannot read what runs.
219    if (/^(iex|invoke-expression)\b/i.test(raw.trim()) && hasUnknownVar(raw, vars)) return '`Invoke-Expression` runs text the guard cannot read'
220    const loop = foreachOf(raw)
221    if (loop !== undefined) vars.set(loop.name, rhsValues(substitute(loop.source, vars), ctx, t => feedsStore(t, ctx, true)))
222    // `$db.Delete()`, `$f.MoveTo(...)` on a variable that holds the store or a listing of it.
223    for (const m of raw.matchAll(METHOD_ON_VAR)) {
224      if ((vars.get((m[1] as string).toLowerCase()) ?? []).some(v => isData(v.replace(/\\/g, '/'), ctx))) return `\`$${m[1] as string}.${m[2] as string}()\` on AQE learning data`
225    }
226    const bound = assignment(raw)
227    const statement = substitute(bound === undefined ? raw : bound.rhs, vars)
228    const parts = stages(statement)
229    for (let i = 0; i < parts.length; i++) {
230      const part = parts[i] as string
231      const what = judgePsSegment(part, ctx, depth)
232      if (what !== undefined) return what
233      const recursive = hasSwitch(verbOf(part).args, 'recurse', 1)
234      if (CONSUMES.test(part)) {
235        // A `(...)`/`@(...)`/`$(...)` argument is a stage of its own (`Remove-Item (gci -r -Filter *.db)`).
236        for (const g of part.matchAll(GROUP)) if (feedsStore(g[1] as string, ctx, recursive)) return `\`${verbOf(part).verb}\` is handed AQE learning data by \`(${(g[1] as string).trim()})\``
237        // Data flow: a destroying stage fed by one that names, lists recursively or lists hidden items of the store,
238        // unless a literal Where-Object filter in between cannot pass a store file.
239        const fed = parts.slice(0, i).some((up, j) => feedsStore(up, ctx, recursive) && !parts.slice(j + 1, i).some(narrowsAwayFromStore))
240        if (i > 0 && fed) return `a PowerShell pipeline feeds AQE learning data to \`${verbOf(part).verb}\``
241      }
242      // `-OutVariable dbs` / `-ov dbs`: the variable holds what this stage outputs.
243      const ov = /-(?:outvariable|ov)\s+\+?([A-Za-z_]\w*)/i.exec(part)
244      if (ov !== null) vars.set((ov[1] as string).toLowerCase(), rhsValues(part, ctx, t => feedsStore(t, ctx, true)))
245    }
246    if (bound !== undefined) {
247      const values = rhsValues(statement, ctx, t => feedsStore(t, ctx, true))
248      vars.set(bound.name, bound.append ? [...(vars.get(bound.name) ?? []), ...values] : values)
249    }
250  }
251  return undefined
252}
253
hooks/producers.ts 109 lines
1/**
2 * Commands whose output becomes other commands' arguments: `$(...)`/backtick
3 * substitutions, `< <(...)` feeding `read`, and pipeline stages feeding
4 * `xargs`/`read`. The guard cannot see their output, so it decides what that
5 * output may be: a substitution that names the store yields those paths; one
6 * that lists files which may include the store (`find`, `ls -A`, `git
7 * ls-files -o`), or whose output is opaque (`cat list`, `base64 -d`), may
8 * yield the store itself. Only known-harmless producers (`date`, `pwd`,
9 * `find . -name '*.tmp'`) read as plain `*`. Pure: no `$`.
10 */
11import { holdsAqe, isVerb, verbName } from './commands'
12import { isData, pathTokens, textNamesData, type Ctx } from './context'
13import { asDeleting, judgeFind } from './find'
14import { commandStart, isOption, parse, type Segment } from './shell'
15
16/** What the output of a command that may list or emit the store can be (`*` first, so a destination slot sees the store). */
17export const DATA_ALTS: readonly string[] = ['*', '.agentic-qe', '.agentic-qe/memory.db']
18
19/** Commands whose output is never a path the guard cares about. */
20const HARMLESS = new Set(['date', 'pwd', 'mktemp', 'basename', 'dirname', 'realpath', 'readlink', 'whoami', 'id', 'uname', 'hostname', 'nproc', 'seq', 'true', 'false', 'tty', 'getconf', 'echo', 'printf', 'wc', 'which', 'whereis'])
21/** Shell-setup generators whose output `eval` runs (`eval "$(ssh-agent -s)"`). */
22const ENV_INIT = new Set(['ssh-agent', 'direnv', 'pyenv', 'rbenv', 'nodenv', 'fnm', 'brew', 'conda', 'zoxide', 'starship', 'mise', 'rtx', 'gpg-agent', 'dircolors', 'keychain'])
23/** Filters that only select or reorder lines they are piped. */
24const FILTERS = new Set(['head', 'tail', 'sort', 'uniq', 'grep', 'egrep', 'fgrep', 'wc', 'cut', 'tr'])
25const GIT_READS = new Set(['rev-parse', 'describe', 'branch', 'log', 'show', 'diff', 'tag', 'config', 'remote', 'symbolic-ref', 'hash-object'])
26/** Package-manager queries that print a cache or store directory (`npm config get cache`, `go env GOCACHE`). */
27const TOOL_PATHS = /^(npm|yarn|pnpm|bun) (cache dir|config get|store path|root|bin|prefix)\b|^go env\b|^pip cache dir\b|^cargo metadata\b/
28
29/** Command words that may list the store (`find`, `ls -A`, `dir`, `git ls-files -o`). */
30const LISTERS = /(^|\/)(find|ls|dir|git)$/
31
32type Verdict = 'harmless' | 'reaches' | 'opaque'
33
34/** Whether one command's output may name the store: never, by listing it (`reaches`), or unknowably (`opaque`). */
35function verdictOf(words: readonly string[], ctx: Ctx, piped: boolean): Verdict {
36  const at = commandStart(words, isVerb)
37  const verb = verbName(words[at] ?? '')
38  const args = words.slice(at + 1)
39  const operands = args.filter(a => !isOption(a))
40  if (verb === '') return 'harmless'
41  // `command -v x` / `type -P x` print where a command lives.
42  if ((words[0] === 'command' && /^-[vV]$/.test(words[1] ?? '')) || (words[0] === 'type' && /^-[pP]+$/.test(words[1] ?? ''))) return 'harmless'
43  if (TOOL_PATHS.test(words.slice(at).join(' '))) return 'harmless'
44  if (verb === 'find') return judgeFind(asDeleting(args), ctx) === undefined ? 'harmless' : 'reaches'
45  if (verb === 'ls' || verb === 'dir') {
46    const all = args.some(a => /^-[A-Za-z]*[aAf]/.test(a) || a === '--all' || a === '--almost-all')
47    return all && (operands.length === 0 || operands.some(o => holdsAqe(o, ctx))) ? 'reaches' : 'harmless'
48  }
49  if (verb === 'git') {
50    const sub = operands[0] ?? ''
51    if (sub === 'ls-files') return args.some(a => /^-[A-Za-z]*[oi]/.test(a) || a === '--others' || a === '--ignored') ? 'reaches' : 'harmless'
52    // `git status` prints untracked (`??`) and, with --ignored, ignored paths: the store among them.
53    if (sub === 'status') return 'reaches'
54    return GIT_READS.has(sub) ? 'harmless' : 'opaque'
55  }
56  // echo/printf print their arguments: harmless unless an unknown variable feeds them.
57  if (HARMLESS.has(verb)) return (verb === 'echo' || verb === 'printf') && args.some(a => /[$][A-Za-z_{@*0-9]/.test(a)) ? 'opaque' : 'harmless'
58  if (FILTERS.has(verb) && (piped || operands.length === 0)) return 'harmless'
59  return 'opaque'
60}
61
62/** The worst verdict over every command a text runs (nested substitutions included). */
63function verdictOfText(text: string, ctx: Ctx): Verdict {
64  let worst: Verdict = 'harmless'
65  for (const seg of parse(text)) {
66    if (seg.dropped !== undefined) return 'opaque'
67    // `$(< file)` prints a file the guard cannot see, as `$(cat file)` does.
68    if (seg.words.length === 0 && seg.redirects.some(r => r.op === '<')) return 'opaque'
69    const v = verdictOf(seg.words, ctx, seg.piped)
70    if (v === 'opaque') return 'opaque'
71    if (v === 'reaches') worst = 'reaches'
72  }
73  return worst
74}
75
76/**
77 * What a `$(...)`/backtick substitution may expand to. Naming the store: those paths (and `*`).
78 * Listing files that may include it, or opaque: DATA_ALTS. Harmless: `*`.
79 */
80export function substitutionAlts(inner: string, ctx: Ctx): readonly string[] {
81  if (inner.trim() === '') return ['']
82  if (textNamesData(inner, ctx)) {
83    const named = pathTokens(inner).filter(t => isData(t, ctx))
84    return ['*', ...new Set(named)]
85  }
86  if (ctx.depth > 6) return DATA_ALTS
87  return verdictOfText(inner, ctx) === 'harmless' ? ['*'] : DATA_ALTS
88}
89
90/** Whether `eval`/`bash -c` would run a script the guard cannot read: one that is wholly an expansion (`"$CMD"`, `"$(curl ... | base64 -d)"`). */
91export function opaqueScript(raw: string, ctx: Ctx): boolean {
92  const word = raw.trim()
93  const sub = /^\$\(([\s\S]*)\)$|^`([\s\S]*)`$/.exec(word)
94  if (sub !== null) {
95    const inner = sub[1] ?? sub[2] ?? ''
96    const first = parse(inner)[0]
97    if (first !== undefined && ENV_INIT.has(verbName(first.words[commandStart(first.words, isVerb)] ?? ''))) return false
98    return verdictOfText(inner, ctx) !== 'harmless' || textNamesData(inner, ctx)
99  }
100  const v = /^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$/.exec(word)
101  return v !== null && !ctx.vars.has(v[1] as string)
102}
103
104/** Whether an earlier stage of this pipeline lists files that may include the store (`find . -name '*.db' | xargs rm`, `git ls-files -oi | xargs rm`). */
105export function fedByProducer(seg: Segment, ctx: Ctx): boolean {
106  // Only these can list the store; most stages are skipped without being read.
107  return seg.stages.some((stage, i) => stage.some(w => LISTERS.test(w)) && verdictOf(stage, ctx, i > 0) === 'reaches')
108}
109
hooks/shell.ts 447 lines
1/**
2 * A small, quote-aware reader for the shell commands the guard judges.
3 *
4 * Pure: no `$`, no imports. It is not a shell: it reads just enough of bash to
5 * find each simple command, its words as the command will see them (quotes
6 * removed, escapes applied, `$(...)` kept inside its word), its redirects,
7 * the text fed to its stdin (heredocs, here-strings, the stages piped into it),
8 * and the commands inside `$(...)`, backticks and `<(...)`, which it reads as
9 * commands of their own. Anything it cannot read stays in a word, so the guard
10 * errs toward judging more, never less.
11 */
12
13export { BRACE_MAX_DEPTH, BRACE_MAX_LENGTH, expandBraces } from './braces'
14
15/** A redirect on one simple command: its operator and target word. */
16export type Redirect = { readonly op: string; readonly target: string }
17
18/** One simple command. */
19export type Segment = {
20  /** Its words as the command sees them, redirects removed. */
21  readonly words: readonly string[]
22  /** Each word with its quoted `{`, `}` and `,` masked (see `mask`): only unquoted braces expand. */
23  readonly expandable: readonly string[]
24  readonly redirects: readonly Redirect[]
25  /** Heredoc and here-string bodies fed to its stdin ('' when none). */
26  readonly stdin: string
27  /** True when an earlier pipeline stage feeds its stdin. */
28  readonly piped: boolean
29  /** The words and stdin of the earlier stages of its pipeline ('' when none). */
30  readonly upstream: string
31  /** The words of each earlier stage of its pipeline (`find ... | xargs rm`). */
32  readonly stages: readonly (readonly string[])[]
33  /** Set on a stand-in segment for a substitution nested past the depth the reader follows: its text, unread. */
34  readonly dropped?: string
35  /** A heredoc fed to it whose end is not in the text: what it reads is unknown. */
36  readonly opaqueStdin?: boolean
37  /** Here-string words (`<<< "$(find ...)"`), as written: what they expand to feeds read/mapfile/xargs. */
38  readonly hereStrings?: readonly string[]
39}
40
41/** How deep `$(...)` / backtick nesting is read; deeper text is handed back unread, as `dropped`. */
42export const MAX_NESTING = 8
43
44/** How many earlier pipeline stages feed a stage (`find | grep | xargs rm` needs two). */
45const FEED = 8
46
47type Building = {
48  words: string[]
49  expandable: string[]
50  redirects: Redirect[]
51  stdin: string
52  pipeline: number
53  stage: number
54  opaqueStdin?: boolean
55  hereStrings?: string[]
56}
57
58type Heredoc = { readonly seg: Building; readonly delim: string; readonly strip: boolean; readonly literal: boolean }
59
60/** Quoted `{`, `}` and `,` stand-ins (private-use characters), so brace expansion skips them. */
61export const mask = (text: string): string => text.replace(/[{},]/g, c => (c === '{' ? '\uE000' : c === '}' ? '\uE001' : '\uE002'))
62export const unmask = (text: string): string => text.replace(/[\uE000-\uE002]/g, c => (c === '\uE000' ? '{' : c === '\uE001' ? '}' : ','))
63
64/** Reads a `$(`, `<(` or `>(` body from just past its `(`; returns the inner text and the index of the closing `)`. */
65function readParen(src: string, from: number): { inner: string; end: number } {
66  let depth = 1
67  let quote: string | undefined
68  for (let i = from; i < src.length; i++) {
69    const c = src[i] as string
70    if (quote !== undefined) {
71      if (c === '\\' && quote === '"') i++
72      else if (c === quote) quote = undefined
73      continue
74    }
75    if (c === '\\') i++
76    else if (c === "'" || c === '"') quote = c
77    else if (c === '(') depth++
78    else if (c === ')' && --depth === 0) return { inner: src.slice(from, i), end: i }
79  }
80  return { inner: src.slice(from), end: src.length }
81}
82
83/** Reads a backtick body from just past the opening backtick. */
84function readBacktick(src: string, from: number): { inner: string; end: number } {
85  for (let i = from; i < src.length; i++) {
86    if (src[i] === '\\') i++
87    else if (src[i] === '`') return { inner: src.slice(from, i), end: i }
88  }
89  return { inner: src.slice(from), end: src.length }
90}
91
92const SIMPLE_ESCAPES: Readonly<Record<string, string>> = { n: '\n', t: '\t', r: '\r', a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' }
93
94/** Reads `$'...'` from just past its opening quote, decoding escapes as bash does; returns the text and the closing quote's index. */
95export function readAnsiC(src: string, from: number): { text: string; end: number } {
96  let text = ''
97  let j = from
98  for (; j < src.length && src[j] !== "'"; j++) {
99    if (src[j] !== '\\' || j + 1 >= src.length) {
100      text += src[j]
101      continue
102    }
103    const e = src[j + 1] as string
104    const hex = e === 'x' ? /^[0-9a-fA-F]{1,2}/.exec(src.slice(j + 2, j + 4)) : e === 'u' || e === 'U' ? /^[0-9a-fA-F]{1,8}/.exec(src.slice(j + 2, j + (e === 'u' ? 6 : 10))) : null
105    const oct = /^[0-7]{1,3}/.exec(src.slice(j + 1, j + 4))
106    if (hex !== null) {
107      text += String.fromCodePoint(Math.min(parseInt(hex[0], 16), 0x10ffff))
108      j += 1 + hex[0].length
109    } else if (oct !== null) {
110      text += String.fromCharCode(parseInt(oct[0], 8) & 0xff)
111      j += oct[0].length
112    } else if (e === 'c' && j + 2 < src.length) {
113      text += String.fromCharCode((src.charCodeAt(j + 2) & 0x1f) >>> 0)
114      j += 2
115    } else {
116      text += SIMPLE_ESCAPES[e] ?? `\\${e}`
117      j++
118    }
119  }
120  return { text, end: j }
121}
122
123/** The command substitutions (`$(...)`, backticks) inside text the shell expands, such as an unquoted heredoc body. */
124export function substitutions(text: string): string[] {
125  const out: string[] = []
126  for (let i = 0; i < text.length; i++) {
127    if (text[i] === '$' && text[i + 1] === '(') {
128      const r = readParen(text, i + 2)
129      out.push(r.inner)
130      i = r.end
131    } else if (text[i] === '`') {
132      const r = readBacktick(text, i + 1)
133      out.push(r.inner)
134      i = r.end
135    }
136  }
137  return out
138}
139
140const REDIRECT = /&>>|&>|>>|>\||>&|>|<<<|<<-|<<|<>|<&|</y
141const FD_DUP = /\s*[\d-]+/y
142/** Characters with no meaning to the reader, read as one run. */
143const PLAIN = /[^ \t\n'"\\$`;&|()<>]+/y
144
145/** Reads a command line into its simple commands, in the order they run (substitutions first). */
146export function parse(src: string, depth = 0): Segment[] {
147  /** What runs, in order: a substitution's commands before the command that holds it. */
148  const order: Array<Building | Segment> = []
149  let pipeline = 0
150  let seg: Building = { words: [], expandable: [], redirects: [], stdin: '', pipeline, stage: 0 }
151  let word = ''
152  /** The word again, quoted braces masked. */
153  let ex = ''
154  const plain = (t: string) => {
155    word += t
156    ex += t
157  }
158  const quoted = (t: string) => {
159    word += t
160    ex += t.length === 1 ? (t === '{' ? '\uE000' : t === '}' ? '\uE001' : t === ',' ? '\uE002' : t) : mask(t)
161  }
162  let started = false
163  let wasQuoted = false
164  let pendingOp: string | undefined
165  const heredocs: Heredoc[] = []
166
167  const nested = (inner: string) => {
168    if (depth < MAX_NESTING) order.push(...parse(inner, depth + 1))
169    else order.push({ words: [], expandable: [], redirects: [], stdin: '', piped: false, upstream: '', stages: [], dropped: inner })
170  }
171  const endWord = () => {
172    if (!started) return
173    if (pendingOp === '<<' || pendingOp === '<<-') heredocs.push({ seg, delim: word, strip: pendingOp === '<<-', literal: wasQuoted })
174    else if (pendingOp === '<<<') {
175      seg.stdin += `${word}\n`
176      seg.hereStrings = [...(seg.hereStrings ?? []), word]
177    }
178    else if (pendingOp !== undefined) seg.redirects.push({ op: pendingOp, target: word })
179    else {
180      seg.words.push(word)
181      seg.expandable.push(ex)
182    }
183    pendingOp = undefined
184    word = ''
185    ex = ''
186    started = false
187    wasQuoted = false
188  }
189  const endSegment = (pipe: boolean) => {
190    endWord()
191    pendingOp = undefined
192    if (seg.words.length > 0 || seg.redirects.length > 0 || heredocs.some(h => h.seg === seg)) order.push(seg)
193    const stage = pipe ? seg.stage + 1 : 0
194    if (!pipe) pipeline++
195    seg = { words: [], expandable: [], redirects: [], stdin: '', pipeline, stage }
196  }
197  const readHeredocs = (from: number): number => {
198    let i = from
199    while (heredocs.length > 0) {
200      const h = heredocs.shift() as Heredoc
201      const body: string[] = []
202      let closed = false
203      while (i < src.length) {
204        const nl = src.indexOf('\n', i)
205        const line = src.slice(i, nl === -1 ? src.length : nl)
206        i = nl === -1 ? src.length : nl + 1
207        if ((h.strip ? line.replace(/^\t+/, '') : line) === h.delim) {
208          closed = true
209          break
210        }
211        body.push(line)
212      }
213      if (!closed) h.seg.opaqueStdin = true
214      const text = body.join('\n')
215      h.seg.stdin += `${text}\n`
216      if (!h.literal) for (const s of substitutions(text)) nested(s)
217    }
218    return i
219  }
220
221  let quote: '"' | "'" | undefined
222  for (let i = 0; i < src.length; i++) {
223    const c = src[i] as string
224    const next = src[i + 1]
225    if (quote === "'") {
226      const close = src.indexOf("'", i)
227      const end = close === -1 ? src.length : close
228      quoted(src.slice(i, end))
229      if (close !== -1) quote = undefined
230      i = end
231      continue
232    }
233    if (quote === '"') {
234      if (c === '"') quote = undefined
235      else if (c === '\\' && next !== undefined && '$`"\\\n'.includes(next)) {
236        if (next !== '\n') quoted(next)
237        i++
238      } else if (c === '$' && next === '(') {
239        const r = readParen(src, i + 2)
240        nested(r.inner)
241        quoted(src.slice(i, r.end + 1))
242        i = r.end
243      } else if (c === '`') {
244        const r = readBacktick(src, i + 1)
245        nested(r.inner)
246        quoted(src.slice(i, r.end + 1))
247        i = r.end
248      } else quoted(c)
249      continue
250    }
251    if (c === ' ' || c === '\t') endWord()
252    else if (c === '\n') {
253      endSegment(false)
254      i = readHeredocs(i + 1) - 1
255    } else if (c === '#' && !started) {
256      const nl = src.indexOf('\n', i)
257      i = (nl === -1 ? src.length : nl) - 1
258    } else if (c === "'" || c === '"') {
259      quote = c
260      started = true
261      wasQuoted = true
262    } else if (c === '$' && next === '"') {
263      // `$"..."` (locale translation) reads as `"..."`.
264      quote = '"'
265      started = true
266      wasQuoted = true
267      i++
268    } else if (c === '$' && next === "'") {
269      // ANSI-C quoting: decoded as bash does (`$'\x2eagentic-qe'` is `.agentic-qe`).
270      const r = readAnsiC(src, i + 2)
271      quoted(r.text)
272      started = true
273      wasQuoted = true
274      i = r.end
275    } else if ((c === '$' || ((c === '<' || c === '>') && !started)) && next === '(') {
276      const r = readParen(src, i + 2)
277      nested(r.inner)
278      plain(src.slice(i, r.end + 1))
279      started = true
280      i = r.end
281    } else if (c === '`') {
282      const r = readBacktick(src, i + 1)
283      nested(r.inner)
284      plain(src.slice(i, r.end + 1))
285      started = true
286      i = r.end
287    } else if (c === '\\') {
288      if (next === '\n') i++
289      else if (next !== undefined) {
290        quoted(next)
291        started = true
292        i++
293      }
294    } else if (c === ';') {
295      if (next === ';' || next === '&') i++
296      endSegment(false)
297    } else if (c === '&' && next === '&') {
298      endSegment(false)
299      i++
300    } else if (c === '|' && next === '|') {
301      endSegment(false)
302      i++
303    } else if (c === '|') {
304      if (next === '&') i++
305      endSegment(true)
306    } else if (c === '(' && started && /[@!+*?]$/.test(word)) {
307      // An extglob group (`.agentic-@(qe)`) belongs to its word.
308      const r = readParen(src, i + 1)
309      plain(src.slice(i, r.end + 1))
310      i = r.end
311    } else if (c === '(' && started && /^[A-Za-z_][A-Za-z0-9_]*\+?=$/.test(word)) {
312      // An array assignment (`arr=($(find ...))`): its elements belong to the word; their substitutions run.
313      const r = readParen(src, i + 1)
314      for (const inner of substitutions(r.inner)) nested(inner)
315      plain(src.slice(i, r.end + 1))
316      i = r.end
317    } else if (c === '(' || c === ')') endSegment(false)
318    else if (c === '>' || c === '<' || (c === '&' && next === '>')) {
319      REDIRECT.lastIndex = i
320      const op = (REDIRECT.exec(src) as RegExpExecArray)[0]
321      // A numeric word right before is the fd (`2>`), not an argument.
322      if (started && !wasQuoted && /^\d+$/.test(word)) {
323        word = ''
324        ex = ''
325        started = false
326      } else endWord()
327      i += op.length - 1
328      FD_DUP.lastIndex = i + 1
329      const dup = op === '>&' || op === '<&' ? FD_DUP.exec(src) : null
330      if (dup !== null) i += dup[0].length
331      else pendingOp = op === '>&' ? '>' : op
332    } else if (c === '&') endSegment(false)
333    else {
334      // A run of ordinary characters at once.
335      PLAIN.lastIndex = i
336      const run = PLAIN.exec(src)
337      plain(run === null ? c : run[0])
338      if (run !== null) i += run[0].length - 1
339      started = true
340    }
341  }
342  endSegment(false)
343  readHeredocs(src.length)
344
345  // Each pipeline's stages in order; a stage reads the (at most FEED) stages right before it.
346  const byPipeline = new Map<number, Building[]>()
347  return order.map(o => {
348    if (!('pipeline' in o)) return o
349    const list = byPipeline.get(o.pipeline) ?? []
350    if (list.length === 0) byPipeline.set(o.pipeline, list)
351    list.push(o)
352    return new Stage(o, list, list.length - 1)
353  })
354}
355
356/** A simple command as `parse` hands it back; what feeds it is built on first read (most commands never look). */
357class Stage implements Segment {
358  readonly words: readonly string[]
359  readonly expandable: readonly string[]
360  readonly redirects: readonly Redirect[]
361  readonly piped: boolean
362  readonly opaqueStdin: boolean
363  readonly hereStrings: readonly string[]
364  private readonly built: Building
365  private readonly pipeline: readonly Building[]
366  private readonly at: number
367  private cachedUpstream: string | undefined
368  private cachedStages: (readonly string[])[] | undefined
369
370  constructor(built: Building, pipeline: readonly Building[], at: number) {
371    this.built = built
372    this.words = built.words
373    this.expandable = built.expandable
374    this.redirects = built.redirects
375    this.piped = built.stage > 0
376    this.opaqueStdin = built.opaqueStdin === true
377    this.hereStrings = built.hereStrings ?? []
378    this.pipeline = pipeline
379    this.at = at
380  }
381
382  private feeders(): Building[] {
383    return this.at === 0 ? [] : this.pipeline.slice(Math.max(0, this.at - FEED), this.at)
384  }
385
386  get stages(): readonly (readonly string[])[] {
387    this.cachedStages ??= this.feeders().map(u => u.words)
388    return this.cachedStages
389  }
390
391  /** Heredoc bodies arrive after the command line, so stdin is read from the builder. */
392  get stdin(): string {
393    return this.built.stdin
394  }
395
396  get upstream(): string {
397    this.cachedUpstream ??= this.feeders().map(u => `${u.words.join(' ')}\n${u.stdin}`).join('\n')
398    return this.cachedUpstream
399  }
400}
401
402/** Splits a command line into the text of its simple commands (words joined by spaces). */
403export const segments = (command: string): string[] => parse(command).map(s => s.words.join(' '))
404
405/** Words of one command line, as the commands see them. */
406export const words = (command: string): string[] => parse(command).flatMap(s => [...s.words])
407
408/** Shell keywords and grouping words that come before a command word (`then rm x`, `! rm x`, `{ rm x; }`). */
409export const KEYWORDS = new Set(['!', '{', '}', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'fi', 'done', 'esac'])
410/** Commands that take a command after them (their own options skipped). */
411export const WRAPPERS = new Set([
412  'sudo', 'doas', 'env', 'command', 'exec', 'nohup', 'time', 'nice', 'ionice', 'stdbuf', 'builtin', 'xargs', 'timeout', 'chronic', 'unbuffer',
413  'npx', 'bunx', 'pnpx', 'watch', 'noglob', 'nocorrect', 'caffeinate', 'busybox', 'parallel', 'shx', 'wsl',
414])
415/** Package runners whose `exec`/`dlx`/`x` subcommand runs the command after it (`pnpm exec rimraf`). */
416const RUNNERS = /^(pnpm|yarn|npm|bun)$/
417const RUNNER_SUBCOMMANDS = /^(exec|dlx|x)$/
418/** Wrapper options that take a separate value (`sudo -u root rm ...`). */
419const VALUED = new Set(['-u', '-g', '-C', '-D', '-h', '-p', '-U', '-r', '-t', '-n', '-I', '-L', '-P', '-s', '-k', '--signal', '--kill-after', '--user', '--group', '--package', '--interval', '-j', '--jobs', '-d', '--distribution', '--cd'])
420
421export const isOption = (w: string): boolean => w.startsWith('-') && w !== '-'
422
423/**
424 * The command word's index, past assignments, keywords, `function NAME`,
425 * wrappers and their options. `isVerb` says whether a word is a command the
426 * guard judges, so a valued-looking flag does not swallow it (`sudo -n rm x`).
427 */
428export function commandStart(ws: readonly string[], isVerb: (w: string) => boolean, from = 0): number {
429  let i = from
430  while (i < ws.length) {
431    const w = ws[i] as string
432    const name = w.replace(/^.*\//, '')
433    if (/^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(w) || KEYWORDS.has(w)) i++
434    else if (w === 'function') i += 2
435    // `coproc NAME { cmd; }` names the coprocess; `coproc cmd args` does not.
436    else if (w === 'coproc') i += ws[i + 2] === '{' || ws[i + 2] === '(' ? 2 : 1
437    else if (WRAPPERS.has(name) || (RUNNERS.test(name) && RUNNER_SUBCOMMANDS.test(ws[i + 1] ?? ''))) {
438      i += WRAPPERS.has(name) ? 1 : 2
439      while (i < ws.length && (isOption(ws[i] as string) || /^\d+(\.\d+)?[smhd]?$/.test(ws[i] as string))) {
440        const after = ws[i + 1]
441        i += VALUED.has(ws[i] as string) && after !== undefined && !isVerb(after) ? 2 : 1
442      }
443    } else return i
444  }
445  return i
446}
447
hooks/verbs.ts 167 lines
1/**
2 * The guard's rules for one simple shell command, by its command word.
3 * Pure: no `$`. Nested shell text (`bash -c`, `eval`, heredocs) goes back
4 * through `ctx.bash`, so every rule applies at any depth.
5 */
6import { isVerb, SHELLS, verbName } from './commands'
7import { expandVars, expandWords, isData, isDataFileOrGlob, textNamesData, WORD_BUDGET, type Ctx } from './context'
8import { judgeFind } from './find'
9import { hasGlob, MAX_PATH, underAqe } from './paths'
10import { fedByProducer, opaqueScript } from './producers'
11import { INTERPRETER, judgeInterpreter, judgeSqlite } from './scripts'
12import { commandStart, expandBraces, isOption, type Segment } from './shell'
13import { judgeGit, judgeWriters } from './writers'
14
15export { isVerb } from './commands'
16
17const WRITE_OPS = new Set(['>', '>>', '>|', '&>', '&>>', '<>'])
18/** Commands that read names (or a script) from stdin: a feed matters to them. */
19const FEED_CONSUMERS = /(^|\/)(xargs|parallel|read|mapfile|readarray|bash|sh|zsh|dash|ksh|fish|eval)$/
20
21/**
22 * `cd`/`pushd`: entering `.agentic-qe` makes bare `memory.db` the store; leaving it does the
23 * opposite. A target the guard cannot resolve (`cd "$DIR"`, `cd $(dirname ...)`) may be it.
24 */
25function changeDir(targets: readonly string[], ctx: Ctx): void {
26  const target = targets[0]
27  if (targets.some(t => underAqe(t) || (hasGlob(t) && t !== '-'))) ctx.inAqe = true
28  else if (target === undefined || target === '~' || target === '-' || target.startsWith('/') || target.startsWith('~')) ctx.inAqe = false
29  else if (target === '..' || target.startsWith('../')) ctx.inAqe = false
30}
31
32/** A value as it is remembered: one too long to be a path reads as `*`, so values cannot grow without bound. */
33const remembered = (v: string): string => (v.length > MAX_PATH ? '*' : v)
34
35/** A word as the shell expands it here (variables, arrays, substitutions). */
36const expanded = (w: string, ctx: Ctx): string[] => expandVars(w, ctx.vars, WORD_BUDGET, inner => ctx.subst(inner, ctx))
37
38/**
39 * What may reach this command's stdin that names the store: the expanded words of earlier
40 * pipeline stages (`echo "$dbs" | xargs rm`), a producer that lists it (`find ... | xargs rm`),
41 * here-strings (`<<< "$(find ...)"`), and a `< <(...)` on the line.
42 */
43function feedValues(seg: Segment, ctx: Ctx): string[] {
44  const out: string[] = []
45  if (seg.piped) {
46    for (const stage of seg.stages) for (const w of stage) out.push(...expanded(w, ctx).filter(v => isData(v, ctx)))
47    if (fedByProducer(seg, ctx)) out.push('.agentic-qe/memory.db', '.agentic-qe')
48  }
49  for (const w of seg.hereStrings ?? []) out.push(...expanded(w, ctx).filter(v => isData(v, ctx)))
50  return out
51}
52
53/** `NAME=value` words before the command word, and `for NAME in ...`, `read NAME`: remembered for `$NAME`. */
54function bindVars(ws: readonly string[], start: number, seg: Segment, ctx: Ctx): void {
55  // An assignment's word may have expanded to several alternatives (`DB=$(ls ...)`): the variable may hold any of them.
56  // An array (`arr=(a $(find ...))`) holds each of its elements; `NAME+=...` adds to what NAME held.
57  const assigned = new Map<string, string[]>()
58  for (const w of ws.slice(0, start)) {
59    const m = /^([A-Za-z_][A-Za-z0-9_]*)(\+?)=(.*)$/s.exec(w)
60    if (m === null) continue
61    const name = m[1] as string
62    const value = m[3] as string
63    const array = /^\(([\s\S]*)\)$/.exec(value)
64    // Elements keep their quotes inside the word (`files+=("$f")`): unquote each one.
65    const values = array === null ? [value] : (array[1] as string).split(/\s+/).filter(v => v !== '').map(v => v.replace(/^(['"])([\s\S]*)\1$/, '$2'))
66    const before = assigned.get(name) ?? (m[2] === '+' ? [...(ctx.vars.get(name) ?? [])] : [])
67    // `arr+=(x)` adds elements; `s+=x` extends the string (`P=.agentic; P+=-qe`).
68    const added = array !== null || m[2] !== '+' || before.length === 0 ? [...before, ...values] : before.map(b => b + value)
69    assigned.set(name, added.map(remembered))
70  }
71  for (const [name, values] of assigned) ctx.vars.set(name, [...new Set(values)])
72  const verb = ws[start]
73  if (verb === 'export' || verb === 'local' || verb === 'declare' || verb === 'readonly' || verb === 'typeset') bindVars(ws.slice(start + 1), ws.length - start - 1, seg, ctx)
74  if ((verb === 'for' || verb === 'select') && ws[start + 2] === 'in') ctx.vars.set(ws[start + 1] as string, ws.slice(start + 3).flatMap(w => expandBraces(w)).map(remembered))
75  // `read f`, `mapfile -t arr`, `readarray arr` hold whatever is fed in: unknown (`*`), plus the store when the feed may be it.
76  if (verb === 'mapfile' || verb === 'readarray' || verb === 'read') {
77    const fed = [...new Set([...feedValues(seg, ctx), ...(ctx.readFed ?? []), '*'])]
78    // Options that take a value differ: `mapfile -t` is a flag, `read -t 5` a timeout.
79    const valued = verb === 'read' ? /^-[dnNptui]$/ : /^-[dnOsuCc]$/
80    const names = ws.slice(start + 1).filter((w, i, all) => !isOption(w) && !valued.test(all[i - 1] ?? ''))
81    if (verb === 'read') for (const name of names) ctx.vars.set(name, fed)
82    else ctx.vars.set(names[names.length - 1] ?? 'MAPFILE', fed)
83  }
84}
85
86/** The raw (unexpanded) word after a shell's `-c` flag, or the words after `eval`. */
87function rawScripts(seg: Segment): readonly string[] {
88  const at = commandStart(seg.words, isVerb)
89  const rest = seg.words.slice(at + 1)
90  if (verbName(seg.words[at] ?? '') === 'eval') return rest
91  const c = rest.findIndex(a => /^-[A-Za-z]*c[A-Za-z]*$/.test(a))
92  return c === -1 ? [] : rest.slice(c + 1, c + 2)
93}
94
95/** `bash -c CMD`, `bash -lc CMD`, `sh -ec CMD`, `eval ...`, `bash <<EOF`, `... | sh`. */
96function judgeShell(verb: string, args: readonly string[], seg: Segment, ctx: Ctx, viaXargs: boolean): string | undefined {
97  // A script that is wholly an unknown expansion (`bash -c "$(... | base64 -d)"`, `eval "$CMD"`) cannot be read: refuse.
98  if (rawScripts(seg).some(w => opaqueScript(w, ctx))) return `\`${verb}\` runs a script the guard cannot read`
99  if (verb === 'eval') return ctx.bash(args.join(' '), ctx)
100  let command: string | undefined
101  for (let i = 0; i < args.length; i++) {
102    const a = args[i] as string
103    if (/^[-+][oO]$/.test(a)) i++
104    else if (/^-[A-Za-z]*c[A-Za-z]*$/.test(a)) {
105      command = args.slice(i + 1).find(x => !isOption(x)) ?? ''
106      break
107    } else if (!isOption(a)) break
108  }
109  if (command !== undefined) {
110    if (viaXargs && ctx.mentionsData) return `\`xargs ${verb} -c\` fed learning-data paths`
111    // The script as written: prefix assignments (`D=.agentic-qe bash -c 'rm -rf $D'`) are bound by now,
112    // so the inner judge expands `$D` itself; the outer expansion read it as unknown.
113    return ctx.bash(rawScripts(seg)[0] ?? command, ctx)
114  }
115  // A heredoc the guard cannot see the end of is a script it cannot read.
116  if (seg.opaqueStdin) return `\`${verb}\` reads a script the guard cannot see`
117  if (seg.stdin !== '') {
118    const what = ctx.bash(seg.stdin, ctx)
119    if (what !== undefined) return what
120  }
121  if (seg.piped && seg.upstream.split(/\s+/).some(w => isData(w, ctx))) return `a script piped into \`${verb}\` names learning data`
122  return undefined
123}
124
125/** One simple command's refusal, or undefined. */
126export function judgeSegment(seg: Segment, ctx: Ctx, viaXargs = false): string | undefined {
127  // Text nested past what the reader follows is not judged piecemeal: it is refused when it names learning data.
128  if (seg.dropped !== undefined) return /agentic/i.test(seg.dropped) || textNamesData(seg.dropped, ctx) ? 'a command nested too deeply to read names learning data' : undefined
129  // What a pipe, producer or here-string feeds in counts as named here (`xargs rm`, `while read f`).
130  // Only commands that take names on stdin need it, so most pipeline stages skip the work.
131  const consumes = seg.words.some(w => FEED_CONSUMERS.test(w))
132  if (consumes && (seg.piped || (seg.hereStrings ?? []).length > 0) && feedValues(seg, ctx).length > 0) ctx.mentionsData = true
133  const ws = expandWords(seg, ctx)
134  const start = commandStart(ws, isVerb)
135  bindVars(ws, start, seg, ctx)
136
137  const redirect = seg.redirects.find(r => WRITE_OPS.has(r.op) && isDataFileOrGlob(r.target, ctx))
138  if (redirect !== undefined) return `a shell redirect overwrites ${redirect.target}`
139  if (start >= ws.length) return undefined
140
141  const verb = verbName(ws[start] as string)
142  const args = ws.slice(start + 1)
143  const piped = viaXargs || ws.slice(0, start).some(w => verbName(w) === 'xargs' || verbName(w) === 'parallel')
144
145  if (verb === 'cd' || verb === 'pushd') {
146    changeDir(args.filter(a => !isOption(a)), ctx)
147    return undefined
148  }
149  if (SHELLS.has(verb) || verb === 'eval') return judgeShell(verb, args, seg, ctx, piped)
150  // `pwsh -c ...` / `powershell -Command ...` from a shell: the PowerShell rules read it.
151  if (/^(pwsh|powershell)(\.exe)?$/i.test(verb)) {
152    const c = args.findIndex(a => /^-(c|command|encodedcommand|ec|e)$/i.test(a))
153    if (c === -1) return seg.opaqueStdin || seg.piped ? `\`${verb}\` reads a script the guard cannot see` : undefined
154    if (/^-(encodedcommand|ec|e)$/i.test(args[c] as string)) return `\`${verb} -EncodedCommand\` runs a script the guard cannot read`
155    return ctx.pwsh(args.slice(c + 1).join(' '), ctx)
156  }
157  if (verb === 'su') {
158    const c = args.findIndex(a => a === '-c' || a === '--command')
159    return c === -1 ? undefined : ctx.bash(args[c + 1] ?? '', ctx)
160  }
161  if (verb === 'sqlite3' || verb === 'sqlite') return judgeSqlite(args, seg, ctx)
162  if (INTERPRETER.test(verb)) return judgeInterpreter(verb, args, seg, ctx)
163  if (verb === 'find') return judgeFind(args, ctx)
164  if (verb === 'git') return judgeGit(args, ctx)
165  return judgeWriters(verb, args, ctx, piped)
166}
167
hooks/version.ts 4 lines
1// Generated by scripts/sync-plugin-versions.cjs from package.json (the npm `version` hook). Do not edit.
2/** The mod's own version: the plugin's version (the console shows it when it matches ^[0-9][0-9A-Za-z.+-]{0,15}$). */
3export const MOD_VERSION = '3.15.14'
4