SLOPSHOPPER

workflows

One loop — work — for work worth doing properly: clarify, an approved plan that is the run's only authority, delegated implementation, independent verification…

bandguardcommandstatusprocesstimer
★ 25v6.57.0no licenseupdated 2026-10-23edwinhu/workflows
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · workflows
› 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) ⎿ Denied by workflows: 🛑 `bun test` runs the whole repo in one serial process. Run multi-file bun suites in ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /farm ⎿ workflows: No farm or work runs in this session. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Workflows

A curated collection of development, data science, writing, workshop, legal, and research workflows for Claude Code.

Requires Claude Code 2.1.287 or later. The tool-call guards and bulk-guard run only as a mod, and mods load from 2.1.287. The plugin manifest has no field for a minimum Claude Code version, so on an older version the SessionStart hook prints a warning that the guards are inactive.

Quick Start

# 1. Install the plugin
/plugin marketplace add edwinhu/workflows

# 2. Install dependencies — per-skill node packages (bun), plus the optional CLIs for
#    knowledge management, email, and calendar
bash ~/.claude/plugins/cache/edwinhu-plugins/workflows/*/bin/install-deps.sh

# 3. (Optional) Live marimo kernel work — only needed by the `marimo` skill
claude plugin marketplace add marimo-team/marimo-pair
claude plugin install marimo-pair@marimo-pair

marimo-pair is a separate upstream plugin, deliberately not declared as a hard dependency: an uninstalled dependency stops the whole plugin from loading, and one skill should not be able to take the other sixty with it. The marimo skill routes live-kernel work to Skill(skill="marimo-pair:marimo-pair") and works for notebook authoring without it.

The script's first step runs bun install in every skill that ships a package.json — cite-check, deep-research and farm-out at the time of writing, each with its own lockfile. node_modules/ is gitignored and never shipped, so a fresh clone or a fresh plugin install has no node dependencies until this runs, and those skills' own test suites cannot even resolve their imports before it. The rest of the script is only needed for skills that use the external tools below. The plugin's own TypeScript hooks and JavaScript/TypeScript workflow runners use Bun; the core workflows do not require the optional CLIs installed by this script.

The script recognizes macOS, Linux, and Windows-like environments on x64 or arm64 and attempts to download matching pre-built binaries from GitHub Releases. If a tool does not publish an asset for the detected platform, the script warns and skips it:

ToolPurposeUsed by
nlmNotebookLM CLIlibrarian agent, internal nlm skill
readwise-customReadwise RAG/chat/uploadlibrarian agent, internal readwise-chat skill
scholarGoogle Scholar searchlibrarian agent, internal google-scholar skill
consensusAcademic paper searchlibrarian agent, internal consensus skill
morgenCalendar & tasksDirect Bash, or session in ~/areas/assistant/
superhumanEmailemail-handling skill (via Bash)

Requires gh (GitHub CLI). Tools already on your $PATH are skipped.


User Commands

These are the skills you invoke directly with /name:

Core Workflows

/work is the spine: clarify with the user, draft a plan they edit and approve, self-set a goal, run workflow.js to implement and independently verify, then put the result in front of a human in tuicr. Human rejection routes back to CLARIFY. The domain workflows dispatch through it and add their own computed gate.

WorkflowAdds to the work loop
/worknothing — the generic loop for any task worth doing properly
/devTDD discipline: a failing test before the change, and lens reviews for security, performance and test coverage
/dsa computed data-quality gate (DQ1-DQ6, M1, R1) over the panel the run builds
/writinga computed plan-grammar and citation gate, plus the domain style register the plan's Domain: selects
/workshopa computed deck gate over the Typst slides and speaker notes built from a paper
/workflow-creatordesigns, repairs and audits workflows themselves

Plan review is computed and happens before dispatch: plan-lint.ts over the built args and plan-preflight.ts executing their commands at baseline, enforced by work-dispatch.sh while the run is still armed. No agent reads the plan markdown looking for defects.

Document Formats

Part of the document skill group — one pipeline (extract → create → repair → build → render → verify) bundling the Anthropic Office skills with this project's repair/build/render tooling.

SkillPurpose
/docxWord document creation, editing, tracked changes
/pdfPDF extraction, creation, form filling
/pptxPresentation creation and editing
/xlsxSpreadsheet creation and analysis
/docx-renderFaithful Word export to PDF/PNG
/law-review-docxMarkdown/legal draft → law-review-styled Word doc
/law-econ-docxMarkdown law-and-economics manuscript → author-date, journal-ready Word doc

Office format skills sourced from anthropics/skills via git submodule. Shared converters + the Google-export OOXML package repair (scripts/docx_repair.py) live in scripts/. See references/document-skills.md for the full group and how the stages decouple.

Data

SkillPurpose
/ds-tablesPublication tables in Python — pyfixest.etable() regression tables and great_tables GT formatting
/ds-figuresPublication-ready, accessible figures for papers, slides, and notebooks
/crsp-lseg-spliceExtend stale CRSP stock panels with current LSEG data
/npx-ownership-panelBuild the WRDS proxy-voting × ownership panel
/fuzzy-name-matchingEntity resolution / record linkage by name — char n-gram TF-IDF + sparse_dot_topn top-k cosine, normalize-first, scoped + global two-pass

Writing, Research & Citation

SkillPurpose
/cite-checkVerify academic citations against source PDFs
/de-ai-reviseRevise flagged prose to remove corpus-validated AI writing tics

Meta

SkillPurpose
/skill-creatorSkill creation with superpowers enforcement patterns
/plugin-creatorPlugin-level creation and editing across manifests, hooks, and skills
/workflow-creatorCreate a new structured workflow through shared-v1
/workflow-creator-improveAudit, repair, redesign, or migrate an existing workflow

Auto-Invoked and Internal Skills

These skills have user-invocable: false — Claude loads them automatically when relevant or a workflow dispatches them internally. You don't call them directly.

Legal & Citation

bluebook, bluebook-audit, docx-repair, source-verify

Data Access

wrds, lseg-data, gemini-vertex

Knowledge Management

nlm, google-scholar, readwise, readwise-chat, readwise-search, readwise-docs, readwise-prune

Research

consensus, research

Notebook Tools

marimo, jupytext, notebook-debug

Utilities

farm-out, look-at, visual-verify, visual-mockup, data-context, continuous-learning, pattern-capture, ai-anti-patterns, obsidian-organize, pptx-render, headline-card

farm-out is the dispatcher work runs its agents through — work-dispatch.sh uses the sibling copy by default, so the plugin dispatches without an outside install. It fetches its own SDK on first run.

Internal Workflow Phases

None. The work spine has no sub-skills: the phases are beats inside skills/work/workflow.js, dispatched as agents, so there is nothing to invoke by name and nothing to keep in sync.


Agents

Specialized subagents. The directory states the scope: agents/ is auto-discovered by Claude Code and registers plugin-scoped (workflows:<name>), while user-agents/ is not auto-discovered and registers user-scoped (bare name, hooks: honoured) via a symlink into ~/.claude/agents/:

AgentRoleScopeHooks
librarianKnowledge management orchestration (NLM, Readwise, Scholar, Workspace)plugin—
dsEmpirical implementer — datasets, tables, figures, numbers; C/V/A/E constraints arrive as task refsuser—
ds-reviewerRead-only grading of existing empirical work against C/V/A/E constraintsuser—
workshopTalk implementer — Typst deck and speaker notes from a paper; preloads typst:typstuser—
workshop-reviewerRead-only grading of slides.typ and notes.typ against the canonical Typst modulesuser—
writingGeneral long-form prose — memos, letters, briefs, reportsusersource-first PreToolUse guard
writing-legalLaw review prose — footnotes, Bluebook short formsusersource-first PreToolUse guard
writing-econFinance and accounting journal proseusersource-first PreToolUse guard
writing-reviewerRead-only prose grading against the preloaded register and the tic tableuser—

The work spine's per-beat verifiers are still dispatched from skills/work/workflow.js with the prompt the run needs, so no agent file exists for them. Implementers are the exception: /ds, /writing and /workshop each set implementerAgentType to the matching agent above, and the teaching plugin sets it to its own lecture-impl. /dev and /workflow-creator deliberately leave it unset.

Why subagents

Claude Code's system prompt tells the model what kind of work it is doing. Its # Doing tasks section opens with "The user will primarily request you to perform software engineering tasks", and instructs that an unclear instruction be read in that context. A separate # Tone and style section asks for short, concise responses and file_path:line_number references. Neither is wrong for code. Both are wrong for a law review article, a lecture, or a seminar deck, where the deliverable is long and the reader is a person rather than a terminal.

An output style can remove the first of those and cannot remove the second. Setting a style drops # Doing tasks entirely unless the style's frontmatter sets keep-coding-instructions: true; # Tone and style is emitted unconditionally. So a custom style does not replace the framing — it competes with what survives, and the surviving half is precisely the half that shortens prose and formats references for an editor.

A subagent replaces the prompt instead of arguing with it. A custom subagent's body is its entire system prompt: Anthropic's documentation says a subagent receives that prompt plus environment details, not the full Claude Code system prompt, and claude --agent <name> applies the same to a main session. Asking one confirms it — it reports neither the software-engineering sentence nor a # Tone and style section at all. That is the whole reason this plugin routes prose, decks, teaching material and empirical work through agents rather than tuning a style.

The directory split follows from a second quirk. A hooks: block in agent frontmatter is ignored for plugin-shipped agents and honoured for user-scoped ones, so any agent that needs a blocking guard has to be user-scoped. user-agents/ is not a discovery location, so a symlink into ~/.claude/agents/ registers each file user-scoped under its bare name with its hooks live, while agents/ stays auto-discovered and plugin-scoped. It is one file either way, and the plugin still ships both.

Judging is not writing, and the roster's shape follows from that. A review lens only reads, so the built-in Explore plus a good prompt and the right reference paths is sufficient and cheaper; an agent earns a file only when it needs a custom prompt, hooks, or preloaded skills. The three domain reviewers exist because grading against a constraint set needs a body this repo controls — a built-in judge's prompt is predefined, so the modules it grades against have to reach it as task refs rather than as anything the lens can skip — and no exam reviewer exists because a prompt covers it. Constraint prose itself is never a skill: it has one canonical home under constraints/ (Typst rule texts under ~/.claude/skills/typst/rules/, checkers under constraints/), reaches dispatched agents as refs, and reaches interactive ones through the typst:typst bang line. The same test explains the two workflows that set no implementer override: /dev and /workflow-creator produce code and workflow definitions, where the software-engineering framing is correct rather than a defect.

The register skills — writing-general, writing-legal, writing-econ, ai-anti-patterns — are user-invocable: false for the same reason. Loading a register into the main chat stacks it on top of the framing it is meant to displace; routing the work to an agent that preloads it replaces that prompt instead. They deliberately do not set disable-model-invocation: true, which would break both the skills: preload and the Skill tool path a persona session needs.


Workflow lifecycle architecture

Every workflow runs the same loop, in skills/work/workflow.js. The plan's <!-- work:dispatch --> block is the sole authority and its canonical specHash is verified by each dispatched agent; the gate is computed in JS from raw counts, fails closed on a dead agent, and returns the selector that drives the fix loop. A domain workflow contributes its own mechanical checks and review lenses — it does not get its own lifecycle.

Hooks

Hooks auto-run at specific lifecycle events. The table has one row per command target registered in hooks/hooks.json:

ScriptEventTriggerPurpose
session-start.tsSessionStartstartup/resume/clear/compactInject using-skills meta-skill; report an unfinished work run
session-end.tsStop*Update LEARNINGS.md timestamp
lint-check.tsPostToolUseEdit/WriteLint after file changes (ESLint, ruff, lintr)
writing-prose-check.tsPostToolUseEdit/WriteCheck edited prose for writing-quality violations
cite-fidelity-lint.tsPostToolUseEdit/WriteCheck edited writing for citation-ledger fidelity
pr-url-logger.tsPostToolUseBashLog PR URLs and GitHub Actions status
pattern-scan.tsSessionEndclear/logout/prompt_input_exit/otherScan session for reusable patterns

Tool-call guards (mod)

The per-call guards run in-process on tool.call in the plugin's mod (hooks/guards/mod.ts), not as spawned settings hooks. Each can only deny or add context, never approve. The scripts of the same name under hooks/ stay as their settings-hook entry points (skills wire some in frontmatter) and share the code; tests/mod-guards-parity.test.ts holds the two to identical answers.

GuardBefore / afterToolsPurpose
image-read-guardbeforeReadRedirect to look-at for media files
read-guardbeforeRead, BashDeny unbounded dumps of large files
suggest-compactbeforeEdit, WriteSuggest compaction at edit-count checkpoints
pgrep-self-matchbeforeBash, MonitorDeny self-matching pgrep/pkill -f and path-less rg
bun-parallel-guardbeforeBashDeny a multi-file bun test without --parallel
cron-delete-guardbefore / afterCronDelete / CronCreateKeep an in-flight work run's heartbeat; record new ids
atomic-constraint-guardafterEdit, WriteValidate atomic constraint file structure
typst-convention-guardafterEdit, WriteTypst convention violations
validate-skill-pathsafterEdit, Write${CLAUDE_*} references to missing files

Bulk-extraction guard (mod)

hooks/bulk-guard.mjs is a Claude Code mod (2.1.287+), listed under "modules" in hooks/hooks.json. It runs in every session that loads the plugin, farm-out children included. It enforces the rule that per-document coding or extraction over many files is ONE gemini-vertex job on pre-cut excerpts. On tool.call it does the following:

RuleToolsAction
Distinct documents read (≥20 KB; .txt .htm .html .xml .sgml .pdf .nc, or a path containing filings/archives/edgar/raw/prospect), via Read or a Bash dump (cat, head, tail, sed -n, less, pdftotext, strings, python/awk one-liners). Rereads do not countRead, Bashnote at 5, deny at 10
farm.sh / farm-team.sh / work-dispatch.sh --tasks with ≥5 rows near-identical to row 0 after masking paths, numbers, CIKs and accessions (similarity ≥0.8)Bashdeny
A for/while/xargs loop that runs claude -p, codex exec, gemini or agy -p per itemBashdeny
A model API call inside a loop (/v1/messages, Anthropic/OpenAI SDK, generateContent outside a batch flow). batches.create, batchPredictionJobs and request-JSONL writing are allowed; an Edit only trips the rule if it introduces the patternBash; Write/Edit of .py .ts .js .shdeny
A Read, Bash or Grep result over 20K tokens (chars/4)Read, Bash, Grepfull output saved under $XDG_RUNTIME_DIR/bulk-guard/; the model sees head 6K + tail 2K

Every threshold has an env override: BULK_GUARD_WARN_DOCS, _DENY_DOCS, _DOC_BYTES, _FANOUT_ROWS, _SIMILARITY, _TRIM_TOKENS, _HEAD_TOKENS, _TAIL_TOKENS. BULK_GUARD_OFF=1 in the user's environment disables the guard, and any command that sets it is denied. Each warn, deny and trim is appended to $XDG_RUNTIME_DIR/bulk-guard/events.jsonl, and the prompt band shows docs read N/10 · trimmed K results.


Session Continuity

A work run keeps two records, one owner each: the approved plan at .claude/plans/<slug>.md is the run's authority and the file work hashes in place, and .work/<run-id>/ holds the args, the verdict JSON and the plan bytes each round actually ran under. Project auto-memory retains reusable facts; project directories retain real inputs and deliverables.

For cross-session task persistence, set CLAUDE_CODE_TASK_LIST_ID in .envrc:

export CLAUDE_CODE_TASK_LIST_ID="my-project"

Repository Structure

workflows/
├── .claude-plugin/             # Plugin manifest
│   ├── plugin.json             # Version and metadata
│   └── marketplace.json        # Marketplace listing
├── agents/                     # Plugin-scoped subagents (auto-discovered)
├── user-agents/                # User-scoped subagents (symlinked into ~/.claude/agents/)
├── skills/                     # User-facing and internal skills
│   ├── work/                   # The spine: workflow.js, plan-lint, dispatch, gate
│   ├── dev/, ds/, writing/, workshop/, workflow-creator/  # Domain workflows
│   ├── farm-out/               # The dispatcher the `work` skill farms agents out through
│   ├── docx, pdf, pptx, xlsx  # Document formats (symlinks)
│   └── ...                     # Internal phases and auto-invoked skills
├── bin/                        # Optional dependency installer
├── docs/                       # Architecture and investigation records
├── hooks/                      # Hook scripts
│   ├── hooks.json              # Hook configuration
│   └── *.ts                    # Hook implementations run with Bun
├── references/                 # Shared constraint and reference docs
├── scripts/                    # Compilers, checks, renderers, and support tools
├── tests/                      # Contract and regression tests
├── workflows/                  # Shared and domain workflow runners
│   ├── lib/                    # Runner libraries and task contracts
│   └── templates/              # Dynamic workflow templates
├── external/
│   └── anthropic-skills/       # Git submodule for document skills
└── PHILOSOPHY.md               # Workflow design philosophy

Key Points:

  • skills/ contains both user-facing and internal phase skills (auto-discovered; internal skills use user-invocable: false)
  • agents/ contains plugin-scoped subagents, auto-discovered by Claude Code as workflows:<name>
  • user-agents/ contains user-scoped subagents; they reach Claude Code only through the symlink into ~/.claude/agents/ that ~/dotfiles/scripts/setup-claude-symlinks.sh creates
  • hooks/ contains TypeScript hook entry points called directly by hooks.json
  • workflows/ contains the shared runner plus writing, workshop, and workflow-creator adapters
  • scripts/ contains deterministic compilers, validation checks, renderers, and support tools
  • references/ contains shared constraint and enforcement docs

Updating External Skills

The office format skills come from Anthropic's official skills repo. To update:

git submodule update --remote external/anthropic-skills

Acknowledgments

This project was heavily inspired by obra/superpowers, particularly:

  • The SessionStart hook pattern for injecting meta-skills
  • The "using-skills" approach that teaches HOW to use skills rather than listing WHAT skills exist
  • The philosophy that skills should be invoked on-demand, not dumped into every session

Office format skills (docx, pdf, pptx, xlsx) are from anthropics/skills.

License

MIT

Author

Edwin Hu

Source 21 files
hooks/register.ts 20 lines
1// The plugin's one hooks module: hooks.json `modules` takes a single path per plugin, so each mod
2// exports a registrar and this file calls them in order.
3import type { Register } from 'claude-code'
4import { register as registerBulkGuard } from './bulk-guard.mjs'
5import { registerGuards } from './guards/mod.ts'
6import { registerJevForecast } from './jev/forecast-mod.ts'
7import { registerJevEdit } from './jev/mod.ts'
8import { registerWatcher } from './watch/watcher.ts'
9
10export const register: Register = (on) => {
11  // First, so outermost: its AbovePrompt band stacks on bulk-guard's rather than being hidden by it.
12  registerJevForecast(on)
13  registerBulkGuard(on)
14  registerWatcher(on)
15  // Above the guards: an edit they deny never reaches it.
16  registerJevEdit(on)
17  // Last, so innermost: the guards sit where the hooks.json settings hooks they replace ran.
18  registerGuards(on)
19}
20
hooks/bulk-guard.mjs 570 lines
1// bulk-guard: a Claude Code mod that stops per-document work at scale from billing Claude/Codex
2// accounts. Per-document coding or extraction over many files goes to Gemini via gemini-vertex
3// (Flex for ≤10 documents, ONE Batch job beyond), never an agent fan-out or an agent-written
4// model-API script.
5//
6// Rules (docs/bulk-guard.md): 1 distinct-document tripwire, 2 template fan-out (rows that name a
7// document or pdftotext, or kind bulk) and per-item agent loops, 3 model-API calls inside a loop,
8// plus trimming of oversized Read/Bash/Grep results.
9// No .catch handlers on purpose: a hook that throws is skipped (fail open). A heuristic guard must
10// never cost the user Bash because of its own bug.
11
12// ── thresholds: each overridable by the env var named beside it ──────────────────────────────
13const DEFAULTS = {
14  warnDocs: 5, //            BULK_GUARD_WARN_DOCS
15  denyDocs: 10, //           BULK_GUARD_DENY_DOCS
16  docMinBytes: 20480, //     BULK_GUARD_DOC_BYTES
17  fanoutRows: 5, //          BULK_GUARD_FANOUT_ROWS
18  fanoutSimilarity: 0.8, //  BULK_GUARD_SIMILARITY
19  trimTokens: 20000, //      BULK_GUARD_TRIM_TOKENS
20  headTokens: 6000, //       BULK_GUARD_HEAD_TOKENS
21  tailTokens: 2000, //       BULK_GUARD_TAIL_TOKENS
22};
23
24export const DENY_MESSAGE =
25  "Per-document reading at scale: route this through Gemini (Skill workflows:gemini-vertex) — ≤10 documents: one Cloud Flex call each; more: ONE Cloud Batch job on pre-cut excerpts (cost gate applies). Reading more filings here bills Claude/Codex accounts per document. Override only if the user sets BULK_GUARD_OFF=1.";
26export const WARN_NOTE =
27  "bulk-guard: this session has now read {n} distinct documents one by one. If the task is per-document coding or extraction, stop and route it through Skill workflows:gemini-vertex — ≤10 documents: Cloud Flex, one call each; more: ONE Cloud Batch job on pre-cut excerpts. At {deny} documents further reads are denied.";
28export const OFF_MESSAGE =
29  "bulk-guard: BULK_GUARD_OFF is the user's override, set in their environment before the session starts; a command may not set it.";
30
31const DOC_EXT = /\.(txt|htm|html|xml|sgml|pdf|nc)$/i;
32const DOC_DIR = /(^|[\/_.-])(filings|archives|edgar|raw|prospect)/i;
33const READ_VERB = /^(cat|head|tail|less|more|pdftotext|strings|bat|zcat)$/;
34const SCRIPT_VERB = /^(python3?|awk|gawk|mawk|perl)$/;
35const SCRIPT_EXT = /\.(py|ts|js|mjs|cjs|sh|bash)$/i;
36const FANOUT_SCRIPT = /(^|\/)(farm|farm-team|work-dispatch)\.sh$/;
37
38// ── config ───────────────────────────────────────────────────────────────────────────────────
39// $.env.get needs a string literal per name, so each override is spelled out.
40let configPromise;
41async function loadConfig($) {
42  const num = (v, d) => (v !== undefined && v !== "" && Number.isFinite(Number(v)) ? Number(v) : d);
43  const [off, w, d, b, r, s, t, h, tl, xdg] = await Promise.all([
44    $.env.get("BULK_GUARD_OFF"),
45    $.env.get("BULK_GUARD_WARN_DOCS"),
46    $.env.get("BULK_GUARD_DENY_DOCS"),
47    $.env.get("BULK_GUARD_DOC_BYTES"),
48    $.env.get("BULK_GUARD_FANOUT_ROWS"),
49    $.env.get("BULK_GUARD_SIMILARITY"),
50    $.env.get("BULK_GUARD_TRIM_TOKENS"),
51    $.env.get("BULK_GUARD_HEAD_TOKENS"),
52    $.env.get("BULK_GUARD_TAIL_TOKENS"),
53    $.env.get("XDG_RUNTIME_DIR"),
54  ]);
55  return {
56    off: off !== undefined && off !== "" && off !== "0",
57    warnDocs: num(w, DEFAULTS.warnDocs),
58    denyDocs: num(d, DEFAULTS.denyDocs),
59    docMinBytes: num(b, DEFAULTS.docMinBytes),
60    fanoutRows: num(r, DEFAULTS.fanoutRows),
61    fanoutSimilarity: num(s, DEFAULTS.fanoutSimilarity),
62    trimTokens: num(t, DEFAULTS.trimTokens),
63    headTokens: num(h, DEFAULTS.headTokens),
64    tailTokens: num(tl, DEFAULTS.tailTokens),
65    dir: `${xdg || "/tmp"}/bulk-guard`,
66  };
67}
68// Read once per load: the model cannot change the engine's environment mid-session.
69const config = ($) => (configPromise ??= loadConfig($));
70
71// ── per-session state (subagents share their parent's count) ──────────────────────────────────
72const sessions = new Map();
73async function stateFor($) {
74  const id = await $.session.id();
75  if (!sessions.has(id)) sessions.set(id, { id, docs: new Set(), warned: false, trimmed: 0 });
76  return sessions.get(id);
77}
78
79// ── shell parsing ────────────────────────────────────────────────────────────────────────────
80/** Quote-aware split of a shell command into segments (on ; & | newline) of words. */
81export function shellSegments(cmd) {
82  const segs = [];
83  let words = [];
84  let cur = "";
85  let had = false;
86  let q = null;
87  const endWord = () => {
88    if (had) words.push(cur);
89    cur = "";
90    had = false;
91  };
92  const endSeg = () => {
93    endWord();
94    if (words.length) segs.push(words);
95    words = [];
96  };
97  for (let i = 0; i < cmd.length; i++) {
98    const c = cmd[i];
99    if (q) {
100      if (c === q) q = null;
101      else if (c === "\\" && q === '"' && i + 1 < cmd.length) cur += cmd[++i];
102      else cur += c;
103      continue;
104    }
105    if (c === "'" || c === '"') {
106      q = c;
107      had = true;
108    } else if (c === "\\" && i + 1 < cmd.length) {
109      cur += cmd[++i];
110      had = true;
111    } else if (c === ";" || c === "&" || c === "|" || c === "\n" || c === "(" || c === ")" || c === "`") {
112      endSeg();
113    } else if (c === " " || c === "\t") {
114      endWord();
115    } else {
116      cur += c;
117      had = true;
118    }
119  }
120  endSeg();
121  return segs;
122}
123
124/** The command word of a segment: skips env assignments and wrappers like sudo/xargs/do/then. */
125function commandWord(seg) {
126  let i = 0;
127  while (i < seg.length) {
128    const w = seg[i];
129    if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) || /^(sudo|env|nice|time|command|exec|do|then|else|xargs|nohup)$/.test(w)) {
130      i++;
131      while (i < seg.length && seg[i - 1] === "xargs" && seg[i].startsWith("-")) i++;
132      continue;
133    }
134    if (seg[i - 1] === "xargs" || (i > 0 && /^-/.test(w) && seg[i - 1] && /^xargs$/.test(seg[i - 1]))) {
135      i++;
136      continue;
137    }
138    return { word: w.replace(/^.*\//, ""), full: w, rest: seg.slice(i + 1) };
139  }
140  return null;
141}
142
143const literals = (s) => [...s.matchAll(/["']([^"'\n]{1,400})["']/g)].map((m) => m[1]);
144
145/**
146 * Paths and globs a Bash command reads with a reader verb or a script one-liner.
147 * Redirect targets (> file) are writes and do not count.
148 */
149export function readerCandidates(cmd) {
150  const segs = shellSegments(cmd);
151  const out = new Set();
152  let reads = false;
153  let scripts = false;
154  for (const seg of segs) {
155    const cw = commandWord(seg);
156    if (!cw) continue;
157    const isRead = READ_VERB.test(cw.word) || (cw.word === "sed" && cw.rest.some((w) => /^-[a-zA-Z]*n/.test(w)));
158    const isScript = SCRIPT_VERB.test(cw.word);
159    if (!isRead && !isScript) continue;
160    reads ||= isRead;
161    scripts ||= isScript;
162    for (let i = 0; i < cw.rest.length; i++) {
163      const w = cw.rest[i];
164      if (/^>>?$/.test(w) || /^\d?>/.test(w)) {
165        i++;
166        continue;
167      }
168      if (w.startsWith("-")) continue;
169      out.add(w);
170      if (isScript) for (const l of literals(w)) out.add(l);
171    }
172  }
173  if (scripts) for (const l of literals(cmd)) out.add(l); // heredoc bodies and -c code
174  if (reads || scripts) {
175    // for f in a/*.txt b.txt; do head "$f"; done — the list feeds the reader
176    for (const m of cmd.matchAll(/\bfor\s+\w+\s+in\s+([^;\n]*?)\s*(;|\n)\s*do\b/g)) {
177      for (const seg of shellSegments(m[1])) for (const w of seg) out.add(w);
178    }
179  }
180  return [...out].filter((p) => p && !p.includes("$") && !/^\d+$/.test(p) && /[\/.]/.test(p));
181}
182
183/** A path is a document candidate by its name; size is checked separately. */
184export const looksLikeDocument = (p) => DOC_EXT.test(p) || DOC_DIR.test(p);
185
186const AGENT_CALL =
187  /(^|[\s;&|(`"'])((\S*\/)?claude\s+([^\n;|&]*\s)?(-p|--print)\b|(\S*\/)?codex\s+exec\b|(\S*\/)?gemini(\s|$|["'])|(\S*\/)?agy\s+([^\n;|&]*\s)?-p\b|(\S*\/)?(farm|farm-team|work-dispatch)\.sh\b)/;
188
189/** Loop bodies of a shell command: for/while/until … do … done, xargs/parallel args, find -exec. */
190export function shellLoopBodies(cmd) {
191  const bodies = [];
192  for (const m of cmd.matchAll(/\b(for|while|until)\b[\s\S]*?\bdo\b([\s\S]*?)\bdone\b/g)) bodies.push(m[2]);
193  for (const m of cmd.matchAll(/\b(xargs|parallel)\b([^|;\n]*)/g)) bodies.push(" " + m[2]);
194  for (const m of cmd.matchAll(/\s-exec(dir)?\s([^;\n]*?)(\\;|\+)/g)) bodies.push(" " + m[2]);
195  return bodies;
196}
197
198/** Rule 2b: a loop that starts a model agent once per item. */
199export const agentLoop = (cmd) => shellLoopBodies(cmd).some((b) => AGENT_CALL.test(b));
200
201// ── rule 3: model API inside a loop ─────────────────────────────────────────────────────────
202const PROVIDER =
203  /\/v1\/messages|ANTHROPIC_BASE_URL|\banthropic\.|Anthropic\(|\bopenai\.|OpenAI\(|chat\.completions|generateContent|generate_content|\bgenai\b|google\.genai|GoogleGenAI|\/v1\/chat\/completions|api\.openai\.com|api\.anthropic\.com/;
204const CALL =
205  /\/v1\/messages|\/v1\/chat\/completions|messages\.create\(|messages\.stream\(|completions\.create\(|responses\.create\(|generateContent|generate_content\b|generate_content_stream|models\.generate|ANTHROPIC_BASE_URL.*(curl|fetch|requests|post)|(curl|fetch|requests\.post|httpx\.post).*(api\.anthropic\.com|api\.openai\.com|generativelanguage|aiplatform)/;
206const GENAI_GENERATE = /generateContent|generate_content|models\.generate/;
207const BATCH_FLOW = /batches\.create|batchPredictionJobs|batch_prediction|BatchPredictionJob|batches\.create_embeddings/;
208const RETRY_HEADER = /range\(\s*\d{1,2}\s*\)|attempt|retr(y|ies)|backoff|while\s+True\b|while\s*\(\s*true\s*\)|tries/i;
209const JSONL_WRITE = /["']url["']\s*:|["']method["']\s*:|json\.dumps|JSON\.stringify|\.write\(|writelines|jsonl/i;
210
211const indentOf = (l) => l.match(/^\s*/)[0].replace(/\t/g, "    ").length;
212
213/** Python: the loop headers enclosing line i (by indentation), plus same-line comprehensions. */
214function pyEnclosing(lines, i) {
215  const loops = [];
216  let fn = null;
217  if (/\bfor\s+\S.*\bin\b/.test(lines[i])) loops.push(lines[i]);
218  let ind = indentOf(lines[i]);
219  for (let j = i - 1; j >= 0 && ind > 0; j--) {
220    const l = lines[j];
221    if (!l.trim() || l.trim().startsWith("#")) continue;
222    const k = indentOf(l);
223    if (k < ind) {
224      ind = k;
225      if (/^\s*(async\s+)?(for|while)\b/.test(l)) loops.push(l);
226      const d = l.match(/^\s*(async\s+)?def\s+(\w+)/);
227      if (d && !fn) fn = d[2];
228    }
229  }
230  return { loops, fn };
231}
232
233/** JS/TS: the lines opening the braces that enclose line i, and the enclosing function's name. */
234function jsEnclosing(lines, i) {
235  const loops = [];
236  let fn = null;
237  if (/\bfor\s*\(|\.(map|forEach|flatMap)\(/.test(lines[i])) loops.push(lines[i]);
238  let depth = 0;
239  for (let j = i - 1; j >= 0; j--) {
240    const l = lines[j];
241    for (let c = l.length - 1; c >= 0; c--) {
242      if (l[c] === "}") depth++;
243      else if (l[c] === "{") {
244        if (depth === 0) {
245          if (/\b(for|while)\s*\(|\bfor\s+await\b|\.(map|forEach|flatMap)\(/.test(l)) loops.push(l);
246          const d = l.match(/function\s*\*?\s*(\w+)|(?:const|let|var)\s+(\w+)\s*=|^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*\{/);
247          if (d && !fn) fn = d[1] || d[2] || d[3];
248        } else depth--;
249      }
250    }
251  }
252  return { loops, fn };
253}
254
255const dataLoop = (headers) => headers.some((h) => !RETRY_HEADER.test(h));
256
257function inLoop(lines, i, lang, depth = 0) {
258  const { loops, fn } = (lang === "py" ? pyEnclosing : jsEnclosing)(lines, i);
259  if (dataLoop(loops)) return true;
260  if (!fn || depth >= 2) return false;
261  // indirection: the enclosing function is mapped over items or called inside a loop
262  const name = fn.replace(/[$]/g, "\\$");
263  const mapped = new RegExp(`\\b(map|imap|imap_unordered|starmap|submit|apply_async|run_in_executor|gather)\\([^)]*\\b${name}\\b|\\.(map|forEach|flatMap)\\(\\s*${name}\\b`);
264  const call = new RegExp(`\\b${name}\\s*\\(`);
265  for (let j = 0; j < lines.length; j++) {
266    if (j === i) continue;
267    const l = lines[j];
268    if (mapped.test(l)) return true;
269    if (call.test(l) && !/^\s*(async\s+)?(def|function)\b/.test(l) && inLoop(lines, j, lang, depth + 1)) return true;
270  }
271  return false;
272}
273
274/**
275 * Rule 3. True when `text` calls a model API inside a loop over items. `lang` is py, js or sh
276 * (a Bash command is checked as sh and as py, so heredoc'd scripts are covered).
277 */
278export function apiInLoop(text, lang) {
279  if (!PROVIDER.test(text) && !CALL.test(text)) return false;
280  const batch = BATCH_FLOW.test(text);
281  const isCall = (l) => CALL.test(l) && !/batch/i.test(l) && !JSONL_WRITE.test(l) && !(batch && GENAI_GENERATE.test(l));
282  if (lang === "sh") return shellLoopBodies(text).some((b) => b.split("\n").some(isCall));
283  const lines = text.split("\n");
284  for (let i = 0; i < lines.length; i++) {
285    if (/^\s*(#|\/\/|\*)/.test(lines[i])) continue;
286    if (isCall(lines[i]) && inLoop(lines, i, lang)) return true;
287  }
288  return false;
289}
290
291export const langOf = (path) =>
292  /\.py$/i.test(path) ? "py" : /\.(sh|bash)$/i.test(path) ? "sh" : SCRIPT_EXT.test(path) ? "js" : null;
293
294// ── rule 2: template fan-out ─────────────────────────────────────────────────────────────────
295/** Mask what varies per item in a templated prompt: paths, accession numbers, CIKs, numbers. */
296export function maskPrompt(s) {
297  return s
298    .replace(/\b\d{10}-\d{2}-\d{6}\b/g, " ACC ")
299    .replace(/(~|\.{0,2})?\/?[\w.~-]+(\/[\w.~@%+-]+)+\/?/g, " PATH ")
300    .replace(/\b[\w-]+\.(txt|htm|html|xml|sgml|pdf|nc|json|csv|md|py|typ|bib)\b/gi, " FILE ")
301    .replace(/\bCIK\s*[:#]?\s*\d+/gi, " CIK ")
302    .replace(/\d+([.,]\d+)*/g, " N ");
303}
304
305const tokens = (s) => s.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean);
306
307function levenshtein(a, b) {
308  if (a === b) return 0;
309  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
310  for (let i = 1; i <= a.length; i++) {
311    const cur = [i];
312    for (let j = 1; j <= b.length; j++)
313      cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
314    prev = cur;
315  }
316  return prev[b.length];
317}
318
319/** Similarity of two masked prompts: the larger of token Jaccard and normalised Levenshtein. */
320export function similarity(a, b) {
321  const ta = new Set(tokens(a));
322  const tb = new Set(tokens(b));
323  let inter = 0;
324  for (const t of ta) if (tb.has(t)) inter++;
325  const union = ta.size + tb.size - inter;
326  const jac = union ? inter / union : 1;
327  // Levenshtein is quadratic; only for short prompts, where a token set is too coarse.
328  const lev = a.length <= 1500 && b.length <= 1500 ? 1 - levenshtein(a, b) / Math.max(a.length, b.length, 1) : 0;
329  return Math.max(jac, lev);
330}
331
332const rowText = (r) => (typeof r?.prompt === "string" ? r.prompt : JSON.stringify(r));
333
334// Only pdftotext counts as a read verb: cat/head/sed appear in ordinary code and audit prompts, so
335// they would deny any templated fan-out; pdftotext only ever means "extract text from a document".
336const EXTRACT_VERB = /\bpdftotext\b/;
337
338/** A templated row counts when it is kind "bulk" or its text (shared or varying) names a document or extracts one. */
339function namesDocument(row) {
340  if (row?.kind === "bulk") return true;
341  const text = rowText(row);
342  if (EXTRACT_VERB.test(text)) return true;
343  return text.split(/[\s"'`()<>,;]+/).some((w) => looksLikeDocument(w.replace(/[.:]+$/, "")));
344}
345
346/** Document-naming rows (row 0 included) that are near-identical to the row-0 template after masking. */
347export function templateRows(rows, threshold) {
348  if (!Array.isArray(rows) || rows.length < 2) return rows?.length ?? 0;
349  const t0 = maskPrompt(rowText(rows[0]));
350  let n = 0;
351  for (let i = 0; i < rows.length; i++)
352    if ((i === 0 || similarity(t0, maskPrompt(rowText(rows[i]))) >= threshold) && namesDocument(rows[i])) n++;
353  return n;
354}
355
356/** The --tasks files of farm.sh / farm-team.sh / work-dispatch.sh calls in a Bash command. */
357export function fanoutTaskFiles(cmd) {
358  const files = [];
359  for (const seg of shellSegments(cmd)) {
360    if (!seg.some((w) => FANOUT_SCRIPT.test(w))) continue;
361    for (let i = 0; i < seg.length; i++) {
362      if (seg[i] === "--tasks" && seg[i + 1]) files.push(seg[i + 1]);
363      else if (seg[i].startsWith("--tasks=")) files.push(seg[i].slice(8));
364    }
365  }
366  return files;
367}
368
369export const setsOverride = (cmd) => /\bBULK_GUARD_OFF\s*=|\bexport\s+BULK_GUARD_OFF\b|\bunset\s+BULK_GUARD_OFF\b/.test(cmd);
370
371// ── result trimming ──────────────────────────────────────────────────────────────────────────
372export const estTokens = (s) => Math.ceil(s.length / 4);
373
374/** Head + marker + tail, or null when `text` is under the limit. */
375export function trimText(text, cfg, path) {
376  const n = estTokens(text);
377  if (n <= cfg.trimTokens) return null;
378  let head = text.slice(0, cfg.headTokens * 4);
379  let tail = text.slice(text.length - cfg.tailTokens * 4);
380  const hb = head.lastIndexOf("\n");
381  if (hb > head.length * 0.9) head = head.slice(0, hb + 1);
382  const tb = tail.indexOf("\n");
383  if (tb >= 0 && tb < tail.length * 0.1) tail = tail.slice(tb + 1);
384  const cut = n - estTokens(head) - estTokens(tail);
385  return { text: `${head}\n[bulk-guard: trimmed ${cut} tokens; full output at ${path}]\n${tail}`, cut };
386}
387
388// ── side effects ─────────────────────────────────────────────────────────────────────────────
389async function logEvent($, cfg, rec) {
390  const line = JSON.stringify({ ts: new Date().toISOString(), session: (await $.session.id()) ?? null, ...rec });
391  try {
392    // >> append is atomic per line across the sessions and children sharing the file
393    await $.process.run(["sh", "-c", 'mkdir -p "$1" && printf "%s\\n" "$2" >> "$1/events.jsonl"', "sh", cfg.dir, line]);
394  } catch {
395    /* the log is visibility, never a gate */
396  }
397}
398
399function redraw($) {
400  try {
401    $.ui.invalidate("ui.render");
402  } catch {
403    /* headless */
404  }
405}
406
407async function absolute($, p) {
408  if (p.startsWith("/")) return p;
409  if (p.startsWith("~/")) return `${(await $.env.get("HOME")) ?? ""}/${p.slice(2)}`;
410  return `${await $.session.cwd()}/${p.replace(/^\.\//, "")}`;
411}
412
413const globRe = (g) =>
414  new RegExp("^" + g.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]") + "$");
415
416/** Distinct documents (absolute path ≥ docMinBytes, document-shaped name) a call would read. */
417export async function documentsRead($, cfg, candidates) {
418  const docs = new Set();
419  for (const raw of candidates) {
420    if (!looksLikeDocument(raw)) continue;
421    const p = await absolute($, raw);
422    if (/[*?]/.test(p)) {
423      const slash = p.lastIndexOf("/");
424      const dir = p.slice(0, slash) || "/";
425      if (/[*?[]/.test(dir)) continue;
426      const re = globRe(p.slice(slash + 1));
427      let entries = [];
428      try {
429        entries = await $.fs.list(dir);
430      } catch {
431        continue;
432      }
433      for (const ent of entries) {
434        if (!re.test(ent.name)) continue;
435        const full = `${dir}/${ent.name}`;
436        let size = ent.size;
437        if (ent.isLink) size = (await $.fs.stat(full, { resolve: true }).catch(() => null))?.size ?? 0;
438        else if (ent.kind !== "file") continue;
439        if (size >= cfg.docMinBytes) docs.add(full);
440      }
441      continue;
442    }
443    const st = await $.fs.stat(p, { resolve: true }).catch(() => null);
444    if (st && st.kind === "file" && st.size >= cfg.docMinBytes) docs.add(p);
445  }
446  return docs;
447}
448
449// ── the guard ────────────────────────────────────────────────────────────────────────────────
450async function deny($, cfg, rule, e, detail) {
451  await logEvent($, cfg, { kind: "deny", rule, tool: e.tool, agent: e.agentId ?? null, ...detail });
452  return { deny: rule === "override" ? OFF_MESSAGE : DENY_MESSAGE };
453}
454
455/** Rules 1-3 before the call; a deny result, or the documents this call would add. */
456async function precheck($, e, cfg, st) {
457  let candidates = [];
458  if (e.tool === "Bash") {
459    const cmd = String(e.command ?? "");
460    if (setsOverride(cmd)) return deny($, cfg, "override", e, { command: cmd.slice(0, 300) });
461    if (agentLoop(cmd)) return deny($, cfg, "agent-loop", e, { command: cmd.slice(0, 300) });
462    for (const f of fanoutTaskFiles(cmd)) {
463      let rows;
464      try {
465        rows = JSON.parse(await $.fs.read(await absolute($, f)));
466      } catch {
467        continue; // farm.sh refuses a missing or malformed file itself
468      }
469      const n = templateRows(rows, cfg.fanoutSimilarity);
470      if (n >= cfg.fanoutRows) return deny($, cfg, "template-fanout", e, { tasks: f, rows: rows.length, template_rows: n });
471    }
472    if (apiInLoop(cmd, "sh") || apiInLoop(cmd, "py") || apiInLoop(cmd, "js"))
473      return deny($, cfg, "api-in-loop", e, { command: cmd.slice(0, 300) });
474    candidates = readerCandidates(cmd);
475  } else if (e.tool === "Read") {
476    candidates = [String(e.file_path ?? "")];
477  } else if (e.tool === "Write" || e.tool === "Edit") {
478    const path = String(e.file_path ?? "");
479    const lang = langOf(path);
480    if (!lang) return { add: new Set() };
481    const old = await $.fs.read(path).catch(() => "");
482    let text = String(e.content ?? "");
483    if (e.tool === "Edit") {
484      const from = String(e.old_string ?? "");
485      const to = String(e.new_string ?? "");
486      text = from ? (e.replace_all ? old.split(from).join(to) : old.replace(from, () => to)) : to;
487    }
488    // Only a change that introduces the pattern: existing tools (pincite.py) stay editable.
489    if (apiInLoop(text, lang) && !apiInLoop(old, lang)) return deny($, cfg, "api-in-loop", e, { file: path });
490    return { add: new Set() };
491  }
492  const docs = await documentsRead($, cfg, candidates);
493  const add = new Set([...docs].filter((d) => !st.docs.has(d)));
494  if (add.size && st.docs.size + add.size >= cfg.denyDocs) {
495    return deny($, cfg, "documents", e, { read: st.docs.size, would_add: [...add].slice(0, 20) });
496  }
497  return { add };
498}
499
500async function guard($, e, next) {
501  const cfg = await config($);
502  if (cfg.off) return next(e);
503  const st = await stateFor($);
504  const pre = await precheck($, e, cfg, st);
505  if (pre.deny) return pre;
506
507  const before = st.docs.size;
508  for (const d of pre.add) st.docs.add(d);
509  const r = await next(e);
510  let out = r;
511  if (!r.deny && !r.isError && ["Read", "Bash", "Grep"].includes(e.tool)) out = await trim($, e, cfg, st, r);
512  if (st.docs.size !== before) redraw($);
513  if (!st.warned && st.docs.size >= cfg.warnDocs && before < cfg.warnDocs) {
514    st.warned = true;
515    await logEvent($, cfg, { kind: "warn", rule: "documents", tool: e.tool, read: st.docs.size });
516    const note = WARN_NOTE.replace("{n}", st.docs.size).replace("{deny}", cfg.denyDocs);
517    out = { ...out, context: [...(out.context ?? []), note] };
518  }
519  return out;
520}
521
522/** The secondary rule: Read/Bash/Grep results over trimTokens keep head + tail; the rest is saved. */
523async function trim($, e, cfg, st, r) {
524  const res = r.result;
525  let field = null;
526  if (e.tool === "Bash" && typeof res?.stdout === "string") field = ["stdout"];
527  else if (e.tool === "Read" && res?.type === "text" && typeof res.file?.content === "string") field = ["file", "content"];
528  else if (e.tool === "Grep" && typeof res?.content === "string") field = ["content"];
529  if (!field) return r;
530  const text = field.length === 1 ? res[field[0]] : res.file.content;
531  if (estTokens(text) <= cfg.trimTokens) return r;
532  const path = `${cfg.dir}/${(await $.session.id()).slice(0, 8)}-${Date.now()}-${e.tool.toLowerCase()}.txt`;
533  try {
534    await $.fs.write(path, text);
535  } catch {
536    await $.process.run(["sh", "-c", 'mkdir -p "$(dirname "$1")" && cat > "$1"', "sh", path], { stdin: text });
537  }
538  const t = trimText(text, cfg, path);
539  const result = field.length === 1 ? { ...res, [field[0]]: t.text } : { ...res, file: { ...res.file, content: t.text } };
540  st.trimmed++;
541  redraw($);
542  await logEvent($, cfg, { kind: "trim", tool: e.tool, tokens: estTokens(text), cut: t.cut, path });
543  return r.context ? { result, context: r.context } : { result };
544}
545
546export function register(on) {
547  on("tool.call", { tool: ["Read", "Bash", "Grep", "Write", "Edit"] }, guard);
548
549  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
550    const cfg = await config($);
551    const st = sessions.get(await $.session.id());
552    if (cfg.off || e.props?.hasSurvey || !st || (st.docs.size === 0 && st.trimmed === 0)) return next(e);
553    const { Box, Text } = $.ui.resolve(e);
554    const hot = st.docs.size >= cfg.warnDocs;
555    return Box({
556      paddingX: 1,
557      children: [
558        Text({ color: hot ? "yellow" : undefined, dimColor: !hot, children: `docs read ${st.docs.size}/${cfg.denyDocs}` }),
559        Text({ dimColor: true, children: ` · trimmed ${st.trimmed} results` }),
560      ],
561    });
562  });
563}
564
565/** Test seam: forget per-session state and the cached config. */
566export function _reset() {
567  sessions.clear();
568  configPromise = undefined;
569}
570
hooks/guards/mod.ts 211 lines
1// The plugin's tool-call guards as one mod: each guard that used to be a hooks.json settings hook
2// runs here in-process, on `tool.call`, over the same payload the settings hook read on stdin.
3//
4// NEVER AN APPROVAL. A guard here can only deny or add context: the handler returns `{ deny }` or
5// what `next(e)` resolved to, and it hooks no `tool.check`, the one event that can allow past an ask
6// rule. A crashed PreToolUse gate denies (as `denyOnCrash` made the script deny); a crashed
7// PostToolUse guard adds nothing (as the script's exit 1 was non-blocking).
8import type { EngineInterface, On, ToolCallResult } from 'claude-code'
9import { absolute, crashDeny, guardNow, type EnvName, type FileStat, type Guard, type GuardIO, type Payload } from './core.ts'
10import { atomicConstraintGuard } from './atomic-constraint.ts'
11import { bunParallelGuard } from './bun-test.ts'
12import { cronDeleteGuard, cronRecord } from './cron-delete.ts'
13import { imageReadGuard } from './image-read.ts'
14import { pgrepSelfMatch } from './pgrep.ts'
15import { readGuard } from './read-guard.ts'
16import { validateSkillPaths } from './skill-paths.ts'
17import { suggestCompact } from './suggest-compact.ts'
18import { typstConventionGuard } from './typst-convention.ts'
19
20type $ = EngineInterface
21
22export interface GuardSpec {
23  /** The settings-hook script this guard was, under hooks/ (its gate name for a crash deny). */
24  script: string
25  gate: string
26  event: 'PreToolUse' | 'PostToolUse'
27  /** The hooks.json matcher it had, as tool names. */
28  tools: string[]
29  guard: Guard
30}
31
32/** In hooks.json order: a call several guards match gets the first deny, contexts in this order. */
33export const GUARDS: GuardSpec[] = [
34  { script: 'image-read-guard.ts', gate: 'IMAGE READ GUARD', event: 'PreToolUse', tools: ['Read'], guard: imageReadGuard },
35  { script: 'read-guard.ts', gate: 'READ GUARD', event: 'PreToolUse', tools: ['Read', 'Bash'], guard: readGuard },
36  { script: 'suggest-compact.ts', gate: 'SUGGEST COMPACT', event: 'PreToolUse', tools: ['Edit', 'Write'], guard: suggestCompact },
37  { script: 'pgrep-self-match.ts', gate: 'PGREP GUARD', event: 'PreToolUse', tools: ['Bash', 'Monitor'], guard: pgrepSelfMatch },
38  { script: 'bun-parallel-guard.ts', gate: 'BUN PARALLEL GUARD', event: 'PreToolUse', tools: ['Bash'], guard: bunParallelGuard },
39  { script: 'cron-delete-guard.ts', gate: 'CRON DELETE GUARD', event: 'PreToolUse', tools: ['CronDelete'], guard: cronDeleteGuard },
40  { script: 'atomic-constraint-guard.ts', gate: 'ATOMIC CONSTRAINT GUARD', event: 'PostToolUse', tools: ['Edit', 'Write'], guard: atomicConstraintGuard },
41  { script: 'typst-convention-guard.ts', gate: 'TYPST CONVENTION GUARD', event: 'PostToolUse', tools: ['Edit', 'Write'], guard: typstConventionGuard },
42  { script: 'validate-skill-paths.ts', gate: 'VALIDATE SKILL PATHS', event: 'PostToolUse', tools: ['Edit', 'Write'], guard: validateSkillPaths },
43  { script: 'cron-delete-guard.ts --record', gate: 'CRON RECORD', event: 'PostToolUse', tools: ['CronCreate'], guard: cronRecord },
44]
45
46/** Every tool some guard matches. registerGuards spells it as a literal regex, which is what
47 *  `claude plugin validate` can read; tests/mod-guards-parity.test.ts holds the two equal. */
48export const TOOLS = [...new Set(GUARDS.flatMap(g => g.tools))]
49
50/** The tool.call input's reserved keys; everything else is the tool's own arguments. */
51const RESERVED = new Set(['tool', 'tool_use_id', 'consent'])
52
53/** Each variable read by its literal name: `claude plugin validate` lists them, and requires it. */
54async function readEnv($: $): Promise<Record<EnvName, string | undefined>> {
55  const [a, b, c, d, e, f, g, h, i, j] = await Promise.all([
56    $.env.get('LOOK_AT_NESTED'),
57    $.env.get('READ_GUARD_BYTES'),
58    $.env.get('COMPACT_THRESHOLD'),
59    $.env.get('COMPACT_INTERVAL'),
60    $.env.get('CLAUDE_CODE_SESSION_ID'),
61    $.env.get('TMPDIR'),
62    $.env.get('TEMP'),
63    $.env.get('TMP'),
64    $.env.get('WORK_ALLOW_CRON_DELETE'),
65    $.env.get('GUARD_NOW_MS'),
66  ])
67  return {
68    LOOK_AT_NESTED: a, READ_GUARD_BYTES: b, COMPACT_THRESHOLD: c, COMPACT_INTERVAL: d,
69    CLAUDE_CODE_SESSION_ID: e, TMPDIR: f, TEMP: g, TMP: h, WORK_ALLOW_CRON_DELETE: i, GUARD_NOW_MS: j,
70  }
71}
72
73/** GuardIO over `$`. Relative paths resolve against the session's cwd, as the scripts' did. */
74export function modIO($: $, env: Record<EnvName, string | undefined>, cwd: string, sessionId: string): GuardIO {
75  const abs = (p: string): string | null => (typeof p === 'string' && p !== '' ? absolute(cwd, p) : null)
76  const read = async (p: string): Promise<string | null> => {
77    const a = abs(p)
78    if (a === null) return null
79    try {
80      return await $.fs.read(a)
81    } catch {
82      return null
83    }
84  }
85  return {
86    env: name => env[name],
87    cwd,
88    pluginRoot: $.plugin.root,
89    // node's os.tmpdir() on POSIX: TMPDIR, TMP, TEMP, then /tmp, a trailing slash dropped.
90    osTmpdir: ((env.TMPDIR || env.TMP || env.TEMP || '/tmp').replace(/(.)\/+$/, '$1')),
91    fallbackKey: sessionId,
92    nowMs: () => guardNow(env.GUARD_NOW_MS),
93    stat: async (p): Promise<FileStat | null> => {
94      const a = abs(p)
95      if (a === null) return null
96      try {
97        const s = await $.fs.stat(a)
98        return { kind: s.kind, size: s.size, mtimeMs: s.mtimeMs }
99      } catch {
100        return null
101      }
102    },
103    read,
104    list: async p => {
105      const a = abs(p)
106      if (a === null) return null
107      try {
108        return (await $.fs.list(a)).map(e => e.name)
109      } catch {
110        return null
111      }
112    },
113    write: async (p, text) => {
114      const a = abs(p)
115      if (a === null) throw new Error(`cannot write ${String(p)}`)
116      await $.fs.write(a, text)
117    },
118    // $.fs has no append: read, then write the whole file. Only the record half appends, to a file
119    // of one id per line that this session alone writes.
120    append: async (p, text) => {
121      const a = abs(p)
122      if (a === null) throw new Error(`cannot append ${String(p)}`)
123      await $.fs.write(a, ((await read(a)) ?? '') + text)
124    },
125  }
126}
127
128/** The settings-hook payload for a tool.call event, as Claude Code would have sent it on stdin. */
129export function payloadFor(
130  e: Record<string, unknown>,
131  event: 'PreToolUse' | 'PostToolUse',
132  sessionId: string,
133  cwd: string,
134  toolResponse?: unknown,
135): Payload {
136  const toolInput: Record<string, unknown> = {}
137  for (const [k, v] of Object.entries(e)) if (!RESERVED.has(k)) toolInput[k] = v
138  const p: Payload = {
139    session_id: sessionId,
140    cwd,
141    hook_event_name: event,
142    tool_name: e.tool,
143    tool_input: toolInput,
144  }
145  if (e.tool_use_id !== undefined) p.tool_use_id = e.tool_use_id
146  if (event === 'PostToolUse') p.tool_response = toolResponse
147  return p
148}
149
150/** Run every guard of `event` matching `tool`; the first deny ends a PreToolUse round. */
151export async function runGuards(
152  specs: readonly GuardSpec[],
153  event: 'PreToolUse' | 'PostToolUse',
154  tool: string,
155  payload: Payload,
156  io: GuardIO,
157): Promise<{ deny?: string; context: string[] }> {
158  const context: string[] = []
159  for (const spec of specs) {
160    if (spec.event !== event || !spec.tools.includes(tool)) continue
161    let out
162    try {
163      out = await spec.guard(payload, io)
164    } catch (error) {
165      if (event === 'PreToolUse') return { deny: crashDeny(spec.gate, 'throw', error), context }
166      continue
167    }
168    if (event === 'PreToolUse' && out.deny !== undefined) return { deny: out.deny, context }
169    if (out.context !== undefined) context.push(out.context)
170  }
171  return { context }
172}
173
174/** `specs` narrows the set for the parity test; the plugin registers all of GUARDS. */
175export function registerGuards(on: On, specs: readonly GuardSpec[] = GUARDS): void {
176  // What next(e) settled to, per call, for the catch handler: once the tool has run, a failure
177  // after it must hand back that result, never run the call a second time.
178  const settled = new Map<string, ToolCallResult>()
179
180  on('tool.call', { tool: /^(Read|Bash|Edit|Write|Monitor|CronDelete|CronCreate)$/ }, async ($, e, next) => {
181    const [sessionId, cwd, env] = await Promise.all([$.session.id(), $.session.cwd(), readEnv($)])
182    const io = modIO($, env, cwd, sessionId)
183    const input = e as unknown as Record<string, unknown>
184
185    const pre = await runGuards(specs, 'PreToolUse', e.tool, payloadFor(input, 'PreToolUse', sessionId, cwd), io)
186    if (pre.deny !== undefined) return { deny: pre.deny }
187
188    const result = await next(e)
189    const key = String(e.tool_use_id ?? '')
190    settled.set(key, result)
191    try {
192      // PostToolUse fires only on a call that ran and succeeded; a refused call gets neither the
193      // post guards nor the pre context, which has nowhere to go.
194      if (result.deny !== undefined) return result
195      const post = result.isError
196        ? { context: [] as string[] }
197        : await runGuards(specs, 'PostToolUse', e.tool, payloadFor(input, 'PostToolUse', sessionId, cwd, result.result), io)
198      const added = [...pre.context, ...post.context]
199      return added.length ? { ...result, context: [...(result.context ?? []), ...added] } : result
200    } finally {
201      settled.delete(key)
202    }
203  }).catch(async ($, e, next) => {
204    // Before next(e): the call has not run, so a gate that could not decide denies. After: the
205    // result next(e) settled to stands.
206    const ran = settled.get(String(e.tool_use_id ?? ''))
207    if (next.called && ran) return ran
208    return { deny: crashDeny('PLUGIN GUARDS', next.error.kind, next.error.message) }
209  })
210}
211
hooks/jev/forecast-mod.ts 45 lines
1// The Jev forecast band, above the prompt: `Jev $19.77 · $3.40/day · ~6 days` (hooks/jev/forecast.ts).
2//
3//   tick     hooks/watch/watcher.ts forecastTick, every 10 min from the watcher's session.start (the
4//            engine takes ONE session.start per module; interactive sessions only, never a farm child):
5//            `openrouter-credits.ts --sample`, which reads the API only when the credit-warn cache is
6//            an hour old (never more than credit-warn's one call an hour, shared by every session),
7//            then one read of that cache, handed here through setForecastCache
8//   render   memory only, never the network or a file: yellow when under 3 days or under
9//            $OPENROUTER_LOW_BALANCE, red OUT OF CREDITS at <= $0; nothing on too few or stale samples
10//
11// Registered outermost of the AbovePrompt hooks so the band stacks on bulk-guard's instead of hiding it.
12import type { On, RenderElement } from 'claude-code'
13import { forecast, type CreditsCache } from './forecast.ts'
14
15// Set by the watcher's forecast tick (hooks/watch/watcher.ts); the engine follows `$` into no
16// function across an import, so the tick, which needs `$`, lives there and hands the parsed cache here.
17let cache: CreditsCache | null = null
18
19export function setForecastCache(c: unknown): void {
20  cache = typeof (c as CreditsCache | null)?.checkedAt === 'number' ? (c as CreditsCache) : null
21}
22
23export function registerJevForecast(on: On) {
24  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
25    const inner = await next(e)
26    if (e.props.hasSurvey) return inner
27    // credit-warn's threshold, read as scripts/lib/openrouter-credits.ts reads it
28    const raw = await $.env.get('OPENROUTER_LOW_BALANCE')
29    const t = raw ? Number(raw) : NaN
30    const v = forecast(cache, await $.clock.now(), Number.isFinite(t) ? t : 3)
31    if (!v) return inner
32    const { Box, Text } = $.ui.resolve(e)
33    const line = Box({
34      paddingX: 1,
35      children: [
36        v.level === 'ok'
37          ? Text({ dimColor: true, children: v.text })
38          : Text({ color: v.level === 'out' ? 'red' : 'yellow', bold: v.level === 'out', children: v.text }),
39      ],
40    }) as RenderElement
41    if ((inner as { type?: string } | undefined)?.type === 'engine') return line
42    return Box({ flexDirection: 'column', children: [line, inner] }) as RenderElement
43  })
44}
45
hooks/jev/mod.ts 242 lines
1// The per-edit Jev mod: after an Edit/Write/MultiEdit lands, score the file against its workflow's
2// WIRED Jev rules and add one line of context per rule at p(VIOLATED) >= 0.85, or >= 0.95 when the
3// luna fallback answered (rules.ts decisionThreshold). Advisory only.
4//
5//   workflow   hooks/jev/rules.ts ruleSetFor: exam question .typ -> exams, skill/agent/command
6//              files, manifests and .planning/ -> authoring, lecture notes -> notes and a lecture
7//              deck -> slides, a talk's slides/notes .typ (or any .typ under a `workflow: workshop`
8//              cursor) -> workshop, addenda/*.typ -> elide, other prose -> writing, tests and shell ->
9//              dev, .py under a `workflow: ds` ACTIVE_WORKFLOW.md -> ds; anything else is left alone.
10//              Writing prose under a `writing/<register>` cursor, or `style: <register>`, is that
11//              nested workflow (writing's rules plus the register's)
12//   rule set   THE LAYOUT, never a constant here: the first of rules.ts workflowsFor that
13//              bin/workflow-check <wf> --list resolves with rules (asked once per workflow per
14//              session). Teaching's workflows live in the teaching plugin; without it, its prose
15//              falls back to writing and the fallback is logged
16//   scoring    ONE $.process.run of skills/work/scripts/rule-check.ts --batch --workflow <wf>: each
17//              rules directory's evidence (uncalibrated/ is below its glob), then ONE Decisions call
18//              for all its rules through work-hold.ts decisionsCall, the plugin's one Jev transport
19//   debounce   at most one evaluation per file per 10 s. An edit inside the window is deferred to
20//              its end, and the deferred lines ride the NEXT tool result of any tool; a newer edit
21//              to the file supersedes a pending, in-flight or undelivered one
22//   where      interactive sessions; headless only with JEV_EDIT_MOD=1 (work-round.sh sets it for
23//              the implementers); JEV_EDIT_MOD=0 turns it off everywhere
24//
25// NEVER A DECISION. It calls next(e) with the input unchanged and returns what that settled to,
26// with context added or not; it never denies. Any failure adds nothing and goes to the debug log.
27import type { EngineInterface, On, ToolCallResult } from 'claude-code'
28import {
29  ancestors, changedFromInput, contextLines, enabled, merge, rangesFromDiff, ruleSetFor, workflowOf, workflowsFor, dirname,
30  type Range, type RuleSet, type Verdict,
31} from './rules.ts'
32
33type $ = EngineInterface
34
35export const WINDOW_MS = 10_000
36const RUN_TIMEOUT_MS = 20_000
37const JEV_MAX_SECONDS = '15'
38
39interface FileState {
40  lastStart: number
41  gen: number
42  pending: Range[]
43  timer?: { cancel: () => void }
44}
45
46// Debounce state per file, and deferred lines per file awaiting the next tool result. Module state,
47// lost on reload by design: a reload forgets the windows and the undelivered lines.
48const files = new Map<string, FileState>()
49const deferred = new Map<string, string[]>()
50
51const log = ($: $, text: string) => $.ui.log(`jev-edit: ${text}`, { to: 'debug' })
52
53function absolute(cwd: string, p: string): string {
54  return p.startsWith('/') ? p : `${cwd.replace(/\/+$/, '')}/${p}`
55}
56
57function shown(cwd: string, file: string): string {
58  const root = cwd.replace(/\/+$/, '') + '/'
59  return file.startsWith(root) ? file.slice(root.length) : file
60}
61
62/** The nearest `.planning/ACTIVE_WORKFLOW.md` text at or above `dir`, up to $HOME. */
63async function cursorAt($: $, dir: string): Promise<string | null> {
64  const home = (await $.env.get('HOME')) || '/'
65  for (const d of ancestors(dir, home)) {
66    try {
67      return await $.fs.read(`${d === '/' ? '' : d}/.planning/ACTIVE_WORKFLOW.md`)
68    } catch {
69      continue
70    }
71  }
72  return null
73}
74
75async function workflowAt($: $, dir: string): Promise<string | null> {
76  const text = await cursorAt($, dir)
77  return text === null ? null : workflowOf(text)
78}
79
80/** Whether `wf` has rules in the layout (bin/workflow-check <wf> --list), asked once per session. */
81const layout = new Map<string, Promise<boolean>>()
82function hasRules($: $, wf: string): Promise<boolean> {
83  let known = layout.get(wf)
84  if (!known) {
85    known = (async () => {
86      const r = await $.process.run(['python3', `${$.plugin.root}/bin/workflow-check`, wf, '--list'], { timeoutMs: RUN_TIMEOUT_MS })
87      if (r.exitCode !== 0) return false
88      try {
89        const dirs = JSON.parse(r.stdout).ruleDirs
90        return Array.isArray(dirs) && dirs.length > 0
91      } catch {
92        return false
93      }
94    })().catch(() => (layout.delete(wf), false))
95    layout.set(wf, known)
96  }
97  return known
98}
99
100/** The set an edit belongs to, and the workflow whose rules score it. */
101interface Target {
102  set: RuleSet
103  workflow: string
104}
105
106/** The first of workflowsFor the layout has rules for; null when none has (nothing to score). */
107async function targetFor($: $, set: RuleSet, file: string): Promise<Target | null> {
108  const tried = workflowsFor(set, file, await cursorAt($, dirname(file)))
109  for (const workflow of tried) {
110    if (!(await hasRules($, workflow))) continue
111    if (workflow !== tried[0]) log($, `no rules for workflow ${tried[0]} in the layout: ${set} scored as ${workflow}`)
112    return { set, workflow }
113  }
114  log($, `${file}: no workflow of ${tried.join(', ')} has rules in the layout; not scored`)
115  return null
116}
117
118async function changedLines($: $, tool: string, input: Record<string, unknown>, file: string): Promise<Range[]> {
119  let text = ''
120  try {
121    text = await $.fs.read(file)
122  } catch {}
123  const fromInput = changedFromInput(tool, input, text)
124  if (fromInput) return fromInput
125  const d = await $.process.run(['git', '-C', dirname(file), 'diff', '--no-color', '-U0', 'HEAD', '--', file], { timeoutMs: 5000 })
126  const fromGit = d.exitCode === 0 ? rangesFromDiff(d.stdout) : []
127  return fromGit.length ? fromGit : [[1, Math.max(1, text.split('\n').length)]]
128}
129
130/** The context lines for one evaluation; [] when nothing reaches the bar or anything failed. */
131async function evaluate($: $, { set, workflow }: Target, file: string, ranges: Range[], cwd: string): Promise<string[]> {
132  // the spend log's caller tag (scripts/jev-spend.ts); `env` because the tag is all this run changes
133  const argv = [
134    'env', 'JEV_CALLER=jev-edit',
135    'bun', `${$.plugin.root}/skills/work/scripts/rule-check.ts`, '--batch',
136    '--workflow', workflow, '--files', file,
137    '--changed-lines', '-', '--max-time', JEV_MAX_SECONDS,
138  ]
139  const started = await $.clock.now()
140  let run: Awaited<ReturnType<$['process']['run']>>
141  try {
142    run = await $.process.run(argv, { stdin: JSON.stringify({ [file]: ranges }), timeoutMs: RUN_TIMEOUT_MS, cwd: dirname(file) })
143  } catch (err) {
144    log($, `${file}: rule-check did not finish (${String(err)})`)
145    return []
146  }
147  let out: { verdicts?: Verdict[]; unavailable?: { rule: string; reason: string }[] }
148  try {
149    out = JSON.parse(run.stdout)
150  } catch {
151    log($, `${file}: rule-check exit ${run.exitCode}, no JSON: ${run.stderr.slice(0, 300)}`)
152    return []
153  }
154  const ms = (await $.clock.now()) - started
155  if (out.unavailable?.length) log($, `${file}: unavailable ${out.unavailable.map(u => `${u.rule} (${u.reason})`).join('; ')}`)
156  log($, `${file}: ${set} as ${workflow} ${(out.verdicts ?? []).map(v => `${v.rule}=${v.p}${v.provider === 'openai' ? '(luna)' : ''}`).join(' ')} in ${ms} ms`)
157  return contextLines(out.verdicts ?? [], shown(cwd, file), ranges)
158}
159
160/** Deferred to the window's end: its lines wait in `deferred` for the next tool result. */
161function defer($: $, file: string, st: FileState, target: Target, cwd: string, now: number) {
162  st.timer?.cancel()
163  st.timer = $.clock.after(Math.max(0, st.lastStart + WINDOW_MS - now), () => {
164    st.timer = undefined
165    void (async () => {
166      const gen = st.gen
167      const ranges = st.pending
168      st.pending = []
169      st.lastStart = await $.clock.now()
170      const lines = await evaluate($, target, file, ranges, cwd)
171      if (st.gen !== gen) {
172        st.pending = merge(st.pending, ranges)
173        return
174      }
175      if (lines.length) deferred.set(file, lines)
176    })().catch(err => log($, `${file}: deferred evaluation failed (${String(err)})`))
177  })
178}
179
180async function afterEdit($: $, e: Record<string, unknown>, result: ToolCallResult): Promise<ToolCallResult> {
181  // Interactive = some surface draws (the terminal, the desktop app, a phone); `claude -p` has none.
182  const isInteractive = (await $.session.surfaces()).length > 0
183  if (!enabled(await $.env.get('JEV_EDIT_MOD'), isInteractive)) return result
184  const raw = e.file_path
185  if (typeof raw !== 'string' || raw === '') return result
186  const cwd = await $.session.cwd()
187  const file = absolute(cwd, raw)
188  const set = await ruleSetFor(file, d => workflowAt($, d))
189  if (!set) return result
190  const target = await targetFor($, set, file)
191  if (!target) return result
192
193  const tool = String(e.tool)
194  const ranges = await changedLines($, tool, e, file)
195  const now = await $.clock.now()
196  const st = files.get(file) ?? { lastStart: -Infinity, gen: 0, pending: [] }
197  files.set(file, st)
198  const gen = ++st.gen
199  st.pending = merge(st.pending, ranges)
200  st.timer?.cancel()
201  st.timer = undefined
202  deferred.delete(file)
203
204  if (now - st.lastStart < WINDOW_MS) {
205    defer($, file, st, target, cwd, now)
206    return result
207  }
208  st.lastStart = now
209  const want = st.pending
210  st.pending = []
211  const lines = await evaluate($, target, file, want, cwd)
212  if (st.gen !== gen) {
213    // A newer edit to this file arrived while this one was scored: its evaluation covers these lines.
214    st.pending = merge(st.pending, want)
215    return result
216  }
217  return lines.length ? { ...result, context: [...(result.context ?? []), lines.join('\n')] } as ToolCallResult : result
218}
219
220export function registerJevEdit(on: On): void {
221  // Every tool: an edit is scored, and any call carries the deferred lines that are ready.
222  on('tool.call', async ($, e, next) => {
223    const result = await next(e)
224    if (result.deny !== undefined) return result
225    let out: ToolCallResult = result
226    try {
227      if (/^(Edit|Write|MultiEdit)$/.test(String(e.tool)) && !result.isError)
228        out = await afterEdit($, e as unknown as Record<string, unknown>, result)
229    } catch (err) {
230      log($, `${String((e as { file_path?: unknown }).file_path)}: ${String(err)}`)
231    }
232    if (!deferred.size || out.deny !== undefined) return out
233    const ready = [...deferred.values()].flat()
234    deferred.clear()
235    return { ...out, context: [...(out.context ?? []), ready.join('\n')] } as ToolCallResult
236  }).catch(($, e, next) => {
237    // Replay-safe: once called, next(e) resolves to what the tool already settled to.
238    log($, `hook failed (${next.error.kind}: ${next.error.message})`)
239    return next(e)
240  })
241}
242
hooks/watch/watcher.ts 224 lines
1// The watcher mod, registered from hooks/watch/watcher.ts: the farm-out runs and work rounds THIS session launched, read from files only.
2//
3//   status line   one compact line while anything runs; cleared when nothing does
4//   wake          $.prompt.submit ONCE per run that reaches DONE or GONE, remembered in $.store
5//   /farm         a table of this session's runs, printed at once, no turn
6//   beacon        <TMPDIR>/farm-events/<session>/watcher.alive, rewritten by every tick that completes:
7//                 the one thing outside this module that can tell a session whose mods never loaded
8//
9// It replaces the farm-runs plugin monitor, which never re-armed once it stopped. A timer started
10// in session.start comes back with every reload. A headless session (`claude -p`, the SDK, a farm
11// child with FARM_OUT_CHILD=1) registers nothing: it has nobody to draw for, and a farm child
12// waking itself about its own runs would loop.
13import type { EngineInterface, On } from 'claude-code'
14import {
15  BEACON, classify, parseEvents, statusLine, table, TICK_MS, pastHorizon, wakeable, wakeText, waitText, workPhase, workRound,
16  type Facts, type Run, type View,
17} from './runs.ts'
18import { setForecastCache } from '../jev/forecast-mod.ts'
19
20// The Jev forecast band's sampling tick (hooks/jev/forecast-mod.ts): ten minutes, and the script's
21// own hourly gate decides whether that reaches the network.
22const FORECAST_TICK_MS = 10 * 60_000
23
24// Notified keys older than this are pruned from the shared store.
25const KEEP_NOTIFIED_MS = 7 * 24 * 3600_000
26
27// Module state: lost on reload by design. The store holds what must survive one.
28const sessions = new Set<string>()
29const firstSeen = new Map<string, number>()
30const cache = new Map<string, { mtimeMs: number; size: number; runs: Run[] }>()
31const woke = new Set<string>()
32let lastStatus: string | undefined
33let ticking = false
34
35async function tmpRoot($: EngineInterface): Promise<string> {
36  return ((await $.env.get('TMPDIR')) || '/tmp').replace(/\/+$/, '')
37}
38
39async function eventDirs($: EngineInterface): Promise<string[]> {
40  const sid = await $.session.id()
41  if (sid) sessions.add(sid)
42  const roots = [...new Set([await tmpRoot($), '/tmp'])]
43  const dirs: string[] = []
44  for (const root of roots) for (const s of sessions) dirs.push(`${root.replace(/\/+$/, '')}/farm-events/${s}`)
45  return dirs
46}
47
48async function readRuns($: EngineInterface, nowMs: number): Promise<Run[]> {
49  const runs: Run[] = []
50  for (const dir of await eventDirs($)) {
51    let entries: Awaited<ReturnType<EngineInterface['fs']['list']>>
52    try { entries = await $.fs.list(dir) } catch { continue }
53    const sid = dir.split('/').pop() ?? ''
54    for (const ent of entries) {
55      const m = /^(\d+)\.ndjson$/.exec(ent.name)
56      if (!m || ent.kind !== 'file') continue
57      const file = `${dir}/${ent.name}`
58      if (!firstSeen.has(file)) firstSeen.set(file, Math.min(nowMs, ent.mtimeMs || nowMs))
59      const hit = cache.get(file)
60      if (hit && hit.mtimeMs === ent.mtimeMs && hit.size === ent.size) { runs.push(...hit.runs); continue }
61      let text = ''
62      try { text = await $.fs.read(file) } catch { continue }
63      const parsed = parseEvents(text, file, Number(m[1]), sid)
64      for (const r of parsed) r.fileMtimeMs = ent.mtimeMs
65      cache.set(file, { mtimeMs: ent.mtimeMs, size: ent.size, runs: parsed })
66      runs.push(...parsed)
67    }
68  }
69  return runs
70}
71
72/** mtime (ms) of a non-empty file, else undefined. */
73async function nonEmptyAt($: EngineInterface, p: string): Promise<number | undefined> {
74  try { const s = await $.fs.stat(p); return s.size > 0 ? s.mtimeMs : undefined } catch { return undefined }
75}
76
77async function readText($: EngineInterface, p: string): Promise<string | undefined> {
78  try { return await $.fs.read(p) } catch { return undefined }
79}
80
81/** Everything classify() needs, gathered with one ps call and a stat per artifact. */
82async function gather($: EngineInterface, runs: Run[]): Promise<Facts> {
83  const facts: Facts = {
84    alive: new Set(), present: new Set(), presentAt: new Map(), firstSeen, loopExit: new Map(), loopExitAt: new Map(), round: new Map(), phase: new Map(),
85  }
86  const open = [...new Set(runs.filter(r => !r.done).map(r => r.pid))]
87  if (open.length) {
88    try {
89      const ps = await $.process.run(['ps', '-o', 'pid=', '-p', open.join(',')], { timeoutMs: 5000 })
90      for (const tok of ps.stdout.split(/\s+/)) if (/^\d+$/.test(tok)) facts.alive.add(Number(tok))
91    } catch {
92      // ps unavailable: claim every open run alive rather than wake the session with false GONEs.
93      for (const p of open) facts.alive.add(p)
94    }
95  }
96  const paths = new Set<string>()
97  const workDirs = new Set<string>()
98  for (const r of runs) {
99    for (const p of [r.out, ...r.claims]) if (p && p.startsWith('/')) paths.add(p)
100    if ((r.label === 'work-round' || r.label === 'work-loop') && r.out) workDirs.add(r.out.replace(/\/[^/]*$/, ''))
101  }
102  for (const p of paths) {
103    const at = await nonEmptyAt($, p)
104    if (at !== undefined) { facts.present.add(p); facts.presentAt!.set(p, at) }
105  }
106  for (const d of workDirs) {
107    const exit = await readText($, `${d}/loop.exit`)
108    if (exit !== undefined && exit.trim() !== '') {
109      facts.loopExit.set(`${d}/loop.exit`, exit.trim())
110      try { facts.loopExitAt!.set(`${d}/loop.exit`, (await $.fs.stat(`${d}/loop.exit`)).mtimeMs) } catch {}
111    }
112    const loopLog = await readText($, `${d}/loop.log`)
113    const round = loopLog && workRound(loopLog)
114    if (round) facts.round.set(d, round)
115    // Round N>1 logs to run-<HHMMSS>.log; the newest run*.log is the live round's.
116    let log = `${d}/run.log`
117    try {
118      const logs = (await $.fs.list(d)).filter((e) => /^run.*\.log$/.test(e.name))
119      logs.sort((a, b) => b.mtimeMs - a.mtimeMs)
120      if (logs[0]) log = `${d}/${logs[0].name}`
121    } catch {}
122    const runLog = await readText($, log)
123    const phase = runLog && workPhase(runLog)
124    if (phase) facts.phase.set(d, phase)
125  }
126  return facts
127}
128
129async function snapshot($: EngineInterface): Promise<{ views: View[]; nowMs: number }> {
130  const nowMs = await $.clock.now()
131  const runs = await readRuns($, nowMs)
132  return { views: classify(runs, await gather($, runs)), nowMs }
133}
134
135async function wake($: EngineInterface, views: View[], nowMs: number) {
136  for (const v of wakeable(views)) {
137    // A live run's newest WAIT alert wakes once per waits value: the run stays running.
138    if (v.state === 'running' && v.wait) {
139      const wid = `${v.id}:wait:${v.wait.waits}`
140      if (!woke.has(wid)) {
141        woke.add(wid)
142        const wkey = `notified:${wid}`
143        if (!(await $.store.get(wkey)) && !pastHorizon(v, nowMs)) {
144          await $.store.set(wkey, nowMs)
145          void $.prompt.submit({ text: waitText(v) })
146        }
147      }
148      continue
149    }
150    if (v.state === 'running' || woke.has(v.id)) continue
151    woke.add(v.id)
152    const key = `notified:${v.id}`
153    if (await $.store.get(key)) continue
154    if (pastHorizon(v, nowMs)) continue
155    // Recorded BEFORE the submit: a reload between the two must not wake twice.
156    await $.store.set(key, nowMs)
157    // Never awaited: submit resolves when the turn starts, and this tick may run mid-turn.
158    void $.prompt.submit({ text: wakeText(v, nowMs) })
159  }
160}
161
162async function prune($: EngineInterface, nowMs: number) {
163  for (const k of await $.store.keys()) {
164    if (!k.startsWith('notified:')) continue
165    const at = Number(await $.store.get(k))
166    if (!(nowMs - at < KEEP_NOTIFIED_MS)) await $.store.delete(k)
167  }
168}
169
170async function tick($: EngineInterface) {
171  if (ticking) return
172  ticking = true
173  try {
174    const { views, nowMs } = await snapshot($)
175    const line = statusLine(views, nowMs)
176    if (line !== lastStatus) {
177      lastStatus = line
178      $.ui.status(line)
179    }
180    await wake($, views, nowMs)
181    // Last, so a tick that throws leaves the beacon to go stale. write() creates the directory, so
182    // the beacon is there before this session's first run files itself.
183    const sid = await $.session.id()
184    if (sid) await $.fs.write(`${await tmpRoot($)}/farm-events/${sid}/${BEACON}`, String(Math.floor(nowMs / 1000)))
185  } finally {
186    ticking = false
187  }
188}
189
190/** One forecast sample, under credit-warn's hourly gate, then the cache handed to the band. */
191async function forecastTick($: EngineInterface): Promise<void> {
192  try {
193    await $.process.run(['bun', `${$.plugin.root}/scripts/lib/openrouter-credits.ts`, '--sample'], { timeoutMs: 20_000 })
194  } catch { /* the read below still shows the last sample */ }
195  let c: unknown = null
196  try { c = JSON.parse(await $.fs.read(`${await tmpRoot($)}/openrouter-credits.json`)) } catch { /* no cache yet */ }
197  setForecastCache(c)
198  try { $.ui.invalidate('ui.render') } catch { /* headless */ }
199}
200
201export function registerWatcher(on: On) {
202  on('session.start', async ($, e, next) => {
203    if (!e.isInteractive || (await $.env.get('FARM_OUT_CHILD')) === '1') return next(e)
204    // The promise is returned so a test clock can settle on it; the engine does not wait on it.
205    $.clock.every(TICK_MS, () => tick($))
206    void tick($)
207    void prune($, await $.clock.now())
208    // The module's one session.start, so the Jev forecast band's tick starts here too.
209    $.clock.every(FORECAST_TICK_MS, () => forecastTick($))
210    void forecastTick($)
211    await $.command.register({
212      name: 'farm',
213      description: "This session's farm-out runs and work rounds: state, elapsed, artifact, report",
214      immediate: true,
215    })
216    return next(e)
217  })
218
219  on('command.run', { command: 'farm' }, async ($) => {
220    const { views, nowMs } = await snapshot($)
221    return { text: table(views, nowMs) }
222  })
223}
224
hooks/guards/core.ts 85 lines
1// The plugin's tool-call guards, written once for two hosts: the settings-hook scripts in hooks/
2// (bun, node fs, stdin/stdout) and the mod (hooks/guards/mod.ts, $.fs/$.env). A hooks module runs
3// with no Node, so nothing under hooks/guards/ may import node:* except node-io.ts, which only the
4// scripts load. Every guard is `(payload, io) => Promise<Outcome>` over the settings-hook payload.
5
6/** The settings-hook stdin payload, as Claude Code sends it (PreToolUse / PostToolUse). */
7export type Payload = Record<string, unknown>
8
9/** A guard's answer. Neither field: no opinion. There is no allow — silence is the pass. */
10export interface Outcome {
11  deny?: string
12  context?: string
13}
14
15export interface FileStat {
16  kind: 'file' | 'dir' | 'other'
17  size: number
18  mtimeMs: number
19}
20
21/** The guard's whole view of the world. Relative paths resolve against `cwd`. */
22export interface GuardIO {
23  env: (name: EnvName) => string | undefined
24  cwd: string
25  pluginRoot: string
26  /** node's os.tmpdir(): TMPDIR, TMP, TEMP, then /tmp. */
27  osTmpdir: string
28  /** The script's process.ppid; the mod's session id. Only a last-resort counter key. */
29  fallbackKey: string
30  nowMs: () => number
31  stat: (p: string) => Promise<FileStat | null>
32  read: (p: string) => Promise<string | null>
33  list: (p: string) => Promise<string[] | null>
34  write: (p: string, text: string) => Promise<void>
35  append: (p: string, text: string) => Promise<void>
36}
37
38/** Every variable a guard reads. The mod reads each by literal name (validate requires it). */
39export const ENV_NAMES = [
40  'LOOK_AT_NESTED',
41  'READ_GUARD_BYTES',
42  'COMPACT_THRESHOLD',
43  'COMPACT_INTERVAL',
44  'CLAUDE_CODE_SESSION_ID',
45  'TMPDIR',
46  'TEMP',
47  'TMP',
48  'WORK_ALLOW_CRON_DELETE',
49  'GUARD_NOW_MS',
50] as const
51export type EnvName = (typeof ENV_NAMES)[number]
52
53/** The guards' clock: GUARD_NOW_MS (epoch ms) when set, so a parity run reads one instant on both sides; else the wall clock. */
54export function guardNow(fixed: string | undefined): number {
55  const n = Number(fixed)
56  return fixed && Number.isFinite(n) ? n : Date.now()
57}
58
59export type Guard = (payload: Payload, io: GuardIO) => Promise<Outcome>
60
61/** `path.join(a, b)` for the shapes guards build: collapses duplicate slashes. */
62export function joinPath(...parts: string[]): string {
63  return parts.filter(p => p !== '').join('/').replace(/\/{2,}/g, '/')
64}
65
66/** Absolute form of `p` against `cwd`, the way the scripts' relative fs calls resolve. */
67export function absolute(cwd: string, p: string): string {
68  return p.startsWith('/') ? p : joinPath(cwd, p)
69}
70
71/** The deny a PreToolUse gate gives when it throws: the same text `denyOnCrash` prints. */
72export function crashDeny(gate: string, kind: string, error: unknown): string {
73  let detail: string
74  try {
75    detail = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
76  } catch {
77    detail = 'an unrepresentable value was thrown'
78  }
79  return (
80    `${gate}: this gate crashed (${kind}: ${detail}) and could not decide. A gate that cannot ` +
81    `resolve identity or policy denies; a non-zero exit would have been treated as non-blocking ` +
82    `and silently permitted this call. Re-run after fixing the underlying fault.`
83  )
84}
85
hooks/guards/atomic-constraint.ts 74 lines
1// PostToolUse(Edit|Write): guard against monolithic constraint files.
2//
3// Two anti-patterns: a .md under references/ (not constraints/) that looks like bundled constraints,
4// and a .md under constraints/ with 3+ ### rule headings. Non-blocking: context only.
5//
6// The heading count reproduces Python's `re.findall(r"^###\s+", content, re.MULTILINE)`: Python's
7// `\s` is [ \t\n\r\f\v] and MULTILINE `^` matches only at start-of-string or after "\n"; JS's `\s`
8// and `m` flag are both wider.
9import type { Guard } from './core.ts'
10
11/** len(re.findall(r"^###\s+", content, re.MULTILINE)) — Python semantics. */
12function countH3(text: string): number {
13  const re = /###[ \t\n\r\f\v]+/g
14  let n = 0
15  for (const m of text.matchAll(re)) {
16    const i = m.index!
17    if (i === 0 || text[i - 1] === '\n') n++
18  }
19  return n
20}
21
22export const atomicConstraintGuard: Guard = async (payload, io) => {
23  const toolName = String(payload.tool_name ?? '')
24  const toolInput = (payload.tool_input as Record<string, unknown>) ?? {}
25  if (toolName !== 'Edit' && toolName !== 'Write') return {}
26
27  const filePath = (toolInput.file_path ?? '') as string
28  if (!filePath) return {}
29
30  // Python pathlib: parts / name / stem / suffix.
31  const parts = String(filePath)
32    .split('/')
33    .filter(p => p !== '' && p !== '.')
34  const name = parts.length ? parts[parts.length - 1]! : ''
35  const dot = name.lastIndexOf('.')
36  const suffix = dot > 0 ? name.slice(dot) : ''
37  const stem = suffix ? name.slice(0, -suffix.length) : name
38
39  if (suffix.toLowerCase() !== '.md') return {}
40  if (!parts.includes('references')) return {}
41
42  const content = await io.read(String(filePath))
43  if (content === null) return {}
44
45  const messages: string[] = []
46  const refIdx = parts.lastIndexOf('references')
47  const inConstraintsDir = refIdx + 1 < parts.length && parts[refIdx + 1] === 'constraints'
48
49  if (!inConstraintsDir) {
50    const h3Count = countH3(content)
51    if ((stem.endsWith('-constraints') || stem.endsWith('-conventions')) && h3Count >= 3) {
52      messages.push(
53        `MONOLITH DETECTED: ${name} has ${h3Count} sections and looks like bundled constraints. ` +
54          `Split into individual .md files in constraints/ — one rule per file. ` +
55          `See the atomic-constraints constraint for details.`,
56      )
57    }
58  }
59
60  if (inConstraintsDir) {
61    const h3Count = countH3(content)
62    // Allow the meta-constraint itself to have structure
63    if (h3Count >= 3 && stem !== 'atomic-constraints') {
64      messages.push(
65        `POTENTIAL MONOLITH: ${name} has ${h3Count} ### headings. ` +
66          `Each constraint file should contain ONE rule. ` +
67          `If these headings describe different rules, split into separate files.`,
68      )
69    }
70  }
71
72  return messages.length ? { context: messages.join('\n') } : {}
73}
74
hooks/guards/bun-test.ts 157 lines
1/**
2 * PreToolUse (Bash) BLOCKING GATE over Bash command TEXT: a `bun test` over more than one test file
3 * — several paths, a directory or name filter, or no path at all (the whole repo) — without
4 * `--parallel`.
5 *
6 * Measured 2026-10-02: this repo's suite took 661-881 s run serially from under ~/.tmp, and 63 s with
7 * `bun test --parallel` from /tmp (scripts/test.sh). bun 1.4.0 has no bunfig.toml key or environment
8 * variable that makes `--parallel` the default: `[test] parallel = true` is silently ignored, so the
9 * flag on the command line is the only switch, and this gate asks for it.
10 *
11 * Exempt by construction: a single test file, `bun test --help`, a command that already passes
12 * `--parallel`, and any harness that runs `bun test` internally (scripts/test.sh included) — the gate
13 * sees only the command text, so it judges only a `bun test` in a command position of that text.
14 *
15 * CONSERVATIVE. Anything the text cannot settle is allowed: a path from a variable or a command
16 * substitution, a quoted glob, `xargs bun test`, global bun flags before `test`. Never rewritten,
17 * never approved: the answer is a deny or silence.
18 */
19import type { Guard } from './core.ts'
20import { commandWordIndex, segments, type Word } from './pgrep.ts'
21
22/** Flags whose operand is the NEXT token when not spelled `--flag=value`, from `bun test --help`
23 *  (bun 1.4.0) plus the runtime flags `bun test` accepts. `--parallel`, `--bail`, `--coverage` and
24 *  `--changed` take an optional `=value` and do NOT consume the next token (measured). */
25const VALUE_LONG = new Set([
26  '--timeout', '--rerun-each', '--retry', '--seed', '--coverage-reporter', '--coverage-dir',
27  '--test-name-pattern', '--reporter', '--reporter-outfile', '--max-concurrency',
28  '--path-ignore-patterns', '--parallel-delay', '--shard', '--timings',
29  '--preload', '--cwd', '--env-file', '--config', '--tsconfig-override', '--define', '--loader', '--conditions',
30])
31const VALUE_SHORT = new Set(['-t', '-r', '-c', '-d', '-l'])
32
33/** Commands that run their arguments as a command, after their own options. */
34const WRAPPERS = new Set(['timeout', 'nice', 'ionice', 'stdbuf'])
35
36/** A wrapper's own option or operand: `-k 10`, `600`, `1.5m`, `KILL`, `VAR=x`. */
37const wrapperArg = (t: string): boolean =>
38  t.startsWith('-') || /^[\d.]+[smhd]?$/.test(t) || /^[A-Z][A-Z0-9]*$/.test(t) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(t)
39
40const SCRIPT_FILE = /\.[cm]?[jt]sx?$/
41
42const basename = (t: string): string => t.split('/').pop() ?? t
43
44/** Drop heredoc bodies: a `bun test` line inside `cat <<EOF` is text being written, not run. */
45function stripHeredocs(command: string): string {
46  const out: string[] = []
47  const pending: string[] = []
48  for (const line of command.split('\n')) {
49    if (pending.length) {
50      if (line.trim() === pending[0]) pending.shift()
51      continue
52    }
53    out.push(line)
54    for (const m of line.matchAll(/(^|[^<])<<-?\s*(['"]?)([A-Za-z_][\w.-]*)\2/g)) pending.push(m[3]!)
55  }
56  return out.join('\n')
57}
58
59/**
60 * Leave a `$SUBST` word where each command substitution opens. The tokenizer ends a segment at `$(`
61 * and at a backtick, so without it `bun test $(git ls-files)` would read as a bare `bun test`; with
62 * it the outer segment has a target the text cannot count, and the inner command is still judged.
63 */
64function markSubstitutions(command: string): string {
65  let ticks = 0
66  return command.replace(/\$\(|`/g, m => (m === '`' ? (ticks++ % 2 === 0 ? ' $SUBST `' : '`') : ' $SUBST $('))
67}
68
69/** The index of the `bun` word of a `bun test` in this segment, or -1. */
70function bunTestAt(words: Word[]): number {
71  let i = commandWordIndex(words)
72  if (i < 0) return -1
73  while (i < words.length && !words[i]!.quoted && WRAPPERS.has(basename(words[i]!.text))) {
74    i++
75    while (i < words.length && wrapperArg(words[i]!.text) && basename(words[i]!.text) !== 'bun') i++
76  }
77  const bun = words[i]
78  const sub = words[i + 1]
79  if (!bun || !sub || bun.quoted || sub.quoted || basename(bun.text) !== 'bun' || sub.text !== 'test') return -1
80  return i
81}
82
83/**
84 * Why this segment's `bun test` runs several files serially, or null when it does not (not a
85 * `bun test`, `--parallel` or `--help` given, one file, or a target the text cannot settle).
86 */
87function serialReason(words: Word[]): string | null {
88  const at = bunTestAt(words)
89  if (at < 0) return null
90  const args = words.slice(at + 2)
91  const positionals: Word[] = []
92  let endOfFlags = false
93  for (let i = 0; i < args.length; i++) {
94    const w = args[i]!
95    const t = w.text
96    if (!w.quoted && /^(\d*|&)[<>]/.test(t)) {
97      // `2>&1` and `>out` carry their operand; a bare `>` / `2>` / `<` takes the next token.
98      if (/^(\d*|&)(<|>>?)$/.test(t)) i++
99      continue
100    }
101    if (!endOfFlags && t === '--') {
102      endOfFlags = true
103      continue
104    }
105    if (!endOfFlags && t.startsWith('-') && t.length > 1) {
106      const long = t.split('=')[0]!
107      if (long === '--parallel' || long === '--help' || t === '-h') return null
108      if ((VALUE_LONG.has(long) && !t.includes('=')) || VALUE_SHORT.has(t)) i++
109      continue
110    }
111    positionals.push(w)
112  }
113  // A path from a variable, a substitution or a quoted glob: the text cannot count the files.
114  if (positionals.some(p => /[$`]/.test(p.text) || (p.quoted && /[*?[]/.test(p.text)))) return null
115  if (positionals.length === 0) return 'the whole repo'
116  if (positionals.length > 1) return `${positionals.length} paths`
117  const only = positionals[0]!
118  if (/[*?[]/.test(only.text)) return `the glob ${only.text}`
119  if (SCRIPT_FILE.test(only.text)) return null
120  return `${only.text}, a directory or name filter that can match many files,`
121}
122
123/** Truncate an untrusted segment before echoing it back into the model's context. */
124function show(s: string): string {
125  const t = s.length > 80 ? s.slice(0, 77) + '...' : s
126  return t.replace(/[\n\r]/g, ' ')
127}
128
129export const FIX =
130  'Run multi-file bun suites in parallel: bun test --parallel ... (or scripts/test.sh where the repo ' +
131  'has one), with TMPDIR outside ~/.tmp.'
132
133/** Every serial multi-file `bun test` in one Bash command, as `[segment text, reason]`. */
134export function serialBunTests(command: string): [string, string][] {
135  const found: [string, string][] = []
136  for (const seg of segments(markSubstitutions(stripHeredocs(command)))) {
137    const why = serialReason(seg.words)
138    if (why) found.push([seg.words.map(w => w.text).join(' '), why])
139  }
140  return found
141}
142
143export const bunParallelGuard: Guard = async payload => {
144  if (payload.tool_name !== 'Bash') return {}
145  const toolInput = (payload.tool_input ?? {}) as Record<string, unknown>
146  const command = typeof toolInput.command === 'string' ? toolInput.command : ''
147  if (!command) return {}
148  const found = serialBunTests(command)
149  if (!found.length) return {}
150  return {
151    deny:
152      '🛑 ' +
153      found.map(([seg, why]) => `\`${show(seg)}\` runs ${why} in one serial process.`).join('\n') +
154      '\n' + FIX,
155  }
156}
157
hooks/guards/cron-delete.ts 214 lines
1// PreToolUse(CronDelete): refuse to cancel the loop that drives a work run still in flight.
2// PostToolUse(CronCreate), `cronRecord`: file the new job id under the run(s) its prompt names.
3//
4// The refusal is TASK-SPECIFIC. The record half appends the new job id to `heartbeatCrons` in the
5// args.json of every `.work/<run>` whose name the prompt names, so the guard denies only when a run
6// CLAIMING this id is in flight; an id no run claims falls back to the old rule (deny while any run
7// is in flight).
8//
9// In flight is decided as work-goal-resend.sh decides it -- a run directory holds args.json with no
10// non-empty result.json beside it. That is a property of the filesystem, not of anyone's belief
11// that the run is over, which is exactly where the judgement failed (measured 2026-09-14: a loop
12// deleted at round 2 of 6 with the goal unmet, on the reasoning that the run had been halted).
13import { joinPath, type Guard, type GuardIO } from './core.ts'
14import { holdStateName, unevaluatedNote } from './hold.ts'
15
16/** A cron job id as CronCreate mints them: 8 lowercase hex chars. */
17const JOB_ID = /\b[0-9a-f]{8}\b/
18
19/** Run directories under `<cwd>/.work` holding an args.json, with what that file says. */
20interface Run {
21  name: string
22  /** The run root this one was found under. */
23  base: string
24  argsPath: string
25  argsMtime: number
26  inFlight: boolean
27  crons: string[]
28}
29
30const RUN_ROOTS = ['.work']
31
32async function runsUnder(io: GuardIO, cwd: string): Promise<Run[] | null> {
33  const runs: Run[] = []
34  let sawRoot = false
35  for (const base of RUN_ROOTS) {
36    const root = joinPath(cwd, base)
37    const entries = await io.list(root)
38    if (entries === null) continue // this root is absent
39    sawRoot = true
40    for (const name of entries) {
41      const argsPath = joinPath(root, name, 'args.json')
42      const args = await io.stat(argsPath)
43      if (!args) continue // not a run directory
44      const result = await io.stat(joinPath(root, name, 'result.json'))
45      // An absent result.json IS the in-flight shape; a non-empty one is a verdict.
46      const inFlight = !(result && result.size > 0)
47      let crons: string[] = []
48      try {
49        const parsed = JSON.parse((await io.read(argsPath)) ?? '')
50        if (parsed && typeof parsed === 'object' && Array.isArray(parsed.heartbeatCrons)) {
51          crons = parsed.heartbeatCrons.filter((x: unknown) => typeof x === 'string')
52        }
53      } catch {
54        // Unparseable args.json claims nothing; it is still a run directory for the fallback rule.
55      }
56      runs.push({ name, base, argsPath, argsMtime: args.mtimeMs, inFlight, crons })
57    }
58  }
59  // Neither root exists: a determinate "no run here".
60  return sawRoot ? runs : null
61}
62
63// grind runs OUTSIDE every session, so the hourly backstop a launching session keeps for it is
64// claimed by no `.work` run and would fall to "nobody claims this id, and something is in flight ->
65// deny". The record half marks such an id beside the hold ledger the guard already reads, so no
66// project file and no per-workflow state is added. farm.sh --workflow prints the same backstop,
67// naming its own run directory. The parenthesised nudge is matched, not the bare word: "farm out
68// the review" is prose about delegating, not a heartbeat.
69const NONRUN_PROMPT = /\bgrind\b|\(farm [^)\n]+\)/i
70
71const tmp = (io: GuardIO): string => io.env('TMPDIR') || io.osTmpdir
72const markedPath = (io: GuardIO, session: string): string => joinPath(tmp(io), `work-cron-nonrun-${session}.txt`)
73
74async function isMarked(io: GuardIO, session: string, id: string): Promise<boolean> {
75  if (!session) return false
76  const text = await io.read(markedPath(io, session))
77  return text !== null && text.split('\n').includes(id)
78}
79
80/**
81 * NEVER blocks and NEVER answers: recording is best-effort, and a run whose id was never recorded
82 * simply falls back to the old rule. Every failure is swallowed.
83 */
84export const cronRecord: Guard = async (payload, io) => {
85  try {
86    const toolInput = (payload?.tool_input ?? {}) as Record<string, unknown>
87    const prompt = String(toolInput?.prompt ?? '')
88    const response = payload?.tool_response as unknown
89
90    // tool_response is an object for some tools and a bare string for others, so both are read.
91    let id = ''
92    if (response && typeof response === 'object' && typeof (response as Record<string, unknown>).id === 'string') {
93      id = (response as Record<string, unknown>).id as string
94    } else if (typeof response === 'string') {
95      id = response.match(JOB_ID)?.[0] ?? ''
96    }
97    if (!JOB_ID.test(id)) return {}
98
99    const cwd = String(payload?.cwd ?? '') || io.cwd
100    const runs = (await runsUnder(io, cwd)) ?? []
101
102    // A prompt that names a run belongs to that run, whatever else it says; only an id NO run claims
103    // can be a grind or farm heartbeat.
104    const session = String(payload?.session_id ?? '')
105    if (session && NONRUN_PROMPT.test(prompt) && !runs.some(r => r.name && prompt.includes(r.name))) {
106      if (!(await isMarked(io, session, id))) await io.append(markedPath(io, session), id + '\n')
107    }
108
109    for (const run of runs) {
110      if (!run.name || !prompt.includes(run.name)) continue
111      if (run.crons.includes(id)) continue // idempotent
112      const raw = await io.read(run.argsPath)
113      if (raw === null) throw new Error('args.json unreadable')
114      const parsed = JSON.parse(raw)
115      if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue
116      parsed.heartbeatCrons = [...run.crons, id]
117      // Keep the file's own formatting: the indent of its first nested line, and its trailing newline.
118      const indent = raw.match(/^\{\r?\n([ \t]+)"/)?.[1] ?? ''
119      await io.write(run.argsPath, JSON.stringify(parsed, null, indent) + (raw.endsWith('\n') ? '\n' : ''))
120    }
121  } catch {
122    // best-effort
123  }
124  return {}
125}
126
127const HOLD_ARMED =
128  'A hold is ARMED for this session, so its objective has not closed yet. The heartbeat ' +
129  'is what re-enters the session while the hold is working; deleting it now leaves the hold ' +
130  'with nothing to wake it. Let the hold release itself (the check goes green AND the ' +
131  'classifier judges the goal met), or have the USER confirm `work-hold.sh --disarm` at a ' +
132  'terminal. If the USER has abandoned this run, retire it with ' +
133  "`work-abandon.sh <run-dir> --why '<reason>'`: it writes the run's verdict, releases the " +
134  'hold, and this delete is then allowed.'
135
136export const cronDeleteGuard: Guard = async (payload, io) => {
137  if (String(payload?.tool_name ?? '') !== 'CronDelete') return {}
138
139  // The deliberate override, for genuinely abandoning a run.
140  if (io.env('WORK_ALLOW_CRON_DELETE') === '1') return {}
141
142  const cwd = String(payload?.cwd ?? '') || io.cwd
143  const deleteId = String(((payload?.tool_input ?? {}) as Record<string, unknown>)?.id ?? '')
144
145  // THE HOLD GATE: DONE MEANS GOAL MET. The authority on "closed" is the hold's own release, read
146  // from the per-session ledger work-hold.ts writes -- not this guard's opinion and not the
147  // session's. ONLY the payload's session_id: an ambient CLAUDE_CODE_SESSION_ID leaking in from the
148  // session that launched the process once made this gate answer about the wrong hold (2026-09-27).
149  // An ARMED hold only; a RELEASED one is not this gate's business. An UNEVALUATED hold still
150  // denies, and names the skew, which is the only thing that ends that deadlock.
151  const session = String(payload?.session_id ?? '')
152  const statePath = joinPath(tmp(io), holdStateName(session))
153  if (session && (await io.stat(statePath))) {
154    let skew: string | null = null
155    try {
156      skew = unevaluatedNote(JSON.parse((await io.read(statePath)) ?? ''), Math.floor(io.nowMs() / 1000))
157    } catch {
158      // An unreadable state file says nothing about the hook's liveness; the deny is unchanged.
159    }
160    return {
161      deny:
162        (skew ? `The hold for this session was ${skew}. Until that is fixed the hold cannot release itself, so this delete stays refused — reload, then let the hold run. ` : '') +
163        HOLD_ARMED,
164    }
165  }
166
167  // No .work at all is a determinate "no run here", not a failure to decide, so it passes.
168  const runs = await runsUnder(io, cwd)
169  if (runs === null) return {}
170
171  // A run that CLAIMS this id answers the question by itself: a heartbeat recorded for run A says
172  // nothing about run B, so an unrelated in-flight run must not hold A's finished loop open.
173  const claiming = deleteId ? runs.filter(r => r.crons.includes(deleteId)) : []
174
175  // A heartbeat recorded as belonging to no run -- a grind or farm backstop -- is not a work run's
176  // loop. A run that CLAIMS the id still wins.
177  if (!claiming.length && (await isMarked(io, session, deleteId))) return {}
178
179  const candidates = claiming.length ? claiming : runs
180
181  // The newest in-flight run among the candidates, by args.json mtime -- the file the dispatch writes.
182  let newest = ''
183  let newestBase = '.work'
184  let newestMtime = 0
185  for (const run of candidates) {
186    if (!run.inFlight) continue
187    if (run.argsMtime > newestMtime) {
188      newestMtime = run.argsMtime
189      newest = run.name
190      newestBase = run.base
191    }
192  }
193  if (!newest) return {}
194
195  // A run-directory name that is not a plain slug is withheld rather than repeated: .work can be
196  // repo-shipped, so the name is untrusted text inside a message the reader acts on.
197  const run = /^[A-Za-z0-9._-]+$/.test(newest) ? newest : `(a run under ${newestBase}/)`
198
199  return {
200    deny:
201      (claiming.length
202        ? `The loop you are deleting drives a work run that is still in flight: ${newestBase}/${run}/args.json ` +
203          'records this cron in heartbeatCrons and has no verdict beside it. '
204        : `A work run is still in flight: ${newestBase}/${run}/args.json has no verdict beside it, and no run ` +
205          "claims this cron, so it cannot be told apart from that run's heartbeat. ") +
206      'The loop is usually what drives that run to completion -- it is what re-enters the session to ' +
207      'read the verdict, fix what failed and redispatch. Deleting it now strands the run: the ' +
208      'dispatch keeps going detached and nothing comes back for it. Let the run finish ' +
209      '(work-result.sh exits 0, or the round cap or time ceiling is reached), then delete the loop. ' +
210      'If you genuinely mean to abandon the run, set WORK_ALLOW_CRON_DELETE=1 for the call and say ' +
211      'so out loud.',
212  }
213}
214
hooks/guards/image-read.ts 40 lines
1// PreToolUse(Read): block Read on image files and redirect to the look-at skill.
2//
3// The case trap: the extension test lowercases `file_path`, but the deny echoes the ORIGINAL value
4// into `--file`. Reusing the lowered string is invisible until a `.PNG` payload arrives.
5import type { Guard } from './core.ts'
6
7const IMAGE_EXTENSIONS = [
8  '.jpg', '.jpeg', '.png', '.webp', '.heic', '.heif',
9  '.gif', '.bmp', '.tiff', '.tif', '.ico', '.svg',
10]
11
12export const imageReadGuard: Guard = async (payload, io) => {
13  const toolName = String(payload?.tool_name ?? '')
14  const toolInput = (payload?.tool_input ?? {}) as Record<string, unknown>
15  if (toolName !== 'Read') return {}
16
17  // look_at.sh sets this in the child it spawns. That child's whole job is to Read the image, and
18  // denying it would point it back at look_at.sh, which spawns another child: unbounded recursion.
19  if (io.env('LOOK_AT_NESTED')) return {}
20
21  const rawFilePath = (toolInput.file_path ?? '') as string
22  const filePath = rawFilePath.toLowerCase()
23  if (!filePath) return {}
24  if (!IMAGE_EXTENSIONS.some(ext => filePath.endsWith(ext))) return {}
25
26  const lookAtScript = `${io.pluginRoot}/skills/look-at/scripts/look_at.sh`
27  return {
28    deny:
29      'Use look-at skill instead of Read for images.\n\n' +
30      'Reading images directly wastes context tokens. ' +
31      'Use the look-at skill to extract only relevant information:\n\n' +
32      '```bash\n' +
33      `${lookAtScript} \\\n` +
34      `    --file "${rawFilePath}" \\\n` +
35      '    --goal "Describe what is in this image"\n' +
36      '```\n\n' +
37      'Set Bash description to: look-at: [your goal]',
38  }
39}
40
hooks/guards/pgrep.ts 562 lines
1/**
2 * PreToolUse (Bash|Monitor) BLOCKING GATE over Bash command TEXT. Three rules, each one a command
3 * whose failure mode is a hang, a suicide or a homicide rather than an error:
4 *
5 *   1. `pgrep -f` / `pkill -f` whose pattern matches the invoking shell's own command line.
6 *   2. `rg` / `rga` with no path argument, in a segment nothing pipes into.
7 *   3. Signalling a shared runtime (bun, node, python, ...) by NAME.
8 *
9 * The file keeps its original name: rule 1 is the one with the incident history below, and the
10 * hook path is wired in hooks.json and referenced by the test.
11 *
12 * ── RULE 3: SIGNALLING A SHARED RUNTIME BY NAME ────────────────────────────────────────────────
13 *
14 * A name selects every process of that name on the machine, and the user's sessions all share one
15 * uid. 2026-10-15: a farmed agent ran `pkill -x bun -u eh` and killed a concurrent canary run's bun
16 * (exit 130, 1177 leaked fixtures, a false regression report); another ran
17 * `kill -TERM $(pgrep -x -o bun)` and killed a different session's `bun test ./skills/`.
18 * `-u <user>` is therefore NOT scoping, and neither is `-s`/`-g` (a test kills its own group by pid).
19 * Only `-P <ppid>` narrows to the caller's own children. Denied: `pkill`/`killall`/`pgrep`-fed
20 * `kill` and `xargs kill` whose name, or whose `-f` pattern's first word/basename, is a shared
21 * runtime. Allowed: `-P`, a literal/`$var`/`$!` pid, a `-f` pattern naming a specific script, and a
22 * bare `pgrep` that kills nothing. This reads Bash command text only, never a test's own source.
23 *
24 * ── RULE 2: `rg` WITH NO PATH ───────────────────────────────────────────────────────────────────
25 *
26 * ripgrep searches STDIN when it is given no path and stdin is not a terminal. Under the Bash tool
27 * stdin is never a terminal, so a path-less `rg` reads a pipe that no one will ever close. Measured
28 * 2026-09-28 on ripgrep 15.2.0, stdin a fifo held open by a sleeping writer:
29 *
30 *     rg foo                          -> blocked until killed   (timeout, exit 124)
31 *     rg foo .                        -> exit 0, immediate
32 *     rg -e foo                       -> blocked
33 *     rg -e foo .                     -> exit 0
34 *     rg -f patterns                  -> blocked  (-f gives the pattern; there is still no path)
35 *     rg --files / --type-list        -> exit 0   (no-pattern modes never read stdin)
36 *     rg (no pattern at all)          -> exit 2   (usage error; rg never gets as far as stdin)
37 *
38 * The incident: a farmed agent ran
39 *     rg -n -i craft --hidden -g '!.git' -g '!CHANGELOG.md' -c | sort
40 * with no path. It hung for 34 minutes until killed. Note the pipe is on the WRONG SIDE — the
41 * segment pipes OUT to sort and nothing pipes IN, so rg's stdin was still the tool's own.
42 *
43 * Parsing rg's flags is the whole difficulty, because a value-taking flag's operand is not a path:
44 * in `-g '!.git' foo` the only positional is the pattern. So the value-taking flags are enumerated
45 * from `rg -h` rather than guessed, and `-e`/`-f` are tracked separately because they supply the
46 * pattern, which makes the FIRST positional already a path.
47 *
48 * ── RULE 1: pgrep/pkill SELF-MATCH ──────────────────────────────────────────────────────────────
49 *
50 * `-f` matches the FULL command line, and the shell running the pgrep is itself in the process table
51 * carrying that pattern in its argv. So `while pgrep -f myjob; do sleep 5; done` finds itself every
52 * time and never exits, and `pkill -f myjob` kills its own subshell.
53 *
54 * WHY THE BRACKET HEURISTIC IS GONE. The previous revision treated '[m]yproc' and an absolute path
55 * as "guarded" and only ever warned. Measured 2026-09-28:
56 *
57 *     pkill -f '[f]arm.sh --tasks .*tasks11.json'; ...; pgrep -f '[t]asks11.json' | xargs -r kill
58 *
59 * killed the invoking shell (exit 144). Both patterns are bracketed, so the old rule stayed silent —
60 * but `[t]asks11.json` matches the literal text `tasks11.json` sitting EARLIER ON THE SAME COMMAND
61 * LINE, inside the first pkill's pattern. Bracketing only stops a pattern matching its own spelling;
62 * it says nothing about the rest of the argv. So the heuristic is replaced by the thing it was
63 * approximating: compile the pattern and TEST IT against the command string the tool will run. That
64 * test subsumes both old exemptions — '[m]yproc' does not match its own text and passes, an absolute
65 * path does match its own text and is a real self-match.
66 *
67 * ONE LAYER, DETERMINISTIC. A model layer that judged over-breadth was built and measured, and
68 * dropped: it scored the incident and a harmless tail alike.
69 *
70 * CRASH POLICY. A crash DENIES in both hosts: the script through `denyOnCrash`, the mod through its
71 * catch (hooks/guards/mod.ts). A non-zero exit is treated as NON-BLOCKING by Claude Code, i.e. a
72 * silent allow.
73 */
74import type { Guard } from './core.ts'
75
76/** Short options that consume a value (pgrep/pkill: -d delim, -u/-U uid, -P ppid, ...). */
77const VALUE_SHORT = "dgGPstuUF";
78/** Long options that consume a following token. */
79const VALUE_LONG = new Set([
80  "--delimiter", "--pgroup", "--group", "--parent", "--session", "--terminal",
81  "--euid", "--uid", "--ns", "--nslist", "--signal", "--pidfile",
82]);
83
84export interface Word {
85  text: string;
86  /** True when every character came from inside quotes -- `echo "pgrep -f x"` must not count. */
87  quoted: boolean;
88}
89
90/**
91 * Split a command into pipeline segments of words, quote-aware.
92 *
93 * Segment boundaries are the unquoted shell separators. This is what makes `echo "pgrep -f x"` a
94 * single `echo` segment (the pgrep text is one quoted WORD, never a command position) while
95 * `while pgrep -f worker.py; do ...` is a segment whose command word is pgrep. Splitting on `$(`
96 * and backtick is what makes `kill $(pgrep -f x)` read as a kill segment plus a pgrep segment.
97 */
98export function segments(command: string): { words: Word[]; piped: boolean; sub?: boolean }[] {
99  const out: { words: Word[]; piped: boolean; sub?: boolean }[] = [];
100  let words: Word[] = [];
101  let cur = "";
102  let curQuoted = false;
103  let curStarted = false;
104  let quote: '"' | "'" | null = null;
105  let pipedInto = false;
106  let nextSub = false; // the next segment opens inside `$(` or a backtick
107  let inTick = false;
108  let curSub = false;
109
110  const endWord = () => {
111    if (curStarted) words.push({ text: cur, quoted: curQuoted && cur.length > 0 });
112    cur = "";
113    curQuoted = false;
114    curStarted = false;
115  };
116  const endSegment = (nextPiped: boolean) => {
117    endWord();
118    if (words.length) out.push({ words, piped: pipedInto, ...(curSub ? { sub: true } : {}) });
119    words = [];
120    pipedInto = nextPiped;
121    curSub = nextSub;
122    nextSub = false;
123  };
124
125  for (let i = 0; i < command.length; i++) {
126    const ch = command[i];
127    if (quote) {
128      if (ch === quote) quote = null;
129      else if (ch === "\\" && quote === '"' && i + 1 < command.length) {
130        cur += command[++i];
131        curStarted = true;
132      } else {
133        cur += ch;
134        curStarted = true;
135      }
136      continue;
137    }
138    if (ch === "'" || ch === '"') {
139      quote = ch as '"' | "'";
140      curStarted = true;
141      if (cur.length === 0) curQuoted = true;
142      continue;
143    }
144    if (ch === "\\" && i + 1 < command.length) {
145      cur += command[++i];
146      curStarted = true;
147      continue;
148    }
149    if (ch === " " || ch === "\t") {
150      endWord();
151      continue;
152    }
153    if (ch === "|") {
154      const isOr = command[i + 1] === "|";
155      endSegment(!isOr);
156      if (isOr) i++;
157      continue;
158    }
159    if (ch === "`") {
160      inTick = !inTick;
161      nextSub = inTick;
162      endSegment(false);
163      continue;
164    }
165    if (ch === ";" || ch === "&" || ch === "\n" || ch === "(" || ch === ")" || ch === "{" || ch === "}") {
166      if (ch === "&" && command[i + 1] === "&") i++;
167      endSegment(false);
168      continue;
169    }
170    if (ch === "$" && command[i + 1] === "(") {
171      nextSub = true;
172      endSegment(false);
173      i++;
174      continue;
175    }
176    cur += ch;
177    curStarted = true;
178  }
179  endSegment(false);
180  return out;
181}
182
183/** Shell keywords and wrappers that sit in front of the real command word. */
184const PREFIXES = new Set(["while", "until", "if", "elif", "then", "do", "done", "!", "sudo", "time", "command", "exec", "nohup", "env"]);
185
186/** Strip leading keywords and `VAR=value` assignments; return the index of the command word. */
187export function commandWordIndex(words: Word[]): number {
188  let i = 0;
189  while (i < words.length) {
190    const w = words[i].text;
191    if (PREFIXES.has(w) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) {
192      i++;
193      continue;
194    }
195    return i;
196  }
197  return -1;
198}
199
200/** `... | grep -v $$` (in any flag spelling) excludes the invoking shell. */
201function excludesSelf(segs: { words: Word[]; piped: boolean }[]): boolean {
202  for (const seg of segs) {
203    if (!seg.piped) continue;
204    const ci = commandWordIndex(seg.words);
205    if (ci < 0) continue;
206    const name = seg.words[ci].text.split("/").pop();
207    if (name !== "grep" && name !== "rg") continue;
208    const rest = seg.words.slice(ci + 1);
209    const hasV = rest.some(w => /^--invert-match$/.test(w.text) || (/^-[A-Za-z]+$/.test(w.text) && w.text.includes("v")));
210    const hasSelf = rest.some(w => w.text.includes("$$"));
211    if (hasV && hasSelf) return true;
212  }
213  return false;
214}
215
216interface Invocation {
217  tool: "pgrep" | "pkill";
218  pattern: string | null;
219}
220
221export interface Analysis {
222  /** Invocations whose pattern MATCHES the command string itself — certain, no model needed. */
223  selfMatches: Invocation[];
224  /** `rg`/`rga` segments with no path and no incoming pipe or redirect — they read a live stdin. */
225  pathlessRg: string[];
226  /** Segments that signal a shared runtime by name — RULE 3. */
227  sharedKills: string[];
228}
229
230// ── rg FLAG TABLE (enumerated from `rg -h`, ripgrep 15.2.0) ─────────────────────────────────────
231
232/** Short flags whose operand is the NEXT token (or the rest of the cluster): -A3, -g '!x', -tpy. */
233const RG_VALUE_SHORT = "ABCdeEfgjmMrtT";
234
235/** Long flags whose operand is the next token when not spelled `--flag=value`. */
236const RG_VALUE_LONG = new Set([
237  "--after-context", "--before-context", "--color", "--colors", "--context",
238  "--context-separator", "--dfa-size-limit", "--encoding", "--engine", "--file",
239  "--field-context-separator", "--field-match-separator", "--generate", "--glob",
240  "--hostname-bin", "--hyperlink-format", "--iglob", "--ignore-file", "--max-columns",
241  "--max-count", "--max-depth", "--max-filesize", "--path-separator", "--pre", "--pre-glob",
242  "--regexp", "--regex-size-limit", "--replace", "--sort", "--sortr", "--threads", "--type",
243  "--type-add", "--type-clear", "--type-not",
244]);
245
246/** Flags that supply the PATTERN, which makes the first positional already a PATH. */
247const RG_PATTERN_FLAGS = new Set(["-e", "--regexp", "-f", "--file"]);
248
249/** Modes that take no pattern and never read stdin — verified empirically, see the header. */
250const RG_NO_PATTERN_MODE = new Set(["--files", "--type-list", "--version", "--help", "--generate"]);
251
252/** An unquoted redirect token: `<`, `<<EOF`, `<<<x`, `2>`, `>out`, `<&3`. */
253function redirectKind(w: Word): "in" | "out" | null {
254  if (w.quoted) return null;
255  if (/^\d*<|^<</.test(w.text)) return "in";
256  if (/^\d*>/.test(w.text)) return "out";
257  return null;
258}
259
260/**
261 * Decide whether one segment is an `rg`/`rga` that will read a stdin nobody closes.
262 *
263 * Returns the offending segment's text, or null. A segment fed by a pipe or by ANY input redirect
264 * is fine — stdin is then a real, finite source, which is ripgrep's documented streaming mode.
265 */
266function pathlessRgSegment(seg: { words: Word[]; piped: boolean }): string | null {
267  const ci = commandWordIndex(seg.words);
268  if (ci < 0) return null;
269  const word = seg.words[ci];
270  if (word.quoted) return null; // came out of quotes; not a command position
271  const name = word.text.split("/").pop();
272  if (name !== "rg" && name !== "rga") return null;
273  if (seg.piped) return null; // `cmd | rg foo` — stdin is the pipe, and it ends
274
275  const args = seg.words.slice(ci + 1);
276  let positionals = 0;
277  let patternFromFlag = false;
278  let noPatternMode = false;
279  let endOfFlags = false;
280
281  for (let i = 0; i < args.length; i++) {
282    const w = args[i];
283    const t = w.text;
284
285    if (!endOfFlags) {
286      const redir = redirectKind(w);
287      if (redir === "in") return null; // `rg foo < file`, heredoc, here-string
288      if (redir === "out") {
289        // A bare `>` / `2>` carries its operand in the next token; `>out.txt` carries its own.
290        if (/^\d*>>?$/.test(t)) i++;
291        continue;
292      }
293      if (t === "--") {
294        endOfFlags = true;
295        continue;
296      }
297      if (t.startsWith("--")) {
298        const long = t.split("=")[0];
299        if (RG_NO_PATTERN_MODE.has(long)) noPatternMode = true;
300        if (RG_PATTERN_FLAGS.has(long)) patternFromFlag = true;
301        if (RG_VALUE_LONG.has(long) && !t.includes("=")) i++;
302        continue;
303      }
304      if (t.length > 1 && t.startsWith("-")) {
305        const chars = t.slice(1);
306        for (let c = 0; c < chars.length; c++) {
307          const ch = chars[c];
308          if (RG_VALUE_SHORT.includes(ch)) {
309            if (ch === "e" || ch === "f") patternFromFlag = true;
310            if (c === chars.length - 1) i++; // operand is the next word
311            break; // rest of this token is the operand
312          }
313        }
314        continue;
315      }
316      if (t === "-") return null; // `-` is the explicit "read stdin" spelling; deliberate
317    }
318    positionals++;
319  }
320
321  if (noPatternMode) return null; // --files / --type-list / --version: no pattern, no stdin read
322  // Without -e/-f the first positional is the PATTERN, so a path needs a SECOND one. With -e/-f the
323  // pattern is already in hand, so the first positional is a path.
324  const paths = patternFromFlag ? positionals : positionals - 1;
325  if (paths > 0) return null;
326  // No pattern anywhere: rg exits 2 on a usage error without ever reaching stdin.
327  if (!patternFromFlag && positionals === 0) return null;
328
329  return seg.words.map(x => x.text).join(" ");
330}
331
332// ── RULE 3: SHARED-RUNTIME KILLS ────────────────────────────────────────────────────────────────
333
334const SHARED_RUNTIMES = new Set(["bun", "node", "deno", "python", "python3", "pytest", "uv", "claude", "typst", "bash", "sh", "zsh"]);
335
336/** The runtime a pgrep/pkill pattern names, or null. `-f` patterns are argv text: first word. */
337function sharedName(pattern: string | null): string | null {
338  if (pattern === null) return null;
339  const first = pattern.trim().replace(/^[\^(]+/, "").split(/\s+/)[0] ?? "";
340  const m = /^([A-Za-z0-9_]+)(?:[$)]*|[^A-Za-z0-9_.-].*)$/.exec(first.split("/").pop() ?? "");
341  return m && SHARED_RUNTIMES.has(m[1]) ? m[1] : null;
342}
343
344/** pgrep/pkill/killall arguments: the pattern(s) and whether `-P` (parent) scopes the match. */
345function nameArgs(words: Word[], ci: number): { names: string[]; parent: boolean } {
346  const names: string[] = [];
347  let parent = false;
348  const args = words.slice(ci + 1);
349  for (let i = 0; i < args.length; i++) {
350    const t = args[i].text;
351    if (t === "--") continue;
352    if (t.startsWith("--")) {
353      const long = t.split("=")[0];
354      if (long === "--parent") parent = true;
355      if ((VALUE_LONG.has(long) || long === "--user") && !t.includes("=")) i++;
356      continue;
357    }
358    if (t.length > 1 && t.startsWith("-")) {
359      if (/^-\d+$/.test(t) || /^-[A-Z]+[0-9]*$/.test(t)) continue; // signal: -9, -TERM
360      const chars = t.slice(1);
361      for (let c = 0; c < chars.length; c++) {
362        const ch = chars[c];
363        if (ch === "P") parent = true;
364        if (VALUE_SHORT.includes(ch) || ch === "u") {
365          if (c === chars.length - 1) i++;
366          break;
367        }
368      }
369      continue;
370    }
371    names.push(t);
372  }
373  return { names, parent };
374}
375
376/** Segments that select a shared runtime by name and signal it (or feed a signaller). */
377function sharedKillSegments(segs: { words: Word[]; piped: boolean; sub?: boolean }[]): string[] {
378  const out: string[] = [];
379  const cmd = (seg: { words: Word[] }) => {
380    const ci = commandWordIndex(seg.words);
381    if (ci < 0 || seg.words[ci].quoted) return null;
382    return { ci, name: seg.words[ci].text.split("/").pop() ?? "" };
383  };
384  for (let k = 0; k < segs.length; k++) {
385    const seg = segs[k];
386    const c = cmd(seg);
387    if (!c) continue;
388    const { names, parent } = nameArgs(seg.words, c.ci);
389    if (parent) continue;
390    let hit: string | null = null;
391    if (c.name === "killall") {
392      hit = names.map(n => sharedName(n)).find(Boolean) ?? null;
393    } else if (c.name === "pkill" || c.name === "pgrep") {
394      hit = sharedName(names[0] ?? null);
395      if (hit && c.name === "pgrep") {
396        // pgrep alone kills nothing: it counts only when `kill $(pgrep ..)` or `pgrep .. | xargs kill`.
397        const prev = k > 0 ? cmd(segs[k - 1]) : null;
398        const next = k + 1 < segs.length && segs[k + 1].piped ? segs[k + 1] : null;
399        const nc = next ? cmd(next) : null;
400        const feedsKill = (seg.sub && prev?.name === "kill") ||
401          (nc?.name === "xargs" && next!.words.slice(nc.ci + 1).some(w => /^(kill|pkill)$/.test(w.text.split("/").pop() ?? "")));
402        if (!feedsKill) hit = null;
403      }
404    }
405    if (hit) out.push(seg.words.map(w => w.text).join(" "));
406  }
407  return out;
408}
409
410/**
411 * Compile a pgrep pattern the way pgrep does — as an extended regex.
412 *
413 * JS RegExp is ERE plus extensions, which is the right direction for a guard: it accepts everything
414 * pgrep accepts except POSIX character classes (`[[:alpha:]]`), which fail to compile here.
415 */
416function compilePattern(pattern: string): RegExp | null {
417  try {
418    return new RegExp(pattern);
419  } catch {
420    return null;
421  }
422}
423
424/** Parse one pgrep/pkill segment. Returns null when the segment is not one, or uses -x. */
425function parseInvocation(seg: { words: Word[] }): { inv: Invocation; full: boolean } | null {
426  const ci = commandWordIndex(seg.words);
427  if (ci < 0) return null;
428  const word = seg.words[ci];
429  if (word.quoted) return null; // came out of quotes; not a command position
430  const name = word.text.split("/").pop();
431  if (name !== "pgrep" && name !== "pkill") return null;
432
433  let full = false;
434  let exact = false;
435  let pattern: string | null = null;
436
437  const args = seg.words.slice(ci + 1);
438  for (let i = 0; i < args.length; i++) {
439    const t = args[i].text;
440    if (t === "--") continue;
441    if (t.startsWith("--")) {
442      const long = t.split("=")[0];
443      if (long === "--full") full = true;
444      if (long === "--exact") exact = true;
445      if (VALUE_LONG.has(long) && !t.includes("=")) i++;
446      continue;
447    }
448    if (t.length > 1 && t.startsWith("-")) {
449      if (/^-\d+$/.test(t) || /^-[A-Z]+[0-9]*$/.test(t)) continue; // pkill signal: -9, -TERM
450      const chars = t.slice(1);
451      for (let c = 0; c < chars.length; c++) {
452        const ch = chars[c];
453        if (ch === "f") full = true;
454        else if (ch === "x") exact = true;
455        else if (VALUE_SHORT.includes(ch)) {
456          if (c === chars.length - 1) i++; // value is the next word
457          break; // rest of this token is the value
458        }
459      }
460      continue;
461    }
462    pattern = t;
463    break;
464  }
465
466  if (exact) return null; // -x is a whole-name match; it cannot pick up a pattern from an argv
467  return { inv: { tool: name, pattern }, full };
468}
469
470/**
471 * Classify every pgrep/pkill in one Bash command string.
472 *
473 * The deterministic test is the whole point: each `-f` pattern is compiled and matched against
474 * `command`, which is what the shell's own argv will carry. A hit means the process will find
475 * itself, and that is certain rather than judged. Anything the text cannot settle — no `-f`, a
476 * pattern from a variable, a pattern that will not compile — is allowed silently: an uncompilable
477 * `-f` pattern is an error pgrep itself will report, and this gate exists only for the certain case.
478 */
479export function analyze(command: string): Analysis {
480  const segs = segments(command);
481  const pathlessRg: string[] = [];
482  const sharedKills = sharedKillSegments(segs);
483  for (const seg of segs) {
484    const bad = pathlessRgSegment(seg);
485    if (bad) pathlessRg.push(bad);
486  }
487
488  if (excludesSelf(segs)) return { selfMatches: [], pathlessRg, sharedKills };
489  const selfMatches: Invocation[] = [];
490
491  for (const seg of segs) {
492    const parsed = parseInvocation(seg);
493    if (!parsed) continue;
494    const { inv, full } = parsed;
495    if (!full || inv.pattern === null) continue; // a name-only match cannot pick the pattern out of an argv
496    const re = compilePattern(inv.pattern);
497    if (re && re.test(command)) selfMatches.push(inv);
498  }
499  return { selfMatches, pathlessRg, sharedKills };
500}
501
502/** Truncate an untrusted pattern before echoing it back into the model's context. */
503function show(pattern: string | null): string {
504  if (pattern === null) return "<pattern from a variable>";
505  const p = pattern.length > 60 ? pattern.slice(0, 57) + "..." : pattern;
506  return p.replace(/[\n\r]/g, " ");
507}
508
509/** The one-line fix, named in every message this gate emits. */
510const FIX =
511  "Fix: bracket the pattern ('[m]yproc') AND make sure that literal text appears nowhere " +
512  "else in the command — or better, signal exact pids, use `pgrep -x <name>` without -f, or a pidfile.";
513
514
515export const pgrepSelfMatch: Guard = async payload => {
516  const toolInput = (payload.tool_input ?? {}) as Record<string, unknown>;
517  const command = typeof toolInput.command === "string" ? toolInput.command : "";
518  if (!command) return {};
519
520  const { selfMatches, pathlessRg, sharedKills } = analyze(command);
521
522  // A path-less rg reads the tool's own stdin, which never closes: the process hangs rather than
523  // erroring, so nothing downstream ever reports it.
524  if (pathlessRg.length) {
525    return {
526      deny:
527        "🛑 " +
528        pathlessRg.map(s => `\`${show(s)}\` has no path argument.`).join("\n") +
529        "\nrg reads stdin when given no path and stdin is not a terminal; pass a path, e.g. `rg PATTERN .`",
530    };
531  }
532
533  // A name-selected kill reaches every session's processes of that name, not just this agent's.
534  if (sharedKills.length) {
535    return {
536      deny:
537        "🛑 " +
538        sharedKills.map(s => `\`${show(s)}\` selects a shared runtime by name.`).join("\n") +
539        "\nIt will signal other sessions' and runs' processes of that name (`-u <user>` is not scoping). " +
540        "Fix: signal only PIDs you launched: capture $! or use pkill -P <your pid>.",
541    };
542  }
543
544  // Any self-match denies: a self-matching kill takes out its own shell, and a self-matching wait
545  // loop never exits.
546  if (selfMatches.length) {
547    return {
548      deny:
549        "🛑 " +
550        selfMatches
551          .map(
552            f =>
553              `\`${f.tool} -f '${show(f.pattern)}'\` matches THIS command's own text, so it will find the ` +
554              `shell running it${f.tool === "pkill" ? " and kill it" : " (a wait loop on it never exits)"}.`,
555          )
556          .join("\n") +
557        "\n" + FIX,
558    };
559  }
560  return {};
561};
562