SLOPSHOPPER

goal-orchestrator

Ship a goal (an issue and its sub-issues) as one PR on one branch: intake asks which models and effort to use and whether you will be away, then a ship…

guardcommandtoaststatusprompttool
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · goal-orchestrator
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /orchestrator-stop ⎿ goal-orchestrator: No goal-orchestrator run is active; cleared /goal. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

goal-orchestrator

A Claude Code plugin that ships a goal (an issue and its sub-issues, a plan doc, or a written goal) as one PR on one branch with a team of sub-agents, verified end to end.

What it does

  1. Intake. One question set: which model and effort the implementers and reviewers use, whether you'll be away (fully autonomous) or around, and how far to go (branch, PR, or PR and merge when green). Then the run arms /goal itself, so it can't lose its finish line.
  2. Recon and plan. Reads the repo's steering docs and every issue, then plans waves of lanes that never edit the same files at the same time.
  3. Ship (a workflow). The build runs as a dynamic workflow: a program, not a prompt, so retries, gates and stop rules run as code. For each wave:
  4. Contract first. An agent turns the Done-when items into failing acceptance tests before any feature code exists.
  5. Lanes. Implementer agents build in parallel, each in its own worktree from the feature branch, with its own database and port, and make the contract tests pass without editing them. A lane that needs another lane's work waits and builds again once that one merges.
  6. Re-checked claims. An integrator re-runs every check a lane reports, compares the counts, and confirms the contract tests are untouched and no lane edited another's files. Gaps go back to the lane, at most twice; then the lane is dropped and the run ends PARTIAL instead of looping. High-risk lanes get a review before they merge.
  7. Merge and review. Ready lanes merge and the fast checks run in a clean worktree. A reviewer (and, for goals with screens, UI auditors with real screenshots) checks the wave and whatever no test can prove, and findings become fix lanes.
  8. Final gate. The full suites, up to two fix rounds, then a whole-diff review that also checks every earlier finding: fixed ones still hold, open ones are reported again or closed.
  9. Deliver. The PR with Issues, Decisions, Migrations, Ops notes and Tests; CI driven to green; a merge if you chose it; tracker checkpoints; and your final results.

The ship phase needs dynamic workflows (the Workflow tool). Without them, the orchestrator drives the waves itself, as in 1.x.

Install

At the prompt of a terminal session:

/plugin install goal-orchestrator --marketplace WaniiDev/goal-orchestrator

In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with WaniiDev/goal-orchestrator, then Add plugin.

To update: claude plugin update goal-orchestrator@goal-orchestrator-marketplace, then /reload-plugins or a new session. For one session from a clone: claude --plugin-dir ./plugins/goal-orchestrator.

Cloud sessions (claude.ai/code)

Cloud sessions don't load plugins from your machine or from a repository's .claude/settings.json. Install the plugin in the cloud environment's setup script (environment menu in the session title bar → Edit → Setup script), which runs before Claude starts:

#!/bin/bash
claude plugin marketplace add WaniiDev/goal-orchestrator || true
claude plugin install goal-orchestrator@goal-orchestrator-marketplace --scope user || true
  • New sessions pick it up; running ones don't. The script clones without your credentials, so this repository must stay public.
  • The environment caches the script's result and runs it again only when the script or its allowed hosts change, or after about 7 days. After a release, edit the script (a comment will do) so new sessions get the new version.
  • To try a branch before it reaches main, pin it: claude plugin marketplace add WaniiDev/goal-orchestrator#<branch>.

Use

/goal-orchestrator:run WAN-346 and its sub-issues
/goal-orchestrator:run docs/plan.md --auto
/goal-orchestrator:status
/goal-orchestrator:report

Or ask in plain words ("ship WAN-346 and its sub-issues as one PR while I sleep"). Claude can start the run skill itself, so another session, or a /goal that names goal-orchestrator, can start a run too.

After the intake, the run arms /goal itself (start_goal), so it keeps going until a terminal state and never past one: goal mode waits while the ship workflow runs, and every terminal state clears it. Watch the ship phase live with /workflows. /orchestrator-stop ends a run by hand (as BLOCKED) and clears /goal.

