SLOPSHOPPER

ouroboros

GitHub milestone loop: an architect turns PRD milestones into sub-issues with checklists; each sub-issue is implemented, reviewed until its checklist passes…

guardcommandtoastpromptprocesstimer
v0.25.0no licenseupdated 2026-10-12StupidCodeFactory/ouroboros
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ouroboros
› 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 › /ouroboros ⎿ ouroboros: GitHub milestone loop: /ouroboros kickoff <milestone-issue> | start <milestone-issue> | status | stop | doctor ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

ouroboros

A Claude Code plugin that runs a milestone of work on a GitHub project board.

An architect turns a milestone from your PRD into sub-issues, each holding an implementation plan and a checklist of verifiable items. The loop then takes the sub-issues one at a time. Each stage runs as a workflow in the session's own checkout, on a branch GitHub links to the sub-issue, so the app shows the diff live and the PR when it opens. The implementer works on that branch. The reviewer runs the checklist, and each item that passes gets ticked. Defects send the sub-issue back to In Progress with a comment, until the reviewer accepts it. An accepted sub-issue moves to Done and gets a PR, and the loop starts the next one.

The design is in docs/specs/2026-10-11-github-milestone-loop.md.

Install

claude plugin marketplace add StupidCodeFactory/ouroboros
claude plugin install ouroboros@ouroboros

The hooks are function hooks: set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 in the env of ~/.claude/settings.json.

Setup

  1. Create a GitHub project with a single-select Status field holding the columns Milestones, Planned, In Progress, QA and Done. Under the project's Workflows, turn off "Auto-close issue": the loop moves a sub-issue to Done before its PR merges, and only the PR's Closes #n should close it.
  2. Create the label needs-owner in the repository.
  3. Write a PRD with one heading per milestone, for example ### M1. Sign-in.
  4. Open one issue per milestone with that heading as its title, and put it in the Milestones column.
  5. Commit .claude/ouroboros.json:
{
  "prd": "docs/prd.md",
  "github": {
    "repo": "owner/repo",
    "project": "My board",
    "status_field": "Status",
    "columns": { "milestones": "Milestones", "planned": "Planned", "in_progress": "In Progress", "qa": "QA", "done": "Done" },
    "labels": { "needs_owner": "needs-owner" }
  }
}

Everything but github.project has the default shown. branch_prefix (default work/) sets the prefix of task branches. gh must be logged in as an account that can edit the repository's issues and the project.

Then run /ouroboros doctor. It checks the gh account's repo and project scopes and push rights, the repository setting "Automatically delete head branches", the board, its status field, columns and "Auto-close issue" workflow, the needs-owner label and the PRD, and names every problem in one answer, or says the setup is ready. Turn "Automatically delete head branches" on under Settings > General > Pull Requests: without it GitHub keeps a merged base branch, and a stacked PR merges into it instead of the default branch.

Use

CommandDoes
/ouroboros kickoff <milestone-issue>The architect plans the milestone. The hook writes its body and creates, updates or drops sub-issues in Planned. Rerun it to revise the plan.
/ouroboros start <milestone-issue>Runs the loop: the next ready sub-issue, then the one after, until none is left or one needs you.
/ouroboros statusShows the milestone, the stage and the sub-issue in progress.
/ouroboros stopStops following the running stage. start resumes.
/ouroboros doctorChecks the setup and names every missing piece, or says it is ready.

A sub-issue needs you (needs-owner label plus a comment) in three cases: its body is incomplete, the implementer is blocked, or three review rounds end without acceptance. Fix the cause, remove the label and run start again.

Every accepted sub-issue gets a PR closing it. While a PR is open, the next sub-issue stacks on its branch. Merge the PRs in order.

Development

./scripts/install-hooks.sh
./scripts/pre-push

pre-push runs claude plugin test . and validates the manifest. It always runs the pushing worktree's own scripts/pre-push in that worktree; ./scripts/acceptance/pre_push_own_checkout.sh checks this.

