SLOPSHOPPER

kit

The agents kit inside Claude Code: the /flow pane

paneguardcommandprocess
v0.5.0MITupdated 2026-10-26alopezari/agents-kit/mods/kit
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · kit
│ ┃ flow ✕ › fix the failing auth test and add an audit log call │ ┃ Gathering… │ ┃ r: Refresh ● kit: kit: agents: still registering after 2 s, so the session start │ ● kit: kit: no review agents: bin/triage --lens-briefs printed someth │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /flow │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · flow
Gathering… r: Refresh
README

agents-kit

One setup for every coding agent you use (Claude Code, Codex): the same instructions, skills, guardrails and checks, whichever harness runs the work. Agents are told to work like a staff engineer, and hooks check that they did: irreversible and outward-facing commands stop and wait for you, every turn that edits code is verified, and a pull request can't be opened until the exact change has been reviewed. You can switch any of those phases off, and back on, for a branch, a repo or everywhere: phase off verify as the first line of a message, or /flow off verify in Claude Code. review-rounds 2 the same way sets how many re-checks the review runs after its first pass (1 by default).

docs/framework.md is the full reference: every hook, guard rule, check, skill, tool and scheduled job, with diagrams. It is generated from the code on every commit, so it describes what the kit does now.

macOS only for now (the scheduled jobs use launchd).

Install

git clone https://github.com/alopezari/agents-kit.git ~/.agents && ~/.agents/install.sh

install.sh wires every installed harness and is safe to re-run. To check the setup afterwards:

~/.agents/install.sh --doctor   # report what's missing, change nothing
~/.agents/tests/run.sh          # regression suite (passes once --doctor is clean)

The kit must live at ~/.agents. The installer:

  • offers to install missing required and recommended programs from deps.txt through Homebrew, asking once (--yes skips the question; without a terminal it only reports them);
  • links AGENTS.md as each harness's global instructions and the skills into each harness;
  • registers the hooks next to any hooks already there;
  • fetches the third-party skills in skills.external, a pinned one at its commit into vendor/, and installs the Node dependencies of tools/ and site/;
  • sets the Claude Code status line and enables the kit's git hooks (they keep docs/framework.md current);
  • registers the kit as a Claude Code plugin marketplace and installs its plugin, the /flow mod (see Mods contract);
  • installs the scheduled jobs;
  • when git uses a per-host proxy, offers to link bin/gh into /usr/local/bin (asks for your password).

It also adds the kit's baseline harness settings (no fast mode, effort defaults) wherever a key is missing, without overwriting one you set. Files it replaces are backed up under backups/.

To remove it, ~/.agents/uninstall.sh lists every link, hook, status line, scheduled job and the kit's Claude Code plugin that still point at the kit, asks, and removes them (--yes skips the question). Your own hooks and settings stay, and so do the baseline settings and the programs installed through Homebrew. It backs up the settings files it edits to ~/.agents-uninstall-backups/, and leaves ~/.agents itself for you to delete.

What it doesn't do, on a new machine:

  1. Install or log in to the harnesses (claude, codex) and gh. Install them before running install.sh, which only wires the harnesses it finds.
  2. Trust the Codex hooks. Open Codex once and approve them; install.sh --doctor warns until you do.
  3. Install harness plugins, other than the kit's own, or MCP servers. Add the ones you use yourself, or keep their setup in a profile.

Requirements: deps.txt lists every program the kit runs. install.sh offers to install the missing required ones (python3, git, jq, node, gh) and recommended ones (semgrep, gitleaks, php) through Homebrew, and says how to install the optional ones, each needed by one feature. install.sh --doctor reports what is missing, and tests/run.sh expects it to report nothing.

Make it yours

  • Instructions: edit AGENTS.md. It is plain Markdown and every harness reads the same file.
  • A repository: add repos/<checkout-directory-name>/notes.md with the context agents should read there. Add an executable verify when the automatic checks aren't enough. Nothing is written into the repository itself. See repos/README.md.
  • A profile: keep anything tied to one employer or client in a separate private repository and layer it in with install.sh --profile <dir>. It can hold repo overlays, work-only skills, research, MCP write rules and the repositories to learn from; examples/sample-profile/ has one of each to start from. The core stays generic and shareable.

Hook contract

Every hook is a small program with one contract: a JSON payload on stdin, a JSON decision on stdout. Claude Code and Codex share this contract natively. Other harnesses need an adapter that translates their events into it.

Payload fields used: tool_name, tool_input.command, tool_input.file_path (or notebook_path, or the file list in Codex's apply_patch input), cwd, session_id, stop_hook_active, transcript_path (whose tail holds the agent's last message, for a yes to its offer), and turn_id to tell Codex apart in the log.

Decisions:

  • Deny a command: {"hookSpecificOutput": {"permissionDecision": "deny", "permissionDecisionReason": ...}}.
  • Block after an edit or at stop: {"decision": "block", "reason": ...}, optionally with systemMessage for the user.

Mods contract

Claude Code also loads the kit as a plugin, mods/kit/, whose mod runs inside Claude Code: it can draw panes, run commands without a turn and define agent types. Mods exist only in Claude Code, so the kit keeps working the same with or without them. Every mod follows these rules:

  1. It owns no workflow state. Specs, stamps, reports and evidence stay where the kit's tools keep them (.git/agents/, or a temporary directory when .git can't be written) and go through bin/ and hooks/review_stamp.py, so a change started in Claude Code can be finished in Codex, and the other way round. What those tools cache or migrate follows their own rules.
  2. It owns no safety. The Python hooks decide what is blocked, in every harness. A mod can add to that in Claude Code, or carry the user's own answer to a hook through the kit's tools, as their next message would; it never decides one. A disabled or failed mod leaves the behavior as it was without it, which is what Codex has.
  3. Every capability names what Codex has instead, or says it has nothing. They are listed in mods/kit/hooks/features.js, which docs/framework.md prints, and the mod's tests fail when the commands or agents it registers, or the buttons it draws, differ from the list.
  4. The flow works fully with the mod disabled or failed. claude --safe-mode turns off the kit's settings hooks too, so it isn't a supported way to run the kit.
  5. Guarantees go by tier. A capability that gives Claude Code a stronger guarantee than Codex has records where each fact came from, so the record shows which tier it holds. A record without that provenance counts as the weaker tier.
  6. It calls the kit's Python instead of reimplementing it, so one rule never has two implementations that drift apart.