Headless (claude -p): set CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0. Otherwise print mode stops background work 10 minutes after the last turn, which cuts the ship workflow off mid-run.

--auto skips the intake and uses the defaults: Sonnet · medium to build, Opus · xhigh to review, away mode, PR only (branch only when origin is missing or a local path; never merges without your yes). Results: the chat summary, the PR body, and tracker checkpoints when a tracker connector exists.

Contents

  • skills/run/: the method (SKILL.md) and its references, each read only at its step: intake, the brief template, delivery, and the manual waves for sessions without workflows (with their review prompts).
  • workflows/ship.js: the ship phase. Its input is the plan the run skill writes; it returns the outcome, what shipped and what didn't (and why), the gate's checks, open findings and decisions.
  • skills/status/, skills/report/: the progress and final-results formats. Only you invoke them, so they add nothing to a session's context until used.
  • hooks/register.ts (a Claude Code mod, v2.1.287+): start_goal (arms /goal after the intake and keeps the finish line in the system prompt), run_start / run_finish tools, a progress and budget watchdog (no new commit, repeated failures, time, quiet runs), /orchestrator-stop, /goal clear on every terminal state, and guards against pkill/killall, force push and --no-verify while a run is active.
  • agents/implementer.md (default Sonnet · medium), agents/reviewer.md and agents/ui-auditor.md (default Opus · xhigh), agents/integrator.md (Sonnet · low: re-checks, merges, the gate). Each carries its own rules, so prompts carry only the lane's facts. The intake's choices override the models per run.
  • Tests: claude plugin test plugins/goal-orchestrator (the mod) and node --test plugins/goal-orchestrator/tests/ship.test.mjs (the workflow's control flow, with every agent faked).

Token use

  • The run's control flow is code: the orchestrator's context holds the plan and one result, not every lane report, retry and merge.
  • The generic rules live once, in the agent definitions. BRIEF.md is a ~50-line repo profile that agents read instead of the steering docs.
  • Agents don't load CLAUDE.md (omitClaudeMd; the brief carries the rules that apply) and see only the tools they use, not every tool and MCP server the session has.
  • Agents report schema-checked JSON, so nothing is parsed twice or re-asked. Mechanical re-checks and merges run on Sonnet · low.
  • Docs-only and test-only lanes skip contract tests and review. A blocked lane stops at once instead of retrying.
  • The watchdog stops loops before they burn tokens.
Source 2 files
hooks/register.ts 441 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3import type { ActiveGoal, Limits, Outcome, Run } from '../types'
4
5// Goal mode and exit paths for a goal-orchestrator run, enforced in code
6// instead of prose: start_goal (queues /goal and keeps its finish line in the
7// system prompt), run_start / run_finish tools, a progress and budget
8// watchdog, a quiet-run wake-up, /orchestrator-stop, a /goal clear on every
9// terminal state, and command guards while a run is active.
10
11type $ = EngineInterface
12
13const RUN = { plugin: 'goal-orchestrator', key: 'run' } as const
14const GOAL = { plugin: 'goal-orchestrator', key: 'goal' } as const
15const START = 'mcp__goal-orchestrator__run_start'
16const FINISH = 'mcp__goal-orchestrator__run_finish'
17const START_GOAL = 'mcp__goal-orchestrator__start_goal'
18/** `/goal`'s own limit on a condition. */
19const MAX_CONDITION = 4000
20/** `/goal clear` and its aliases. */
21const CLEARS = new Set(['clear', 'stop', 'off', 'reset', 'none', 'cancel'])
22// The desktop app's end-of-turn tools (task list, wrap-up box): bookkeeping, not work.
23const TURN_TOOLS = 'mcp__ccd_turn__'
24const OUTCOMES: readonly Outcome[] = ['DONE', 'PARTIAL', 'BLOCKED']
25const CHECK_HEAD_MS = 30_000
26const TICK_MS = 5 * 60_000
27const MAX_QUIET_WAKES = 2
28
29export const DEFAULTS: Limits = {
30  maxHours: 8,
31  maxIdleCalls: 60,
32  maxSameFailure: 3,
33  graceCalls: 15,
34  maxQuietMinutes: 45,
35}
36
37// Commands no agent may run while a run is active.
38export const GUARDS: readonly (readonly [RegExp, string])[] = [
39  [/(^|[\s;&|(])(pkill|killall)\s/, 'never kill by pattern; kill only PIDs you started'],
40  [/\bkill\b[^;&|]*\$\(\s*pgrep/, 'never kill by pattern; kill only PIDs you started'],
41  [/\bgit\s+push\b[^;&|]*\s(--force(?![\w-])|-f\b|\+\S)/, 'no force push (use --force-with-lease on your own lane branch if you must)'],
42  [/\bgit\b[^;&|]*\s--no-verify\b/, 'never skip git hooks'],
43]
44
45export function guardReason(command: string): string | undefined {
46  return GUARDS.find(([pattern]) => pattern.test(command))?.[1]
47}
48
49export function failureKey(command: string): string {
50  return command.trim().replace(/\s+/g, ' ').slice(0, 200)
51}
52
53export function finalLine(outcome: Outcome, summary: string, userAction?: string): string {
54  const action = userAction ? `; you must: ${userAction}` : ''
55  return `GOAL: ${outcome} — ${summary}${action}`
56}
57
58let run: Run | null = null
59let ticker: Timer | null = null
60
61async function save($: $): Promise<void> {
62  await $.state.set(RUN, run)
63}
64
65function status($: $, now: number): void {
66  if (run === null) {
67    $.ui.status(undefined)
68    return
69  }
70  const minutes = Math.round((now - run.startedAt) / 60_000)
71  const elapsed = `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
72  const label = run.phase === 'active' ? `idle ${run.idleCalls}/${run.limits.maxIdleCalls}` : run.phase
73  $.ui.status(`orchestrator · ${elapsed}/${run.limits.maxHours}h · ${label}`)
74}
75
76async function headOf($: $, current: Run): Promise<string> {
77  const ran = await $.process.run(['git', '-C', current.repoDir, 'rev-parse', current.branch])
78  return ran.exitCode === 0 ? ran.stdout.trim() : ''
79}
80
81function progress(current: Run, now: number): void {
82  current.idleCalls = 0
83  current.failures = {}
84  current.quietWakes = 0
85  current.lastActivityAt = now
86}
87
88function wrapUp(current: Run, reason: string): void {
89  if (current.phase !== 'active') return
90  current.phase = 'wrapup'
91  current.reason = reason
92  current.graceLeft = current.limits.graceCalls
93}
94
95function end($: $, current: Run, phase: 'ended' | 'stopped', outcome: Outcome, summary: string): void {
96  current.phase = phase
97  current.outcome = outcome
98  current.summary = summary
99  ticker?.cancel()
100  ticker = null
101  const line = finalLine(outcome, summary)
102  // A session the desktop app hosts has no notification channel for mods: toast there.
103  void $.ui
104    .notify(line, { title: 'goal-orchestrator' })
105    .then(sent => {
106      if (!sent.isSent) $.ui.toast(line)
107    })
108    .catch(() => undefined)
109}
110
111// /goal only clears itself on met / impossible / fatal error, so every
112// terminal state clears it here, once the session is idle.
113function clearGoal($: $): void {
114  void $.state.set(GOAL, null)
115  $.clock.after(0, () => {
116    void $.command.run({ command: 'goal', args: 'clear' }).catch(error => {
117      $.ui.log(`goal-orchestrator: could not run /goal clear (${String(error)}); run it yourself.`)
118    })
119  })
120}
121
122function wrapUpNotice(current: Run): string {
123  return [
124    `goal-orchestrator watchdog: ${current.reason}.`,
125    'Stop starting new work, and stop a running ship workflow with TaskStop. Push the branch, save state (RUN.md, DECISIONS.md, draft PR),',
126    `remove lane worktrees, then call run_finish with PARTIAL or BLOCKED. ${current.graceLeft} tool calls left before a hard stop.`,
127  ].join(' ')
128}
129
130function startTicker($: $): void {
131  ticker?.cancel()
132  ticker = $.clock.every(TICK_MS, () => {
133    void tick($)
134  })
135}
136
137async function tick($: $): Promise<void> {
138  if (run === null || run.phase !== 'active') return
139  const now = await $.clock.now()
140  if (now - run.startedAt >= run.limits.maxHours * 3_600_000) {
141    wrapUp(run, `time budget of ${run.limits.maxHours}h is spent`)
142    await save($)
143    await $.prompt.submit({ text: wrapUpNotice(run) }).catch(() => undefined)
144    return
145  }
146  if (now - run.lastActivityAt < run.limits.maxQuietMinutes * 60_000) return
147  if (run.quietWakes >= MAX_QUIET_WAKES) {
148    end($, run, 'stopped', 'BLOCKED', `no activity for ${run.limits.maxQuietMinutes} min after ${MAX_QUIET_WAKES} wake-ups`)
149    await save($)
150    status($, now)
151    clearGoal($)
152    return
153  }
154  run.quietWakes += 1
155  run.lastActivityAt = now
156  await save($)
157  await $.prompt
158    .submit({
159      text: `goal-orchestrator watchdog: no tool call and no agent report for ${run.limits.maxQuietMinutes} min. Check the ship workflow and any running agents; relaunch or drop what hangs, or call run_finish if the run cannot continue.`,
160    })
161    .catch(() => undefined)
162}
163
164function num(value: unknown, fallback: number): number {
165  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
166}
167
168const startSpec = {
169  name: 'run_start',
170  description:
171    'Start the goal-orchestrator watchdog for this run (call once after intake, and again on resume). It ends the run as BLOCKED instead of looping when there is no progress, the same command keeps failing, or the time budget is spent.',
172  isDeferred: true,
173  inputSchema: {
174    type: 'object',
175    properties: {
176      branch: { type: 'string', description: 'The feature branch; a new commit on it counts as progress.' },
177      repo_dir: { type: 'string', description: 'Absolute path of the main checkout.' },
178      max_hours: { type: 'number', description: `Wall-clock budget (default ${DEFAULTS.maxHours}).` },
179      max_idle_calls: { type: 'number', description: `Orchestrator tool calls without progress before wrap-up (default ${DEFAULTS.maxIdleCalls}).` },
180      max_same_failure: { type: 'number', description: `Times the same command may fail without progress (default ${DEFAULTS.maxSameFailure}).` },
181    },
182    required: ['branch', 'repo_dir'],
183  },
184}
185
186const finishSpec = {
187  name: 'run_finish',
188  description:
189    'End the goal-orchestrator run in exactly one terminal state. Call it last, after pushing the branch, saving state and removing lane worktrees. DONE: everything shipped and verified. PARTIAL: some issues shipped, the rest listed. BLOCKED: only the user can unblock it (auth, secret, permission, approval) or the run cannot make progress.',
190  isDeferred: true,
191  inputSchema: {
192    type: 'object',
193    properties: {
194      outcome: { type: 'string', enum: OUTCOMES },
195      summary: { type: 'string', description: 'One line: PR/branch, what shipped, what did not and why.' },
196      user_action: { type: 'string', description: 'For BLOCKED or PARTIAL: what the user must do.' },
197    },
198    required: ['outcome', 'summary'],
199  },
200}
201
202const startGoalSpec = {
203  name: 'start_goal',
204  description:
205    "Turn on Claude Code goal mode for a goal-orchestrator run: queues `/goal <condition>` exactly as if the user typed it. Call it once, right after the run skill's intake. The goal starts when this turn ends: say in one line that goal mode is armed, then end your turn.",
206  isDeferred: true,
207  inputSchema: {
208    type: 'object',
209    properties: {
210      condition: { type: 'string', description: `The /goal completion condition, at most ${MAX_CONDITION} characters.` },
211      run_file: { type: 'string', description: "Absolute path of the run's RUN.md." },
212    },
213    required: ['condition'],
214  },
215}
216
217function finishLine(goal: ActiveGoal): string {
218  return [
219    'A goal-orchestrator run is active in this session, in goal mode.',
220    `Its finish line (the /goal condition): ${goal.condition}`,
221    `Its state is in ${goal.runFile || 'RUN.md in the scratchpad'}: re-read it before acting after a compaction or a resume, then continue the goal-orchestrator:run skill from the step it records.`,
222    'If `/goal` reports the goal achieved or cleared, this section no longer applies.',
223  ].join('\n')
224}
225
226export const register: Register = on => {
227  on('session.start', async ($, e, next) => {
228    run = (await $.state.get(RUN)).value ?? null
229    await $.tool.register(startGoalSpec)
230    await $.tool.register(startSpec)
231    await $.tool.register(finishSpec)
232    await $.command.register({
233      name: 'orchestrator-stop',
234      description: 'End the running goal-orchestrator run as BLOCKED and clear /goal',
235    })
236    if (run !== null && run.phase !== 'ended' && run.phase !== 'stopped') startTicker($)
237    return next(e)
238  })
239
240  on('command.run', { command: 'orchestrator-stop' }, async $ => {
241    if (run === null || run.phase === 'ended' || run.phase === 'stopped') {
242      clearGoal($)
243      return { text: 'No goal-orchestrator run is active; cleared /goal.' }
244    }
245    end($, run, 'stopped', 'BLOCKED', 'stopped by the user')
246    await save($)
247    status($, await $.clock.now())
248    clearGoal($)
249    return { text: 'Run stopped as BLOCKED. The next tool call is refused and /goal is cleared.' }
250  })
251
252  on('tool.call', { tool: START_GOAL }, async ($, e) => {
253    const input = e as unknown as Record<string, unknown>
254    const condition = typeof input.condition === 'string' ? input.condition.trim() : ''
255    if (condition === '') return { deny: 'start_goal needs a condition.' }
256    if (condition.length > MAX_CONDITION) {
257      return { deny: `The condition is ${condition.length} characters; /goal takes at most ${MAX_CONDITION}.` }
258    }
259    const runFile = typeof input.run_file === 'string' ? input.run_file.trim() : ''
260    const goal: ActiveGoal = { condition, runFile, setAt: await $.clock.now() }
261    await $.state.set(GOAL, goal)
262    // A slash command can't run inside the hook the turn is waiting on: queue it for when the session is idle.
263    $.clock.after(0, () => {
264      void $.command.run({ command: 'goal', args: condition }).catch(() => {
265        $.ui.toast('goal-orchestrator: /goal could not start. Type /goal and paste the condition from RUN.md.')
266      })
267    })
268    return {
269      result: `Goal mode is queued: /goal starts when this turn ends and keeps the run going until this condition is met:\n${condition}\nEnd your turn now.`,
270    }
271  }).catch(() => ({ deny: 'start_goal failed inside the goal-orchestrator mod; give the user the /goal line from RUN.md to paste.' }))
272
273  // `/goal clear`, or a /goal for something else, ends this run's hold on the finish line.
274  on('command.run', { command: 'goal' }, async ($, e, next) => {
275    const args = e.args.trim()
276    const goal = (await $.state.get(GOAL)).value ?? null
277    if (goal !== null && args !== '' && (CLEARS.has(args.toLowerCase()) || args !== goal.condition)) {
278      await $.state.set(GOAL, null)
279    }
280    return next(e)
281  }).catch(($, e, next) => next(e))
282
283  // Keeps the finish line in the system prompt, so it survives a compaction even if the conversation does not.
284  on('prompt.compose', async ($, e, next) => {
285    const composed = await next(e)
286    const goal = (await $.state.get(GOAL)).value ?? null
287    if (goal === null) return composed
288    return { ...composed, sections: [...composed.sections, { id: 'goal-orchestrator:finish-line', text: finishLine(goal), scope: 'session' }] }
289  })
290
291  on('tool.call', { tool: START }, async ($, e) => {
292    const input = e as unknown as Record<string, unknown>
293    const branch = typeof input.branch === 'string' ? input.branch : ''
294    const repoDir = typeof input.repo_dir === 'string' ? input.repo_dir : ''
295    if (branch === '' || repoDir === '') return { deny: 'run_start needs branch and repo_dir.' }
296    const now = await $.clock.now()
297    const limits: Limits = {
298      ...DEFAULTS,
299      maxHours: num(input.max_hours, DEFAULTS.maxHours),
300      maxIdleCalls: num(input.max_idle_calls, DEFAULTS.maxIdleCalls),
301      maxSameFailure: num(input.max_same_failure, DEFAULTS.maxSameFailure),
302    }
303    const fresh: Run = {
304      branch,
305      repoDir,
306      startedAt: now,
307      lastActivityAt: now,
308      checkedAt: now,
309      head: '',
310      idleCalls: 0,
311      failures: {},
312      quietWakes: 0,
313      graceLeft: limits.graceCalls,
314      phase: 'active',
315      reason: '',
316      outcome: null,
317      summary: '',
318      limits,
319    }
320    fresh.head = await headOf($, fresh)
321    run = fresh
322    await save($)
323    startTicker($)
324    status($, now)
325    return {
326      result: `Watchdog on for ${branch}: ${limits.maxHours}h, ${limits.maxIdleCalls} idle calls, ${limits.maxSameFailure} same failures. End the run only through run_finish.`,
327    }
328  }).catch(() => ({ deny: 'run_start failed inside the goal-orchestrator mod; continue without the watchdog and follow the skill\'s stop rules.' }))
329
330  on('tool.call', { tool: FINISH }, async ($, e) => {
331    const input = e as unknown as Record<string, unknown>
332    const outcome = OUTCOMES.find(one => one === input.outcome)
333    const summary = typeof input.summary === 'string' ? input.summary.trim() : ''
334    if (outcome === undefined || summary === '') return { deny: 'run_finish needs outcome (DONE, PARTIAL or BLOCKED) and a summary.' }
335    const userAction = typeof input.user_action === 'string' && input.user_action.trim() !== '' ? input.user_action.trim() : undefined
336    const line = finalLine(outcome, summary, userAction)
337    if (run !== null) {
338      end($, run, 'ended', outcome, userAction ? `${summary}; you must: ${userAction}` : summary)
339      await save($)
340      status($, await $.clock.now())
341    }
342    return {
343      result: `Run recorded as ${outcome}. Make no more tool calls, apart from the app's own end-of-turn wrap-up if it asks for one. End your reply with this exact line:\n${line}`,
344    }
345  }).catch(() => ({ deny: 'run_finish failed inside the goal-orchestrator mod; end your reply with the GOAL line yourself.' }))
346
347  // Every other tool call: the guards, the terminal lock, and the watchdog.
348  on('tool.call', async ($, e, next) => {
349    if (e.tool === START || e.tool === FINISH || e.tool === START_GOAL || String(e.tool).startsWith(TURN_TOOLS) || run === null) {
350      return next(e)
351    }
352    const current = run
353    const isMain = e.agentId === undefined
354
355    if (current.phase === 'ended' || current.phase === 'stopped') {
356      if (e.tool === 'TaskStop') return next(e)
357      return {
358        deny: `The goal-orchestrator run is over (${current.outcome}). Make no more tool calls; end your reply with: ${finalLine(current.outcome ?? 'BLOCKED', current.summary)}`,
359      }
360    }
361
362    const command = e.tool === 'Bash' ? e.command : ''
363    const guard = command === '' ? undefined : guardReason(command)
364    if (guard !== undefined) return { deny: `goal-orchestrator guard: ${guard}.` }
365
366    if (!isMain) {
367      // A sub-agent at work is activity, not progress: a long lane is not a quiet run.
368      current.lastActivityAt = await $.clock.now()
369      return next(e)
370    }
371
372    if (current.phase === 'wrapup') {
373      if (e.tool === 'Agent' || e.tool === 'Workflow') return { deny: `No new agents or workflows: ${current.reason}. Wrap up and call run_finish.` }
374      current.graceLeft -= 1
375      if (current.graceLeft <= 0) {
376        end($, current, 'stopped', 'BLOCKED', `watchdog: ${current.reason}, and run_finish was not called`)
377        await save($)
378        status($, await $.clock.now())
379        clearGoal($)
380        return { deny: `Hard stop. ${finalLine('BLOCKED', current.summary)} — end your reply with that line.` }
381      }
382    }
383
384    const ran = await next(e)
385    const now = await $.clock.now()
386    current.lastActivityAt = now
387    current.idleCalls += 1
388
389    if (now - current.checkedAt >= CHECK_HEAD_MS || /\bgit\s+(merge|commit|push)\b/.test(command)) {
390      current.checkedAt = now
391      const head = await headOf($, current)
392      if (head !== '' && head !== current.head) {
393        current.head = head
394        progress(current, now)
395      }
396    }
397
398    if (command !== '' && ran.deny === undefined && ran.isError === true) {
399      const key = failureKey(command)
400      const count = (current.failures[key] ?? 0) + 1
401      current.failures[key] = count
402      if (count >= current.limits.maxSameFailure) {
403        wrapUp(current, `"${key.slice(0, 80)}" failed ${count} times with no new commit`)
404      }
405    }
406    if (current.idleCalls >= current.limits.maxIdleCalls) {
407      wrapUp(current, `${current.idleCalls} tool calls with no new commit on ${current.branch}`)
408    }
409
410    await save($)
411    status($, now)
412    if (current.phase !== 'wrapup' || ran.deny !== undefined) return ran
413    return { ...ran, context: [...(ran.context ?? []), wrapUpNotice(current)] }
414  }).catch(($, e, next) => {
415    // A watchdog failure must not stall the session: keep the guards, let the rest through.
416    if (next.called) return next(e)
417    const guard = e.tool === 'Bash' ? guardReason(e.command) : undefined
418    return guard === undefined ? next(e) : { deny: `goal-orchestrator guard: ${guard}.` }
419  })
420
421  on('turn.complete', async ($, e, next) => {
422    const done = await next(e)
423    if (run === null) return done
424    if (e.agentId !== undefined) {
425      // A sub-agent reported back: activity, and progress for the stall count.
426      if (run.phase === 'active') {
427        progress(run, await $.clock.now())
428        await save($)
429      }
430      return done
431    }
432    if (run.phase === 'ended' || run.phase === 'stopped') {
433      run = null
434      await save($)
435      status($, 0)
436      clearGoal($)
437    }
438    return done
439  })
440}
441
types/index.d.ts 47 lines
1export type Outcome = 'DONE' | 'PARTIAL' | 'BLOCKED'
2
3/** active: working · wrapup: a budget tripped, finish soon · ended: run_finish called · stopped: the watchdog ended it */
4export type Phase = 'active' | 'wrapup' | 'ended' | 'stopped'
5
6export type Limits = {
7  maxHours: number
8  maxIdleCalls: number
9  maxSameFailure: number
10  graceCalls: number
11  maxQuietMinutes: number
12}
13
14export type Run = {
15  branch: string
16  repoDir: string
17  startedAt: number
18  lastActivityAt: number
19  checkedAt: number
20  head: string
21  idleCalls: number
22  failures: Record<string, number>
23  quietWakes: number
24  graceLeft: number
25  phase: Phase
26  reason: string
27  outcome: Outcome | null
28  summary: string
29  limits: Limits
30}
31
32/** The finish line of the run this session is orchestrating, as `start_goal` set it. */
33export type ActiveGoal = {
34  /** The `/goal` condition, word for word. */
35  condition: string
36  /** Where the run keeps its state (`RUN.md`), so it can be re-read after a compaction. */
37  runFile: string
38  /** When the goal was queued, in epoch milliseconds. */
39  setAt: number
40}
41
42declare module 'claude-code' {
43  interface PluginState {
44    'goal-orchestrator': { run: Run | null; goal: ActiveGoal | null }
45  }
46}
47