SLOPSHOPPER

mm

Cross-model review and delegation: /mm:review and /mm:run, built on mmrun

guardpromptprocesstimer
v0.4.26MITupdated 2026-10-18Paradox07127/claude-utopia/plugins/mm
A shopper browsing a rack in a slop shop
README

claude-utopia

Under active development. This repo is updated continuously, and interfaces, names and defaults can change between versions. Star or watch the repo to follow the changes.

简体中文

Five Claude Code plugins built on mods (function hooks), plus two agent templates.

PluginWhat it does
dashboardA status band above the prompt for running subagents and mmrun reviews, a line under the prompt with context use and the tightest rate-limit window, and a seven-page workbench (Overview / Agents / Reviews / GPU / Timeline / Usage / Progress) opened with /dashboard, /subagents, /mmrun, /gpu, /timeline. The Reviews, GPU and Progress tabs show once they have data: an ~/.claude/mmruns folder, a GPU host, a progress board. The Timeline page draws the main loop's turns as a waterfall of model requests and tool calls, with a hotspot view of the slowest tools and turns. Renders subagent cards, test summaries and blocked-command notices in the transcript.
harnessSkills: ai-code-cleanup, interrogate, shape-task, verify-change, setup. Guards: refuse subagents on blocked models, refuse git commands that discard uncommitted work in the shared main worktree, refuse tool calls that would print API-key config files (~/.claude.json and its backups, Claude settings, Codex config and auth, grok auth, OpenViking config) or an environment dump (env, printenv, export -p, set, …) into the transcript, run /compact when the main thread idles until the prompt cache is about to expire.
mmCross-model code review and delegation: /mm:review runs codex / grok / agy in parallel as read-only reviewers, /mm:run hands a task to another model in its own worktree. Ships the mmrun CLI. A guard refuses reading mmrun's *.raw event streams (except a lone tail of 50 lines or fewer) and moves a foreground mmrun wait to the background.
next-promptPredicts your next message. After each main-thread turn, one fork of the session's own model (reusing its prompt cache, no tools, nothing written to the transcript) writes the message you are likely to send next; it shows as the prompt box's dim suggestion, Tab to take. A reply of NONE shows nothing. /prediction-stats prints how many were taken or near-taken, the characters kept, the abstentions, the median fork time and the cache share. Hides Claude Code's own suggestion in the terminal; in the desktop app set "promptSuggestionEnabled": false. One fork per turn, billed to your session.
progressA per-project progress board. After each turn you typed that changed files or made a commit, the plugin asks Sonnet to record the work as 1–3 nodes (title, summary, status, kind, links to earlier nodes); the main model spends no tokens on it. The board is kept under ~/.claude/progress/ or committed with the project, as you choose once per project. The plugin mirrors the board to an optional Artifact canvas. Works without dashboard; with it, the workbench's Progress page lists the board.
agents/worker and researcher subagent templates to copy into ~/.claude/agents/.

Screenshots

The status band above the prompt while a worker subagent runs, with the transcript cards for the dispatched agent and the test summary. Context use and the rate-limit window show only in the line under the prompt:

Status band and transcript cards in the terminal

The workbench's Timeline page: each model request of the last turn, its tool calls and the critical path.

Workbench Timeline page in the terminal

Both screenshots come from a real terminal session with language set to English. With zh-CN, the same UI is drawn in Chinese; see 简体中文.

Requirements

  • Claude Code 2.1.287 or later (mods are on by default from that version). Drawing works in the terminal and the Desktop Code tab; the VS Code panel and claude -p run the hooks without drawing.
  • harness: python3.
  • mm: at least one of the codex, grok or agy CLIs, plus bash, git, jq, python3. The grok and agy read-only fence uses sandbox-exec, so it is macOS only; codex uses its own sandbox.
  • dashboard GPU page: key-based ssh to the hosts and nvidia-smi (or tegrastats) on them.
  • Optional: /mm:run suggests the /impeccable skill for frontend tasks, and verify-change suggests the codegraph_impact MCP tool. Neither ships here; they are used when installed, and the plugins work without them.

Install

Let Claude do it: paste this into a Claude Code session.

Fetch and follow the instructions in https://raw.githubusercontent.com/Paradox07127/claude-utopia/main/INSTALL.md

Or by hand:

claude plugin marketplace add Paradox07127/claude-utopia
claude plugin install dashboard@claude-utopia
claude plugin install harness@claude-utopia
claude plugin install mm@claude-utopia
claude plugin install next-prompt@claude-utopia
claude plugin install progress@claude-utopia

Then start a new Claude Code session. Run the setup skill (/harness:setup) at any time to review and change the options below.

Options

Set with /plugin configure <plugin>@claude-utopia, or claude plugin configure <plugin>@claude-utopia --values-stdin with a JSON object of strings. Changes take effect in the next session.

PluginKeyDefaultMeaning
dashboardlanguageautoUI language: auto, zh-CN or en. auto follows the settings language, then LC_ALL / LANG, else English.
dashboardgpuHostsemptyComma-separated ssh hosts; ssh <host> … in Bash opens that host's GPU page.
dashboardcacheTtlMinutes60The fallback prompt cache TTL: after this many idle minutes the band warns that the next message rewrites the prompt cache. Used only until the real TTL is known; a TTL read from the transcript or reported by a model switch overrides it.
dashboardtoastPeerAskstrueToast when another Claude Code session asks a permission or its turn fails. Other sessions' toasts show only in the session you typed in last within two minutes, or in every session when you typed in none.
dashboardtoastPeerRepliestrueToast when another session replies after a turn of two minutes or more. Shown by the same rule.
dashboardaskSoundfalsePlay a short chime with the toast of another session asking a permission or failing. Needs toastPeerAsks.
dashboardtoastRunstrueToast when an mmrun model returns, fails or goes stale.
harnesslanguageautoSame as above, for the harness toast.
harnessblockedSubagentModelsemptyComma-separated; a subagent whose model name contains any entry is refused. Empty allows all.
harnesssharedTreeGitGuardtrueIn the main worktree, refuse git commands that discard uncommitted changes or rewrite HEAD: checkout <path>, checkout --force / -f, restore (except --staged alone), stash (except list, show, create), clean (except -n / --dry-run), switch --discard-changes / --force / -f, reset --hard, commit --amend. Linked worktrees are exempt.
harnessidleCompacttrueWhen the main thread sits idle until just before the prompt cache expires, run /compact automatically: with a 1h cache 10 minutes before, at 100k tokens or more; with a 5m cache 1 minute before, at 200k or more. The TTL is read from the transcript.
mmreviewModelscodex,grokModels /mm:review uses when no --models is given.

next-prompt and progress have no options.

Skills, command docs and every instruction the plugins send to the model are in English; skill descriptions also carry Chinese trigger words so Chinese prompts match them. Claude replies in your language. Only the drawn UI follows language.

Privacy and trust

Mods run in-process with your user permissions, like any plugin hook. mm sends the code under review to the external model CLIs you have installed, under their own accounts and terms. Nothing here phones home.

harness hides the built-in general-purpose agent when worker.md or researcher.md exists in ~/.claude/agents/ or the project's .claude/agents/.

License

MIT