Its /flow pane shows where the branch is in the flow, with the phases switched off, and runs verify without a turn; /flow off <phase> [--repo|--global] and /flow on … switch a phase as the message line does. When a guard blocks an MCP write or a DROP/TRUNCATE command, the mod asks you in a dialog that shows the call; allowing it, for that call or until your next message, writes the approval your message would have (bin/approve), and the objects that write touches stay approved for the session as after a message. A dialog that can't ask says so in the transcript, and an MCP write block in a Claude Code session where the mod didn't start says no dialog will show. docs/framework.md lists every capability with its Codex equivalent.

install.sh registers ~/.agents as the agents-kit plugin marketplace and installs kit@agents-kit. The plugin loads in place, so a pull reaches it at the next session start or /reload-plugins. To work on the mod, run claude --plugin-dir ~/.agents/mods/kit, which reloads it on save; tests/run.sh mods validates and tests it.

Adding a harness

  1. Point its global instructions file at AGENTS.md, and its skills directory at skills/ if it has one.
  2. If it has no hook settings of its own, write adapters/<harness>/ to translate its events into the payloads above:
  3. before a command → guard_bash.py;
  4. after an edit → post_edit.py;
  5. at idle or stop → stop_checks.py, with a guard so the stop check continues the agent only once per user turn.
  6. Add a section to install.sh and run install.sh --doctor. Then test with a harmless blocked command in a scratch repo.
  7. Teach bin/docs where the new harness registers its hooks (HARNESS_OF_SETTINGS and harness_hooks), then commit: the pre-commit hook regenerates docs/framework.md.

Testing a hook change through a real harness

tests/ feeds the hooks hand-made payloads. To see a branch's hooks run inside Codex itself, with its real payloads, point HOME at a directory whose .agents is the branch's checkout. Codex's hooks.json runs python3 $HOME/.agents/hooks/<hook>.py, and it trusts a hook by that command text, so the branch's code runs through the entries you already approved. CODEX_HOME keeps Codex's own settings, login and trust, and GH_CONFIG_DIR keeps gh logged in; they come before HOME= because bash and zsh expand ~ with the HOME assigned before it:

H=$(mktemp -d) && ln -s ~/.agents-worktree-<name> "$H/.agents"   # the branch's checkout
git init -q /tmp/hook-probe && git -C /tmp/hook-probe commit -q --allow-empty -m init
echo 'Run this shell command once and report what happened: <a command the change should block or allow>' \
  | CODEX_HOME=~/.codex GH_CONFIG_DIR=~/.config/gh HOME="$H" \
    codex exec -C /tmp/hook-probe --skip-git-repo-check -s workspace-write --ephemeral -
tail -3 ~/.agents-worktree-<name>/logs/hooks.jsonl

The hooks log to the branch checkout's logs/ (not in git), so the last lines show each decision with "harness": "codex". The checkout has no repos/<repo>/verify overlay, so the stop hook falls back to the automatic verify. Use a scratch repo: a hook that fails to block lets the command run.

Not in git