Source 8 files
hooks/register.ts 624 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { WORKFLOWS_QUERY, autoCloseProblems, boardProblems, deleteHeadBranchesProblems, doctorAnswer, labelProblems, loginOf, prdProblems, pushProblems, scopeProblems } from './github/doctor'
4import { milestoneGaps, renderMilestoneBody } from './github/contract'
5import type { MilestoneBody } from './github/contract'
6import {
7  addLabelCommand,
8  addToBoardCommand,
9  boardIdsOf,
10  closePullRequestCommand,
11  commentCommand,
12  createSubIssueCommand,
13  creationOrder,
14  deleteBranchCommand,
15  deleteCommentCommand,
16  developCommand,
17  dropCommand,
18  editIssueCommand,
19  githubConfigOf,
20  issueOfPosition,
21  linkSubIssueCommand,
22  linkedBranchOf,
23  linkedBranchesCommand,
24  pullRequestCommand,
25  removeLabelCommand,
26  setColumnCommand,
27  shellCommand,
28} from './github/gh_commands'
29import type { BoardIds, Column, GhCommand, GithubConfig, GithubSettings } from './github/gh_commands'
30import { architectResult, kickoffAnswer, kickoffIssueNumber, milestoneColumn, prdSection } from './github/kickoff_issue'
31import { kickoffChanges, plannedBody } from './github/kickoff_plan'
32import type { KickoffChanges, PlannedTask } from './github/kickoff_plan'
33import { MAX_REVIEW_ROUNDS, branchName, escalationComment, nextSubIssue, readinessComment, reviewOutcome, stageComment } from './loop'
34import type { BoardSubIssue, Review } from './loop'
35import { implementPrompt, kickoffPrompt, reviewPrompt } from './prompts'
36import type { KickoffBrief, StageBrief } from './prompts'
37
38type Stage = 'kickoff' | 'implement' | 'review'
39type Launch = { agent: string; stage: Stage; label: string; brief: string }
40type LoopState = {
41  milestone?: number
42  stage?: Stage
43  label?: string
44  pending?: Launch
45  run?: string
46  issue?: number
47  title?: string
48  branch?: string
49  base?: string
50  round: number
51  defects?: string[]
52  tip?: string
53}
54type Config = { prd?: string; branch_prefix?: string; github?: GithubSettings }
55type StageResult = { status?: string; question?: string } & Partial<Review>
56
57const CONFIG_PATH = '.claude/ouroboros.json'
58const RUNTIME_DIR = '.claude/ouroboros'
59const STATE_PATH = `${RUNTIME_DIR}/state.json`
60const BRIEFS_DIR = `${RUNTIME_DIR}/briefs`
61const STAGE_WORKFLOW = 'stage'
62const OUTPUT_FILE = /<output-file>([^<]+)<\/output-file>/
63const IDLE: LoopState = { round: 0 }
64const AGENTS: Record<Stage, string> = { kickoff: 'architect', implement: 'implementer', review: 'reviewer' }
65
66const OUROBOROS_COMMAND = {
67  name: 'ouroboros',
68  description: 'GitHub milestone loop: /ouroboros kickoff <milestone-issue> | start <milestone-issue> | status | stop | doctor',
69}
70
71const words = (text: string) => text.trim().split(/\s+/).filter(Boolean)
72
73const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
74
75const loudly = (error: unknown) => `ouroboros: ${messageOf(error)}`
76
77async function run($: EngineInterface, argv: string[], stdin?: string) {
78  const { exitCode, stdout, stderr } = await $.process.run(argv, stdin === undefined ? undefined : { stdin })
79  if (exitCode !== 0) throw new Error(`\`${shellCommand(argv)}\` failed: ${stderr.trim() || stdout.trim()}`)
80  return stdout.trim()
81}
82
83const gh = ($: EngineInterface, command: GhCommand) => run($, command.argv, command.stdin)
84
85let stageInverses: GhCommand[] = []
86
87const undoWith = (inverse: GhCommand | undefined) => {
88  if (inverse !== undefined) stageInverses.push(inverse)
89}
90
91async function rollBack($: EngineInterface, inverses: GhCommand[]) {
92  const failures: string[] = []
93  for (const inverse of [...inverses].reverse()) await gh($, inverse).catch(error => failures.push(messageOf(error)))
94  return failures
95}
96
97async function undoingOnFailure($: EngineInterface, stage: () => Promise<string>) {
98  stageInverses = []
99  try {
100    return await stage()
101  } catch (error) {
102    const failures = await rollBack($, stageInverses)
103    await writeState($, withoutStage(await readState($)))
104    const restored = failures.length === 0 ? 'GitHub is back as it was before the stage' : `undoing the stage also failed: ${failures.join('; ')}`
105    throw new Error(`stopped: ${messageOf(error)}; ${restored}`)
106  } finally {
107    stageInverses = []
108  }
109}
110
111async function editIssue($: EngineInterface, repo: string, previous: { number: number; title: string; body: string }, title: string, body: string) {
112  undoWith(editIssueCommand(repo, previous.number, previous.title, previous.body))
113  await gh($, editIssueCommand(repo, previous.number, title, body))
114}
115
116async function comment($: EngineInterface, repo: string, number: number, text: string) {
117  undoWith(deleteCommentCommand(repo, await gh($, commentCommand(repo, number, text))))
118}
119
120async function repositoryRoot($: EngineInterface) {
121  const { stdout } = await $.process.run(['git', 'rev-parse', '--show-toplevel'])
122  return stdout.trim() || (await $.session.cwd())
123}
124
125async function projectPath($: EngineInterface, relative: string) {
126  return `${await repositoryRoot($)}/${relative}`
127}
128
129async function readConfig($: EngineInterface): Promise<Config | undefined> {
130  const path = await projectPath($, CONFIG_PATH)
131  return (await $.fs.exists(path)) ? JSON.parse(await $.fs.read(path)) : undefined
132}
133
134async function readState($: EngineInterface): Promise<LoopState> {
135  const path = await projectPath($, STATE_PATH)
136  return (await $.fs.exists(path)) ? { ...IDLE, ...JSON.parse(await $.fs.read(path)) } : IDLE
137}
138
139async function writeRuntimeFile($: EngineInterface, relative: string, text: string) {
140  const ignore = await projectPath($, `${RUNTIME_DIR}/.gitignore`)
141  if (!(await $.fs.exists(ignore))) await $.fs.write(ignore, '*\n')
142  const path = await projectPath($, relative)
143  await $.fs.write(path, text)
144  return path
145}
146
147const writeState = ($: EngineInterface, state: LoopState) => writeRuntimeFile($, STATE_PATH, JSON.stringify(state, null, 2))
148
149const withoutStage = (state: LoopState): LoopState => ({ ...state, stage: undefined, label: undefined, pending: undefined, run: undefined })
150
151async function githubConfig($: EngineInterface, config: Config): Promise<GithubConfig> {
152  const github = githubConfigOf(config.github)
153  if (github.repo !== undefined) return github
154  return { ...github, repo: await run($, ['gh', 'repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']) }
155}
156
157const ownerOf = (github: GithubConfig) => (github.repo ?? '').split('/')[0] ?? ''
158
159async function boardAnswers($: EngineInterface, github: GithubConfig) {
160  const owner = ownerOf(github)
161  const projects = JSON.parse(await run($, ['gh', 'project', 'list', '--owner', owner, '--limit', '100', '--format', 'json']))
162  const project = projects.projects.find((candidate: { title: string }) => candidate.title === github.project)
163  const fields = project === undefined ? { fields: [] } : JSON.parse(await run($, ['gh', 'project', 'field-list', String(project.number), '--owner', owner, '--format', 'json']))
164  return { projects, fields }
165}
166
167async function boardIds($: EngineInterface, github: GithubConfig) {
168  const { projects, fields } = await boardAnswers($, github)
169  return boardIdsOf(projects, fields, github)
170}
171
172type Board = { github: GithubConfig; ids: BoardIds; config: Config }
173
174async function board($: EngineInterface): Promise<Board | string> {
175  const config = await readConfig($)
176  if (config === undefined) return `no ${CONFIG_PATH} at the checkout root: create one (README, Setup)`
177  const github = await githubConfig($, config)
178  if (github.project === undefined) return `ouroboros needs github.project in ${CONFIG_PATH}`
179  const ids = await boardIds($, github)
180  return 'missing' in ids ? `ouroboros needs ${ids.missing}` : { github, ids, config }
181}
182
183async function readIssue($: EngineInterface, github: GithubConfig, number: number) {
184  return JSON.parse(await run($, ['gh', 'issue', 'view', String(number), '-R', github.repo ?? '', '--json', 'number,title,body'])) as { number: number; title: string; body: string }
185}
186
187async function issueColumn($: EngineInterface, github: GithubConfig, number: number) {
188  const items = JSON.parse(await run($, ['gh', 'issue', 'view', String(number), '-R', github.repo ?? '', '--json', 'projectItems', '--jq', '.projectItems']))
189  return milestoneColumn(items, github.project ?? '')
190}
191
192async function readSubIssues($: EngineInterface, github: GithubConfig, milestone: number): Promise<BoardSubIssue[]> {
193  const lines = await run($, ['gh', 'api', `repos/${github.repo}/issues/${milestone}/sub_issues`, '--paginate', '--jq', '.[] | {number, state, title, body, labels: [.labels[].name]}'])
194  const subIssues = lines.split('\n').filter(Boolean).map(line => JSON.parse(line) as BoardSubIssue)
195  return Promise.all(subIssues.map(async subIssue => ({ ...subIssue, labels: subIssue.labels ?? [], column: await issueColumn($, github, subIssue.number) })))
196}
197
198const issueUrl = (github: GithubConfig, number: number) => `https://github.com/${github.repo}/issues/${number}`
199
200const columnNamed = (github: GithubConfig, name: string | undefined) => (Object.entries(github.columns) as Array<[Column, string]>).find(([, each]) => each === name)?.[0]
201
202async function moveToColumn($: EngineInterface, { github, ids }: Board, number: number, column: Column, note?: string) {
203  const previous = columnNamed(github, await issueColumn($, github, number))
204  const itemId = await gh($, addToBoardCommand(ownerOf(github), ids, issueUrl(github, number)))
205  if (previous !== undefined) undoWith(setColumnCommand(ids, itemId, previous))
206  await gh($, setColumnCommand(ids, itemId, column))
207  if (note !== undefined) await comment($, github.repo ?? '', number, note)
208}
209
210const stageDetail = (state: LoopState, round: number, pullRequest?: string) => ({ branch: state.branch as string, base: state.base as string, round, pullRequest })
211
212const labelOf = (state: LoopState, stage: Stage) => (stage === 'kickoff' ? `kickoff:#${state.milestone}` : `${stage}:#${state.issue} round ${state.round + 1}`)
213
214const spokenLabel = (label: string) => label.replace(':', ' ')
215
216const workflowCall = (launch: Launch) => `Workflow name=${launch.agent.split(':')[0]}:${STAGE_WORKFLOW}`
217
218const launchNote = (launch: Launch) => `ouroboros: next, ${spokenLabel(launch.label)}. Launch it: ${workflowCall(launch)}`
219
220const submitWhenIdle = ($: EngineInterface, text: string) =>
221  $.clock.after(0, () => {
222    $.prompt.submit({ text }).catch(error => $.ui.toast(loudly(error)))
223  })
224
225async function offerStage($: EngineInterface, state: LoopState, stage: Stage, prompt: string) {
226  const label = labelOf(state, stage)
227  const brief = await writeRuntimeFile($, `${BRIEFS_DIR}/${label.replace(/\W+/g, '-')}.md`, prompt)
228  const pending: Launch = { agent: `${$.plugin.name}:${AGENTS[stage]}`, stage, label, brief }
229  await writeState($, { ...state, stage, label, pending, run: undefined })
230  submitWhenIdle($, launchNote(pending))
231}
232
233const isStageWorkflow = (name: string | undefined) => (name ?? '').split(':').pop() === STAGE_WORKFLOW
234
235async function milestonePrdSection($: EngineInterface, config: Config, title: string) {
236  const prd = config.prd ?? 'docs/prd.md'
237  const path = await projectPath($, prd)
238  if (!(await $.fs.exists(path))) return { refusal: `no PRD at ${prd}: set prd in ${CONFIG_PATH}` }
239  const found = prdSection(await $.fs.read(path), title)
240  return 'section' in found ? found : { refusal: `no heading of ${prd} matches "${title}"; headings: ${found.headings.join(', ')}` }
241}
242
243const busy = (state: LoopState) => (state.run === undefined ? undefined : `ouroboros is running ${state.label}; wait for its result, or \`/ouroboros stop\``)
244
245async function kickoff($: EngineInterface, state: LoopState, argument: string) {
246  const number = kickoffIssueNumber(argument)
247  if (number === undefined) return 'usage: `/ouroboros kickoff <milestone-issue>`'
248  const refusal = busy(state)
249  if (refusal !== undefined) return refusal
250  const found = await board($)
251  if (typeof found === 'string') return found
252  const milestone = await readIssue($, found.github, number)
253  if ((await issueColumn($, found.github, number)) !== found.github.columns.milestones) return `#${number} is not in the "${found.github.columns.milestones}" column of "${found.github.project}"`
254  const prd = await milestonePrdSection($, found.config, milestone.title)
255  if ('refusal' in prd) return prd.refusal
256  const sub_issues = (await readSubIssues($, found.github, number)).map(({ number, state, title, body }) => ({ number, state, title, body }))
257  const brief: KickoffBrief = { issue: number, title: milestone.title, prd_section: prd.section, milestone_body: milestone.body, sub_issues }
258  await offerStage($, { ...(state.milestone === number ? state : IDLE), milestone: number }, 'kickoff', kickoffPrompt(brief))
259  return `kickoff #${number}: the architect is planning ${sub_issues.length === 0 ? 'its sub-issues' : `against ${sub_issues.length} existing sub-issues`}`
260}
261
262async function createSubIssue($: EngineInterface, github: GithubConfig, milestone: number, title: string, body: string) {
263  const number = Number((await gh($, createSubIssueCommand(github.repo ?? '', title, body))).split('/').pop())
264  const id = Number(await run($, ['gh', 'api', `repos/${github.repo}/issues/${number}`, '--jq', '.id']))
265  await gh($, linkSubIssueCommand(github.repo ?? '', milestone, id))
266  return number
267}
268
269async function applyKickoffChanges($: EngineInterface, found: Board, milestone: number, tasks: PlannedTask[], changes: KickoffChanges) {
270  const { github } = found
271  const created = new Map<number, number>()
272  const bodyOf = (task: PlannedTask) => plannedBody(task, issueOfPosition(tasks, created))
273  for (const position of creationOrder(tasks, changes.create)) {
274    const task = tasks[position - 1] as PlannedTask
275    created.set(position, await createSubIssue($, github, milestone, task.title, bodyOf(task)))
276  }
277  for (const number of changes.update) {
278    const task = tasks.find(candidate => candidate.issue === number) as PlannedTask
279    await editIssue($, github.repo ?? '', await readIssue($, github, number), task.title, bodyOf(task))
280  }
281  for (const number of changes.drop) await gh($, dropCommand(github.repo ?? '', number))
282  for (const number of [...created.values(), ...changes.update, ...changes.unchanged]) await moveToColumn($, found, number, 'planned')
283  return { created: [...created.values()], updated: changes.update, dropped: changes.drop, unchanged: changes.unchanged, closed: changes.closed }
284}
285
286async function writeMilestoneBody($: EngineInterface, github: GithubConfig, number: number, body: MilestoneBody) {
287  const previous = await readIssue($, github, number)
288  await editIssue($, github.repo ?? '', previous, previous.title, renderMilestoneBody(body))
289}
290
291async function applyKickoff($: EngineInterface, milestone: number, result: Record<string, unknown> | undefined) {
292  const planned = architectResult(result)
293  if ('error' in planned) return `kickoff #${milestone} failed: ${planned.error}`
294  const bodyGaps = milestoneGaps(renderMilestoneBody(planned.milestone))
295  if (bodyGaps.length > 0) return `kickoff #${milestone} rejected, nothing applied: the milestone body misses ${bodyGaps.join(', ')}`
296  const found = await board($)
297  if (typeof found === 'string') return `kickoff #${milestone} failed: ${found}`
298  const changes = kickoffChanges(await readSubIssues($, found.github, milestone), planned.tasks)
299  if ('rejected' in changes) return `kickoff #${milestone} rejected, nothing applied: ${changes.rejected}`
300  const applied = await applyKickoffChanges($, found, milestone, planned.tasks, changes)
301  await writeMilestoneBody($, found.github, milestone, planned.milestone)
302  return `${kickoffAnswer(milestone, applied)}. Next: \`/ouroboros start ${milestone}\``
303}
304
305async function escalate($: EngineInterface, found: Board, state: LoopState, number: number, text: string) {
306  undoWith(removeLabelCommand(found.github.repo ?? '', number, found.github.labels.needs_owner))
307  await gh($, addLabelCommand(found.github.repo ?? '', number, found.github.labels.needs_owner))
308  await comment($, found.github.repo ?? '', number, text)
309  await writeState($, { ...withoutStage(state), issue: number })
310  return `#${number} needs you: see its comment, then remove ${found.github.labels.needs_owner} and run \`/ouroboros start ${state.milestone}\``
311}
312
313async function defaultBranch($: EngineInterface, root: string) {
314  const ref = await run($, ['git', '-C', root, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD']).catch(() => 'origin/main')
315  return ref.replace(/^origin\//, '')
316}
317
318async function isOpenPullRequestHead($: EngineInterface, github: GithubConfig, branch: string) {
319  const state = await run($, ['gh', 'pr', 'view', branch, '-R', github.repo ?? '', '--json', 'state', '--jq', '.state']).catch(() => '')
320  return state === 'OPEN'
321}
322
323async function stackBase($: EngineInterface, found: Board, state: LoopState, subIssue: BoardSubIssue, root: string) {
324  if (state.issue === subIssue.number && state.base !== undefined) return state.base
325  const stacked = state.tip !== undefined && (await isOpenPullRequestHead($, found.github, state.tip))
326  return stacked ? (state.tip as string) : defaultBranch($, root)
327}
328
329async function uncommittedRefusal($: EngineInterface, root: string, branch: string, milestone: number) {
330  const current = await run($, ['git', '-C', root, 'branch', '--show-current'])
331  if (current === branch || (await run($, ['git', '-C', root, 'status', '--porcelain'])) === '') return undefined
332  return `the session checkout has uncommitted changes on ${current}: commit or stash them, then \`/ouroboros start ${milestone}\``
333}
334
335async function checkOutSubIssueBranch($: EngineInterface, found: Board, state: LoopState, subIssue: BoardSubIssue) {
336  const repo = found.github.repo ?? ''
337  const root = await repositoryRoot($)
338  const linked = linkedBranchOf(await gh($, linkedBranchesCommand(repo, subIssue.number)))
339  const branch = linked ?? branchName(found.config.branch_prefix ?? 'work/', subIssue.number, subIssue.title)
340  const refusal = await uncommittedRefusal($, root, branch, state.milestone as number)
341  if (refusal !== undefined) return { refusal }
342  const base = await stackBase($, found, state, subIssue, root)
343  if (linked === undefined) {
344    undoWith(deleteBranchCommand(repo, branch))
345    await gh($, developCommand(repo, subIssue.number, branch, base))
346  }
347  await run($, ['git', '-C', root, 'fetch', 'origin'])
348  await run($, ['git', '-C', root, 'switch', branch])
349  return { branch, base }
350}
351
352const stageBrief = (state: LoopState, body: string): StageBrief => ({
353  issue: state.issue as number,
354  title: state.title ?? '',
355  body,
356  branch: state.branch as string,
357  base: state.base as string,
358  round: state.round,
359  defects: state.defects ?? [],
360})
361
362async function launchStage($: EngineInterface, state: LoopState, stage: 'implement' | 'review', body: string) {
363  const brief = stageBrief(state, body)
364  await offerStage($, state, stage, stage === 'implement' ? implementPrompt(brief) : reviewPrompt(brief))
365}
366
367async function startSubIssue($: EngineInterface, found: Board, state: LoopState, subIssue: BoardSubIssue) {
368  if (subIssue.labels.includes(found.github.labels.needs_owner)) return `#${subIssue.number} still carries ${found.github.labels.needs_owner}: answer its comment, remove the label, then \`/ouroboros start ${state.milestone}\``
369  const unready = readinessComment(subIssue.body)
370  if (unready !== undefined) return escalate($, found, state, subIssue.number, unready)
371  if (isInFlight(state, subIssue, found.github)) return resumeSubIssue($, found, state, subIssue)
372  const resuming = state.issue === subIssue.number
373  const place = await checkOutSubIssueBranch($, found, state, subIssue)
374  if ('refusal' in place) return place.refusal
375  const next: LoopState = { ...state, issue: subIssue.number, title: subIssue.title, ...place, round: 0, defects: resuming ? state.defects : [] }
376  await moveToColumn($, found, subIssue.number, 'in_progress', stageComment('in_progress', stageDetail(next, next.round + 1)))
377  await launchStage($, next, 'implement', subIssue.body)
378  return `#${subIssue.number} "${subIssue.title}": In Progress on ${place.branch} (from ${place.base}); implementing`
379}
380
381const isInFlight = (state: LoopState, subIssue: BoardSubIssue, github: GithubConfig) =>
382  state.stage !== undefined && state.issue === subIssue.number && subIssue.state === 'open' && (subIssue.column === github.columns.in_progress || subIssue.column === github.columns.qa)
383
384async function resumeSubIssue($: EngineInterface, found: Board, state: LoopState, subIssue: BoardSubIssue) {
385  const stage = state.stage === 'review' || subIssue.column === found.github.columns.qa ? 'review' : 'implement'
386  const column = stage === 'review' ? 'qa' : 'in_progress'
387  const place = await checkOutSubIssueBranch($, found, state, subIssue)
388  if ('refusal' in place) return place.refusal
389  if (subIssue.column !== found.github.columns[column]) await moveToColumn($, found, subIssue.number, column)
390  await launchStage($, { ...state, title: subIssue.title, ...place }, stage, subIssue.body)
391  return `#${subIssue.number} "${subIssue.title}": resumed ${stage} round ${state.round + 1} on ${place.branch}`
392}
393
394const isActive = (subIssue: BoardSubIssue, github: GithubConfig) => subIssue.state === 'open' && (subIssue.column === github.columns.in_progress || subIssue.column === github.columns.qa || subIssue.column === github.columns.planned)
395
396async function advance($: EngineInterface, state: LoopState) {
397  const found = await board($)
398  if (typeof found === 'string') return found
399  const subIssues = await readSubIssues($, found.github, state.milestone as number)
400  const current = subIssues.find(subIssue => subIssue.number === state.issue)
401  if (current !== undefined && isActive(current, found.github)) return startSubIssue($, found, state, current)
402  const next = nextSubIssue(subIssues, found.github.columns)
403  const cleared: LoopState = { ...state, issue: undefined, title: undefined, branch: undefined, base: undefined, round: 0, defects: [] }
404  if ('finished' in next) {
405    await writeState($, cleared)
406    return `milestone #${state.milestone} finished: every sub-issue is Done`
407  }
408  if ('none' in next) {
409    await writeState($, cleared)
410    return next.none
411  }
412  return startSubIssue($, found, isStarted(next.issue, found.github) ? rebuiltState(found, cleared, next.issue) : cleared, next.issue)
413}
414
415const isStarted = (subIssue: BoardSubIssue, github: GithubConfig) => subIssue.column === github.columns.in_progress || subIssue.column === github.columns.qa
416
417const rebuiltState = (found: Board, cleared: LoopState, subIssue: BoardSubIssue): LoopState => ({
418  ...cleared,
419  issue: subIssue.number,
420  title: subIssue.title,
421  stage: subIssue.column === found.github.columns.qa ? 'review' : 'implement',
422  round: 0,
423})
424
425async function start($: EngineInterface, state: LoopState, argument: string) {
426  const number = kickoffIssueNumber(argument)
427  if (number === undefined) return 'usage: `/ouroboros start <milestone-issue>`'
428  const refusal = busy(state)
429  if (refusal !== undefined) return refusal
430  return advance($, state.milestone === number ? state : { ...IDLE, milestone: number })
431}
432
433const statusText = (state: LoopState) => {
434  if (state.milestone === undefined) return 'ouroboros: idle'
435  const doing = state.stage === undefined ? 'idle' : `${state.stage}${state.issue === undefined ? '' : ` #${state.issue}`}${state.stage === 'kickoff' ? '' : ` (review round ${state.round})`}`
436  return `ouroboros milestone #${state.milestone} · ${doing}${state.tip === undefined ? '' : ` · stack tip ${state.tip}`}`
437}
438
439async function stop($: EngineInterface, state: LoopState) {
440  await writeState($, withoutStage(state))
441  return 'stopped: a running stage workflow keeps going but its result is ignored; `/ouroboros start <milestone>` resumes'
442}
443
444const problemsOf = (check: Promise<string[]>) => check.catch(error => [error instanceof Error ? error.message : String(error)])
445
446async function boardCheck($: EngineInterface, github: GithubConfig) {
447  if (github.project === undefined) return [`ouroboros needs github.project in ${CONFIG_PATH}`]
448  const { projects, fields } = await boardAnswers($, github)
449  const project = projects.projects.find((candidate: { title: string }) => candidate.title === github.project)
450  if (project === undefined) return boardProblems(projects, fields, github)
451  const workflows = run($, ['gh', 'api', 'graphql', '-f', `query=${WORKFLOWS_QUERY}`, '-F', `id=${project.id}`])
452  return [...boardProblems(projects, fields, github), ...(await problemsOf(workflows.then(answer => autoCloseProblems(github.project as string, answer))))]
453}
454
455async function prdCheck($: EngineInterface, config: Config) {
456  const prd = config.prd ?? 'docs/prd.md'
457  const path = await projectPath($, prd)
458  return prdProblems(prd, (await $.fs.exists(path)) ? await $.fs.read(path) : undefined)
459}
460
461async function repoChecks($: EngineInterface, github: GithubConfig, login: Promise<string>) {
462  const repo = github.repo ?? ''
463  const checks = [
464    login.then(name => run($, ['gh', 'api', `repos/${repo}`, '--jq', '.permissions.push']).then(answer => pushProblems(name, repo, answer))),
465    run($, ['gh', 'api', `repos/${repo}`, '--jq', '.delete_branch_on_merge']).then(answer => deleteHeadBranchesProblems(repo, answer)),
466    boardCheck($, github),
467    run($, ['gh', 'label', 'list', '-R', repo, '--limit', '500', '--json', 'name']).then(answer => labelProblems(repo, github.labels.needs_owner, answer)),
468  ]
469  return (await Promise.all(checks.map(problemsOf))).flat()
470}
471
472async function doctor($: EngineInterface) {
473  const config = await readConfig($)
474  if (config === undefined) return doctorAnswer([`no ${CONFIG_PATH} at the checkout root: create one (README, Setup)`])
475  const user = run($, ['gh', 'api', '-i', 'user'])
476  const login = user.then(loginOf, () => loginOf(''))
477  const checks = [
478    user.then(scopeProblems),
479    githubConfig($, config).then(github => repoChecks($, github, login)),
480    prdCheck($, config),
481  ]
482  return doctorAnswer((await Promise.all(checks.map(problemsOf))).flat())
483}
484
485async function runCommand($: EngineInterface, args: string) {
486  const [head = '', ...rest] = words(args)
487  const state = await readState($)
488  if (head === 'kickoff') return undoingOnFailure($, () => kickoff($, state, rest.join(' ')))
489  if (head === 'start') return undoingOnFailure($, () => start($, state, rest.join(' ')))
490  if (head === 'status') return statusText(state)
491  if (head === 'stop') return stop($, state)
492  if (head === 'doctor') return doctor($)
493  return OUROBOROS_COMMAND.description
494}
495
496async function finishSubIssue($: EngineInterface, found: Board, state: LoopState) {
497  const branch = state.branch as string
498  await run($, ['git', '-C', await repositoryRoot($), 'push', '-u', 'origin', branch])
499  const pullRequest = await gh($, pullRequestCommand(found.github.repo ?? '', { base: state.base as string, head: branch, title: state.title ?? branch, number: state.issue as number }))
500  undoWith(closePullRequestCommand(found.github.repo ?? '', pullRequest))
501  await moveToColumn($, found, state.issue as number, 'done', stageComment('done', stageDetail(state, state.round, pullRequest)))
502  return { state: { ...state, tip: branch }, pullRequest }
503}
504
505async function onImplemented($: EngineInterface, found: Board, state: LoopState, result: StageResult) {
506  if (result.status !== 'done') return escalate($, found, state, state.issue as number, escalationComment(result.question || 'The implementer stopped without a question.'))
507  await moveToColumn($, found, state.issue as number, 'qa', stageComment('qa', stageDetail(state, state.round + 1)))
508  const { body } = await readIssue($, found.github, state.issue as number)
509  await launchStage($, state, 'review', body)
510  return `#${state.issue} in QA: reviewing (round ${state.round + 1})`
511}
512
513async function onReviewed($: EngineInterface, found: Board, state: LoopState, result: StageResult) {
514  const number = state.issue as number
515  const issue = await readIssue($, found.github, number)
516  const outcome = reviewOutcome(issue.body, { items: result.items ?? [], defects: result.defects ?? [] })
517  if (outcome.body !== issue.body) await editIssue($, found.github.repo ?? '', issue, issue.title, outcome.body)
518  const round = state.round + 1
519  if (outcome.accepted) {
520    const finished = await finishSubIssue($, found, { ...state, round })
521    const next = await advance($, withoutStage(finished.state))
522    return `#${number} Done: ${finished.pullRequest} opened from ${state.branch} into ${state.base}; show it in this session's PR bar. ${next}`
523  }
524  await comment($, found.github.repo ?? '', number, outcome.comment)
525  if (round >= MAX_REVIEW_ROUNDS) {
526    await moveToColumn($, found, number, 'in_progress')
527    return escalate($, found, { ...state, round }, number, escalationComment(`${MAX_REVIEW_ROUNDS} review rounds ended without acceptance. Decide how to proceed: clarify the plan or checklist, or fix it by hand.`))
528  }
529  await moveToColumn($, found, number, 'in_progress', stageComment('in_progress', stageDetail(state, round + 1)))
530  const defects = outcome.comment.split('\n').filter(line => line.startsWith('- ') || line.startsWith('  '))
531  await launchStage($, { ...state, round, defects }, 'implement', outcome.body)
532  return `#${number} review round ${round} found defects: back to In Progress, implementing again`
533}
534
535async function conductResult($: EngineInterface, state: LoopState, result: Record<string, unknown> | undefined) {
536  const settled = withoutStage(state)
537  if (state.stage === 'kickoff') {
538    await writeState($, settled)
539    return applyKickoff($, state.milestone as number, result)
540  }
541  const found = await board($)
542  if (typeof found === 'string') {
543    await writeState($, settled)
544    return found
545  }
546  if (state.stage === 'implement') return onImplemented($, found, settled, result === undefined ? { status: 'blocked', question: 'The implementer ended without a readable answer.' } : (result as StageResult))
547  return onReviewed($, found, settled, result === undefined ? { items: [], defects: ['The reviewer ended without a readable answer.'] } : (result as StageResult))
548}
549
550const resultOf = (outputFileText: string): Record<string, unknown> | undefined => {
551  try {
552    const { result } = JSON.parse(outputFileText) as { result?: unknown }
553    return result !== null && typeof result === 'object' ? (result as Record<string, unknown>) : undefined
554  } catch {
555    return undefined
556  }
557}
558
559async function stageResult($: EngineInterface, notification: string) {
560  const outputFile = OUTPUT_FILE.exec(notification)?.[1]
561  return outputFile !== undefined && (await $.fs.exists(outputFile)) ? resultOf(await $.fs.read(outputFile)) : undefined
562}
563
564const mentionsTask = (text: string, taskId: string) => new RegExp(`(^|[^\\w-])${taskId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^\\w-]|$)`).test(text)
565
566async function onStageNotification($: EngineInterface, notification: string) {
567  const state = await readState($)
568  if (state.run === undefined || !mentionsTask(notification, state.run)) return undefined
569  const result = await stageResult($, notification)
570  return `ouroboros: ${await undoingOnFailure($, () => conductResult($, state, result)).catch(messageOf)}`
571}
572
573async function launchPendingStage($: EngineInterface, call: () => Promise<unknown>) {
574  const state = await readState($)
575  const refusal = busy(state)
576  if (refusal !== undefined) return { deny: refusal }
577  if (state.pending === undefined) return { deny: 'no ouroboros stage is waiting to launch: `/ouroboros start <milestone-issue>`' }
578  const launched = (await call()) as { result?: { taskId?: string } }
579  const taskId = launched.result?.taskId
580  if (taskId !== undefined) await writeState($, { ...state, pending: undefined, run: taskId })
581  return launched
582}
583
584const contextText = (state: LoopState) =>
585  state.pending === undefined ? statusText(state) : `${statusText(state)}\npending launch: ${spokenLabel(state.pending.label)} with ${workflowCall(state.pending)}`
586
587export const register: Register = on => {
588  on('session.start', async ($, e, next) => {
589    await $.command.register(OUROBOROS_COMMAND)
590    return next(e)
591  })
592
593  on('command.run', { command: OUROBOROS_COMMAND.name }, async ($, e) => {
594    try {
595      return { text: await runCommand($, e.args) }
596    } catch (error) {
597      return { text: loudly(error) }
598    }
599  })
600
601  on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
602    if (e.agentId !== undefined || !isStageWorkflow(e.name)) return next(e)
603    return launchPendingStage($, async () => next({ ...e, args: (await readState($)).pending }))
604  })
605
606  on('session.receive', { origin: { kind: 'task-notification' } }, async ($, e, next) => {
607    if (e.agentId !== undefined) return next(e)
608    const note = await onStageNotification($, e.text)
609    return next(note === undefined ? e : { ...e, text: note })
610  })
611
612  on('prompt.submit', async ($, e, next) => {
613    if (e.origin?.kind !== 'task-notification') return next(e)
614    const note = await onStageNotification($, e.text)
615    return next(note === undefined ? e : { ...e, text: note })
616  })
617
618  on('prompt.context', async ($, e, next) => {
619    const state = await readState($)
620    if (state.milestone === undefined) return next(e)
621    return next({ ...e, blocks: [...e.blocks, { name: 'ouroboros', text: contextText(state) }] })
622  })
623}
624
hooks/github/doctor.ts 60 lines
1import { boardIdsOf } from './gh_commands'
2import type { GithubConfig } from './gh_commands'
3
4type ProjectList = Parameters<typeof boardIdsOf>[0]
5type FieldList = Parameters<typeof boardIdsOf>[1]
6
7const REQUIRED_SCOPES = ['repo', 'project']
8
9export const loginOf = (userAnswer: string) => /"login"\s*:\s*"([^"]+)"/.exec(userAnswer)?.[1] ?? 'the gh account'
10
11const grantedScopes = (userAnswer: string) =>
12  (/^x-oauth-scopes:(.*)$/im.exec(userAnswer)?.[1] ?? '').split(',').map(scope => scope.trim()).filter(Boolean)
13
14export const scopeProblems = (userAnswer: string) => {
15  const missing = REQUIRED_SCOPES.filter(scope => !grantedScopes(userAnswer).includes(scope))
16  if (missing.length === 0) return []
17  return [`the gh token of ${loginOf(userAnswer)} lacks the ${missing.join(' and ')} scope: run gh auth refresh -s ${missing.join(',')}`]
18}
19
20export const pushProblems = (login: string, repo: string, pushAnswer: string) =>
21  pushAnswer.trim() === 'true' ? [] : [`${login} cannot push to ${repo}: ask for write access`]
22
23export const deleteHeadBranchesProblems = (repo: string, answer: string) =>
24  answer.trim() === 'true' ? [] : [`the setting "Automatically delete head branches" of ${repo} is off, so a stacked PR can merge into a branch already in the default branch: turn it on under Settings > General > Pull Requests, or run gh api -X PATCH repos/${repo} -F delete_branch_on_merge=true`]
25
26const absentColumns = (fields: FieldList, github: GithubConfig) => {
27  const options = fields.fields.find(field => field.name === github.status_field)?.options ?? []
28  return Object.values(github.columns).filter(name => !options.some(option => option.name === name))
29}
30
31export const boardProblems = (projects: ProjectList, fields: FieldList, github: GithubConfig) => {
32  const ids = boardIdsOf(projects, fields, github)
33  if (!('missing' in ids)) return []
34  if (!ids.missing.startsWith('column ')) return [`missing ${ids.missing}`]
35  return absentColumns(fields, github).map(name => `missing column "${name}" of field "${github.status_field}" on project "${github.project}"`)
36}
37
38const AUTO_CLOSE = 'Auto-close issue'
39
40export const WORKFLOWS_QUERY = 'query($id: ID!) { node(id: $id) { ... on ProjectV2 { workflows(first: 50) { nodes { name enabled } } } } }'
41
42type WorkflowsAnswer = { data?: { node?: { workflows?: { nodes?: Array<{ name: string; enabled: boolean }> } } } }
43
44export const autoCloseProblems = (project: string, workflowsAnswer: string) => {
45  const nodes = (JSON.parse(workflowsAnswer || '{}') as WorkflowsAnswer).data?.node?.workflows?.nodes ?? []
46  if (!nodes.some(workflow => workflow.name === AUTO_CLOSE && workflow.enabled)) return []
47  return [`the "${AUTO_CLOSE}" workflow of project "${project}" closes a sub-issue when the loop moves it to Done, before its PR merges: turn it off under the project's Workflows, so only the PR's Closes #n closes it on merge`]
48}
49
50export const labelProblems = (repo: string, label: string, labelsAnswer: string) =>
51  (JSON.parse(labelsAnswer || '[]') as Array<{ name: string }>).some(each => each.name === label) ? [] : [`missing label "${label}" in ${repo}: gh label create ${label} -R ${repo}`]
52
53export const prdProblems = (path: string, text: string | undefined) => {
54  if (text === undefined) return [`no PRD at ${path}: write one or set prd in .claude/ouroboros.json`]
55  return /^### /m.test(text) ? [] : [`the PRD ${path} has no "### " milestone headings`]
56}
57
58export const doctorAnswer = (problems: string[]) =>
59  problems.length === 0 ? 'ouroboros doctor: ready' : [`ouroboros doctor found ${problems.length} problems:`, ...problems.map(problem => `- ${problem}`)].join('\n')
60
hooks/github/contract.ts 98 lines
1export type CommandItem = { text: string; command: string; done: boolean }
2export type TaskContract = {
3  goal: string
4  plan: string
5  checklist: CommandItem[]
6  depends_on: number[]
7}
8export type MilestoneBody = { goal: string; brief: string; acceptance: CommandItem[] }
9
10const TASK_SECTIONS = ['Goal', 'Plan', 'Checklist', 'Depends on'] as const
11const MILESTONE_SECTIONS = ['Goal', 'Brief', 'Acceptance'] as const
12const SECTION_HEADING = /^## (.+)$/m
13const COMMAND_ITEM = /^- \[( |x)\] (.+): `([^`]+)`$/
14const FILES_LINE = /^Files: .*`[^`]+`/m
15const DEPENDS_ON = /^(none|#\d+(?:, #\d+)*)$/
16
17const sectionsOf = (body: string): Map<string, string> => {
18  const parts = body.split(SECTION_HEADING)
19  const sections = new Map<string, string>()
20  for (let index = 1; index < parts.length; index += 2) sections.set(parts[index] ?? '', (parts[index + 1] ?? '').trim())
21  return sections
22}
23
24const renderSections = (sections: Array<[string, string]>) => sections.map(([name, text]) => `## ${name}\n${text}\n`).join('\n')
25
26const linesOf = (text: string) => text.split('\n').filter(line => line.trim() !== '')
27
28const allOrNothing = <T>(parsed: Array<T | undefined>): T[] | undefined =>
29  parsed.length === 0 || parsed.some(item => item === undefined) ? undefined : (parsed as T[])
30
31const renderCommandItems = (items: CommandItem[]) => items.map(item => `- [${item.done ? 'x' : ' '}] ${item.text}: \`${item.command}\``).join('\n')
32
33const commandItemOf = (line: string): CommandItem | undefined => {
34  const match = COMMAND_ITEM.exec(line)
35  return match === null ? undefined : { text: match[2] ?? '', command: match[3] ?? '', done: match[1] === 'x' }
36}
37
38const parseCommandItems = (text: string) => allOrNothing(linesOf(text).map(commandItemOf))
39
40export const parseDependsOn = (text: string) => {
41  const match = DEPENDS_ON.exec(text.trim())
42  if (match === null) return undefined
43  return match[1] === 'none' ? [] : (match[1] ?? '').split(', ').map(reference => Number(reference.slice(1)))
44}
45
46const renderDependsOn = (dependsOn: number[]) => (dependsOn.length === 0 ? 'none' : dependsOn.map(number => `#${number}`).join(', '))
47
48export const renderTaskBody = (task: TaskContract) =>
49  renderSections([
50    ['Goal', task.goal],
51    ['Plan', task.plan],
52    ['Checklist', renderCommandItems(task.checklist)],
53    ['Depends on', renderDependsOn(task.depends_on)],
54  ])
55
56const SECTION_CHECKS: Record<string, (text: string) => boolean> = {
57  Plan: text => FILES_LINE.test(text),
58  Checklist: text => parseCommandItems(text) !== undefined,
59  'Depends on': text => parseDependsOn(text) !== undefined,
60  Acceptance: text => parseCommandItems(text) !== undefined,
61}
62
63const isSectionValid = (name: string, text: string) => text !== '' && (SECTION_CHECKS[name]?.(text) ?? true)
64
65const gapsOf = (body: string, names: readonly string[]) => {
66  const sections = sectionsOf(body)
67  return names.filter(name => !isSectionValid(name, sections.get(name) ?? ''))
68}
69
70export const contractGaps = (body: string) => gapsOf(body, TASK_SECTIONS)
71
72export const milestoneGaps = (body: string) => gapsOf(body, MILESTONE_SECTIONS)
73
74export const parseTaskBody = (body: string): TaskContract | undefined => {
75  if (contractGaps(body).length > 0) return undefined
76  const sections = sectionsOf(body)
77  const section = (name: string) => sections.get(name) ?? ''
78  return {
79    goal: section('Goal'),
80    plan: section('Plan'),
81    checklist: parseCommandItems(section('Checklist')) ?? [],
82    depends_on: parseDependsOn(section('Depends on')) ?? [],
83  }
84}
85
86export const renderMilestoneBody = (milestone: MilestoneBody) =>
87  renderSections([
88    ['Goal', milestone.goal],
89    ['Brief', milestone.brief],
90    ['Acceptance', renderCommandItems(milestone.acceptance)],
91  ])
92
93export const parseMilestoneBody = (body: string): MilestoneBody | undefined => {
94  if (milestoneGaps(body).length > 0) return undefined
95  const sections = sectionsOf(body)
96  return { goal: sections.get('Goal') ?? '', brief: sections.get('Brief') ?? '', acceptance: parseCommandItems(sections.get('Acceptance') ?? '') ?? [] }
97}
98
hooks/github/gh_commands.ts 140 lines
1import type { PlannedTask } from './kickoff_plan'
2
3export type Column = 'milestones' | 'planned' | 'in_progress' | 'qa' | 'done'
4export type GithubSettings = {
5  repo?: string
6  project?: string
7  status_field?: string
8  columns?: Partial<Record<Column, string>>
9  labels?: { needs_owner?: string }
10}
11export type GithubConfig = Omit<GithubSettings, 'status_field' | 'columns' | 'labels'> & {
12  status_field: string
13  columns: Record<Column, string>
14  labels: { needs_owner: string }
15}
16export type BoardIds = { project_id: string; project_number: number; status_field_id: string; columns: Record<Column, string> }
17export type GhCommand = { argv: string[]; stdin?: string }
18
19type ProjectList = { projects: Array<{ number: number; id: string; title: string }> }
20type FieldList = { fields: Array<{ id: string; name: string; options?: Array<{ id: string; name: string }> }> }
21
22export const KICKOFF_DROPPED_COMMENT = 'Closed as not planned: kickoff dropped this task from the milestone plan.'
23
24const DEFAULT_COLUMNS: Record<Column, string> = { milestones: 'Milestones', planned: 'Planned', in_progress: 'In Progress', qa: 'QA', done: 'Done' }
25
26export const githubConfigOf = (settings: GithubSettings | undefined): GithubConfig => ({
27  ...settings,
28  status_field: settings?.status_field ?? 'Status',
29  columns: { ...DEFAULT_COLUMNS, ...settings?.columns },
30  labels: { needs_owner: settings?.labels?.needs_owner ?? 'needs-owner' },
31})
32
33export const createSubIssueCommand = (repo: string, title: string, body: string): GhCommand => ({
34  argv: ['gh', 'issue', 'create', '-R', repo, '--title', title, '--body-file', '-'],
35  stdin: body,
36})
37
38export const linkSubIssueCommand = (repo: string, parent: number, subIssueId: number): GhCommand => ({
39  argv: ['gh', 'api', '-X', 'POST', `repos/${repo}/issues/${parent}/sub_issues`, '-F', `sub_issue_id=${subIssueId}`],
40})
41
42export const editIssueCommand = (repo: string, number: number, title: string, body: string): GhCommand => ({
43  argv: ['gh', 'issue', 'edit', String(number), '-R', repo, '--title', title, '--body-file', '-'],
44  stdin: body,
45})
46
47export const dropCommand = (repo: string, number: number): GhCommand => ({
48  argv: ['gh', 'issue', 'close', String(number), '-R', repo, '--reason', 'not planned', '--comment', KICKOFF_DROPPED_COMMENT],
49})
50
51export const commentCommand = (repo: string, number: number, text: string): GhCommand => ({
52  argv: ['gh', 'issue', 'comment', String(number), '-R', repo, '--body-file', '-'],
53  stdin: text,
54})
55
56export const addLabelCommand = (repo: string, number: number, label: string): GhCommand => ({
57  argv: ['gh', 'issue', 'edit', String(number), '-R', repo, '--add-label', label],
58})
59
60export type PullRequest = { base: string; head: string; title: string; number: number }
61
62export const pullRequestCommand = (repo: string, pr: PullRequest): GhCommand => ({
63  argv: ['gh', 'pr', 'create', '-R', repo, '--base', pr.base, '--head', pr.head, '--title', pr.title, '--body-file', '-'],
64  stdin: `Closes #${pr.number}\n`,
65})
66
67export const addToBoardCommand = (owner: string, ids: BoardIds, issueUrl: string): GhCommand => ({
68  argv: ['gh', 'project', 'item-add', String(ids.project_number), '--owner', owner, '--url', issueUrl, '--format', 'json', '--jq', '.id'],
69})
70
71export const setColumnCommand = (ids: BoardIds, itemId: string, column: Column): GhCommand => ({
72  argv: ['gh', 'project', 'item-edit', '--id', itemId, '--project-id', ids.project_id, '--field-id', ids.status_field_id, '--single-select-option-id', ids.columns[column]],
73})
74
75const newTaskDependencies = (task: PlannedTask, created: number[]) =>
76  task.depends_on.flatMap(dependency => ('task' in dependency && created.includes(dependency.task) ? [dependency.task] : []))
77
78export const creationOrder = (tasks: PlannedTask[], created: number[]) => {
79  const ordered: number[] = []
80  while (ordered.length < created.length) {
81    const ready = created.find(position => !ordered.includes(position) && newTaskDependencies(tasks[position - 1] as PlannedTask, created).every(dependency => ordered.includes(dependency)))
82    if (ready === undefined) return ordered
83    ordered.push(ready)
84  }
85  return ordered
86}
87
88const columnIds = (options: Array<{ id: string; name: string }>, github: GithubConfig) =>
89  Object.entries(github.columns).map(([column, name]) => ({ column, name, id: options.find(option => option.name === name)?.id }))
90
91export const boardIdsOf = (projects: ProjectList, fields: FieldList, github: GithubConfig): BoardIds | { missing: string } => {
92  if (github.project === undefined) return { missing: 'github.project in .claude/ouroboros.json' }
93  const project = projects.projects.find(candidate => candidate.title === github.project)
94  if (project === undefined) return { missing: `project "${github.project}"` }
95  const status = fields.fields.find(field => field.name === github.status_field)
96  if (status === undefined) return { missing: `field "${github.status_field}" on project "${github.project}"` }
97  const columns = columnIds(status.options ?? [], github)
98  const absent = columns.find(column => column.id === undefined)
99  if (absent !== undefined) return { missing: `column "${absent.name}" of field "${github.status_field}"` }
100  return {
101    project_id: project.id,
102    project_number: project.number,
103    status_field_id: status.id,
104    columns: Object.fromEntries(columns.map(column => [column.column, column.id])) as Record<Column, string>,
105  }
106}
107
108export const issueOfPosition = (tasks: PlannedTask[], created: Map<number, number>) => (position: number) => tasks[position - 1]?.issue ?? created.get(position) ?? 0
109
110const SHELL_SAFE = /^[\w@%+=:,./-]+$/
111
112export const shellCommand = (argv: readonly string[]) => argv.map(arg => (SHELL_SAFE.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`)).join(' ')
113
114export const removeLabelCommand = (repo: string, number: number, label: string): GhCommand => ({
115  argv: ['gh', 'issue', 'edit', String(number), '-R', repo, '--remove-label', label],
116})
117
118export const deleteCommentCommand = (repo: string, commentUrl: string): GhCommand | undefined => {
119  const id = /#issuecomment-(\d+)$/.exec(commentUrl)?.[1]
120  return id === undefined ? undefined : { argv: ['gh', 'api', '-X', 'DELETE', `repos/${repo}/issues/comments/${id}`] }
121}
122
123export const closePullRequestCommand = (repo: string, pullRequestUrl: string): GhCommand => ({
124  argv: ['gh', 'pr', 'close', pullRequestUrl, '-R', repo, '--delete-branch=false'],
125})
126
127export const developCommand = (repo: string, number: number, branch: string, base: string): GhCommand => ({
128  argv: ['gh', 'issue', 'develop', String(number), '-R', repo, '--name', branch, '--base', base],
129})
130
131export const linkedBranchesCommand = (repo: string, number: number): GhCommand => ({
132  argv: ['gh', 'issue', 'develop', String(number), '-R', repo, '--list'],
133})
134
135export const linkedBranchOf = (listed: string) => listed.split('\n')[0]?.split('\t')[0] || undefined
136
137export const deleteBranchCommand = (repo: string, branch: string): GhCommand => ({
138  argv: ['gh', 'api', '-X', 'DELETE', `repos/${repo}/git/refs/heads/${branch}`],
139})
140
hooks/github/kickoff_issue.ts 50 lines
1import type { CommandItem, MilestoneBody } from './contract'
2import type { PlannedTask } from './kickoff_plan'
3
4export type AppliedKickoff = { created: number[]; updated: number[]; dropped: number[]; unchanged: number[]; closed: number[] }
5type ProjectItem = { title: string; status?: { name: string } }
6type CommandSpec = { text: string; command: string }
7type ArchitectTask = Omit<PlannedTask, 'checklist'> & { checklist: CommandSpec[] }
8type ArchitectJson = { milestone?: { goal: string; brief: string; acceptance: CommandSpec[] }; tasks?: ArchitectTask[] }
9
10const ISSUE_ARGUMENT = /^(?:#|.*\/issues\/)?(\d+)$/
11const HEADING = /^(#{1,6})\s+(.+?)\s*$/
12
13export const kickoffIssueNumber = (argument: string) => {
14  const match = ISSUE_ARGUMENT.exec(argument.trim())
15  return match === null ? undefined : Number(match[1])
16}
17
18const headingOf = (line: string) => {
19  const match = HEADING.exec(line)
20  return match === null ? undefined : { level: (match[1] ?? '').length, text: match[2] ?? '' }
21}
22
23export const prdSection = (prd: string, title: string): { section: string } | { headings: string[] } => {
24  const lines = prd.split('\n')
25  const start = lines.findIndex(line => headingOf(line)?.text === title)
26  if (start === -1) return { headings: lines.flatMap(line => headingOf(line)?.text ?? []) }
27  const level = headingOf(lines[start] ?? '')?.level ?? 1
28  const rest = lines.slice(start + 1)
29  const end = rest.findIndex(line => (headingOf(line)?.level ?? Infinity) <= level)
30  return { section: (end === -1 ? rest : rest.slice(0, end)).join('\n').trim() }
31}
32
33export const milestoneColumn = (projectItems: ProjectItem[], project: string) => projectItems.find(item => item.title === project)?.status?.name
34
35const unticked = (items: CommandSpec[]): CommandItem[] => items.map(({ text, command }) => ({ text, command, done: false }))
36
37export const architectResult = (json: unknown): { milestone: MilestoneBody; tasks: PlannedTask[] } | { error: string } => {
38  const result = json as ArchitectJson | undefined
39  if (result?.milestone === undefined || !Array.isArray(result.tasks)) return { error: 'the architect returned no milestone body and task list' }
40  return {
41    milestone: { goal: result.milestone.goal, brief: result.milestone.brief, acceptance: unticked(result.milestone.acceptance) },
42    tasks: result.tasks.map(task => ({ ...task, checklist: unticked(task.checklist) })),
43  }
44}
45
46const numbersText = (numbers: number[]) => (numbers.length === 0 ? 'none' : numbers.map(number => `#${number}`).join(', '))
47
48export const kickoffAnswer = (milestone: number, applied: AppliedKickoff) =>
49  `kickoff #${milestone}: created ${numbersText(applied.created)}; updated ${numbersText(applied.updated)}; dropped ${numbersText(applied.dropped)}; unchanged ${numbersText(applied.unchanged)}; left closed ${numbersText(applied.closed)}`
50
hooks/github/kickoff_plan.ts 130 lines
1import { contractGaps, renderTaskBody } from './contract'
2import type { TaskContract } from './contract'
3
4export type Dependency = { issue: number } | { task: number }
5export type PlannedTask = Omit<TaskContract, 'depends_on'> & { title: string; issue?: number; depends_on: Dependency[] }
6export type SubIssue = { number: number; state: 'open' | 'closed'; title: string; body: string }
7export type KickoffChanges = { create: number[]; update: number[]; drop: number[]; unchanged: number[]; closed: number[] }
8
9const MAX_SUB_ISSUES = 100
10const UNRESOLVED = 0
11
12const positionOf = (index: number) => index + 1
13
14export const plannedBody = (task: PlannedTask, issueOfTask: (position: number) => number) =>
15  renderTaskBody({ ...task, depends_on: task.depends_on.map(dependency => ('issue' in dependency ? dependency.issue : issueOfTask(dependency.task))) })
16
17const sizeProblem = (tasks: PlannedTask[]) =>
18  tasks.length > MAX_SUB_ISSUES ? `${tasks.length} tasks: a milestone holds at most ${MAX_SUB_ISSUES} sub-issues; split the milestone` : undefined
19
20const revisionProblem = (task: PlannedTask, position: number, existing: SubIssue[]) => {
21  if (task.issue === undefined) return undefined
22  const revised = existing.find(subIssue => subIssue.number === task.issue)
23  if (revised === undefined) return `task ${position} revises #${task.issue}, which is not a sub-issue of this milestone`
24  if (revised.state === 'closed') return `task ${position} revises #${task.issue}, which is closed`
25  return undefined
26}
27
28const duplicateProblem = (tasks: PlannedTask[]) => {
29  for (const [index, task] of tasks.entries()) {
30    const earlier = tasks.findIndex(other => other.issue !== undefined && other.issue === task.issue)
31    if (earlier < index && earlier !== -1) return `tasks ${positionOf(earlier)} and ${positionOf(index)} both revise #${task.issue}`
32  }
33  return undefined
34}
35
36const gapProblem = (task: PlannedTask, position: number) => {
37  const gaps = contractGaps(plannedBody(task, () => UNRESOLVED))
38  return gaps.length === 0 ? undefined : `task ${position} "${task.title}" misses ${gaps.join(', ')}`
39}
40
41const taskDependencyProblem = (position: number, target: number, tasks: PlannedTask[]) => {
42  if (target === position) return `task ${position} depends on itself`
43  if (tasks[target - 1] === undefined) return `task ${position} depends on task ${target}, which the list does not hold`
44  return undefined
45}
46
47const issueDependencyProblem = (position: number, target: number, tasks: PlannedTask[], existing: SubIssue[]) => {
48  const subIssue = existing.find(candidate => candidate.number === target)
49  if (subIssue === undefined) return `task ${position} depends on #${target}, which is not a sub-issue of this milestone`
50  if (subIssue.state === 'open' && !tasks.some(candidate => candidate.issue === target)) return `task ${position} depends on #${target}, which kickoff drops`
51  return undefined
52}
53
54const dependencyProblem = (task: PlannedTask, position: number, tasks: PlannedTask[], existing: SubIssue[]) => {
55  for (const dependency of task.depends_on) {
56    const problem = 'issue' in dependency ? issueDependencyProblem(position, dependency.issue, tasks, existing) : taskDependencyProblem(position, dependency.task, tasks)
57    if (problem !== undefined) return problem
58  }
59  return undefined
60}
61
62const dependencyPositions = (task: PlannedTask, tasks: PlannedTask[]) =>
63  task.depends_on.flatMap(dependency => {
64    if ('task' in dependency) return [dependency.task]
65    const revising = tasks.findIndex(candidate => candidate.issue === dependency.issue)
66    return revising === -1 ? [] : [positionOf(revising)]
67  })
68
69const cycleFrom = (start: number, tasks: PlannedTask[], path: number[] = []): number[] | undefined => {
70  if (path.includes(start)) return path.slice(path.indexOf(start))
71  for (const next of dependencyPositions(tasks[start - 1] as PlannedTask, tasks)) {
72    const cycle = cycleFrom(next, tasks, [...path, start])
73    if (cycle !== undefined) return cycle
74  }
75  return undefined
76}
77
78const positionsText = (positions: number[]) => {
79  const sorted = [...positions].sort((left, right) => left - right)
80  return `${sorted.slice(0, -1).join(', ')} and ${sorted[sorted.length - 1]}`
81}
82
83const cycleProblem = (tasks: PlannedTask[]) => {
84  for (const index of tasks.keys()) {
85    const cycle = cycleFrom(positionOf(index), tasks)
86    if (cycle !== undefined) return `tasks ${positionsText(cycle)} depend on each other in a cycle`
87  }
88  return undefined
89}
90
91const taskProblem = (task: PlannedTask, position: number, tasks: PlannedTask[], existing: SubIssue[]) =>
92  revisionProblem(task, position, existing) ?? gapProblem(task, position) ?? dependencyProblem(task, position, tasks, existing)
93
94const listProblem = (tasks: PlannedTask[], existing: SubIssue[]) => {
95  const problem = sizeProblem(tasks) ?? duplicateProblem(tasks)
96  if (problem !== undefined) return problem
97  for (const [index, task] of tasks.entries()) {
98    const found = taskProblem(task, positionOf(index), tasks, existing)
99    if (found !== undefined) return found
100  }
101  return cycleProblem(tasks)
102}
103
104const dependsOnNewTask = (task: PlannedTask) => task.depends_on.some(dependency => 'task' in dependency)
105
106const isUnchanged = (task: PlannedTask, subIssue: SubIssue) =>
107  !dependsOnNewTask(task) && task.title === subIssue.title && plannedBody(task, () => UNRESOLVED) === subIssue.body
108
109const numbersOf = (subIssues: SubIssue[]) => subIssues.map(subIssue => subIssue.number)
110
111const revisedOpen = (tasks: PlannedTask[], existing: SubIssue[]) =>
112  existing.filter(subIssue => subIssue.state === 'open' && tasks.some(task => task.issue === subIssue.number))
113
114const changesOf = (tasks: PlannedTask[], existing: SubIssue[]): KickoffChanges => {
115  const revised = revisedOpen(tasks, existing)
116  const unchanged = revised.filter(subIssue => isUnchanged(tasks.find(task => task.issue === subIssue.number) as PlannedTask, subIssue))
117  return {
118    create: tasks.flatMap((task, index) => (task.issue === undefined ? [positionOf(index)] : [])),
119    update: numbersOf(revised.filter(subIssue => !unchanged.includes(subIssue))),
120    drop: numbersOf(existing.filter(subIssue => subIssue.state === 'open' && !revised.includes(subIssue))),
121    unchanged: numbersOf(unchanged),
122    closed: numbersOf(existing.filter(subIssue => subIssue.state === 'closed')),
123  }
124}
125
126export const kickoffChanges = (existing: SubIssue[], tasks: PlannedTask[]): KickoffChanges | { rejected: string } => {
127  const problem = listProblem(tasks, existing)
128  return problem === undefined ? changesOf(tasks, existing) : { rejected: problem }
129}
130
hooks/loop.ts 91 lines
1import { contractGaps, parseDependsOn, parseTaskBody, renderTaskBody } from './github/contract'
2import type { CommandItem } from './github/contract'
3import type { Column } from './github/gh_commands'
4
5export type BoardSubIssue = { number: number; state: 'open' | 'closed'; title: string; body: string; column?: string; labels: string[] }
6export type ItemVerdict = { index: number; pass: boolean; evidence: string }
7export type Review = { items: ItemVerdict[]; defects: string[] }
8
9export const ESCALATION_HEADING = '## Ouroboros needs the owner'
10export const MAX_REVIEW_ROUNDS = 3
11
12const DEPENDS_ON_SECTION = /^## Depends on\n([\s\S]*?)(?=\n## |$)/m
13const NOT_REPORTED = 'not reported by the review'
14
15const dependenciesOf = (body: string) => parseDependsOn(DEPENDS_ON_SECTION.exec(body)?.[1] ?? 'none') ?? []
16
17const isFinished = (subIssue: BoardSubIssue, columns: Record<Column, string>) => subIssue.state === 'closed' || subIssue.column === columns.done
18
19const blockersOf = (subIssue: BoardSubIssue, all: BoardSubIssue[], columns: Record<Column, string>) =>
20  dependenciesOf(subIssue.body).filter(number => {
21    const dependency = all.find(candidate => candidate.number === number)
22    return dependency === undefined || !isFinished(dependency, columns)
23  })
24
25const waitingLine = (subIssue: BoardSubIssue, all: BoardSubIssue[], columns: Record<Column, string>) =>
26  `#${subIssue.number} waits on ${blockersOf(subIssue, all, columns).map(number => `#${number}`).join(', ')}`
27
28const openIn = (subIssues: BoardSubIssue[], ...columnNames: string[]) =>
29  subIssues.filter(subIssue => subIssue.state === 'open' && columnNames.includes(subIssue.column ?? '')).sort((left, right) => left.number - right.number)
30
31export const nextSubIssue = (subIssues: BoardSubIssue[], columns: Record<Column, string>): { issue: BoardSubIssue } | { none: string } | { finished: true } => {
32  const started = openIn(subIssues, columns.in_progress, columns.qa)[0]
33  if (started !== undefined) return { issue: started }
34  const planned = openIn(subIssues, columns.planned)
35  const ready = planned.find(subIssue => blockersOf(subIssue, subIssues, columns).length === 0)
36  if (ready !== undefined) return { issue: ready }
37  if (subIssues.every(subIssue => isFinished(subIssue, columns))) return { finished: true }
38  if (planned.length === 0) return { none: 'no sub-issue is in Planned' }
39  return { none: `no sub-issue is ready: ${planned.map(subIssue => waitingLine(subIssue, subIssues, columns)).join('; ')}` }
40}
41
42export const readinessComment = (body: string) => {
43  const gaps = contractGaps(body)
44  if (gaps.length === 0) return undefined
45  return `${ESCALATION_HEADING}\nThis sub-issue cannot start: ${gaps.join(', ')} are missing or incomplete. Every section must be present, the plan must end in a \`Files:\` line, and every checklist item must name a command. Fix the body, remove the \`needs-owner\` label and run \`/ouroboros start\` again.`
46}
47
48export const escalationComment = (question: string) => `${ESCALATION_HEADING}\n${question}\n\nAnswer here, remove the \`needs-owner\` label and run \`/ouroboros start\` again.`
49
50const slugOf = (title: string) =>
51  title
52    .toLowerCase()
53    .replace(/[^a-z0-9]+/g, '-')
54    .replace(/^-+|-+$/g, '')
55    .slice(0, 50)
56    .replace(/-+$/, '')
57
58export const branchName = (prefix: string, number: number, title: string) => `${prefix}${number}-${slugOf(title)}`
59
60const verdictOf = (review: Review, index: number): ItemVerdict => review.items.find(item => item.index === index) ?? { index, pass: false, evidence: NOT_REPORTED }
61
62const failureLine = (item: CommandItem, verdict: ItemVerdict) => `- ${item.text}: \`${item.command}\`\n  ${verdict.evidence}`
63
64const reviewComment = (failures: string[], defects: string[]) =>
65  [
66    '## Review found defects',
67    ...(failures.length === 0 ? [] : ['Failed checks:', ...failures, '']),
68    ...(defects.length === 0 ? [] : ['Defects:', ...defects.map(defect => `- ${defect}`), '']),
69    'Back to In Progress.',
70  ].join('\n')
71
72export const reviewOutcome = (body: string, review: Review) => {
73  const task = parseTaskBody(body)
74  if (task === undefined) return { accepted: false, body, comment: reviewComment([], ['the sub-issue body no longer parses', ...review.defects]) }
75  const verdicts = task.checklist.map((_, position) => verdictOf(review, position + 1))
76  const checklist = task.checklist.map((item, position) => ({ ...item, done: verdicts[position]?.pass === true }))
77  const failures = checklist.flatMap((item, position) => (item.done ? [] : [failureLine(item, verdicts[position] as ItemVerdict)]))
78  const accepted = failures.length === 0 && review.defects.length === 0
79  return { accepted, body: renderTaskBody({ ...task, checklist }), comment: accepted ? '' : reviewComment(failures, review.defects) }
80}
81
82export type StageDetail = { branch: string; base: string; round: number; pullRequest?: string }
83
84const pullRequestNumber = (url = '') => url.split('/').pop()
85
86export const stageComment = (column: 'in_progress' | 'qa' | 'done', { branch, base, round, pullRequest }: StageDetail) => {
87  if (column === 'in_progress') return `Ouroboros: In Progress on \`${branch}\` (from ${base}), implementing, round ${round}`
88  if (column === 'qa') return `Ouroboros: QA, reviewing round ${round}`
89  return `Ouroboros: Done, PR #${pullRequestNumber(pullRequest)} opened from \`${branch}\` into ${base}; the merge closes this issue`
90}
91
hooks/prompts.ts 30 lines
1import type { SubIssue } from './github/kickoff_plan'
2
3export type KickoffBrief = { issue: number; title: string; prd_section: string; milestone_body: string; sub_issues: SubIssue[] }
4export type StageBrief = { issue: number; title: string; body: string; branch: string; base: string; round: number; defects: string[] }
5
6const KICKOFF_ANSWER = 'Answer with the milestone body (goal, brief, acceptance) and the full task list. Give a task an `issue` only when it revises that open sub-issue.'
7
8const IMPLEMENT_ANSWER = 'Answer `status: "done"` with a summary once every checklist command passes and your work is committed, or `status: "blocked"` with one question for the owner.'
9
10const REVIEW_ANSWER = 'Answer one entry in `items` per checklist item, `index` counting from 1 in the order listed, and the `defects` you found.'
11
12const subIssueText = (subIssue: SubIssue) => `### #${subIssue.number} (${subIssue.state}) ${subIssue.title}\n${subIssue.body}`
13
14export const kickoffPrompt = (brief: KickoffBrief) =>
15  `Plan milestone #${brief.issue} "${brief.title}".\n\n` +
16  `PRD section:\n${brief.prd_section}\n\n` +
17  `Current milestone body:\n${brief.milestone_body || '(empty)'}\n\n` +
18  `Sub-issues (${brief.sub_issues.length}):\n${brief.sub_issues.map(subIssueText).join('\n\n') || '(none)'}\n\n` +
19  KICKOFF_ANSWER
20
21const where = (brief: StageBrief) => `Branch: ${brief.branch} (based on ${brief.base}), checked out in this session's checkout`
22
23const defectsText = (brief: StageBrief) =>
24  brief.defects.length === 0 ? '' : `\n\nReview round ${brief.round} rejected the work. Fix all of this:\n${brief.defects.join('\n')}`
25
26export const implementPrompt = (brief: StageBrief) =>
27  `Implement sub-issue #${brief.issue} "${brief.title}".\n${where(brief)}\n\nSub-issue:\n${brief.body}${defectsText(brief)}\n\n${IMPLEMENT_ANSWER}`
28
29export const reviewPrompt = (brief: StageBrief) => `Review sub-issue #${brief.issue} "${brief.title}".\n${where(brief)}\n\nSub-issue:\n${brief.body}\n\n${REVIEW_ANSWER}`
30