Source 6 files
hooks/register.ts 710 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, HookFailure, PromptSubmitResult, Register, Timer } from 'claude-code'
3
4import type { MmWatch } from '../types'
5import { cutOutputs, doneMessage, isFlagForm, splitArgs } from './args'
6import type { ModelResult } from './args'
7import { register as registerGuard } from './guard'
8
9const POLL_MS = 5000
10const RUN_LINE = /^RUN (\S+)/m
11const RUN_MODE = /\bmode=(\S+)/
12const REPORT = /\bmmrun\s+report\b/
13const READ_LATEST = /\bmmrun\s+(result|report)\b/
14const OUT_OPTION = /\s(-o|--out)\b/
15const RID_SHAPED = /\d{8}-\d{6}-[0-9a-f]+/
16const SEGMENT_END = /&&|\|\||[;|\n]/
17const FOLLOW_UP = /^(NEXT|THEN) /
18const MMRUN_START = /\bmmrun\s+(review|run|start|ask)\b/
19const EXHAUSTIVE_TAG = /^tag=.*:(full|exhaustive)$/m
20const GROUP_LINE = /^group=(.*)$/m
21const CONTEXT_MAX = 32_000
22const MESSAGE_MAX = 16_000
23const RESULT_TRIES = 3
24// Finished runs took at most 2972 s (codex), p95 1904 s.
25const REMIND_MS = 60 * 60_000
26
27/** `parts`: the watches of a split review's runs, when this one stands for all of them. */
28type Waiting = MmWatch & { message: string; parts?: Waiting[] }
29
30const watches = atom({ plugin: 'mm', key: 'watches' } as const, [] as MmWatch[])
31
32// Module timers die with the module on reload; session.start fires again then and restarts it.
33let poller: Timer | null = null
34let isPolling = false
35// From a prompt entering until the main thread stops with no background task left to wake it.
36let isBusy = false
37// Runs started whose watch could not be written yet; the next poll writes them.
38const unwatched: Pick<MmWatch, 'rid' | 'kind'>[] = []
39// Ticks in a row `mmrun result` failed, by run.
40const resultFailures = new Map<string, number>()
41// Bumped by each /clear: work that started before one must not watch or deliver its runs.
42let clears = 0
43// Reminders waiting for the next prompt; kept out of `watches` so taking one claims no run and touches no mark.
44const reminders: string[] = []
45
46function logFailure($: EngineInterface, event: string, error: HookFailure): void {
47  $.ui.log(`mm: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
48}
49
50/** Runs work no hook awaits (a timer tick, a submit in flight), logging its failure. */
51function detach($: EngineInterface, what: string, work: () => Promise<unknown>): void {
52  void work().catch((error: unknown) => $.ui.log(`mm: ${what} failed: ${String(error)}`, { to: 'debug' }))
53}
54
55/** Whether the run's message can go: a part of a split review waits until every watched part has its message. */
56function isReady(one: MmWatch, list: MmWatch[]): one is Waiting {
57  return (
58    one.message !== undefined &&
59    (one.group ?? []).every(rid => {
60      const part = list.find(other => other.rid === rid)
61
62      return part === undefined || part.message !== undefined
63    })
64  )
65}
66
67/** Claims the messages of ended runs: removed from `watches` in one write, so each is handed to one taker. The parts of a split review become one. */
68async function takeMessages($: EngineInterface): Promise<Waiting[]> {
69  if (!(await read($, watches)).some(one => one.message !== undefined)) {
70    return []
71  }
72
73  let taken: Waiting[] = []
74
75  await update($, watches, list => {
76    taken = list.filter(one => isReady(one, list))
77
78    return list.filter(one => !taken.includes(one as Waiting))
79  })
80
81  // Emptied before the hand-over, so a reload or exit in between cannot leave a delivered run marked.
82  for (const watch of taken) {
83    await mark($, watch.rid, false)
84  }
85
86  const merged: Waiting[] = []
87
88  for (const one of taken) {
89    const group = one.group ?? []
90
91    if (group.length > 1 && one.rid === group.find(rid => taken.some(other => other.rid === rid))) {
92      const parts = group.map(rid => taken.find(other => other.rid === rid)).filter(part => part !== undefined)
93      const missing = group.filter(rid => !parts.some(part => part.rid === rid))
94      const head =
95        missing.length === 0
96          ? `mm plugin: /mm:review was split by files into ${group.length} parts (${group.join(', ')}); every part has ended, each result follows.`
97          : `mm plugin: /mm:review was split by files into ${group.length} parts (${group.join(', ')}); the results of ${parts.map(part => part.rid).join(', ')} follow. Not watched by this session: ${missing.join(', ')} (\`mmrun result <model> ${missing[0]}\` reads it).`
98
99      merged.push({ ...one, message: [head, ...parts.map(part => part.message)].join('\n\n'), parts })
100    }
101  }
102
103  // A run another's group holds goes out inside that group's message, even when its own run.meta named no group.
104  return [...merged, ...taken.filter(one => (one.group ?? []).length < 2 && !merged.some(group => group.parts?.includes(one)))]
105}
106
107/** Puts claimed messages back for the next poll or prompt, replacing a watch of the same run; not across a /clear since `at`. */
108async function putBack($: EngineInterface, taken: Waiting[], at: number): Promise<void> {
109  if (taken.length > 0 && at === clears) {
110    const back = taken.flatMap(one => one.parts ?? [one])
111
112    await update($, watches, list => [...list.filter(one => !back.some(other => other.rid === one.rid)), ...back])
113
114    for (const watch of back) {
115      await mark($, watch.rid, true)
116    }
117  }
118}
119
120/** Puts taken reminders back for the next poll or prompt; not across a /clear since `at`. */
121function putBackReminders(taken: string[], at: number): void {
122  if (at === clears) {
123    reminders.push(...taken)
124  }
125}
126
127/** Submits the text as a prompt of its own, without waiting for its turn; `back` runs when it is not accepted. */
128function submitAlone($: EngineInterface, what: string, text: string, back: (at: number) => Promise<void>): void {
129  detach($, what, async () => {
130    const at = clears
131    let r: PromptSubmitResult
132
133    try {
134      r = await $.prompt.submit({ text })
135    } catch (error) {
136      await back(at)
137      throw error
138    }
139
140    if (r.drop !== undefined) {
141      await back(at)
142    }
143  })
144}
145
146/** Submits each waiting message as a prompt of its own; one not accepted goes back. Reminders wait for a prompt: alone they would wake an idle session. */
147async function flush($: EngineInterface): Promise<void> {
148  for (const watch of await takeMessages($)) {
149    submitAlone($, 'submitting a finished run', watch.message, at => putBack($, [watch], at))
150  }
151}
152
153async function home($: EngineInterface): Promise<string> {
154  return (await $.env.get('HOME')) ?? ''
155}
156
157/** The text of a `watched` mark: the session id after the word limits guard.ts's denial to this session. */
158async function watchedText($: EngineInterface): Promise<string> {
159  try {
160    return `watched ${await $.session.id()}\n`
161  } catch {
162    return 'watched\n'
163  }
164}
165
166/** Writes the run's `watched` mark, by which guard.ts denies a main-thread `mmrun wait` on it; empty means not watched. */
167async function mark($: EngineInterface, rid: string, isWatched: boolean): Promise<void> {
168  try {
169    await $.fs.write(`${await home($)}/.claude/mmruns/${rid}/watched`, isWatched ? await watchedText($) : '')
170  } catch (error) {
171    $.ui.log(`mm: marking ${rid} failed: ${String(error)}`, { to: 'debug' })
172  }
173}
174
175async function readText($: EngineInterface, path: string): Promise<string | null> {
176  try {
177    return String(await $.fs.read(path))
178  } catch {
179    return null
180  }
181}
182
183/** Each model's status file in the run directory; 'gone' when the directory is, null when a listing or read failed. */
184async function statusesOf($: EngineInterface, dir: string): Promise<{ model: string; status: string }[] | 'gone' | null> {
185  let models: string[]
186
187  try {
188    models = (await $.fs.list(dir)).filter(entry => entry.name.endsWith('.status')).map(entry => entry.name.slice(0, -'.status'.length))
189  } catch {
190    return (await $.fs.exists(dir).catch(() => true)) ? null : 'gone'
191  }
192
193  const found: { model: string; status: string }[] = []
194
195  for (const model of models.sort()) {
196    const status = await readText($, `${dir}/${model}.status`)
197
198    if (status === null) {
199      return null
200    }
201
202    found.push({ model, status: status.trim() })
203  }
204
205  return found
206}
207
208/** Each model's result; null while a failed `mmrun result` is still to be tried again, a failure note after RESULT_TRIES ticks. */
209async function resultsOf($: EngineInterface, mmrun: string, watch: MmWatch, models: { model: string; status: string }[]): Promise<ModelResult[] | null> {
210  const results: ModelResult[] = []
211  let isFailed = false
212
213  for (const { model, status } of models) {
214    let output = ''
215
216    if (status === 'DONE') {
217      const r = await $.process
218        .run([mmrun, 'result', model, watch.rid, ...(watch.kind === 'run' ? [] : ['--top'])])
219        .catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: String(error) }))
220
221      isFailed ||= r.exitCode !== 0
222      output =
223        r.exitCode === 0
224          ? r.stdout.trim()
225          : `mm plugin: could not read the result of ${model} in ${watch.rid} after ${RESULT_TRIES} tries (${r.stderr.split('\n')[0] ?? ''}); \`mmrun result ${model} ${watch.rid}\` prints it.`
226    }
227
228    // mmrun writes one line saying why a model ended without a result; older runs have none.
229    const reason = status === 'DONE' ? '' : ((await readText($, `${await home($)}/.claude/mmruns/${watch.rid}/${model}.reason`))?.trim().split('\n')[0] ?? '')
230    // mmrun collects a run model's patch whatever its exit code.
231    const patchPath = `${await home($)}/.claude/mmruns/${watch.rid}/${model}.patch`
232    const patch = watch.kind === 'run' && status !== 'DONE' && ((await readText($, patchPath))?.trim() ?? '') !== '' ? patchPath : ''
233
234    results.push({ model, status, output, ...(reason !== '' && { reason }), ...(patch !== '' && { patch }) })
235  }
236
237  const failures = isFailed ? (resultFailures.get(watch.rid) ?? 0) + 1 : 0
238
239  if (failures > 0 && failures < RESULT_TRIES) {
240    resultFailures.set(watch.rid, failures)
241
242    return null
243  }
244
245  resultFailures.delete(watch.rid)
246
247  return results
248}
249
250/** Whether run.meta tags the run as an exhaustive review. */
251async function isExhaustiveRun($: EngineInterface, rid: string): Promise<boolean> {
252  return EXHAUSTIVE_TAG.test((await readText($, `${await home($)}/.claude/mmruns/${rid}/run.meta`)) ?? '')
253}
254
255/** The runs of the split review run.meta names the run a part of; empty for an unsplit run. */
256async function groupOf($: EngineInterface, rid: string): Promise<string[]> {
257  const group = (GROUP_LINE.exec((await readText($, `${await home($)}/.claude/mmruns/${rid}/run.meta`)) ?? '')?.[1] ?? '').split(',').filter(one => one !== '')
258
259  return group.length > 1 ? group : []
260}
261
262/** The results with a message within `max`: a review's read again `--top --oneline` first, then each output cut to an equal share. */
263async function boundResults($: EngineInterface, mmrun: string, watch: MmWatch, results: ModelResult[], isExhaustive: boolean, max: number): Promise<ModelResult[]> {
264  const fits = (list: ModelResult[]) => doneMessage(watch.kind, watch.rid, list, watch.seen, isExhaustive).length <= max
265
266  if (fits(results)) {
267    return results
268  }
269
270  let bounded = results
271
272  if (watch.kind === 'review') {
273    bounded = []
274
275    for (const one of results) {
276      const r = one.status === 'DONE' ? await $.process.run([mmrun, 'result', one.model, watch.rid, '--top', '--oneline']).catch(() => null) : null
277
278      bounded.push(r?.exitCode === 0 ? { ...one, output: r.stdout.trim() } : one)
279    }
280
281    if (fits(bounded)) {
282      return bounded
283    }
284  }
285
286  return cutOutputs(watch.kind, watch.rid, bounded, watch.seen ?? [], isExhaustive, max)
287}
288
289/** One pass over the watches: queues the message of each run whose models have all ended, then forgets it. */
290async function pollWatches($: EngineInterface): Promise<void> {
291  if (isPolling) {
292    return
293  }
294
295  isPolling = true
296
297  try {
298    const mmrun = `${$.plugin.root}/bin/mmrun`
299
300    if (unwatched.length > 0) {
301      const at = clears
302      const adding = unwatched.splice(0)
303      const startedAt = await $.clock.now()
304
305      try {
306        await update($, watches, list =>
307          at === clears ? [...list, ...adding.filter(one => !list.some(other => other.rid === one.rid)).map(one => ({ ...one, startedAt }))] : list,
308        )
309      } catch (error) {
310        unwatched.push(...adding)
311        throw error
312      }
313
314      if (at === clears) {
315        for (const one of adding) {
316          await mark($, one.rid, true)
317        }
318      }
319    }
320
321    for (const watch of (await read($, watches)).filter(one => one.message === undefined)) {
322      // A dead worker leaves RUNNING behind until `mmrun status` rewrites it to STALE.
323      await $.process.run([mmrun, 'status', watch.rid])
324
325      const models = await statusesOf($, `${await home($)}/.claude/mmruns/${watch.rid}`)
326      const running = Array.isArray(models) ? models.filter(one => one.status === 'RUNNING').map(one => one.model) : []
327
328      if (running.length > 0 && watch.reminded !== true && (await $.clock.now()) - watch.startedAt >= REMIND_MS) {
329        await update($, watches, list => list.map(one => (one.rid === watch.rid ? { ...one, reminded: true } : one)))
330        reminders.push(
331          `mm plugin: run ${watch.rid} has run for 60 minutes; still running: ${running.join(',')}. mmrun ends a model on its own at 90 minutes. To stop it now: mmrun cancel ${watch.rid}.`,
332        )
333      }
334
335      if (models === null || (models !== 'gone' && (models.length === 0 || models.some(one => one.status === 'RUNNING')))) {
336        continue
337      }
338
339      const ended = models === 'gone' ? null : await resultsOf($, mmrun, watch, models)
340
341      if (models !== 'gone' && ended === null) {
342        continue
343      }
344
345      const isExhaustive = ended !== null && watch.kind === 'review' && (await isExhaustiveRun($, watch.rid))
346      const group = ended !== null && watch.kind === 'review' ? await groupOf($, watch.rid) : []
347      // The parts of a split review go out as one message: each gets its share, less room for the joined message's header.
348      const max = group.length > 1 ? Math.floor(MESSAGE_MAX / group.length) - 300 : MESSAGE_MAX
349      const results = ended === null ? null : await boundResults($, mmrun, watch, ended, isExhaustive, max)
350
351      await update($, watches, list =>
352        results === null
353          ? list.filter(one => one.rid !== watch.rid)
354          : list.map(one =>
355              one.rid === watch.rid
356                ? { ...one, results, message: doneMessage(one.kind, one.rid, results, one.seen, isExhaustive), ...(group.length > 0 && { group }) }
357                : one,
358            ),
359      )
360    }
361
362    if (!isBusy) {
363      await flush($)
364    }
365  } finally {
366    isPolling = false
367  }
368}
369
370/** Records the models of watched runs whose ended result the segments (of a Bash command, or a Read path) read, and rebuilds a waiting message without them. */
371async function noteRead($: EngineInterface, segments: string[]): Promise<void> {
372  const list = await read($, watches)
373  const first = list[0]
374  // `mmrun result`/`report` without a rid reads mmrun's latest run of the session, which may be a delivered run no longer in `watches`.
375  const session =
376    first !== undefined && segments.some(segment => READ_LATEST.test(segment) && !RID_SHAPED.test(segment))
377      ? (/^session=(.+)$/m.exec((await readText($, `${await home($)}/.claude/mmruns/${first.rid}/run.meta`)) ?? '')?.[1] ?? '')
378      : ''
379  const latest = session === '' ? '' : ((await readText($, `${await home($)}/.claude/mmruns/.latest-${session}`))?.trim() ?? '')
380
381  for (const watch of list) {
382    const own = segments.filter(segment => segment.includes(watch.rid) || (watch.rid === latest && READ_LATEST.test(segment) && !RID_SHAPED.test(segment)))
383
384    if (own.length === 0) {
385      continue
386    }
387
388    const models = await statusesOf($, `${await home($)}/.claude/mmruns/${watch.rid}`)
389
390    if (!Array.isArray(models)) {
391      continue
392    }
393
394    // A read while the model runs sees partial output; `report -o` prints only the file it wrote.
395    const seen = models
396      .filter(
397        ({ model, status }) =>
398          status !== 'RUNNING' &&
399          own.some(
400            segment =>
401              new RegExp(`\\bmmrun\\s+result\\s+${model}\\b`).test(segment) ||
402              (REPORT.test(segment) && !OUT_OPTION.test(segment)) ||
403              segment.includes(`${model}.json`) ||
404              segment.includes(`${model}.out`),
405          ),
406      )
407      .map(one => one.model)
408
409    if (seen.length === 0) {
410      continue
411    }
412
413    const isExhaustive = watch.kind === 'review' && (await isExhaustiveRun($, watch.rid))
414
415    await update($, watches, list =>
416      list.map(one => {
417        if (one.rid !== watch.rid) {
418          return one
419        }
420
421        const all = [...new Set([...(one.seen ?? []), ...seen])]
422
423        return {
424          ...one,
425          seen: all,
426          ...(one.message !== undefined && one.results !== undefined && { message: doneMessage(one.kind, one.rid, one.results, all, isExhaustive) }),
427        }
428      }),
429    )
430  }
431}
432
433function ensurePoller($: EngineInterface): void {
434  if (poller === null) {
435    poller = $.clock.every(POLL_MS, () => detach($, 'poll', () => pollWatches($)))
436  }
437}
438
439/** Starts `mmrun <kind> …` in the session root and watches the run it prints; review without --models runs `reviewModels`. */
440async function start($: EngineInterface, kind: MmWatch['kind'], words: string[], reviewModels: string): Promise<{ text: string; context?: string[] }> {
441  const models = kind === 'review' && reviewModels !== '' && !words.includes('--models') ? ['--models', reviewModels] : []
442  const dir = words.includes('--dir') ? [] : ['--dir', await $.session.root()]
443  // mmrun writes it into <model>.events.jsonl; a Bash-started mmrun has it from the engine, this child process does not.
444  const sid = await $.session.id().catch(() => null)
445  const r = await $.process.run([`${$.plugin.root}/bin/mmrun`, kind, ...words, ...models, ...dir], sid === null ? undefined : { env: { CLAUDE_CODE_SESSION_ID: sid } })
446
447  if (r.exitCode !== 0) {
448    return { text: `mmrun ${kind} failed: ${r.stderr.split('\n')[0] ?? ''}` }
449  }
450
451  const text = r.stdout
452    .split('\n')
453    .filter(line => !FOLLOW_UP.test(line))
454    .join('\n')
455    .trim()
456  // A large review is split into parts, one run each.
457  const rids = r.stdout
458    .split('\n')
459    .map(line => RUN_LINE.exec(line)?.[1])
460    .filter(rid => rid !== undefined)
461
462  if (rids.length === 0) {
463    return { text }
464  }
465
466  const note =
467    kind === 'review'
468      ? `Review ${rids.join(', ')} was started by /mm:review. When ${rids.length > 1 ? 'each run' : 'it'} finishes, the mm plugin sends each model's critical/major findings; do not run \`mmrun wait\` yourself.`
469      : `Run ${rids.join(', ')} was started by /mm:run. When it finishes, the mm plugin sends the results; do not run \`mmrun wait\` yourself.`
470
471  // The run is started: a failure from here on must not reach the hook's catch, whose markdown fallback starts another.
472  for (const rid of rids) {
473    try {
474      const watch: MmWatch = { rid, kind, startedAt: await $.clock.now() }
475
476      await update($, watches, list => [...list, watch])
477      await mark($, rid, true)
478    } catch (error) {
479      $.ui.log(`mm: watching ${rid} failed, the next poll tries again: ${String(error)}`, { to: 'debug' })
480      unwatched.push({ rid, kind })
481    }
482  }
483
484  ensurePoller($)
485
486  return { text, context: [note] }
487}
488
489/** Whether the words start mmrun from the mod: options only, and for run both --model and --task. */
490function isStartable(kind: MmWatch['kind'], words: string[]): boolean {
491  return isFlagForm(words) && (kind === 'review' || (words.includes('--model') && words.includes('--task')))
492}
493
494export const register: Register = (on, options) => {
495  registerGuard(on, options)
496  const reviewModels = String(options.reviewModels)
497
498  on('session.start', async ($, e, next) => {
499    poller?.cancel()
500    poller = null
501    ensurePoller($)
502
503    return next(e)
504  }).catch(($, e, next) => {
505    logFailure($, 'session.start', next.error)
506
507    return next(e)
508  })
509
510  // /clear ends the conversation the runs would report to: forget them (they keep running, as Claude Code's background tasks do).
511  // Every end empties the marks: what follows (/resume, a new process) has no watches, so nothing would send the results.
512  on('session.end', async ($, e, next) => {
513    let ended = await read($, watches)
514
515    if (e.reason === 'clear') {
516      clears++
517      unwatched.splice(0)
518      reminders.splice(0)
519      resultFailures.clear()
520
521      await update($, watches, list => {
522        ended = list
523
524        return []
525      })
526    }
527
528    for (const watch of ended) {
529      await mark($, watch.rid, false)
530    }
531
532    return next(e)
533  }).catch(($, e, next) => {
534    logFailure($, 'session.end', next.error)
535
536    return next(e)
537  })
538
539  // Options only start mmrun here; anything with natural language goes to commands/review.md.
540  on('command.run', { command: 'mm:review' }, async ($, e, next) => {
541    const words = splitArgs(e.args)
542
543    return isFlagForm(words) ? start($, 'review', words, reviewModels) : next(e)
544  }).catch(($, e, next) => {
545    logFailure($, 'command.run', next.error)
546
547    return next(e)
548  })
549
550  on('command.run', { command: 'mm:run' }, async ($, e, next) => {
551    const words = splitArgs(e.args)
552
553    return isStartable('run', words) ? start($, 'run', words, reviewModels) : next(e)
554  }).catch(($, e, next) => {
555    logFailure($, 'command.run', next.error)
556
557    return next(e)
558  })
559
560  // The model's own Skill call to the same commands. Never hook tool.call on Bash (claude-code#92533).
561  on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
562    if (e.tool !== 'Skill' || e.agentId !== undefined || (e.skill !== 'mm:review' && e.skill !== 'mm:run')) {
563      return next(e)
564    }
565
566    const kind = e.skill === 'mm:review' ? 'review' : 'run'
567    const words = splitArgs(e.args ?? '')
568
569    if (words.length === 0 || !isStartable(kind, words)) {
570      return next(e)
571    }
572
573    const r = await start($, kind, words, reviewModels)
574
575    if (r.context === undefined) {
576      // The command's markdown loads, so the model can follow it.
577      const loaded = await next(e)
578
579      return loaded.deny !== undefined
580        ? loaded
581        : { ...loaded, context: [...(loaded.context ?? []), `mmrun failed to start: ${r.text}; start it with Bash as /${e.skill} describes instead`] }
582    }
583
584    // The note names the run already; mmrun's output is worth adding only for what else it says (warnings, SKIP lines).
585    const isRunOnly = r.text.split('\n').every(line => RUN_LINE.test(line))
586
587    return { result: { success: true, commandName: e.skill }, context: isRunOnly ? r.context : [...r.context, `mmrun output:\n${r.text}`] }
588  }).catch(($, e, next) => {
589    logFailure($, 'tool.call', next.error)
590
591    return next(e)
592  })
593
594  // Runs the model starts through Bash, so their end is handed over as /mm:review's are.
595  on('classic.PostToolUse', async ($, e, next) => {
596    const input = typeof e.tool_input === 'object' && e.tool_input !== null ? (e.tool_input as Record<string, unknown>) : {}
597    const output = typeof e.tool_response === 'object' && e.tool_response !== null ? (e.tool_response as Record<string, unknown>) : {}
598    const verb = e.agent_id === undefined && e.tool_name === 'Bash' && typeof input.command === 'string' ? MMRUN_START.exec(input.command)?.[1] : undefined
599    // One command can start several runs; `mmrun ask --from` continues a run in that run's mode.
600    const lines = verb !== undefined && typeof output.stdout === 'string' ? output.stdout.split('\n').filter(line => RUN_LINE.test(line)) : []
601
602    for (const line of lines) {
603      const rid = RUN_LINE.exec(line)?.[1] ?? ''
604      const mode = RUN_MODE.exec(line)?.[1]
605      const kind = mode === 'review' || mode === 'run' ? mode : mode === 'start' ? 'ask' : verb === 'review' || verb === 'run' ? verb : 'ask'
606      const watch: MmWatch = { rid, kind, startedAt: await $.clock.now() }
607
608      await update($, watches, list => (list.some(one => one.rid === rid) ? list : [...list, watch]))
609      await mark($, rid, true)
610    }
611
612    if (lines.length > 0) {
613      ensurePoller($)
614    }
615
616    const reading =
617      e.agent_id !== undefined
618        ? undefined
619        : e.tool_name === 'Bash' && typeof input.command === 'string'
620          ? input.command.split(SEGMENT_END)
621          : e.tool_name === 'Read' && typeof input.file_path === 'string'
622            ? [input.file_path]
623            : undefined
624
625    if (reading !== undefined) {
626      await noteRead($, reading)
627    }
628
629    return next(e)
630  }).catch(($, e, next) => {
631    logFailure($, 'classic.PostToolUse', next.error)
632
633    return next(e)
634  })
635
636  // Waiting messages ride the prompt that enters first, so none is also submitted. Not prompt.context: that spends the cache.
637  // A prompt that does not enter (dropped, or a hook beneath failing) puts its messages back.
638  on('prompt.submit', async ($, e, next) => {
639    const wasBusy = isBusy
640
641    isBusy = true
642
643    const at = clears
644    const waiting = await takeMessages($)
645    const notes = reminders.splice(0)
646    const taken: Waiting[] = []
647
648    // Whole messages in order while the text stays within CONTEXT_MAX; the rest go back for the next poll or prompt.
649    for (const one of waiting) {
650      if (taken.length > 0 && [...taken, one].map(watch => watch.message).concat(notes).join('\n\n').length > CONTEXT_MAX) {
651        break
652      }
653
654      taken.push(one)
655    }
656
657    await putBack($, waiting.slice(taken.length), at)
658
659    const text = [...taken.map(one => one.message), ...notes].join('\n\n')
660    let r: PromptSubmitResult
661
662    try {
663      r = await next(taken.length === 0 && notes.length === 0 ? e : { ...e, context: [...(e.context ?? []), text] })
664    } catch (error) {
665      await putBack($, taken, at)
666      putBackReminders(notes, at)
667      throw error
668    }
669
670    if (r.drop !== undefined) {
671      isBusy = wasBusy
672      await putBack($, taken, at)
673      putBackReminders(notes, at)
674    }
675
676    return r
677  }).catch(($, e, next) => {
678    logFailure($, 'prompt.submit', next.error)
679
680    return next(e)
681  })
682
683  // An interrupted or failed turn may end with no Stop; it leaves nothing running that would hand the messages over.
684  on('turn.complete', async ($, e, next) => {
685    if (e.agentId === undefined && e.reason !== 'answer') {
686      isBusy = false
687    }
688
689    return next(e)
690  }).catch(($, e, next) => {
691    logFailure($, 'turn.complete', next.error)
692
693    return next(e)
694  })
695
696  // Background work still in flight wakes the session again, so the messages wait for that turn. The next poll
697  // submits them: the host refuses a submit from a Stop hook.
698  on('classic.Stop', async ($, e, next) => {
699    if (e.agent_id === undefined) {
700      isBusy = (e.background_tasks ?? []).length > 0
701    }
702
703    return next(e)
704  }).catch(($, e, next) => {
705    logFailure($, 'classic.Stop', next.error)
706
707    return next(e)
708  })
709}
710
hooks/args.ts 187 lines
1// Options of `mmrun review` and `mmrun run` that take the next word as their value; any other `--x` is a switch.
2const VALUED = new Set([
3  '--base',
4  '--commit',
5  '--paths',
6  '--focus',
7  '--notes-file',
8  '--max',
9  '--models',
10  '--dir',
11  '--grok-model',
12  '--codex-model',
13  '--agy-model',
14  '--deepseek-model',
15  '--patch',
16  '--model',
17  '--task',
18  '--model-name',
19])
20
21/** One model's end of a run: its status file, `mmrun result` output when it is DONE, else the reason mmrun wrote and the non-empty patch a run left, if any. */
22export type ModelResult = { model: string; status: string; output: string; reason?: string; patch?: string }
23
24/** Splits like a shell: blanks separate words, '…' is literal, "…" and a bare \ escape; no expansion. */
25export function splitArgs(args: string): string[] {
26  const words: string[] = []
27  let word = ''
28  let isWord = false
29  let quote: '' | "'" | '"' = ''
30
31  for (let i = 0; i < args.length; i++) {
32    const ch = args[i] ?? ''
33
34    if (quote === "'") {
35      if (ch === "'") {
36        quote = ''
37      } else {
38        word += ch
39      }
40    } else if (quote === '"') {
41      if (ch === '"') {
42        quote = ''
43      } else if (ch === '\\' && '"\\$`'.includes(args[i + 1] ?? '')) {
44        word += args[++i]
45      } else {
46        word += ch
47      }
48    } else if (/\s/.test(ch)) {
49      if (isWord) {
50        words.push(word)
51        word = ''
52        isWord = false
53      }
54    } else {
55      isWord = true
56
57      if (ch === "'" || ch === '"') {
58        quote = ch
59      } else if (ch === '\\' && i + 1 < args.length) {
60        word += args[++i]
61      } else {
62        word += ch
63      }
64    }
65  }
66
67  if (isWord) {
68    words.push(word)
69  }
70
71  return words
72}
73
74/** Options only: the first word is an option, and every other word is the value of the option before it. */
75export function isFlagForm(words: string[]): boolean {
76  if (words.length === 0) {
77    return true
78  }
79
80  return words.every((word, i) => (i === 0 ? word.startsWith('--') : word.startsWith('--') || VALUED.has(words[i - 1] ?? '')))
81}
82
83// A `--top` section, or a `--oneline` finding.
84const SEVERE = /^## (CRITICAL|MAJOR)\b|\[(critical|major)\]/m
85const NOT_EXPANDED = /^Not expanded: (\d+)/m
86
87/** The judge rules a review's findings call for; one line when no DONE model reports a critical or major finding. */
88function judge(rid: string, results: ModelResult[], isExhaustive: boolean): string[] {
89  const outputs = results.filter(one => one.status === 'DONE').map(one => one.output)
90
91  if (outputs.length === 0) {
92    return []
93  }
94
95  if (!outputs.some(output => SEVERE.test(output))) {
96    return ['No critical or major findings: say plainly there are no issues; do not pad.']
97  }
98
99  return [
100    'Judge rules:',
101    '- Settle each finding by reading the code it points at. Keep only those at confidence 80 or above: you read the code and can name the input that makes it fail. Mention the dropped ones only in one line at the end: `Dropped N low-confidence findings`.',
102    '- Drop without scoring: what a linter, typechecker or compiler catches; style with no basis in CLAUDE.md; a generic "consider …" with no file:line. A suggestion to add an abstraction, a config option or a fallback is Optional at most.',
103    '- For a diff review, also drop lines this change did not touch and old problems unrelated to it. For a `--full` review keep them: the existing code is what was asked for.',
104    '- A finding both models report is high confidence, but still read the code. One that only a single model reports, settle by reading the code yourself: no voting, and do not drop it because the other model did not report it.',
105    `- Act only on critical/major.${isExhaustive ? ` For an --exhaustive run, also read minor/optional: \`mmrun result <model> ${rid}\` without --top.` : ''}`,
106    '- Coming back empty-handed is fine: with no finding at 80 or above, say plainly there are no issues; do not pad.',
107    ...(outputs.some(output => Number(NOT_EXPANDED.exec(output)?.[1] ?? 0) > 0)
108      ? ['- When the findings show `Not expanded` greater than 0, tell the user and let them decide whether to upgrade to --exhaustive.']
109      : []),
110    '- Do not change the code unless the user asked for it.',
111  ]
112}
113
114/** A run's next steps, from what each model left: a patch to check and apply, or a worktree to discard. */
115function runNext(rid: string, results: ModelResult[]): string[] {
116  const patched = results.filter(one => one.status === 'DONE' && !/^patch: no changes/m.test(one.output))
117
118  return [
119    ...(patched.length > 0
120      ? [
121          `Next: read the patch above against the task's acceptance items, then \`mmrun check ${rid} -- <gate command>\`; if it passes, \`mmrun apply ${rid}\` and run the gate again in the main tree; otherwise \`mmrun discard ${rid}\`.`,
122        ]
123      : []),
124    ...results
125      .filter(one => !patched.includes(one))
126      .map(one =>
127        one.status !== 'DONE' && one.patch !== undefined
128          ? `- ${one.model}: ${one.status}, but it left a patch: ${one.patch}; read it before \`mmrun discard ${rid}\`, which removes the worktree.`
129          : `- ${one.model}: ${one.status === 'DONE' ? 'no changes' : 'no patch'}; \`mmrun discard ${rid}\` removes the worktree.`,
130      ),
131    ...(results.some(one => one.status === 'DONE' && one.output.split('\n')[0] === 'status: blocked')
132      ? ['- status blocked: take the questions to the user; do not guess the answers and delegate again.']
133      : []),
134  ]
135}
136
137/** The message handed to the model when every model of a watched run has ended; the `seen` models' output is left out. */
138export function doneMessage(kind: 'review' | 'run' | 'ask', rid: string, results: ModelResult[], seen: string[] = [], isExhaustive = false): string {
139  // The engine refuses a submitted text that begins with `/`: it would run as a command.
140  const head =
141    kind === 'review'
142      ? `mm plugin: /mm:review review ${rid} has finished`
143      : kind === 'run'
144        ? `mm plugin: /mm:run run ${rid} has finished`
145        : `mm plugin: mmrun start/ask run ${rid} has finished`
146  const sections = results.map(one =>
147    seen.includes(one.model)
148      ? `## ${one.model}(${one.status})\nYou already read this result.`
149      : one.status === 'DONE'
150        ? `## ${one.model}(${one.status})\n${one.output}`
151        : one.reason !== undefined
152          ? `## ${one.model}(${one.status})\nNo result: ${one.reason}`
153          : `## ${one.model}(${one.status})\nNo result. \`tail -n 20 ~/.claude/mmruns/${rid}/${one.model}.raw | cut -c1-300\` shows the end of its log; report it to the user.`,
154  )
155  // Ahead of the model sections, so a reader that stops early still has them.
156  const judged = kind === 'review' ? judge(rid, results, isExhaustive) : []
157  const rules = judged.length > 0 ? [judged.join('\n')] : []
158  const tail = kind === 'run' ? runNext(rid, results) : []
159
160  return [head, ...rules, ...sections, ...(tail.length > 0 ? [tail.join('\n')] : [])].join('\n\n')
161}
162
163/** The results with each output the message shows cut to an equal share of the `max` characters its other parts leave, keeping its head and tail. */
164export function cutOutputs(
165  kind: 'review' | 'run' | 'ask',
166  rid: string,
167  results: ModelResult[],
168  seen: string[],
169  isExhaustive: boolean,
170  max: number,
171): ModelResult[] {
172  const shown = results.filter(one => one.status === 'DONE' && !seen.includes(one.model))
173  const rest = doneMessage(kind, rid, results, seen, isExhaustive).length - shown.reduce((sum, one) => sum + one.output.length, 0)
174  const share = Math.floor((max - rest) / Math.max(shown.length, 1))
175
176  return results.map(one => {
177    const note = `\n[cut; full: mmrun result ${one.model} ${rid}]\n`
178    const keep = Math.max(share - note.length, 0)
179    // The tail holds the patch line and Not expanded, which the next steps and the judge rules read.
180    const head = Math.floor(keep * 0.4)
181
182    return shown.includes(one) && one.output.length > share
183      ? { ...one, output: one.output.slice(0, head) + note + one.output.slice(one.output.length - (keep - head)) }
184      : one
185  })
186}
187
hooks/guard.ts 281 lines
1// Denies reading mmrun's *.raw and a main-thread `mmrun wait` on a run the mm plugin watches;
2// moves any other foreground `mmrun wait` to the background.
3import type { EngineInterface, HookFailure, Register } from 'claude-code'
4
5import { basename, isabs, join, normpath } from './posixpath'
6import { pySplit, shlexTokens } from './shlex'
7
8const RAW_DENY =
9  'mm: *.raw is the full event stream (tens of thousands of tokens); do not read it. ' +
10  'Use `mmrun status <RUNID>` for status and `mmrun result <model> <RUNID>` for findings. ' +
11  'For troubleshooting, the only allowed form is `tail -n N <file>.raw` with N at most 50, optionally `| cut -c1-M` with M at most 1000.'
12const WAIT_DENY = 'mm: the mm plugin watches {} and sends its result when it ends; do not wait for it.'
13
14// RAW_PATH's end also holds before a final newline; word characters (\w, \b) are Unicode letters, digits and _.
15const RAW_PATH = /\/\.claude\/mmruns\/[^/]+\/[^/]+\.raw(?=\n?$)/
16// The whole command is one `tail -N|-n N <file>.raw`, optionally piped to `cut -c1-M`: the troubleshooting step the mm docs recommend.
17const BOUNDED_TAIL = /^\s*tail\s+(?:-(\d+)|-n\s+(\d+))\s+[^\s;&|<>()$`'"\\*?]+\.raw\s*(?:\|\s*cut\s+-c1-(\d+)\s*)?$/
18const ASSIGN = /^[A-Za-z_][\p{L}\p{N}_]*=/u
19const HOME_VAR = /\$(?:HOME(?![\p{L}\p{N}_])|\{HOME\})/gu
20const HEREDOC = /<<-?\s*(['"]?)([\p{L}\p{N}_]+)\1([^\n]*)\n.*?\n\s*\2\s*(?=\n|$)/gsu
21const SHELL_FED = /^(?:(?:ba|z|da|k)?sh|python[\p{Nd}.]*|node|ruby|perl)$/u
22const SEPARATORS = ';&|()\n'
23// A login name sh expands after an unquoted ~; any other ~name names no user and keeps the path.
24const USER_NAME = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/
25// Background Bash is stopped at its `timeout` (default 30 min, max 2 h).
26const BASH_TIMEOUT_MS = 1_800_000
27const BASH_TIMEOUT_MAX_MS = 7_200_000
28const LOG_TIMEOUT_MS = 5_000
29
30/** What the guard reads of the host; register answers it from `$`, a test from its own world. */
31export type MmIo = {
32  env: (name: 'HOME' | 'MMRUN_SESSION' | 'CLAUDE_CODE_HOST_SESSION_ID') => Promise<string | undefined>
33  /** User `name`'s home directory ('' for the current user); undefined when there is no such user. */
34  userHome: (name: string) => Promise<string | undefined>
35  /** The file's text; undefined when it cannot be read. */
36  read: (path: string) => Promise<string | undefined>
37}
38
39/** The call as the guard sees it: the tool, its arguments, and lazily whose loop made it. */
40export type MmCall = {
41  tool: string
42  input: Record<string, unknown>
43  cwd: string | undefined
44  session: string | undefined
45  isMainThread: () => Promise<boolean>
46}
47
48export type MmDecision = { deny: { guard: string; op: string; message: string } } | { updatedInput: Record<string, unknown> } | undefined
49
50/** os.path.expanduser: `~` is $HOME (the user database when unset), `~name` that user's home; an unknown user keeps the path. */
51async function expanduser(io: MmIo, path: string): Promise<string> {
52  if (!path.startsWith('~')) return path
53  const cut = path.indexOf('/', 1) < 0 ? path.length : path.indexOf('/', 1)
54  const name = path.slice(1, cut)
55  const home = name === '' ? ((await io.env('HOME')) ?? (await io.userHome(''))) : await io.userHome(name)
56  if (home === undefined) return path
57  return home.replace(/\/+$/, '') + path.slice(cut) || '/'
58}
59
60/** The command's simple commands as word lists, split at ; & | ( ) and newlines outside quotes. */
61function commands(command: string): string[][] {
62  let tokens: string[]
63  try {
64    tokens = shlexTokens(command, SEPARATORS, ' \t\r')
65  } catch {
66    tokens = pySplit(command)
67  }
68  const out: string[][] = []
69  let cur: string[] = []
70  for (const t of tokens) {
71    if (Array.from(t).every(c => SEPARATORS.includes(c))) {
72      out.push(cur)
73      cur = []
74    } else {
75      cur.push(t)
76    }
77  }
78  return [...out, cur].filter(words => words.length > 0)
79}
80
81/** The command without heredoc bodies, except those on a line that runs a shell or interpreter. */
82function dropHeredocs(command: string): string {
83  return command.replace(HEREDOC, (whole: string, _quote: string, _delimiter: string, rest: string, at: number) => {
84    const line = command.slice(at === 0 ? 0 : command.lastIndexOf('\n', at - 1) + 1, at) + rest
85    const isFed = commands(line)
86      .map(executable)
87      .some(run => run.length > 0 && SHELL_FED.test(basename(run[0] ?? '')))
88    return isFed ? whole : rest
89  })
90}
91
92/** The words of the command actually run, past assignments, keywords and the env / timeout / nice / command / exec launchers. */
93function executable(words: string[]): string[] {
94  while (words.length > 0) {
95    const w = basename(words[0] ?? '')
96    if (ASSIGN.test(words[0] ?? '') || ['!', '{', 'then', 'do', 'else', 'time', 'nohup'].includes(w)) {
97      words = words.slice(1)
98    } else if (w === 'env') {
99      words = words.slice(1)
100      while (words[0] !== undefined && (words[0].startsWith('-') || ASSIGN.test(words[0]))) {
101        words = words.slice(['-u', '--unset', '-C', '--chdir', '-S', '--split-string'].includes(words[0]) ? 2 : 1)
102      }
103    } else if (w === 'timeout') {
104      words = words.slice(1)
105      while (words[0]?.startsWith('-')) words = words.slice(['-s', '--signal', '-k', '--kill-after'].includes(words[0]) ? 2 : 1)
106      words = words.slice(1) // the duration
107    } else if (w === 'nice' || w === 'command' || w === 'exec') {
108      words = words.slice(1)
109      while (words[0]?.startsWith('-')) words = words.slice(words[0] === '-n' || words[0] === '-a' ? 2 : 1)
110    } else {
111      return words
112    }
113  }
114  return words
115}
116
117/** Absolute paths the word may name: ~ and $HOME expanded, relative to each possible directory; none if unresolvable. */
118async function resolve(io: MmIo, word: string, dirs: string[]): Promise<string[]> {
119  const home = await expanduser(io, '~')
120  const path = await expanduser(io, word.replace(HOME_VAR, () => home))
121  if (path.includes('$') || path.includes('`')) return []
122  if (isabs(path)) return [normpath(path)]
123  return dirs.map(d => normpath(join(d, path)))
124}
125
126/** True when a *.raw operand resolves, against the cwd and any cd, into an mmruns run directory. */
127async function namesRaw(io: MmIo, command: string, cwd: string | undefined): Promise<boolean> {
128  const dirs = cwd ? [cwd] : []
129  for (const words of commands(command)) {
130    if (words[0] === 'cd' && words.length > 1 && words[1] !== '-') {
131      dirs.push(...(await resolve(io, words[1] ?? '', dirs)))
132      continue
133    }
134    for (const word of words) {
135      for (const part of word.split(/[=<>]/)) {
136        if (part.endsWith('.raw') && (await resolve(io, part, dirs)).some(p => RAW_PATH.test(p))) return true
137      }
138    }
139  }
140  return false
141}
142
143/** mmrun's session_key(); undefined where mmrun falls back to its own parent pid, which the guard cannot know. */
144async function sessionKey(io: MmIo): Promise<string | undefined> {
145  const k = (await io.env('MMRUN_SESSION')) || (await io.env('CLAUDE_CODE_HOST_SESSION_ID'))
146  if (!k) return undefined
147  // mmrun replaces each UTF-8 byte outside [A-Za-z0-9_.-] with _.
148  let key = ''
149  for (const c of k) {
150    const cp = c.codePointAt(0) ?? 0
151    key += /[A-Za-z0-9_.-]/.test(c) ? c : '_'.repeat(cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4)
152  }
153  return key.slice(0, 64)
154}
155
156/** The first waited run whose `watched` mark the mm plugin wrote in this session (a bare `watched`: any session);
157 * RUNID parsed as mmrun's cmd_wait does. */
158async function watchedRun(io: MmIo, waits: string[][], session: string | undefined): Promise<string | undefined> {
159  const root = await expanduser(io, '~/.claude/mmruns')
160  for (const run of waits) {
161    let words = run.slice(2)
162    // A redirection ends mmrun's own words: `2>&1` reaches here as `2>`, `> f` as `>` and `f`.
163    const redirect = words.findIndex(w => w.includes('<') || w.includes('>'))
164    words = words.slice(0, redirect < 0 ? words.length : redirect)
165    let rid = ''
166    while (words.length > 0) {
167      if (words[0] === '--timeout') {
168        words = words.slice(2)
169      } else {
170        rid = words[0] ?? ''
171        words = words.slice(1)
172      }
173    }
174    if (!rid) {
175      const key = await sessionKey(io)
176      if (key === undefined) continue
177      const latest = await io.read(`${root}/.latest-${key}`)
178      if (latest === undefined) continue
179      rid = latest.trim()
180    }
181    const text = await io.read(`${root}/${rid}/watched`)
182    if (text === undefined) continue
183    const mark = text.split(/\s+/).filter(word => word !== '')
184    if (mark[0] === 'watched' && (mark.length === 1 || mark[1] === session)) return rid
185  }
186  return undefined
187}
188
189export async function mmGuard(io: MmIo, call: MmCall): Promise<MmDecision> {
190  const rawDeny = { deny: { guard: 'mm-raw', op: 'read *.raw', message: RAW_DENY } }
191  if (call.tool === 'Read') return RAW_PATH.test(String(call.input.file_path ?? '')) ? rawDeny : undefined
192  if (call.tool !== 'Bash') return undefined
193  const command = String(call.input.command ?? '')
194  const text = dropHeredocs(command)
195  // Best effort: a word naming the mmruns tree and a *.raw, or a *.raw operand that resolves into a run directory.
196  // A word with whitespace is quoted prose unless it holds a command substitution.
197  const words = commands(text).flat()
198  const isNamed = words.some(w => w.includes('mmruns') && /\.raw(?![\p{L}\p{N}_])/u.test(w) && (!/\s/.test(w) || w.includes('$(') || w.includes('`')))
199  if (isNamed || (await namesRaw(io, text, call.cwd))) {
200    const tail = BOUNDED_TAIL.exec(command)
201    if (!tail || Number(tail[1] ?? tail[2]) > 50 || Number(tail[3] ?? 0) > 1000) return rawDeny
202  }
203  const waits = commands(text)
204    .map(executable)
205    .filter(run => run.length > 1 && basename(run[0] ?? '') === 'mmrun' && run[1] === 'wait')
206  if (waits.length === 0) return undefined
207  const rid = await watchedRun(io, waits, call.session)
208  if (rid !== undefined && (await call.isMainThread())) {
209    return { deny: { guard: 'mm-wait', op: 'mmrun wait', message: WAIT_DENY.replace('{}', rid) } }
210  }
211  const updated: Record<string, unknown> = { ...call.input, run_in_background: true }
212  // Background Bash is stopped at its `timeout`: cover mmrun's own --timeout plus a minute.
213  const asked = /--timeout\s+(\d+)/.exec(command)
214  if (asked) {
215    const need = Math.min((Number(asked[1]) + 60) * 1000, BASH_TIMEOUT_MAX_MS)
216    const timeout = call.input.timeout ?? BASH_TIMEOUT_MS
217    if (typeof timeout === 'number' && timeout < need) updated.timeout = need
218  }
219  const isChanged = call.input.run_in_background !== true || updated.timeout !== call.input.timeout
220  return isChanged ? { updatedInput: updated } : undefined
221}
222
223function logFailure($: EngineInterface, event: string, error: HookFailure): void {
224  $.ui.log(`mm: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
225}
226
227/** Whether the main thread made the call: its tool_use is in the main conversation while the call is decided. */
228async function isMainThread($: EngineInterface, toolUseId: string): Promise<boolean> {
229  return (await $.session.messages()).some(row => row.toolUses.some(use => use.tool_use_id === toolUseId))
230}
231
232/** The subagent that made the call, or null for the main thread or when no loop holds it. */
233async function agentOf($: EngineInterface, toolUseId: string): Promise<string | null> {
234  if (await isMainThread($, toolUseId)) return null
235  for (const agent of await $.agent.list()) {
236    const rows = await $.session.messages({ agentId: agent.id })
237    if (Array.isArray(rows) && rows.some(row => row.toolUses.some(use => use.tool_use_id === toolUseId))) return agent.id
238  }
239  return null
240}
241
242/** Appends one line to ~/.claude/harness/guard.jsonl; a log that cannot be written is skipped. */
243async function logDeny($: EngineInterface, guard: string, op: string, cwd: string, agentId: string | null): Promise<void> {
244  const home = await $.env.get('HOME')
245  if (home === undefined) return
246  const line = `${JSON.stringify({ at: await $.clock.now(), guard, decision: 'deny', op, cwd, agent_id: agentId })}\n`
247  await $.process
248    .run(['/bin/sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'sh', `${home}/.claude/harness/guard.jsonl`], { stdin: line, timeoutMs: LOG_TIMEOUT_MS })
249    .catch(() => undefined)
250}
251
252export const register: Register = on => {
253  // classic.PreToolUse, never tool.call: a tool.call hook on Bash breaks isolation: worktree subagents (claude-code#92533).
254  on('classic.PreToolUse', { tool: ['Bash', 'Read'] }, async ($, e, next) => {
255    const { tool, tool_use_id: toolUseId, ...input } = e
256    const io: MmIo = {
257      env: name => (name === 'HOME' ? $.env.get('HOME') : name === 'MMRUN_SESSION' ? $.env.get('MMRUN_SESSION') : $.env.get('CLAUDE_CODE_HOST_SESSION_ID')),
258      userHome: async name => {
259        if (name !== '' && !USER_NAME.test(name)) return undefined
260        const got = await $.process.run(['/bin/sh', '-c', `printf %s ~${name}`]).catch(() => undefined)
261        return got?.exitCode === 0 && got.stdout.startsWith('/') ? got.stdout : undefined
262      },
263      read: path => $.fs.read(path).catch(() => undefined),
264    }
265    const cwd = await $.session.cwd()
266    const decision = await mmGuard(io, { tool, input, cwd, session: await $.session.id().catch(() => undefined), isMainThread: () => isMainThread($, toolUseId) })
267    if (decision === undefined) return next(e)
268    if ('deny' in decision) {
269      await logDeny($, decision.deny.guard, decision.deny.op, cwd, await agentOf($, toolUseId))
270      return { deny: decision.deny.message }
271    }
272    // Hooks beneath see the call as the model made it; a rewrite of theirs keeps all but the fields this one changes.
273    const below = await next(e)
274    const changes = Object.fromEntries(Object.entries(decision.updatedInput).filter(([key, value]) => input[key as keyof typeof input] !== value))
275    return { ...below, updatedInput: { ...input, ...below.updatedInput, ...changes } }
276  }).catch(($, e, next) => {
277    logFailure($, 'classic.PreToolUse', next.error)
278    return next(e)
279  })
280}
281
hooks/posixpath.ts 45 lines
1// CPython's posixpath, the lexical part, ported line for line: the guards resolve paths exactly as it does.
2// plugins/harness/hooks/posixpath.ts and plugins/mm/hooks/posixpath.ts are the same file: each plugin ships on its own.
3
4export function basename(path: string): string {
5  return path.slice(path.lastIndexOf('/') + 1)
6}
7
8/** os.path.split: the head keeps a root of slashes and loses any other trailing ones. */
9export function split(path: string): [string, string] {
10  const cut = path.lastIndexOf('/') + 1
11  const head = path.slice(0, cut)
12  return [/^\/*$/.test(head) ? head : head.replace(/\/+$/, ''), path.slice(cut)]
13}
14
15export function dirname(path: string): string {
16  return split(path)[0]
17}
18
19export function isabs(path: string): boolean {
20  return path.startsWith('/')
21}
22
23export function join(first: string, ...rest: string[]): string {
24  let path = first
25  for (const part of rest) {
26    if (part.startsWith('/')) path = part
27    else if (path === '' || path.endsWith('/')) path += part
28    else path += `/${part}`
29  }
30  return path
31}
32
33export function normpath(path: string): string {
34  if (path === '') return '.'
35  // POSIX leaves the meaning of exactly two leading slashes to the implementation, so Python keeps them.
36  const slashes = !path.startsWith('/') ? 0 : path.startsWith('//') && !path.startsWith('///') ? 2 : 1
37  const parts: string[] = []
38  for (const part of path.split('/')) {
39    if (part === '' || part === '.') continue
40    if (part !== '..' || (slashes === 0 && parts.length === 0) || parts.at(-1) === '..') parts.push(part)
41    else if (parts.length > 0) parts.pop()
42  }
43  return '/'.repeat(slashes) + parts.join('/') || '.'
44}
45
hooks/shlex.ts 113 lines
1// CPython's shlex (posix mode, comments off), ported line for line: the guards split shell text exactly as it does.
2// plugins/harness/hooks/shlex.ts and plugins/mm/hooks/shlex.ts are the same file: each plugin ships on its own.
3
4const QUOTES = `'"`
5// Python's str.split() with no argument splits on these (str.isspace); JS \s lacks \x1c-\x1f and \x85, and adds \ufeff.
6const PY_SPACE = /[\t\n\v\f\r \x1c-\x1f\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/
7
8/** The words of shlex.shlex(text, posix=True, punctuation_chars=punctuation) with whitespace_split on and no commenters.
9 * Throws where shlex raises ValueError (an open quote, a trailing backslash). */
10export function shlexTokens(text: string, punctuation = '', whitespace = ' \t\r\n'): string[] {
11  const chars = Array.from(text)
12  const pushback: string[] = []
13  const tokens: string[] = []
14  let at = 0
15  let state: string | null = ' '
16  let token = ''
17  const read = (): string => pushback.pop() ?? chars[at++] ?? ''
18
19  for (;;) {
20    let quoted = false
21    let escapedState = ' '
22    for (;;) {
23      const c = read()
24      if (state === null) {
25        token = ''
26        break
27      }
28      if (state === ' ') {
29        if (c === '') {
30          state = null
31          break
32        } else if (whitespace.includes(c)) {
33          if (token !== '' || quoted) break
34        } else if (c === '\\') {
35          escapedState = 'a'
36          state = c
37        } else if (punctuation.includes(c)) {
38          token = c
39          state = 'c'
40        } else if (QUOTES.includes(c)) {
41          state = c
42        } else {
43          token = c
44          state = 'a'
45        }
46      } else if (QUOTES.includes(state)) {
47        quoted = true
48        if (c === '') throw new Error('No closing quotation')
49        if (c === state) {
50          state = 'a'
51        } else if (c === '\\' && state === '"') {
52          escapedState = state
53          state = c
54        } else {
55          token += c
56        }
57      } else if (state === '\\') {
58        if (c === '') throw new Error('No escaped character')
59        // Inside double quotes a backslash escapes only the quote and itself.
60        if (QUOTES.includes(escapedState) && c !== state && c !== escapedState) token += state
61        token += c
62        state = escapedState
63      } else {
64        if (c === '') {
65          state = null
66          break
67        } else if (whitespace.includes(c)) {
68          state = ' '
69          if (token !== '' || quoted) break
70        } else if (state === 'c') {
71          if (punctuation.includes(c)) {
72            token += c
73          } else {
74            pushback.push(c)
75            state = ' '
76            break
77          }
78        } else if (QUOTES.includes(c)) {
79          state = c
80        } else if (c === '\\') {
81          escapedState = 'a'
82          state = c
83        } else if (!punctuation.includes(c)) {
84          token += c
85        } else {
86          pushback.push(c)
87          state = ' '
88          if (token !== '' || quoted) break
89        }
90      }
91    }
92    const word = token
93    token = ''
94    if (word === '' && !quoted) return tokens
95    tokens.push(word)
96  }
97}
98
99/** shlex.split(text); throws where it raises ValueError. */
100export function shlexSplit(text: string): string[] {
101  return shlexTokens(text)
102}
103
104/** Python's text.split(): the fallback the guards use when shlex refuses the text. */
105export function pySplit(text: string): string[] {
106  return text.split(PY_SPACE).filter(word => word !== '')
107}
108
109/** shlex.join(words). */
110export function shlexJoin(words: readonly string[]): string {
111  return words.map(word => (word === '' ? "''" : /[^\w@%+=:,./-]/.test(word) ? `'${word.replaceAll("'", `'"'"'`)}'` : word)).join(' ')
112}
113
types/index.d.ts 27 lines
1/** An mmrun run started by /mm:review, /mm:run, or a main-thread Bash `mmrun review|run|start|ask`, watched until every model has ended. */
2export type MmWatch = {
3  rid: string
4  /** 'ask' stands for `mmrun start` and `mmrun ask` alike. */
5  kind: 'review' | 'run' | 'ask'
6  /** Epoch ms, from `$.clock.now()` when the run was started. */
7  startedAt: number
8  /** The run's conclusions once every model ended, waiting to be handed to the model; absent while it runs. */
9  message?: string
10  /** Each model's result the message was built from, so a read of one can rebuild it. */
11  results?: { model: string; status: string; output: string; reason?: string; patch?: string }[]
12  /** Models whose ended result the main thread already read; the message leaves their output out. */
13  seen?: string[]
14  /** Every run of the review this run is a part of, in part order (run.meta `group`); absent for an unsplit run. */
15  group?: string[]
16  /** The 60-minute reminder has been sent for this run. */
17  reminded?: boolean
18}
19
20declare module 'claude-code' {
21  interface PluginState {
22    mm: {
23      watches: MmWatch[]
24    }
25  }
26}
27