logs/, backups/, research/, approvals/, monitors/state/, review-mining/runs/, review-mining/baseline.json and usage/*.json hold local, possibly private data; site/dist/ is the built website. Profiles are linked in and never committed here.

License

MIT, see LICENSE.

Source 2 files
hooks/register.js 620 lines
1// The kit inside Claude Code. Everything here shows or runs the kit's own tools: the state stays with them
2// and the decisions in the Python hooks, so Codex and a session without this mod get the same flow.
3import { FEATURES } from './features.js'
4
5const PANE = 'flow'
6const PROCESS_TIMEOUT_MS = 30_000
7// phase_switches.py's exit for a switch it refused; 1 is Python's own for a crash.
8const SWITCH_REFUSED = 3
9// ci-wait --once makes one GitHub round trip per check source, and one more for the no-CI probe when there are none,
10// each bounded at 30 s; a GitHub slower than this reads as couldn't read.
11const CI_TIMEOUT_MS = 90_000
12const STAMPS = [['verify', 'verify'], ['review', 'review'], ['validate', 'validate']]
13const CI_OUTCOMES = { 0: 'passed', 1: 'failed', 2: 'running', 3: 'no checks', 4: 'unreadable', 5: 'none in this repo' }
14const REPORT_LINE = /^(ran|skipped|warning|error):/
15const VERIFY_TAIL_LINES = 8
16// Claude Code refuses a Text string over 10,000 characters; a verify line can be any length.
17const LINE_CHARS = 500
18// stop_checks.py bounds the repo's verify at 600 s, but not its own git reads and stamp writes around it.
19const VERIFY_DEADLINE_MS = 660_000
20// What `stop_checks.py verify` prints when the run passed without checking anything.
21const CHECKED_NOTHING = 'verify passed, but it checked nothing'
22// A gathering whose branch or HEAD moved while it ran is gathered again, this many times in all.
23const GATHER_ATTEMPTS = 2
24const NEEDS_ATTENTION = /couldn't read|^Couldn't|^CI: failed|^Run verify.* failed/
25
26// Each review lens becomes the agent type `kit:review-<key>`, briefed from what `bin/triage --lens-briefs` cuts
27// out of lenses.md. No edit tools is a convenience for the reviewer, not a guard (Bash can still write): the hooks
28// run for subagents too.
29const REVIEWER_TOOLS = ['Read', 'Grep', 'Glob', 'Bash']
30// The build runs on the model and effort of the spec's risk tier; the session plans, delegates and fixes.
31const BUILDERS = [
32  { tier: 'low', model: 'sonnet', effort: 'medium' },
33  { tier: 'standard', model: 'sonnet', effort: 'high' },
34  { tier: 'high', model: 'opus', effort: 'high' },
35]
36// Registering takes tens of milliseconds and must land before the first turn (`claude -p` starts one at once), so the
37// session start waits for it, but never longer than this.
38const AGENTS_WAIT_MS = 2_000
39
40// What the pane draws. One gathering runs at a time: a request during one gathers again once it ends.
41let shown = null
42let gathering = false
43let gatherAgain = false
44let verifyRun = { state: 'idle' }
45// A verify stopped at its deadline holds the button until its child is gone, so two never write one report.
46let verifyStopping = false
47
48async function run($, argv, cwd, timeoutMs = PROCESS_TIMEOUT_MS) {
49  try {
50    return await $.process.run(argv, { cwd, timeoutMs })
51  } catch (error) {
52    return { failure: messageOf(error) }
53  }
54}
55
56function messageOf(error) {
57  return String(error?.message ?? error)
58}
59
60function failureOf(result) {
61  if (result.failure) return result.failure
62  return 'exit ' + result.exitCode + (result.stderr?.trim() ? ': ' + result.stderr.trim().split('\n')[0] : '')
63}
64
65async function kitDir($) {
66  return (await $.env.get('HOME')) + '/.agents'
67}
68
69async function stampLine($, kit, root, label, kind) {
70  const check = (stampKind) => run($, ['python3', kit + '/hooks/review_stamp.py', 'check', '--kind', stampKind], root)
71  const result = await check(kind)
72  if (result.exitCode === 0) return label + ': current'
73  if (result.exitCode !== 1) return label + ": couldn't read: " + failureOf(result)
74  if (kind === 'verify') {
75    const empty = await check('verify-empty')
76    if (empty.exitCode === 0) return label + ': current, but it checked nothing'
77    if (empty.exitCode !== 1) return label + ": couldn't read: " + failureOf(empty)
78  }
79  return label + ': not current'
80}
81
82async function verifyReportLines($, kit, root) {
83  const path = await run($, [kit + '/bin/reports', 'path', 'verify'], root)
84  if (path.failure || path.exitCode !== 0) return ["couldn't read: " + failureOf(path)]
85  const file = path.stdout.trim()
86  try {
87    if (!(await $.fs.exists(file))) return ['no verify run yet']
88    const { mtimeMs } = await $.fs.stat(file)
89    const lines = (await $.fs.read(file)).split('\n')
90    return [lines[0].replace(/^# /, '') + ' · ' + dateTimeOf(mtimeMs), ...lines.filter((line) => REPORT_LINE.test(line))]
91  } catch (error) {
92    return ["couldn't read: " + messageOf(error)]
93  }
94}
95
96async function ciLine($, kit, root, head) {
97  const upstream = await run($, ['git', 'rev-parse', '--verify', '--quiet', '@{u}'], root)
98  if (upstream.exitCode === 1) return 'CI: HEAD not pushed (no upstream)'
99  if (upstream.failure || upstream.exitCode !== 0) return "CI: couldn't read: " + failureOf(upstream)
100  const pushed = await run($, ['git', 'merge-base', '--is-ancestor', head, '@{u}'], root)
101  if (pushed.failure || pushed.exitCode > 1) return "CI: couldn't read: " + failureOf(pushed)
102  if (pushed.exitCode === 1) return 'CI: HEAD not pushed'
103  const ci = await run($, [kit + '/bin/ci-wait', '--sha', head, '--once', '--no-log'], root, CI_TIMEOUT_MS)
104  const outcome = ci.failure ? undefined : CI_OUTCOMES[ci.exitCode]
105  if (!outcome) return "CI: couldn't read: " + failureOf(ci)
106  const reason = ci.exitCode === 4 ? (ci.stderr.trim() || ci.stdout.trim()).split('\n')[0] : ''
107  const line = 'CI: ' + outcome + (reason ? ': ' + reason : '')
108  const status = await run($, ['git', 'status', '--porcelain'], root)
109  if (status.failure || status.exitCode !== 0) {
110    return line + ", for " + head.slice(0, 7) + "; couldn't tell whether there are uncommitted changes: " + failureOf(status)
111  }
112  return line + (status.stdout.trim() !== '' ? ', for ' + head.slice(0, 7) + ' without the uncommitted changes' : '')
113}
114
115async function contextLine($) {
116  try {
117    const { context } = await $.session.usage()
118    return 'context: ' + (context?.percent === undefined ? '–' : Math.round(context.percent) + '%')
119  } catch {
120    return 'context: –'
121  }
122}
123
124function timeOf(ms) {
125  return new Date(ms).toTimeString().slice(0, 8)
126}
127
128function dateTimeOf(ms) {
129  const date = new Date(ms)
130  const pad = (n) => String(n).padStart(2, '0')
131  return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + timeOf(ms)
132}
133
134// The checkout at `cwd`: { root, branch, head, inMain? }, or { none } saying why there is no change to follow.
135async function checkout($, cwd) {
136  const top = await run($, ['git', 'rev-parse', '--show-toplevel'], cwd)
137  if (top.failure) return { none: "Couldn't read the repository: " + top.failure }
138  // git exits 128 for "not a git repository", and for a refused or broken one too.
139  if (top.exitCode !== 0 && /not a git repository/.test(top.stderr)) return { none: 'Not in a git repository: no change to follow.' }
140  if (top.exitCode !== 0) return { none: "Couldn't read the repository: " + failureOf(top) }
141  const at = await branchAt($, top.stdout.trim())
142  if (at.none || at.branch) return at
143  return (await mainCheckout($, at.root)) ?? { none: 'Detached HEAD: no change to follow.' }
144}
145
146async function branchAt($, root) {
147  const [branch, head] = await Promise.all([
148    run($, ['git', 'branch', '--show-current'], root),
149    run($, ['git', 'rev-parse', 'HEAD'], root),
150  ])
151  if (head.failure || head.exitCode !== 0) return { none: "Couldn't read HEAD: " + failureOf(head) }
152  if (branch.failure || branch.exitCode !== 0) return { none: "Couldn't read the branch: " + failureOf(branch) }
153  return { root, branch: branch.stdout.trim(), head: head.stdout.trim() }
154}
155
156// kit-ship frees the branch by detaching the session's worktree (bin/free-branch), and the user checks it out in the main one.
157async function mainCheckout($, root) {
158  const listed = await run($, ['git', 'worktree', 'list', '--porcelain'], root)
159  if (listed.failure || listed.exitCode !== 0) return { none: "Detached HEAD, and couldn't find the main checkout: " + failureOf(listed) }
160  const first = listed.stdout.split('\n\n')[0]
161  const main = /^worktree (.+)$/m.exec(first)?.[1]
162  if (!main || main === root || /^bare$/m.test(first)) return null
163  const at = await branchAt($, main)
164  return at.none || at.branch ? { ...at, inMain: !at.none } : null
165}
166
167function clip(text) {
168  return text.length > LINE_CHARS ? text.slice(0, LINE_CHARS - 1) + '…' : text
169}
170
171function nameOf(at) {
172  return at.branch + ' @ ' + at.head.slice(0, 7) + (at.inMain ? ' in the main checkout' : '')
173}
174
175function sameCheckout(a, b) {
176  return !a.none && !b.none && a.root === b.root && a.branch === b.branch && a.head === b.head
177}
178
179// The facts for the change the session is on: { none } when there is no change to follow, otherwise a
180// heading naming the branch and HEAD they describe, and one list of lines per section.
181async function collect($) {
182  const kit = await kitDir($)
183  for (let attempt = 1; ; attempt++) {
184    const at = await checkout($, await $.session.cwd())
185    if (at.none) return at
186    // The brief comes first: on the default branch it is the only answer, and CI can take ninety seconds.
187    const brief = await run($, [kit + '/bin/reports', 'brief'], at.root)
188    let flow
189    if (brief.failure || brief.exitCode !== 0) flow = ["couldn't read: " + failureOf(brief)]
190    else {
191      flow = brief.stdout.split('\n').filter((line) => line && !/^\s/.test(line) && !line.startsWith('Read one in full'))
192      if (flow[0] === 'phase: ') {
193        return { none: at.inMain ? 'Detached HEAD, and the main checkout is on the default branch: no change to follow.' : 'On the default branch: no change to follow.' }
194      }
195    }
196    const [stamps, report, ci, context, gatheredAt] = await Promise.all([
197      Promise.all(STAMPS.map(([label, kind]) => stampLine($, kit, at.root, label, kind))),
198      verifyReportLines($, kit, at.root),
199      ciLine($, kit, at.root, at.head),
200      contextLine($),
201      $.clock.now(),
202    ])
203    // Read again from the session's directory: Claude Code's /cd can move it while this gathers.
204    const after = await checkout($, await $.session.cwd())
205    if (after.none) return after
206    const moved = !sameCheckout(at, after)
207    if (moved && attempt < GATHER_ATTEMPTS) continue
208    return {
209      root: at.root,
210      branch: at.branch,
211      heading: nameOf(at) + ' · gathered ' + timeOf(gatheredAt) + (moved ? ' · the checkout moved while gathering: Refresh' : ''),
212      sections: [['Flow', flow], ['Stamps', stamps], ['Last verify report', report], ['CI and context', [ci, context]]],
213    }
214  }
215}
216
217async function collectOrSayWhy($) {
218  try {
219    return await withSwitches($, await collect($))
220  } catch (error) {
221    return { none: "Couldn't gather the flow: " + messageOf(error) }
222  }
223}
224
225async function gather($) {
226  if (gathering) {
227    gatherAgain = true
228    return
229  }
230  gathering = true
231  try {
232    $.ui.invalidate('ui.render')
233    do {
234      gatherAgain = false
235      shown = await collectOrSayWhy($)
236      $.ui.invalidate('ui.render')
237    } while (gatherAgain)
238  } finally {
239    gathering = false
240  }
241  $.ui.invalidate('ui.render')
242}
243
244// With no change to follow, the repo's and every repo's switches still apply.
245async function withSwitches($, facts) {
246  if (!facts.none) return facts
247  const listed = await run($, [(await kitDir($)) + '/bin/phase', 'switches'], await $.session.cwd())
248  if (listed.failure || listed.exitCode !== 0) return { none: facts.none + "\nPhases off: couldn't read: " + failureOf(listed) }
249  const off = listed.stdout.trim().split('\n').filter(Boolean).map((line) => line.replace(': off (', ' ('))
250  return off.length ? { none: facts.none + '\nPhases off: ' + off.join(', ') } : facts
251}
252
253function asText(facts) {
254  if (facts.none) return clip(facts.none)
255  return [clip(facts.heading), ...facts.sections.flatMap(([title, lines]) => ['', title + ':', ...lines.map((l) => '  ' + clip(l))])].join('\n')
256}
257
258function verifyLines() {
259  if (verifyRun.state === 'idle') return []
260  if (verifyRun.state === 'running') return ['Run verify: running…']
261  return ['Run verify ' + verifyRun.verdict, ...(verifyStopping ? ['stopping it: the button works again once it has ended'] : []), ...verifyRun.tail]
262}
263
264// One verify on the checkout the pane follows now: its verdict and the last lines of its own output.
265async function verifyHere($) {
266  const at = await checkout($, await $.session.cwd())
267  if (at.none) return { verdict: 'did not run: ' + at.none, tail: [] }
268  const kit = await kitDir($)
269  const startedAt = await $.clock.now()
270  const named = (verdict) => ({ verdict: 'on ' + nameOf(at) + ' at ' + timeOf(startedAt) + ': ' + verdict, tail })
271  const tail = []
272  const partial = { stdout: '', stderr: '' }
273  let checkedNothing = false
274  // The marker is stop_checks.py's own, on stderr; the repo's verify output reaches stdout.
275  const keep = (line, stream) => {
276    if (stream === 'stderr' && line.startsWith(CHECKED_NOTHING)) checkedNothing = true
277    if (!line.trim()) return
278    tail.push(line)
279    if (tail.length > VERIFY_TAIL_LINES) tail.shift()
280  }
281  const child = $.process.spawn({ argv: ['python3', kit + '/hooks/stop_checks.py', 'verify'], cwd: at.root })
282  const timer = new AbortController()
283  const deadline = $.clock.sleep(VERIFY_DEADLINE_MS, { signal: timer.signal }).then(() => 'deadline', () => 'cancelled')
284  try {
285    for (;;) {
286      const step = await Promise.race([child.next(), deadline])
287      if (step === 'deadline') {
288        // Not awaited: a child stuck mid-step finishes its return only after that step.
289        verifyStopping = true
290        child.return()
291          .catch((error) => $.ui.log('flow: stopping verify: ' + messageOf(error), { to: 'debug' }))
292          .finally(() => {
293            verifyStopping = false
294            $.ui.invalidate('ui.render')
295          })
296        return named('failed (no result after ' + VERIFY_DEADLINE_MS / 1000 + ' s)')
297      }
298      if (step.done) {
299        keep(partial.stdout, 'stdout')
300        keep(partial.stderr, 'stderr')
301        const { code, signal } = step.value
302        if (code !== 0) return named('failed (' + (signal ? 'killed by ' + signal : 'exit ' + code) + ')')
303        return named(checkedNothing ? 'passed, but it checked nothing' : 'passed')
304      }
305      const stream = step.value.stream === 'stderr' ? 'stderr' : 'stdout'
306      const lines = (partial[stream] + step.value.text).split('\n')
307      partial[stream] = lines.pop().slice(0, LINE_CHARS + 1)
308      lines.forEach((line) => keep(line, stream))
309    }
310  } finally {
311    timer.abort()
312  }
313}
314
315async function runVerify($) {
316  if (verifyRun.state === 'running' || verifyStopping) return
317  verifyRun = { state: 'running' }
318  $.ui.invalidate('ui.render')
319  try {
320    verifyRun = { state: 'done', ...(await verifyHere($)) }
321  } catch (error) {
322    verifyRun = { state: 'done', verdict: "failed: couldn't run: " + messageOf(error), tail: [] }
323  }
324  await gather($)
325}
326
327function reviewerPrompt(lens) {
328  return [
329    `You are one reviewer in the kit's review, with one lens: ${lens.title}. You read files and run read-only`,
330    'commands; you never edit files. The spawn prompt gives the base ref, the goal, the spec when there is one, and how',
331    "to report. The repository's own AGENTS.md or CLAUDE.md, when it has one, holds its conventions: read it when a",
332    'finding depends on them. When `~/.agents/repos/$(~/.agents/bin/repo-name)/review.md` exists (run `repo-name` in the',
333    'checkout you review), it is the review guide for that repository: what failure looks like there and what to skip. Read it',
334    "first and apply it; where it conflicts with the spawn prompt's instructions (a nit cap, say), the guide wins.",
335    '',
336    lens.brief,
337  ].join('\n')
338}
339
340const BUILDER_PROMPT = [
341  "You build one change in the kit's flow, as the session that delegated it would: you have its tools and its",
342  'CLAUDE.md, and its hooks run for you. You do not see its conversation: the spawn prompt gives the goal, the spec',
343  "path when there is one, and any correction the user made. Read the spec, the code it touches and the repository's",
344  'AGENTS.md or CLAUDE.md first. Build test first: for each acceptance criterion whose verify: can be an automated',
345  'test, write the test, run it and see it fail for the reason the criterion names, then implement until it passes.',
346  'Keep to the spec; when the work needs something it does not say, stop and report that instead of widening the',
347  'change. Commit nothing. Report the files you changed, each test you ran with the failing output before the code',
348  'and the passing output after, and every departure from the spec, with why.',
349].join('\n')
350
351const RUNNER_PROMPT = [
352  "You run the local checks of the kit's validation that the spawn prompt lists, each with its id and command. Run",
353  'each one through `~/.agents/bin/evidence <id> <command>`, so its output is saved; a check that needs setup is a',
354  'script that sets up, runs and cleans up, which you write in `$EV/checks/`, outside the working tree, and run by',
355  'its path from the working tree (EV is `~/.agents/bin/reports path evidence`; inside `.git` the evidence records no',
356  'content): it stays with the evidence, so anyone can re-run the check. A check leaves no untracked files behind.',
357  'Never edit the repository, and never print a secret. For each check, report its id, exit code, evidence file',
358  'and the output line that bears on what it checks, never a PASS or FAIL verdict: the session judges each one',
359  'against what it expected. A check that could not run is reported as such, with the error.',
360].join('\n')
361
362const DESCRIBER_PROMPT = [
363  "You write the title and description of the kit's pull request for the change the spawn prompt names. Read",
364  '`~/.agents/skills/kit-write-pr-description/SKILL.md` and follow it, with the evidence it asks for: the reports',
365  '`~/.agents/bin/reports` prints, the validation section `~/.agents/bin/pr-validation` builds, and the spec the spawn',
366  'prompt names. Write the description to the body file the spawn prompt names, and report the title and that path.',
367  'You never open, edit or comment on a pull request, and never push: the session does.',
368].join('\n')
369
370// Registered whatever triage does: a build, a validation run or a description needs no lens briefs.
371async function registerWorkers($) {
372  const workers = [
373    ...BUILDERS.map(({ tier, model, effort }) => ({
374      name: 'build-' + tier,
375      description: `Builds a change whose spec's tier, on triage's Spec: line, is ${tier}` + (tier === 'standard' ? ', or that has none' : '') +
376        `, on ${model} at ${effort} effort: the first build only, fixes after it are the session's. Give it the goal, the ` +
377        'spec path and any correction the user made.',
378      prompt: BUILDER_PROMPT,
379      model,
380      effort,
381    })),
382    {
383      name: 'validate-runner',
384      description: "Runs the validation's local checks through bin/evidence and reports what each printed, without a " +
385        'verdict. Give it each check id with its command, and `$EV/checks/` for its scripts.',
386      prompt: RUNNER_PROMPT,
387      tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write'],
388      model: 'sonnet',
389      effort: 'medium',
390    },
391    {
392      name: 'pr-description',
393      description: "Writes the pull request's title and description into a file, from the kit's reports and the spec. Give " +
394        'it the spec path, the base branch and the body file to write.',
395      prompt: DESCRIBER_PROMPT,
396      tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write'],
397      model: 'sonnet',
398      effort: 'medium',
399    },
400  ]
401  for (const spec of workers) {
402    await $.agent.register(spec).catch((error) => $.ui.log(`kit: ${spec.name} not registered: ` + messageOf(error), { to: 'debug' }))
403  }
404}
405
406async function registerReviewers($) {
407  const kit = await kitDir($)
408  const briefs = await run($, [kit + '/bin/triage', '--lens-briefs'], kit)
409  if (briefs.failure || briefs.exitCode !== 0) {
410    return $.ui.log('kit: no review agents: bin/triage --lens-briefs: ' + failureOf(briefs), { to: 'debug' })
411  }
412  let lenses
413  try {
414    lenses = JSON.parse(briefs.stdout)
415  } catch (error) {
416    return $.ui.log('kit: no review agents: bin/triage --lens-briefs printed something not JSON: ' + messageOf(error), { to: 'debug' })
417  }
418  if (!Array.isArray(lenses)) {
419    return $.ui.log('kit: no review agents: bin/triage --lens-briefs printed JSON that is not a list of lenses', { to: 'debug' })
420  }
421  for (const lens of lenses) {
422    await $.agent
423      .register({
424        name: 'review-' + lens.key,
425        description: `The review's ${lens.title} lens: a read-only reviewer of a change. Give it the base ref, ` +
426          'the goal, the spec path and the evidence instruction.',
427        prompt: reviewerPrompt(lens),
428        tools: REVIEWER_TOOLS,
429        omitClaudeMd: true,
430        model: 'opus',
431        effort: 'high',
432      })
433      .catch((error) => $.ui.log(`kit: review-${lens.key} not registered: ` + messageOf(error), { to: 'debug' }))
434  }
435}
436
437// A kit hook's PreToolUse deny as Claude Code words it when next(e) hands it back: the call never ran. Only the
438// start counts, so a tool's own error that quotes a deny is never run again.
439const KIT_BLOCK = /^PreToolUse:\S+ hook error: Blocked by ~\/\.agents\/hooks\//
440const ALLOW_ONCE = 'Allow once'
441const KEEP_BLOCKED = 'Keep it blocked'
442// The user approves what they read: a cut preview says how much it leaves out.
443const PREVIEW_CHARS = 2_000
444
445async function approveHelper($, kit, args, stdin = '') {
446  try {
447    const done = await $.process.run([kit + '/bin/approve', ...args], { stdin, timeoutMs: PROCESS_TIMEOUT_MS })
448    return done.exitCode === 0 ? done : { failure: failureOf(done) }
449  } catch (error) {
450    return { failure: messageOf(error) }
451  }
452}
453
454// `/flow off|on <phase> [--repo|--global]` and `/flow review-rounds <0-9> [--repo|--global]`: phase_switches.py decides
455// and records, in the session's own directory, as for the message lines `phase off …` and `review-rounds …`, which the
456// prompt hook reads from the same directory.
457async function switchPhase($, e) {
458  const args = e.args.trim().split(/\s+/)
459  const action = args[0].toLowerCase()
460  const rounds = action === 'review-rounds'
461  if (e.origin?.kind !== 'composer') {
462    const line = [...(rounds ? [] : ['phase']), action, ...args.slice(1).map((word) => word.replace(/^--/, ''))].join(' ')
463    return { text: `/flow ${action} ${rounds ? 'sets the re-check rounds' : 'switches a phase'} only when typed at this terminal's prompt: nothing was switched. A message opening with \`${line}\` does it from anywhere.` }
464  }
465  const kit = await kitDir($)
466  const done = await run($, ['python3', kit + '/hooks/phase_switches.py', 'set', action, ...args.slice(1)], await $.session.cwd())
467  // After a failure too: a run that died or timed out may have written the switch first.
468  refreshIfOpen($, 'a switch')
469  const said = done.stdout?.trim()
470  if (done.exitCode === 0 && rounds) return { text: said, context: [`The user set the review re-check rounds with /flow: ${said}`] }
471  if (done.exitCode === 0) return { text: said, context: [`The user switched a phase with /flow: ${said} Skip the steps of the phases off.`] }
472  if (done.exitCode === SWITCH_REFUSED) return { text: said }
473  if (rounds) {
474    return {
475      text: `Couldn't tell whether review-rounds was set to ${args[1] ?? 'a number'}: ${failureOf(done)}. Run \`~/.agents/bin/phase review-rounds\` to see the value.`,
476      context: ['A /flow review-rounds setting may or may not have been recorded: read `~/.agents/bin/phase review-rounds` before the review.'],
477    }
478  }
479  return {
480    text: `Couldn't tell whether ${args[1] ?? 'the phase'} was switched ${action}: ${failureOf(done)}. Run /flow to see what is off.`,
481    context: ['A /flow switch may or may not have been recorded: check `~/.agents/bin/phase switches` before a step of the flow.'],
482  }
483}
484
485function refreshIfOpen($, after) {
486  // Asked each time: a pane whose drawing threw is dropped without a ui.close this mod hears.
487  $.ui.panes()
488    .then((panes) => panes.some((pane) => pane.id === PANE) && gather($))
489    .catch((error) => $.ui.log(`flow: refresh after ${after}: ` + messageOf(error), { to: 'debug' }))
490}
491
492function previewOf(tool, input) {
493  const call = tool === 'Bash' ? String(input.command) : tool + ' ' + JSON.stringify(input, null, 2)
494  if (call.length <= PREVIEW_CHARS) return call
495  return call.slice(0, PREVIEW_CHARS) + `… (${call.length - PREVIEW_CHARS} more characters not shown)`
496}
497
498// The guards decide; this only carries the user's answer to them, as their next message would.
499async function askToLiftBlock($, e, next) {
500  const blocked = await next(e)
501  if (!blocked.isError || !KIT_BLOCK.test(String(blocked.text ?? ''))) return blocked
502  const { tool, tool_use_id, agentId, ...input } = e
503  const kit = await kitDir($)
504  const session = await $.session.id()
505  const asked = await approveHelper($, kit, ['needed'],
506    JSON.stringify({ tool_name: tool, tool_input: input, session_id: session, cwd: await $.session.cwd(), deny: blocked.text }))
507  let needed = null
508  try {
509    needed = asked.failure ? null : JSON.parse(asked.stdout)
510  } catch (error) {
511    asked.failure = 'printed something not JSON: ' + messageOf(error)
512  }
513  if (asked.failure) {
514    $.ui.log(`kit: approval dialog unavailable: bin/approve needed ${asked.failure}, so the call stays blocked`)
515    return blocked
516  }
517  if (!needed?.names?.length) return blocked
518  const allowTurn = `Allow ${needed.scope} until my next message`
519  let unanswered = ''
520  const answer = await $.ui
521    .ask(`A kit guard blocked this call: ${needed.what}.\n\n${previewOf(tool, input)}\n\nAllow it?`,
522      { header: 'Approval', options: [ALLOW_ONCE, allowTurn, KEEP_BLOCKED] })
523    .then((given) => given || null, (error) => {
524      unanswered = messageOf(error)
525      return null
526    })  // dismissed, interrupted, or a -p run with no one to ask: the block stands, as without the mod
527  if (answer === null) {
528    // The engine rejects a dismissal and a dialog it couldn't show alike: the line says what is known, not which.
529    $.ui.log(`kit: the approval dialog for ${needed.names.join(', ')} closed without an answer${unanswered && ` (${unanswered})`}, so the call stays blocked`)
530    return blocked
531  }
532  const outcome = [ALLOW_ONCE, allowTurn, KEEP_BLOCKED].includes(answer) ? answer : 'answered in their own words'
533  $.ui.log(`kit: approval dialog for ${needed.names.join(', ')}: ${outcome}`, { to: 'debug' })
534  if (answer !== ALLOW_ONCE && answer !== allowTurn) {
535    const said = answer === KEEP_BLOCKED ? '' : ` They answered: ${JSON.stringify(answer)}.`
536    return { deny: `${blocked.text}\nThe user was asked in a dialog and kept it blocked.${said} Don't ask them to approve it again this turn.` }
537  }
538  const granted = await approveHelper($, kit, [answer === ALLOW_ONCE ? 'once' : 'grant', session, ...needed.names])
539  if (granted.failure) {
540    $.ui.log("kit: couldn't record your approval, so the call stays blocked: " + granted.failure)
541    return blocked
542  }
543  try {
544    return await next(e)
545  } finally {
546    if (answer === ALLOW_ONCE) {
547      const revoked = await approveHelper($, kit, ['revoke', session, ...needed.names])
548      if (revoked.failure) $.ui.log(`kit: couldn't take back the one-time approval of ${needed.scope}, so it lasts until your next message: ` + revoked.failure)
549    }
550  }
551}
552
553export function register(on) {
554  on('tool.call', { tool: ['Bash', /^mcp__/] }, askToLiftBlock)
555
556  on('session.start', async ($, e, next) => {
557    // First: guard_mcp tells the user no dialog can ask when a Claude Code hook runs without it (KIT_MOD_MARKER).
558    await $.env.set('AGENTS_KIT_MOD', '1').catch((error) => $.ui.log('kit: AGENTS_KIT_MOD not set: ' + messageOf(error), { to: 'debug' }))
559    const flow = FEATURES.find((feature) => feature.command === 'flow')
560    await $.command.register({ name: 'flow', description: flow.description, argumentHint: '[off|on <phase> | review-rounds <0-9> [--repo|--global]]', immediate: true })
561    const waited = new AbortController()
562    const registering = registerWorkers($)
563      .then(() => registerReviewers($))
564      .catch((error) => $.ui.log('kit: agents: ' + messageOf(error), { to: 'debug' }))
565      .finally(() => waited.abort())
566    const timer = $.clock.sleep(AGENTS_WAIT_MS, { signal: waited.signal }).then(() => 'timed out', () => 'registered')
567    if ((await Promise.race([registering.then(() => 'registered'), timer])) === 'timed out') {
568      await $.ui.log('kit: agents: still registering after 2 s, so the session started without the ones not registered yet', { to: 'debug' })
569    }
570    return next(e)
571  })
572
573  on('command.run', { command: 'flow' }, async ($, e) => {
574    if (/^(off|on|review-rounds)(\s|$)/i.test(e.args.trim())) return switchPhase($, e)
575    if ((await $.session.surfaces()).length === 0) return { text: asText(await collectOrSayWhy($)) }
576    // Without closeOnEscape: Escape hands the keys back to the prompt and the pane stays, refreshing after each turn.
577    await $.ui.open({ id: PANE, title: 'flow', focus: true })
578    void gather($)
579    return {}
580  })
581
582  on('turn.complete', async ($, e, next) => {
583    if (!e.agentId) refreshIfOpen($, 'the turn')
584    return next(e)
585  })
586
587  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
588    if (e.requestId !== PANE) return next(e)
589    const { Box, Text, Button } = $.ui.resolve(e)
590    const line = (text) => Text({ bold: NEEDS_ATTENTION.test(text), wrap: 'wrap', children: [clip(text)] })
591    const refreshing = shown && gathering ? ' · refreshing…' : ''
592    const top = !shown
593      ? [Text({ children: ['Gathering…'] })]
594      : shown.none
595        ? [line(shown.none + refreshing)]
596        : [Text({ bold: true, children: [clip(shown.heading + refreshing)] })]
597    const sections = (shown?.sections ?? []).flatMap(([title, lines]) => [
598      Text({ children: [' '] }),
599      Text({ dimColor: true, children: [title] }),
600      ...lines.map((text, i) => (title === 'Flow' && i === 0 ? Text({ bold: true, children: [clip(text)] }) : line(text))),
601    ])
602    // A press starts the work and returns: Claude Code skips a hook still running after 10 s.
603    // Run verify only where there is a change: elsewhere a press would do nothing.
604    const buttons = [
605      ...(shown?.root ? [Button({ key: 'run-verify', label: 'Run verify', hotkey: 'v', plain: true, onPress: () => void runVerify($) })] : []),
606      Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', plain: true, onPress: () => void gather($) }),
607    ]
608    // The buttons and the run they started come first: a long report scrolls the bottom of the pane away.
609    return Box({
610      flexDirection: 'column',
611      children: [
612        ...top,
613        Box({ flexDirection: 'row', columnGap: 2, children: buttons }),
614        ...verifyLines().map(line),
615        ...sections,
616      ],
617    })
618  })
619}
620
hooks/features.js 65 lines
1// What each command, hook and agent type of the mod offers, and what Codex has instead: bin/docs prints it in
2// docs/framework.md, and tests/flow.test.ts fails when the mod registers a command or agent, or draws a button,
3// this list doesn't name.
4// Kept as one JSON value after the `=`, which bin/docs reads without running JavaScript.
5export const FEATURES = [
6  {
7    "command": "flow",
8    "description": "Show where this branch is in the kit's flow, run verify without a turn, and switch a phase off or on or set the review's re-check rounds",
9    "capabilities": [
10      {"name": "Phase and reports", "codex": "`bin/reports brief`"},
11      {"name": "The phases switched off, with their scope, also on the default branch", "codex": "`bin/phase switches`"},
12      {"name": "`/flow off|on <phase> [--repo|--global]`, typed at the prompt, switches a phase for the branch, the repo or every repo", "codex": "a message whose first line is `phase off|on <phase> [branch|repo|global]`"},
13      {"name": "`/flow review-rounds <0-9> [--repo|--global]`, typed at the prompt, sets how many re-checks the review runs after its first pass (1 when unset)", "codex": "a message whose first line is `review-rounds <0-9> [branch|repo|global]`; `bin/phase review-rounds` reads it"},
14      {"name": "Follows the branch into the main checkout once kit-ship detaches the session's own", "codex": "the commands of this list, run from the main checkout"},
15      {"name": "Stamps (verify, review, validate), current or not, and a verify that checked nothing", "codex": "`python3 ~/.agents/hooks/review_stamp.py check --kind <kind>`"},
16      {"name": "The last verify report's ran/skipped/warning/error lines", "codex": "`cat \"$(~/.agents/bin/reports path verify)\"`"},
17      {"name": "CI of the pushed HEAD", "codex": "`bin/ci-wait --once --no-log`"},
18      {"name": "Context use", "codex": "nothing (Codex shows its own)"},
19      {"name": "Run verify button, without a turn, on the checkout the pane shows", "codex": "`python3 ~/.agents/hooks/stop_checks.py verify` in a terminal"},
20      {"name": "Refresh button, and a refresh after each turn while the pane is open", "codex": "running the commands above again"}
21    ]
22  },
23  {
24    "hook": "tool.call",
25    "description": "Ask the user in a dialog when a kit guard blocks a call they could approve",
26    "capabilities": [
27      {"name": "A blocked MCP write or `DROP`/`TRUNCATE` command shown in a dialog: allowed once, until the user's next message, or kept blocked", "codex": "the user's next message naming the service, saying yes to the agent's question offering that write by name, or opening with `allow <statement>`; or `touch ~/.agents/approvals/<service>`"},
28      {"name": "A dialog that can't ask (`bin/approve` failed, or it closed without an answer) said in the transcript, and an MCP write block in a session without the mod says no dialog will show", "codex": "none: Codex has no dialog, and its blocks say how to approve"}
29    ]
30  },
31  {
32    "agentPrefix": "review",
33    "agent": "review-<lens>",
34    "description": "One reviewer agent type per review lens",
35    "capabilities": [
36      {"name": "One for each lens `bin/triage --lens-briefs` prints: its brief from lenses.md, no edit tools, no CLAUDE.md block", "codex": "a subagent given the lens text from `skills/kit-review/lenses.md`"},
37      {"name": "Each lens on Opus at high effort, whatever the session runs on", "codex": "the session's model"}
38    ]
39  },
40  {
41    "agentPrefix": "build",
42    "agent": "build-<tier>",
43    "description": "One builder agent type per risk tier",
44    "capabilities": [
45      {"name": "`build-low` on Sonnet at medium effort, `build-standard` (also without a spec) on Sonnet at high, `build-high` on Opus at high, each with the session's tools and CLAUDE.md; until 2026-11-13 `bin/build-ab` gives low and standard builds Sonnet or Opus in turn, at the same effort", "codex": "the session builds it, on its own model"}
46    ]
47  },
48  {
49    "agentPrefix": "validate",
50    "agent": "validate-runner",
51    "description": "A runner for the validation's local checks",
52    "capabilities": [
53      {"name": "`validate-runner` runs the checks through `bin/evidence` on Sonnet at medium effort and reports what each printed, leaving the verdict to the session", "codex": "the session runs the checks itself"}
54    ]
55  },
56  {
57    "agentPrefix": "pr",
58    "agent": "pr-description",
59    "description": "A writer for the pull request's description",
60    "capabilities": [
61      {"name": "`pr-description` writes the title and description into the body file on Sonnet at medium effort, following kit-write-pr-description; the session opens the PR", "codex": "the session writes it"}
62    ]
63  }
64]
65