SLOPSHOPPER

harness-rules

Loads the owner's direction at session start and enforces the global CLAUDE.md rules on agent models, the 5-hour quota, cleanup commands, merges, version 4…

guardpromptprocessagents
A shopper browsing a rack in a slop shop
README

dotfiles

My AI-agent setup and Linux workstation, as code.

CI License

AI harness config · Global agent rules · Apps · Shell · Sync · Host limits · Development

Demo video, 58 seconds: one reviewer agent from ai-harnesses/ shown side by side as Claude Code, OpenCode and DSH render it. One edit to the source reaches all three, and deno task ai --check catches a hand edit to one copy.

I run several AI coding agents at once, in Claude Code, OpenCode and DSH (a DeepSeek harness). Their rules, skills, agents and settings are written once, in ai-harnesses/, and deno task ai renders them into the format each harness reads. deno task ai --check writes nothing: it compares what every harness on this machine reads with what is committed, and exits 1 if they differ.

The rest of the repository is the workstation those agents run on: the apps, the shell, the config files synced into my home directory, and the kernel and systemd limits a dozen parallel agent sessions need. It is this machine's live config: a merged change is not done until it is applied here.

The AI-agent setup

  • One rules file, every harness. ai-harnesses/AGENTS.md holds the global rules: autonomy, Git flow, secrets, cleanup, subagent orchestration. It becomes Claude Code's CLAUDE.md and OpenCode's and DSH's AGENTS.md, byte for byte.
  • Agents and skills, written once. The agents and skills in one harness-neutral format. Validated frontmatter picks a model tier and effort per agent; each adapter renders its harness's format, covered by golden tests.
  • A reviewer gate. A separate, read-only reviewer runs the checks itself, breaks the code to prove each test goes red, and counts every claim in the PR body. Its verdict is what authorises a merge.
  • Nothing left running. tools/sweep-orphans.sh lists the processes and stale systemd-run scopes an agent session left behind, and the anonymous Docker volumes and networks no container uses, and stops exactly those on request. The rules cap the processes and memory of anything that spawns processes, and give every wait a deadline.
  • Costs you can see. tools/session-cost.ts reports each session's and subagent's cost, peak context and compactions from Claude Code's transcripts.
  • Secrets stay local. Committed env files are age-encrypted one value per line, and tools/env-key-copy.ts gives a worktree its key without the key ever being printed.

How the rendering works, the file layout per harness and how to write a skill or an agent: ai-harnesses/README.md.

The workstation

  • Apps. install-apps.ts installs everything in apps.jsonc with dnf, apt or zypper, and falls back to Flatpak.
  • Claude Desktop. tools/claude-desktop-update.sh installs or updates the app from Anthropic's Debian package, which Fedora has no updater for. A nightly timer runs it and says when to restart.
  • Secrets backup. tools/secrets-backup.sh backs up the age keys and plaintext env files that Syncthing keeps on this machine, with restic, every night.
  • Shell. install-shell.ts sets up Zsh, Oh My Zsh, Powerlevel10k and the aliases in aliases.sh.
  • Config in home. tmux, Neovim, Zsh and the prompt are symlinked from this repository.
  • Limits for many agents. system/ raises inotify instances and zram swap, cleans /tmp sooner, and caps the tasks each app can start.
  • VPN only while it works. tools/vpn-guard/ connects a full-tunnel VPN at boot and every 30 minutes, and drops it when the internet does not work through it.
  • Synced, not cloned. The repository lives in a Syncthing folder, and agent worktrees are ignored so they never replicate.

Use it if you want a working example of one rules source driving several AI coding agents, or a Linux workstation set up by script. Skip it if you want a framework: these are my own settings, not a configurable product.

Quick start

curl -fsSL https://deno.land/install.sh | sh   # install Deno
git clone https://github.com/spy4x/dotfiles && cd dotfiles
deno task ai --check       # compare your harness homes with ai-harnesses/, write nothing
deno task install-all      # installs my apps and replaces your shell setup

Only the last line installs my setup: it adds my apps and replaces your shell configuration. Read docs/apps.md and docs/shell.md before you run it.

deno task ai without --check replaces the global rules, skills and agents of every installed harness with mine, and merges my settings into theirs. Read ai-harnesses/README.md first.

Development

deno task test             # adapter golden files, engine, tools
deno task ai --check       # exit 1 if any harness differs from ai-harnesses/

File layout, adding apps and the encrypted env file: development.md.

Licence

MIT.

Built by

I'm Anton Shubin, a senior full-stack engineer and tech lead. This is how I run AI agents on real work, on my own machine. Need something like it built for your product? That's my day job →


Made by Anton Shubin · antonshubin.com/tools

Source 2 files
hooks/register.ts 171 lines
1import type { EngineInterface, Register } from "claude-code"
2import {
3  bashVerdict,
4  DIRECTION_PATH,
5  directionBlock,
6  ghPost,
7  leakVerdict,
8  markerVerdict,
9  spawnVerdict,
10  uuidVerdict,
11  type Where,
12} from "./rules.ts"
13
14/**
15 * Added to every refused Bash call. Agents often fix a body (`sed -i '1i <!-- agent -->'`) and
16 * post it in one command, then retry that same command after the refusal.
17 */
18const NOTHING_RAN = `Nothing in this command ran, not even the steps before the refused one: ` +
19  `run any fix in a command of its own, then retry.`
20
21/** The file's text, or undefined when it cannot be read yet. */
22async function readable($: EngineInterface, path: string): Promise<string | undefined> {
23  try {
24    return await $.fs.read(path)
25  } catch {
26    return undefined
27  }
28}
29
30/**
31 * Appends one JSON line to ~/.claude/mods-log/harness-rules.jsonl: every spawn and every
32 * refusal, so the experiment can count what the mod did. Fail-open: a lost line is no reason
33 * to stop work.
34 */
35async function log(
36  $: EngineInterface,
37  entry: Record<string, unknown>,
38  timeoutMs = 2000,
39): Promise<void> {
40  try {
41    const home = await $.env.get(`HOME`)
42    if (!home) return
43    const line = JSON.stringify({ at: new Date(await $.clock.now()).toISOString(), ...entry })
44    await $.process.run(
45      [
46        `sh`,
47        `-c`,
48        `mkdir -p "$1" && cat >> "$1/harness-rules.jsonl"`,
49        `sh`,
50        `${home}/.claude/mods-log`,
51      ],
52      { stdin: `${line}\n`, timeoutMs },
53    )
54  } catch {
55    // Logging is not critical.
56  }
57}
58
59/** The 5-hour window's use in percent, when the session has a reading. */
60async function fiveHourPercent($: EngineInterface): Promise<number | undefined> {
61  const { rateLimits } = await $.session.usage()
62  return rateLimits.find((limit) => limit.kind === `five_hour`)?.percentUsed
63}
64
65/**
66 * The session's directory and home, for the `rm` rule. Each is left out when it cannot be read:
67 * the rule then still refuses variable paths and the paths it can judge without them.
68 */
69async function whereOf($: EngineInterface): Promise<Where> {
70  const [cwd, home] = await Promise.all([
71    $.session.cwd().catch(() => undefined),
72    $.env.get(`HOME`).catch(() => undefined),
73  ])
74  return { cwd, home }
75}
76
77/**
78 * The owner's direction.md as a context block, or undefined. Fail-open: a missing file, an
79 * unknown home or a failed read starts the session without it. Reads that one path only.
80 */
81async function direction($: EngineInterface) {
82  try {
83    const home = await $.env.get(`HOME`)
84    if (!home) return undefined
85    return directionBlock(await readable($, `${home}/${DIRECTION_PATH}`))
86  } catch {
87    return undefined
88  }
89}
90
91export const register: Register = (on) => {
92  // The conversation's first message carries direction.md, as it carries CLAUDE.md.
93  on(`prompt.context`, async ($, e, next) => {
94    const context = await next(e)
95    const block = await direction($)
96    return block ? { ...context, blocks: [...context.blocks, block] } : context
97  })
98
99  on(`tool.call`, { tool: `Write` }, async ($, e, next) => {
100    const verdict = uuidVerdict(e.file_path, (await readable($, e.file_path)) ?? ``, e.content)
101    if (!verdict.deny) return next(e)
102    await log($, { event: `write`, path: e.file_path, deny: verdict.deny })
103    return { deny: verdict.deny }
104  })
105
106  on(`tool.call`, { tool: `Edit` }, async ($, e, next) => {
107    const verdict = uuidVerdict(e.file_path, e.old_string, e.new_string)
108    if (!verdict.deny) return next(e)
109    await log($, { event: `edit`, path: e.file_path, deny: verdict.deny })
110    return { deny: verdict.deny }
111  })
112
113  on(`agent.spawn`, async ($, e, next) => {
114    const verdict = spawnVerdict(e, await fiveHourPercent($))
115    await log($, {
116      event: `spawn`,
117      subagentType: e.subagentType,
118      model: e.model ?? null,
119      fork: e.fork,
120      parentAgentId: e.parentAgentId ?? null,
121      deny: verdict.deny ?? null,
122    })
123    return verdict.deny ? { deny: verdict.deny } : next(e)
124  })
125
126  on(`tool.call`, { tool: `Bash` }, async ($, e, next) => {
127    const verdict = bashVerdict(e.command, await whereOf($))
128    if (!verdict.deny) return next(e)
129    // The whole command, read on this machine to judge each refusal; none when it also posts,
130    // since a post's body may hold a secret.
131    const command = ghPost(e.command).kind === `none` ? e.command : null
132    await log($, { event: `bash`, command, deny: verdict.deny })
133    return { deny: `${verdict.deny} ${NOTHING_RAN}` }
134  })
135
136  // A body we post leaves the machine, so this guard fails closed: a hook that throws refuses,
137  // and a re-entry (a gh call another hook makes beneath this one) is refused when it posts.
138  on(`tool.call`, { tool: `Bash` }, async ($, e, next) => {
139    const post = ghPost(e.command)
140    if (post.kind === `none`) return next(e)
141    // A body file is often written earlier in this same command (a heredoc, `sed -i`) or named
142    // through a variable (`$D/b.md`), so it cannot be read yet; `--body-file -` reads a heredoc.
143    // The command text holds a heredoc body, so it counts for the marker and is always scanned.
144    // A body the command fills from elsewhere (`cat f >>`, `cp`, `curl >`) goes out unscanned.
145    const file = post.kind === `file` ? await readable($, post.path) : undefined
146    let verdict = markerVerdict(post.kind === `inline` ? post.body : `${file ?? ``}\n${e.command}`)
147    if (!verdict.deny) {
148      const scan = await $.process.run(
149        [`gitleaks`, `stdin`, `--no-banner`, `--redact`],
150        // The whole command too: the word parser is not a shell, and a body it cut short
151        // (an escaped quote, `$(…)`) must not hide a secret.
152        { stdin: file === undefined ? e.command : `${file}\n${e.command}`, timeoutMs: 8000 },
153      )
154      verdict = leakVerdict(scan.exitCode)
155    }
156    if (!verdict.deny) return next(e)
157    // The command can hold the secret gitleaks found, so the log keeps only the refusal.
158    await log($, { event: `gh`, deny: verdict.deny })
159    return { deny: `${verdict.deny} ${NOTHING_RAN}` }
160  }).catch(async ($, e, next) => {
161    if (next.error.kind === `re-entry` && ghPost(e.command).kind === `none`) return next(e)
162    if (next.error.kind !== `re-entry` && next.called) return next(e)
163    const deny = `The check of this post failed: gitleaks did not run, or the check broke. ` +
164      `It was not sent.`
165    // Short: a handler that outruns its 1-second grace counts as absent, and the post would go.
166    // On a re-entry the engine rejects this handler's own calls, so nothing is logged.
167    await log($, { event: `gh`, deny }, 500)
168    return { deny: `${deny} ${NOTHING_RAN}` }
169  })
170}
171
hooks/rules.ts 368 lines
1// The rules this mod enforces, as pure functions: no `$`, so `claude plugin test` checks them
2// directly. register.ts wires them to events.
3
4/** What a rule decides: nothing to say, or a refusal with the reason the model reads. */
5export interface Verdict {
6  readonly deny?: string
7}
8
9export const ALLOW: Verdict = {}
10
11/** The marker every comment, issue and PR body we post starts with (global CLAUDE.md). */
12export const AGENT_MARKER = `<!-- agent -->`
13
14/** At or above this share of the 5-hour limit, no new agent starts (wave skill, "Usage"). */
15export const FIVE_HOUR_STOP = 90
16
17/** The fields of an `agent.spawn` the rules read. */
18export interface Spawn {
19  readonly subagentType: string
20  readonly model?: string
21  readonly fork: boolean
22}
23
24/** Agent types that run on Opus only (global CLAUDE.md, "Subagents"). */
25const OPUS_ONLY = new Set([`implementer`, `implementer-xhigh`, `reviewer`, `design-reviewer`])
26
27/**
28 * Judges a subagent spawn. A fork inherits its parent's model by design, so only the quota
29 * applies to it. Everything else must name its model, and implementers and reviewers must run on
30 * Opus.
31 */
32export function spawnVerdict(spawn: Spawn, fiveHourPercent: number | undefined): Verdict {
33  if (fiveHourPercent !== undefined && fiveHourPercent >= FIVE_HOUR_STOP) {
34    return {
35      deny: `The 5-hour limit is at ${fiveHourPercent}%. Start no new agent: let the running ` +
36        `ones finish, post the handoff and end the turn.`,
37    }
38  }
39  if (spawn.fork) return ALLOW
40  if (spawn.model === undefined) {
41    return {
42      deny: `Pass \`model\` on every Agent call: an omitted one inherits the lead's model. ` +
43        `Search and inventory: haiku. Everything else, implementers and reviewers ` +
44        `included: opus.`,
45    }
46  }
47  if (OPUS_ONLY.has(spawn.subagentType) && !spawn.model.includes(`opus`)) {
48    return {
49      deny: `${spawn.subagentType} runs on opus (global CLAUDE.md, "Subagents": implementers ` +
50        `and reviewers run on opus).`,
51    }
52  }
53  return ALLOW
54}
55
56/**
57 * Splits a shell command into simple commands, each a list of words. Quotes group words and are
58 * dropped; `;`, `&`, `|` and newlines outside quotes end a command. No expansion: `"$D"` stays
59 * the word `$D`. Best effort, not a shell: a heredoc's lines read as commands of their own.
60 */
61export function commandsOf(command: string): string[][] {
62  const commands: string[][] = []
63  let words: string[] = []
64  let word: string | undefined
65  let quote: string | undefined
66  const endWord = () => {
67    if (word !== undefined) words.push(word)
68    word = undefined
69  }
70  const endCommand = () => {
71    endWord()
72    if (words.length > 0) commands.push(words)
73    words = []
74  }
75  for (const char of command) {
76    if (quote) {
77      if (char === quote) quote = undefined
78      else word = (word ?? ``) + char
79    } else if (char === `"` || char === `'`) {
80      quote = char
81      word = word ?? ``
82    } else if (/[;&|\n]/.test(char)) endCommand()
83    else if (/\s/.test(char)) endWord()
84    else word = (word ?? ``) + char
85  }
86  endCommand()
87  return commands
88}
89
90/** Words that run the command after them: `sudo rm`, `then rm`, `timeout 60 rm`. */
91const PREFIXES = [
92  `sudo`,
93  `command`,
94  `builtin`,
95  `exec`,
96  `nohup`,
97  `time`,
98  `env`,
99  `timeout`,
100  `if`,
101  `then`,
102  `else`,
103  `elif`,
104  `while`,
105  `until`,
106  `do`,
107  `!`,
108]
109
110/** Prefix flags that take a value: `sudo -u x`, `timeout -s KILL`. */
111const VALUE_FLAGS = [`-u`, `-g`, `-s`, `-k`]
112
113/**
114 * Drops what runs before the command proper: prefixes and their flags, a `timeout` duration,
115 * `X=1` assignments, and a `(` or `{` that opens a group. So `do (X=1 sudo -n rm` reads as `rm`.
116 */
117function commandProper(words: string[]): string[] {
118  const rest = [...words]
119  let i = 0
120  while (i < rest.length) {
121    const word = (rest[i] ?? ``).replace(/^[({]+/, ``)
122    rest[i] = word
123    if (word === `` || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) {
124      i++
125    } else if (PREFIXES.includes(word)) {
126      i++
127      while (rest[i]?.startsWith(`-`)) i += VALUE_FLAGS.includes(rest[i] ?? ``) ? 2 : 1
128      if (word === `timeout`) i++
129    } else break
130  }
131  return rest.slice(i).map((word) => word.replace(/[)}]+$/, ``))
132}
133
134/** Where a command runs: the session's directory and the home directory, both absolute. */
135export interface Where {
136  readonly cwd?: string
137  readonly home?: string
138}
139
140const LITERAL_PATH = `Delete by literal path: \`find "<literal path>" -delete\`, or \`rm -rf\` ` +
141  `a literal path.`
142
143/**
144 * Resolves `path` the way the shell would name it, without expansion: `~` becomes `home`, a
145 * relative path joins `cwd`, and `.`, `..`, a trailing `/` or `/*` fold away. Undefined when
146 * the path is relative or starts with `~` and that base is unknown.
147 */
148function resolved(path: string, { cwd, home }: Where): string | undefined {
149  let full = path
150  if (full === `~` || full.startsWith(`~/`)) {
151    if (!home) return undefined
152    full = home + full.slice(1)
153  } else if (!full.startsWith(`/`)) {
154    if (!cwd) return undefined
155    full = `${cwd}/${full}`
156  }
157  const parts: string[] = []
158  for (const part of full.replace(/\/\*$/, ``).split(`/`)) {
159    if (part === `..`) parts.pop()
160    else if (part !== `` && part !== `.`) parts.push(part)
161  }
162  return `/${parts.join(`/`)}`
163}
164
165/**
166 * What `path` is when Claude Code guards it even in bypass mode: `/`, a top-level directory,
167 * home, or the working directory or one of its parents. Undefined for any other path.
168 */
169function criticalKind(path: string, where: Where): string | undefined {
170  if ([`~`, `~/`].includes(path)) return `home`
171  if ([`.`, `./`, `./*`, `*`].includes(path)) return `the working directory`
172  if ([`..`, `../`].includes(path)) return `a parent of the working directory`
173  const full = resolved(path, where)
174  if (full === undefined) return undefined
175  if (full === `/`) return `the root`
176  if (full.split(`/`).length === 2) return `a top-level directory`
177  if (where.home && full === resolved(where.home, {})) return `home`
178  const cwd = where.cwd ? resolved(where.cwd, {}) : undefined
179  if (cwd === full) return `the working directory`
180  if (cwd?.startsWith(`${full}/`)) return `a parent of the working directory`
181  return undefined
182}
183
184/**
185 * Judges a Bash command against the cleanup rules in the global CLAUDE.md ("Leave nothing
186 * running"): `rm` and `rmdir` take only literal paths, never a critical one, no `find /` and no
187 * `ulimit -u`; and against Git Flow: `gh pr merge` takes `--repo` and never `--admin`.
188 * Claude Code stops for approval on critical paths and some substitutions even in bypass mode;
189 * a refusal instead tells the agent how to retry. Best effort: it reads the command's words, not
190 * what the shell would expand.
191 */
192export function bashVerdict(command: string, where: Where = {}): Verdict {
193  for (const words of commandsOf(command).map(commandProper)) {
194    const name = (words[0] ?? ``).replace(/^\\/, ``).split(`/`).pop()
195    if (name === `rm` || name === `rmdir`) {
196      const paths = words.slice(1).filter((word) => !word.startsWith(`-`))
197      if (paths.some((path) => /[$`]/.test(path))) {
198        return {
199          deny: `Never pass \`${name}\` a path from a variable or a command substitution: an ` +
200            `empty one deletes from \`/\`, and some forms (\`rm -rf $(…)\`) make Claude Code ` +
201            `stop for approval even in bypass mode. ${LITERAL_PATH}`,
202        }
203      }
204      for (const path of paths) {
205        const kind = criticalKind(path, where)
206        if (kind === undefined) continue
207        return {
208          deny: `Never \`${name}\` \`${path}\`: it is ${kind}, and Claude Code stops for ` +
209            `approval on it even in bypass mode. Delete only what you created. ${LITERAL_PATH}`,
210        }
211      }
212    }
213    if (words[0] === `find` && words[1] === `/`) {
214      return { deny: `Never \`find /\`: search the directory that can hold the answer.` }
215    }
216    if (name === `ulimit` && words.slice(1).some((word) => /^-[A-Za-z]*u/.test(word))) {
217      return {
218        deny: `Never \`ulimit -u\`: it counts every thread the user owns, so the first fork ` +
219          `fails. Cap a run with \`systemd-run --user --scope --quiet -p TasksMax=4000 ` +
220          `-p MemoryMax=8G timeout <seconds> <cmd>\`.`,
221      }
222    }
223    if (words[0] === `gh` && words[1] === `pr` && words[2] === `merge`) {
224      const verdict = mergeVerdict(words)
225      if (verdict.deny) return verdict
226    }
227  }
228  return ALLOW
229}
230
231/**
232 * Judges a `gh pr merge` against the Git Flow rules: never `--admin`, which skips the branch
233 * protection only the owner may lift, and always `--repo`, without which gh skips the remote
234 * branch delete while the worktree exists.
235 */
236function mergeVerdict(words: string[]): Verdict {
237  if (words.includes(`--admin`)) {
238    return {
239      deny: `Never pass \`--admin\` to \`gh pr merge\`: the branch protection is the owner's. ` +
240        `Wait for the check with \`timeout 900 gh pr checks <n> --repo <owner>/<repo> ` +
241        `--watch\`, or leave the PR open and say so.`,
242    }
243  }
244  if (!words.some((word) => word === `--repo` || word === `-R` || word.startsWith(`--repo=`))) {
245    return {
246      deny: `Pass \`--repo <owner>/<repo>\` to \`gh pr merge\`: without it, gh tries to delete ` +
247        `the local branch, fails while its worktree exists, and skips the remote delete.`,
248    }
249  }
250  return ALLOW
251}
252
253/**
254 * Calls that make a version 4 UUID. Built from parts so this file does not hold the calls it
255 * refuses: an edit to it would otherwise count them.
256 */
257const UUID_V4_CALLS = [`crypto.random` + `UUID`, `gen_random` + `_uuid`, `uuid_generate` + `_v4`]
258  .map((name) => new RegExp(`\\b${name.replace(`.`, `\\.`)}\\s*\\(`, `g`))
259  .concat(new RegExp(`\\buuid` + `v4\\s*\\(`, `gi`))
260
261/** Source files the id rule covers: JavaScript, TypeScript and SQL. */
262const CODE_FILE = /\.(?:[cm]?[jt]sx?|sql)$/i
263
264/** How many version 4 UUID calls `text` holds. */
265function uuidV4Calls(text: string): number {
266  return UUID_V4_CALLS.reduce((sum, call) => sum + (text.match(call)?.length ?? 0), 0)
267}
268
269/**
270 * Judges a file write against the id rule in the global CLAUDE.md ("TS style"): it refuses one
271 * that adds a version 4 UUID call to a code file. `before` is the text the write replaces (the
272 * file, or an Edit's `old_string`), so keeping an existing call is no refusal.
273 */
274export function uuidVerdict(path: string, before: string, after: string): Verdict {
275  if (!CODE_FILE.test(path) || uuidV4Calls(after) <= uuidV4Calls(before)) return ALLOW
276  return {
277    deny: `Never create a version 4 UUID: every id is a version 7 UUID. Use \`uuidV7()\` from ` +
278      `\`@spy4x/platform/universal/uuid\`, \`generate\` from \`@std/uuid/v7\` in a repo that ` +
279      `does not import ts-libs, or \`uuidv7()\` in Postgres 18 SQL. A secret token is the ` +
280      `owner's choice: ask before implementing it.`,
281  }
282}
283
284/** Where the owner's direction lives, relative to home (global CLAUDE.md, "Direction"). */
285export const DIRECTION_PATH = `sync/code/ai-memory/direction.md`
286
287/** A context block the conversation's first message carries. */
288export interface ContextBlock {
289  readonly name: string
290  readonly text: string
291}
292
293/**
294 * The context block that carries direction.md, or undefined when the file is missing or empty:
295 * the session then starts without it.
296 */
297export function directionBlock(text: string | undefined): ContextBlock | undefined {
298  if (!text?.trim()) return undefined
299  return {
300    name: `direction`,
301    text: `Contents of ~/${DIRECTION_PATH}, the owner's current direction ("Direction" in ` +
302      `the global rules):\n\n${text.trim()}`,
303  }
304}
305
306/**
307 * What a `gh` command posts: nothing, an inline body, a body read from a file, or a body read
308 * from standard input (`--body-file -`, usually a heredoc in the same command).
309 */
310export type GhPost =
311  | { readonly kind: `none` }
312  | { readonly kind: `inline`; readonly body: string }
313  | { readonly kind: `file`; readonly path: string }
314  | { readonly kind: `stdin` }
315
316const POSTING_VERBS = [`create`, `comment`, `edit`, `review`]
317
318/** The value of `flag` in `words`, given as `flag value` or `--long=value`. */
319function flagValue(words: string[], flags: string[]): string | undefined {
320  for (let i = 0; i < words.length; i++) {
321    const word = words[i] ?? ``
322    if (flags.includes(word)) return words[i + 1] ?? ``
323    const long = flags.find((flag) => flag.startsWith(`--`) && word.startsWith(`${flag}=`))
324    if (long) return word.slice(long.length + 1)
325  }
326  return undefined
327}
328
329/**
330 * Finds the body a `gh issue|pr create|comment|edit|review` command posts, reading only that
331 * command's own words. One with no body flag (a title-only edit, `--fill`) posts none this mod
332 * can check.
333 */
334export function ghPost(command: string): GhPost {
335  for (const words of commandsOf(command)) {
336    const [gh, noun, verb] = words
337    if (gh !== `gh` || (noun !== `issue` && noun !== `pr`)) continue
338    if (!POSTING_VERBS.includes(verb ?? ``)) continue
339    const path = flagValue(words, [`--body-file`, `-F`])
340    if (path === `-`) return { kind: `stdin` }
341    if (path !== undefined) return { kind: `file`, path }
342    const body = flagValue(words, [`--body`, `-b`])
343    if (body !== undefined) return { kind: `inline`, body }
344  }
345  return { kind: `none` }
346}
347
348/** Judges a body we are about to post: it must carry the agent marker. */
349export function markerVerdict(text: string): Verdict {
350  return text.includes(AGENT_MARKER) ? ALLOW : {
351    deny: `Start every comment, issue and PR body with \`${AGENT_MARKER}\`: a comment ` +
352      `without it reads as the owner's.`,
353  }
354}
355
356/**
357 * Judges what gitleaks said about a body: exit 0 is clean, 1 is a finding, anything else is a
358 * failed scan. Both of the last refuse: a secret-bearing send fails closed.
359 */
360export function leakVerdict(exitCode: number): Verdict {
361  if (exitCode === 0) return ALLOW
362  return {
363    deny: exitCode === 1
364      ? `gitleaks found a secret in this body. Replace it with <REDACTED:KIND> before posting.`
365      : `The gitleaks scan of this body failed (exit ${exitCode}), so it was not posted.`,
366  }
367}
368