SLOPSHOPPER

pipeline-gates

The pipeline skill's gates as code: no dev agent and no worktree edit before the Teams status and the grill confirmation, no PR before a QC pass that rests on…

panebandguardcommandprompttool
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pipeline-gates
│ ┃ pipeline ✕ › fix the failing auth test and add an audit log call │ ┃ No pipeline run in this session. │ ┃ /pipeline-gate start [TASK] starts one by ⏺ Read(src/auth.ts) │ ┃ hand. ⎿ 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 │ │ › /pipeline-gate │ ⎿ pipeline-gates: no pipeline run in this session. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · pipeline
No pipeline run in this session. /pipeline-gate start [TASK] starts one by hand.
README

nixodoo-copier-template

A Copier template that generates a complete Odoo development environment on Nix flakes: native processes, systemd user services, a project-local PostgreSQL cluster, and a Python environment locked with uv.

No container, no global install, no pip in sight. The same generated project also runs as a test or production server.

Quickstart

uvx copier copy --trust gh:okolovmark/nixodoo-copier-template my-odoo-project
cd my-odoo-project

nix run .#create-env          # .env: ports, database credentials
nix run .#update-repos        # clone Odoo and the addon repos, build the symlink farm
nix run .#bootstrap-deps      # import Odoo's requirements.txt into uv.lock
nix profile add .#dev-server  # odoo, psql, ruff and friends into your profile
nix run .#setup-dev           # postgres cluster (+ odoo.conf, nginx and systemd units without worktree envs)
systemctl --user enable --now postgres.service

With Claude Code and a custom addons repo, every pipeline run then gets its own worktree env (wt-start.sh <slug>): its own Odoo on its own port and its own restore of the prod dump; there is no main Odoo, nginx or database. Without them, setup-dev builds the classic single env (odoo.service, nginx.service, odoo-logrotate.timer) on the ports derived from your version. The generated README.md walks through the test and production flows the same way.

You need Nix with flakes enabled, uv (uvx runs copier without installing it), and a systemd user session. Starting from nothing:

curl -LsSf https://astral.sh/uv/install.sh | sh
sh <(curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install) --daemon
echo 'experimental-features = nix-command flakes' >> ~/.config/nix/nix.conf
sudo systemctl restart nix-daemon

What it generates

  • Odoo 16.0 to 20.0 on Python 3.10 to 3.14 and PostgreSQL 13 to 18, chosen at generation time and verified end to end for every version.
  • Three toolchains as flake packages: dev-server, test-server, prod-server, the first two wrapping odoo and the Postgres client tools against this project's cluster; prod-server carries Odoo alone - no proxy, no database client.
  • Pinned sources: repos.yaml for Odoo, addons.yaml for OCA and custom addon repos, pinned by branch or commit, with a symlink farm builder.
  • Generated configuration: .env, odoo.conf with a random master password, systemd user units, a log-rotation timer, and an nginx reverse proxy for test (and dev without worktree envs) - production is left to whatever already fronts it.
  • Python dependencies straight from Odoo's own requirements.txt, locked with uv and built with uv2nix, so the flake and your shell agree.
  • Claude Code integration, optional: CLAUDE.md, guard hooks, Odoo skills including semantic code navigation over the official language server, a requirements interview, a development pipeline, deploy and production-operations runbooks, and a persistent memory.
  • Optional extras, each behind a question: a custom addons repo, S3 backup restore with native neutralization, SSH helpers for the prod and test boxes, OCA queue_job.

The full inventory, including every skill and agent, is in docs/features.md.

The choices that matter

Copier asks about twenty questions; most have a sensible default derived from your Odoo version. These are the ones worth a thought:

QuestionDefaultWhy you might change it
odoo_version20.0everything else follows from it
custom_repo_pattern / custom_repo_nameemptyyour own addons repo; unlocks the development pipeline
use_claude_codetruethe whole .claude/ layer
use_kbfalsememory in kb instead of markdown files
use_antigravityfalsework in Google Antigravity: next to Claude Code, or instead of it
service_suffixemptyset it to run two generated projects on one machine
project_dir_varODOO<major>_PROJECT_DIRsame reason, for the project-root variable
status_mcp / tickets_mcpnonewire status posting and ticket tracking to Teams and Odoo
backup_s3_bucketemptyrestore production dumps locally
prod_ssh_host / test_ssh_hostsemptythe deploy and prod-ops runbooks

Every question and its default: docs/questions.md.

Keeping a project current

uvx copier update --trust

Template improvements land in the generated project. A few files are yours and are never overwritten (odools.toml, the estimate calibration table); for the rest, resolve conflicts in favour of the project where you have edited it. Hook arrays in .claude/settings.json deserve a second look after an update: copier can add a second key with the same name, and JSON keeps only the last one.

More

  • docs/features.md — everything a generated project contains
  • docs/questions.md — every question copier asks
  • docs/notes.md — gotchas worth knowing before they bite
  • nix flake check shellchecks every generated script; python3 tests/test_nudge_find_code.py runs the hook regression corpus; claude plugin test in a mod's folder runs that mod's tests (CI runs every mod a render ships)

License

MIT

Source 3 files
hooks/register.tsx 724 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { BlockTask, Gate, GateName, Run, TaskState } from '../types'
5import {
6  ASK_CONFIRM,
7  ASK_HEADER,
8  ASK_MECHANICAL,
9  ASK_NOT_YET,
10  GATE_LABELS,
11  PHASES,
12  RESUME_REFUSAL,
13  addTasks,
14  addressOf,
15  askedNote,
16  blockLine,
17  bump,
18  closedForDev,
19  devRefusal,
20  enterPhase,
21  filePathOf,
22  grantRounds,
23  closesOn,
24  grillQuestion,
25  hasTask,
26  isActive,
27  isAwayGrillAnswer,
28  isChildArgs,
29  isDocPath,
30  isMotherRunFor,
31  isNewRound,
32  isOpen,
33  isPrCreate,
34  isWorktreeCode,
35  mayAskGrill,
36  moveTasks,
37  newRun,
38  openGate,
39  prRefusal,
40  prUrlIn,
41  qcEvidence,
42  qcHolds,
43  recordVerdict,
44  roundsLeft,
45  roundsLine,
46  roundsRefusal,
47  runKeys,
48  runName,
49  startRound,
50  takeGates,
51  taskCounts,
52  taskKeyIn,
53  taskKeysIn,
54  tasksOf,
55  testSummary,
56  withBlock,
57  withoutStrayTasks,
58} from './gates'
59import { HAS_STATUS_GATE, ODOO_WEB_URL, TASK_URL_BASE, TICKET_PREFIXES } from './config'
60
61const PANE = 'pipeline'
62const RUNS_KEPT = 20
63const GATES: readonly GateName[] = ['status', 'grill', 'qc']
64// the person's own input: the prompt box, the desktop bridge, an SDK host; never a plugin or another agent
65const PERSON_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
66const USAGE = 'usage: /pipeline-gate [status] | open <status|grill|qc|rounds> <reason> | start [TASK-KEY ...] | end'
67const TASK_STATES: readonly TaskState[] = ['pending', 'active', 'done']
68// a task key as the model is shown one, in this project's first ticket prefix
69const SAMPLE_KEY = `${TICKET_PREFIXES[0] ?? 'PROJ'}-1234`
70
71const run = atom({ plugin: 'pipeline-gates', key: 'run' } as const, null)
72
73// subagent id -> its type (dev, review, documenter, ...), from $.agent.list()
74const agentTypes = new Map<string, string>()
75
76async function agentType($: EngineInterface, agentId: string): Promise<string> {
77  if (!agentTypes.has(agentId)) {
78    for (const agent of await $.agent.list()) agentTypes.set(agent.id, agent.type)
79  }
80  return agentTypes.get(agentId) ?? ''
81}
82
83// the type of the agent SendMessage addresses, by its id or its name
84async function addresseeType($: EngineInterface, to: unknown): Promise<string> {
85  const address = addressOf(to)
86  if (address === '') return ''
87  const agent = (await $.agent.list()).find(each => each.id === address || each.name === address)
88  return agent?.type ?? ''
89}
90
91async function save($: EngineInterface, next: Run | null): Promise<void> {
92  await update($, run, () => next)
93  await $.store.set(`run:${await $.session.id()}`, next)
94}
95
96async function change($: EngineInterface, apply: (current: Run) => Run): Promise<void> {
97  const current = await read($, run)
98  if (isActive(current)) await save($, apply(current))
99}
100
101// A run for another task is a new run with its gates closed again: an earlier run left open (stopped
102// halfway, never ended) must not lend its open gates to the next one. A block is one run: a task of the
103// block keeps it, and `block` (the keys a pipeline started with) joins it.
104async function start($: EngineInterface, task: string, block: readonly string[] = []): Promise<void> {
105  const current = await read($, run)
106  const now = await $.clock.now()
107  if (isActive(current) && (task === '' || current.task === '' || task === current.task || hasTask(current, task))) {
108    const named = task !== '' && current.task === '' ? { ...current, task } : current
109    const joined = addTasks(named, block, now, ODOO_WEB_URL)
110    if (joined !== current) await save($, joined)
111    return
112  }
113  await save($, addTasks(newRun(task, now, HAS_STATUS_GATE), block, now, ODOO_WEB_URL))
114  void $.ui.open({ id: PANE, title: 'pipeline' })
115}
116
117// The runs of the other sessions, newest first: the store holds every session's run under run:<id>.
118async function otherRuns($: EngineInterface): Promise<{ id: string; run: Run }[]> {
119  const mine = `run:${await $.session.id()}`
120  const found: { id: string; run: Run }[] = []
121  for (const key of await $.store.keys()) {
122    if (!key.startsWith('run:') || key === mine) continue
123    const other = (await $.store.get(key)) as Run | null | undefined
124    if (other !== null && other !== undefined) found.push({ id: key.slice('run:'.length), run: other })
125  }
126  return found.sort((a, b) => b.run.startedAt - a.run.startedAt)
127}
128
129// A child session takes the gates the person opened in its mother: the newest run of another session
130// that works on `task` with the Teams status and the grill both opened there.
131async function adoptMother($: EngineInterface, task: string): Promise<boolean> {
132  const current = await read($, run)
133  if (!isActive(current) || task === '' || closedForDev(current).length === 0) return false
134  const mother = (await otherRuns($)).find(other => isMotherRunFor(other.run, task))
135  if (mother === undefined) return false
136  await save($, takeGates(current, mother.run, mother.id, await $.clock.now()))
137  return true
138}
139
140// The pipeline skill loaded with `args`, typed as /pipeline or called through the Skill tool: its task
141// keys start or join the run, and a child takes its mother's gates.
142async function startPipeline($: EngineInterface, args: string): Promise<void> {
143  const keys = taskKeysIn(args)
144  await start($, keys[0] ?? '', keys)
145  if (isChildArgs(args)) {
146    for (const key of keys) if (await adoptMother($, key)) break
147  }
148}
149
150// What a run with no QC pass of its own closes on at Phase 7: another session's run for its tasks that
151// recorded a QC pass or a PR, named for the person; '' when there is none.
152async function closureFor($: EngineInterface, current: Run): Promise<string> {
153  const keys = runKeys(current)
154  for (const other of await otherRuns($)) {
155    const what = closesOn(other.run, keys)
156    if (what !== '') return `${what} of ${runName(other.run, other.id)}`
157  }
158  return ''
159}
160
161async function restore($: EngineInterface): Promise<void> {
162  const saved = await $.store.get(`run:${await $.session.id()}`)
163  if (saved !== undefined && saved !== null) await update($, run, () => withoutStrayTasks(saved as Run))
164  const keys = (await $.store.keys()).filter(key => key.startsWith('run:'))
165  for (const key of keys.slice(0, Math.max(0, keys.length - RUNS_KEPT))) await $.store.delete(key)
166}
167
168// the whole output of a Bash call: inline, or the file a large one was persisted to
169async function bashOutput($: EngineInterface, result: unknown, text: string | undefined): Promise<string> {
170  const record = (result ?? {}) as { stdout?: string; stderr?: string; persistedOutputPath?: string }
171  if (typeof record.persistedOutputPath === 'string') {
172    try {
173      return await $.fs.read(record.persistedOutputPath)
174    } catch {
175      // fall through to what the record holds inline
176    }
177  }
178  return `${record.stdout ?? ''}\n${record.stderr ?? ''}\n${text ?? ''}`
179}
180
181async function confirmGrill($: EngineInterface, how: string): Promise<void> {
182  const at = await $.clock.now()
183  await change($, current => openGate(current, 'grill', how, at))
184  $.ui.toast(`pipeline-gates: grill gate open (${how})`)
185}
186
187// a block task's link: the record URL it was given, else its key's /tasks/<key> where the project has one
188function taskLink(task: BlockTask): string {
189  if (task.url !== undefined && task.url !== '') return task.url
190  return TASK_URL_BASE === '' ? '' : `${TASK_URL_BASE}${task.key}`
191}
192
193// one grill dialog at a time: a call blocked while it is open waits for the same answer
194let asking: Promise<string> | null = null
195
196// The grill gate waits on the person. They get a push (on the phone through Remote Control; the engine
197// skips it while they are at the screen) and the engine's own question dialog, which every surface draws,
198// the phone included. Only a press on Confirm or Mechanical opens the gate; Not yet, a dismissal, a dialog
199// that resolved itself while they were away and text typed under Other leave it shut and mute the dialog
200// until the person's next message.
201async function askGrill($: EngineInterface, current: Run, what: string): Promise<string> {
202  const task = current.task || 'pipeline'
203  try {
204    await $.tool.call({ tool: 'PushNotification', message: `${task}: ${what} waits on your grill confirm`, status: 'proactive' })
205  } catch {
206    // notifications off or nowhere to send them: the dialog still asks
207  }
208  let answer = ''
209  try {
210    const options = [ASK_CONFIRM, ASK_MECHANICAL, ASK_NOT_YET]
211    answer = (await $.ui.ask(grillQuestion(task, what), { header: ASK_HEADER, options })).trim()
212  } catch {
213    // dismissed, or a run with no one to ask
214  }
215  if (answer === ASK_CONFIRM) await confirmGrill($, 'confirmed by you in the dialog')
216  else if (answer === ASK_MECHANICAL) await confirmGrill($, 'mechanical task, grill skipped by you in the dialog')
217  else await change($, r => ({ ...r, isAskMuted: true }))
218  return answer
219}
220
221function waitForGrill($: EngineInterface, current: Run, what: string): Promise<string> {
222  asking ??= askGrill($, current, what).finally(() => {
223    asking = null
224  })
225  return asking
226}
227
228// how a run that is over ended: Phase 7 ends it, and so does the person's /pipeline-gate end
229function endedLine(current: Run): string {
230  const how = current.phase === PHASES.length - 1 ? 'ended at' : 'was ended by you at'
231  return `the pipeline run for ${current.task || '(task not set)'} ${how} Phase ${current.phase} ${PHASES[current.phase]}`
232}
233
234// A call about a run that is over (its task, a task of its block, or none named) answers how it
235// ended and never opens a fresh run with its gates closed again: a pipeline that marked its tasks
236// done after Phase 7 got an empty run that gated what came next.
237function isOfEnded(current: Run | null, keys: readonly string[]): current is Run {
238  return current !== null && current.isDone && keys.every(key => key === current.task || hasTask(current, key))
239}
240
241// a tasks call with no run in progress changes nothing
242function noRunAnswer(current: Run | null): string {
243  if (current === null) return 'pipeline-gates: no pipeline run is active, so nothing changed; a tasks call starts a run only when `add` names a task.'
244  const hint = current.phase === PHASES.length - 1 ? " Mark a block's tasks done before Phase 7, which ends the run." : ''
245  return `pipeline-gates: ${endedLine(current)}, so nothing changed.${hint}`
246}
247
248function describe(current: Run | null): string {
249  if (current === null) return 'pipeline-gates: no pipeline run in this session.'
250  if (current.isDone) {
251    return [
252      `pipeline-gates: ${endedLine(current)}; nothing is gated any more.`,
253      ...(blockLine(current) === '' ? [] : [`tasks: ${blockLine(current)}`]),
254      `PR: ${current.pr ?? 'no gh pr create seen in this run'}`,
255      ...((current.closedOn ?? '') === '' ? [] : [`closed on the ${current.closedOn}`]),
256      'A new pipeline (the pipeline skill, Phase 0, or tasks with `add` naming another task) starts a new run.',
257    ].join('\n')
258  }
259  const evidence = qcEvidence(current)
260  return [
261    `pipeline ${current.task || '(task not set)'} · phase ${current.phase} ${PHASES[current.phase]}`,
262    ...(blockLine(current) === '' ? [] : [`tasks: ${blockLine(current)}`]),
263    ...GATES.map(name => {
264      const gate = current[name]
265      return `${GATE_LABELS[name]}: ${gate === null ? 'closed' : `${gate.how}${gate.isOpen ? '' : ' (closed)'}`}`
266    }),
267    `QC evidence since the last code change: review ${evidence.review ? 'yes' : 'no'}, green tests ${evidence.tests ? 'yes' : 'no'}${current.lastTests ? ` (last run: ${current.lastTests})` : ''}`,
268    `dev allowed: ${closedForDev(current).length === 0 ? 'yes' : 'no'} · PR allowed: ${qcHolds(current) ? 'yes' : 'no'}`,
269    roundsLine(current),
270  ].join('\n')
271}
272
273async function runCommand($: EngineInterface, args: string, isPerson: boolean): Promise<string> {
274  const [verb = 'status', name = '', ...rest] = args.trim().split(/\s+/).filter(part => part !== '')
275  const current = await read($, run)
276  if (verb === 'status') return describe(current)
277  // `end` and `open` let work past the gates; `start` may come from anyone, a new run's gates are closed
278  if ((verb === 'end' || verb === 'open') && !isPerson) {
279    return 'pipeline-gates: only the person at the keyboard ends a run or opens a gate by hand.'
280  }
281  if (verb === 'start') {
282    // by hand the label is taken as typed: KIO-1834, a block of keys, or a name for a trial run
283    const keys = taskKeysIn([name, ...rest].join(' ').toUpperCase())
284    await start($, keys[0] ?? name.toUpperCase().slice(0, 40), keys)
285    return describe(await read($, run))
286  }
287  if (verb === 'end') {
288    if (!isActive(current)) return describe(current)
289    await save($, { ...current, isDone: true })
290    return 'pipeline-gates: the run is ended; nothing is gated any more.'
291  }
292  if (verb === 'open') {
293    if (!isActive(current)) return describe(current)
294    if (name === 'rounds' && rest.length > 0) {
295      const granted = grantRounds(current)
296      await save($, granted)
297      return `pipeline-gates: three more fix rounds (${rest.join(' ')}); ${roundsLine(granted)}.`
298    }
299    if (!GATES.includes(name as GateName) || rest.length === 0) return USAGE
300    await save($, openGate(current, name as GateName, `opened by you: ${rest.join(' ')}`, await $.clock.now()))
301    return `pipeline-gates: the ${GATE_LABELS[name as GateName]} gate is open (${rest.join(' ')}).`
302  }
303  return USAGE
304}
305
306export const register: Register = on => {
307  on('session.start', async ($, e, next) => {
308    const started = await next(e)
309    await $.tool.register({
310      name: 'phase',
311      description:
312        "Records that the pipeline enters a phase (0 memory bootstrap ... 7 memory closure), with the task key once known. Call it at the start of every phase. Refused for Phase 2 and later while the Teams status gate or the grill gate is closed, and for Phase 6 and later until the QC verdict passed; the refusal says what is missing. A child session (the pipeline skill loaded as `child <TASK-KEYS>`) runs on the status and grill gates the person opened in its mother's run for the task, each naming that run; its QC gate stays its own. A run without a QC pass of its own (the mother's) enters Phase 7 once a run for its task in another session recorded a QC pass or a PR. Starts the run when none is active.",
313      inputSchema: {
314        type: 'object',
315        properties: {
316          phase: { type: 'integer', minimum: 0, maximum: 7 },
317          task: { type: 'string', description: `The task key, ${SAMPLE_KEY}` },
318        },
319        required: ['phase'],
320      },
321    })
322    await $.tool.register({
323      name: 'qc_verdict',
324      description:
325        "Records the Phase-3 QC gate decision. A pass is accepted only when a review agent finished and a green Odoo test run (more than 0 tests) happened after the last code change in the worktree; otherwise it is refused with what is missing. Until a pass stands, gh pr create is refused; a later code change voids it.",
326      inputSchema: {
327        type: 'object',
328        properties: {
329          verdict: { type: 'string', enum: ['pass', 'blocking'] },
330          summary: { type: 'string', description: 'The gate report line' },
331        },
332        required: ['verdict', 'summary'],
333      },
334    })
335    await $.tool.register({
336      name: 'tasks',
337      description:
338        `The block of tasks this pipeline run works through, and where each stands: the user watches it as progress in the pipeline pane and band. A block is one run (one Teams status, one grill alignment), so a task of the block never resets the gates. \`add\` the block's tasks, each "${SAMPLE_KEY} short title <its _url from the Odoo connector>" (the URL gives the task an open button in the pane; a pipeline started with several keys has the keys already, add again to give titles and URLs). Then move them as the work goes: \`active\` when you start on a task, \`done\` when it is finished (its part is in the PR, or it closed without code), \`pending\` to put one back. Tasks that share one PR are yours to mark.`,
339      inputSchema: {
340        type: 'object',
341        properties: {
342          add: { type: 'array', items: { type: 'string' }, description: `Tasks of the block: "${SAMPLE_KEY} short title https://…/web#id=…" (title and URL optional)` },
343          active: { type: 'array', items: { type: 'string' }, description: 'Task keys now in work' },
344          done: { type: 'array', items: { type: 'string' }, description: 'Task keys finished' },
345          pending: { type: 'array', items: { type: 'string' }, description: 'Task keys put back to pending' },
346        },
347      },
348    })
349    await $.tool.register({
350      name: 'gates',
351      description: 'The current pipeline run: phase, the three gates, and what the QC gate still lacks.',
352      inputSchema: { type: 'object', properties: {} },
353    })
354    await $.command.register({
355      name: 'pipeline-gate',
356      description: 'The pipeline gates: status, or open a gate by hand with a reason',
357      argumentHint: '[status | open <status|grill|qc> <reason> | start [TASK ...] | end]',
358    })
359    await restore($)
360    if (isActive(await read($, run))) void $.ui.open({ id: PANE, title: 'pipeline' })
361    return started
362  })
363
364  // /pipeline typed; not at skill.prompt, which Claude Code's built-in cc-plugin-sec-default (outermost
365  // for Team and Enterprise organizations) sends past every plugin a person installs
366  on('prompt.submit', { command: { name: 'pipeline' } }, async ($, e, next) => {
367    await startPipeline($, e.command?.args ?? '')
368    return next(e)
369  })
370
371  on('tool.call', { tool: 'mcp__pipeline-gates__phase' }, async ($, e) => {
372    const input = e as unknown as Record<string, unknown>
373    const task = typeof input.task === 'string' ? taskKeyIn(input.task.toUpperCase()) : ''
374    const phase = Number(input.phase)
375    // Phase 0 starts a pipeline; a later phase of the run that is over starts none
376    const before = await read($, run)
377    if (phase !== 0 && isOfEnded(before, task === '' ? [] : [task])) return { result: describe(before) }
378    await start($, task)
379    const current = await read($, run)
380    if (!isActive(current)) return { result: describe(current) }
381    // a mother's closure rests on its child's run: the QC pass or the PR it recorded
382    const closure = phase === PHASES.length - 1 && !qcHolds(current) ? await closureFor($, current) : ''
383    let entered = enterPhase(current, phase, task, await $.clock.now(), closure)
384    let asked = ''
385    if (typeof entered === 'string' && phase >= 2 && mayAskGrill(current)) {
386      const answer = await waitForGrill($, current, `Phase ${phase}`)
387      const fresh = await read($, run)
388      if (!isActive(fresh)) return { result: describe(fresh) }
389      entered = enterPhase(fresh, phase, task, await $.clock.now(), closure)
390      if (typeof entered === 'string' && !isOpen(fresh.grill)) asked = askedNote(answer)
391    }
392    if (typeof entered === 'string') {
393      const latest = await read($, run)
394      if (isActive(latest)) await save($, withBlock(latest, `Phase ${String(input.phase)}`, await $.clock.now()))
395      return { result: asked === '' ? entered : `${entered} ${asked}` }
396    }
397    await save($, entered)
398    return { result: describe(entered) }
399  })
400
401  on('tool.call', { tool: 'mcp__pipeline-gates__qc_verdict' }, async ($, e) => {
402    const input = e as unknown as Record<string, unknown>
403    const current = await read($, run)
404    if (!isActive(current)) return { result: describe(current) }
405    const summary = typeof input.summary === 'string' ? input.summary.slice(0, 300) : ''
406    const recorded = recordVerdict(current, String(input.verdict), summary, await $.clock.now())
407    if (typeof recorded === 'string') return { result: recorded }
408    await save($, recorded)
409    return { result: describe(recorded) }
410  })
411
412  on('tool.call', { tool: 'mcp__pipeline-gates__gates' }, async $ => ({ result: describe(await read($, run)) }))
413
414  on('tool.call', { tool: 'mcp__pipeline-gates__tasks' }, async ($, e) => {
415    const input = e as unknown as Record<string, unknown>
416    const list = (value: unknown) => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])
417    const added = list(input.add)
418    const now = await $.clock.now()
419    const current = await read($, run)
420    // added to the run in progress, never a reason to start over; with none, a run starts only for a
421    // task `add` names that the run just over did not have, and a move alone changes nothing
422    if (isActive(current)) await change($, r => addTasks(r, added, now, ODOO_WEB_URL))
423    else {
424      const named = added.map(item => taskKeyIn(item.toUpperCase())).filter(key => key !== '')
425      if (named.length === 0 || isOfEnded(current, named)) return { result: noRunAnswer(current) }
426      await start($, named[0] ?? '', added)
427    }
428    for (const state of TASK_STATES) {
429      const keys = list(input[state])
430      if (keys.length > 0) await change($, r => moveTasks(r, keys, state, now))
431    }
432    return { result: describe(await read($, run)) }
433  })
434
435  // a grill dialog that resolved itself while the person was away carries no press: its answer is dropped
436  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
437    const ran = await next(e)
438    if (!isAwayGrillAnswer(e.questions, ran.result)) return ran
439    const result = { ...(ran.result as object), answers: {} }
440    return ran.context === undefined ? { result } : { result, context: ran.context }
441  })
442
443  // the person's own message lets the grill dialog ask again
444  on('prompt.submit', async ($, e, next) => {
445    if (PERSON_ORIGINS.has(e.origin.kind) && (await read($, run))?.isAskMuted === true) {
446      await change($, r => ({ ...r, isAskMuted: false }))
447    }
448    return next(e)
449  })
450
451  // the surface already heads a command's output with the plugin's name
452  on('command.run', { command: 'pipeline-gate' }, async ($, e) => ({
453    text: (await runCommand($, e.args, PERSON_ORIGINS.has(e.origin.kind))).replace(/^pipeline-gates: /, ''),
454  }))
455
456  // the gates themselves, and the facts the QC gate rests on
457  on('tool.call', async ($, e, next) => {
458    const tool = String(e.tool)
459    const input = e as unknown as Record<string, unknown>
460    if (tool === 'Skill' && input.skill === 'pipeline') await startPipeline($, String(input.args ?? ''))
461
462    const current = await read($, run)
463    const path = filePathOf(tool, input)
464    const command = tool === 'Bash' && typeof input.command === 'string' ? input.command : ''
465    const isPr = command !== '' && isPrCreate(command)
466    if (isActive(current)) {
467      const isDev = tool === 'Agent' && input.subagent_type === 'dev'
468      const isWorktreeEdit = path !== null && isWorktreeCode(path)
469      if ((isDev || isWorktreeEdit) && closedForDev(current).length > 0) {
470        const what = isDev ? 'spawning the dev agent' : `editing ${path}`
471        const answer = mayAskGrill(current) ? await waitForGrill($, current, what) : null
472        const latest = await read($, run)
473        if (isActive(latest) && closedForDev(latest).length > 0) {
474          await save($, withBlock(latest, what, await $.clock.now()))
475          $.ui.toast(`pipeline-gates: ${what} blocked`)
476          return { deny: devRefusal(latest, what, answer === null || isOpen(latest.grill) ? '' : askedNote(answer)) }
477        }
478      }
479      // a fix round: a fresh dev agent, and no more than the rounds the person allows
480      if (isNewRound(current) && closedForDev(current).length === 0) {
481        if (tool === 'SendMessage' && (await addresseeType($, input.to)) === 'dev') {
482          await save($, withBlock(current, 'a fix round sent into an old dev agent', await $.clock.now()))
483          $.ui.toast('pipeline-gates: fix round into an old dev agent blocked')
484          return { deny: RESUME_REFUSAL }
485        }
486        if (isDev) {
487          if (roundsLeft(current) <= 0) {
488            await save($, withBlock(current, `fix round ${(current.fixRounds ?? 0) + 1}`, await $.clock.now()))
489            $.ui.toast('pipeline-gates: fix round blocked, the user decides')
490            return { deny: roundsRefusal(current) }
491          }
492          await change($, r => (isNewRound(r) ? startRound(r) : r))
493        }
494      }
495      if (isPr && !qcHolds(current)) {
496        await save($, withBlock(current, 'gh pr create', await $.clock.now()))
497        $.ui.toast('pipeline-gates: gh pr create blocked')
498        return { deny: prRefusal(current) }
499      }
500    }
501
502    const ran = await next(e)
503    if (!isActive(await read($, run)) || ran.deny !== undefined || ran.isError === true) return ran
504
505    const agentId = (e as { agentId?: string }).agentId
506    if (path !== null && isWorktreeCode(path) && !isDocPath(path)) {
507      const isDocumenter = agentId !== undefined && (await agentType($, agentId)) === 'documenter'
508      if (!isDocumenter) {
509        await change($, r => {
510          const [next2, seq] = bump(r)
511          return { ...next2, lastChange: seq }
512        })
513      }
514    }
515    if (command.includes('--test-enable')) {
516      const summary = testSummary(await bashOutput($, ran.result, ran.text))
517      if (summary !== null) {
518        await change($, r => {
519          const [next2, seq] = bump(r)
520          return { ...next2, lastTests: summary.text, lastGreen: summary.isGreen ? seq : r.lastGreen }
521        })
522      }
523    }
524    if (isPr) {
525      const url = prUrlIn(await bashOutput($, ran.result, ran.text))
526      if (url !== '') await change($, r => ({ ...r, pr: url }))
527    }
528    if (tool.endsWith('__teams_send_chat_message')) {
529      const chat = typeof input.chatId === 'string' ? input.chatId : 'a chat'
530      const at = await $.clock.now()
531      await change($, r => (isOpen(r.status) ? r : openGate(r, 'status', `sent to ${chat.slice(0, 16)}…`, at)))
532    }
533    return ran
534  })
535
536  // a subagent's end: dev counts as a code change, review as the review the QC gate needs
537  on('turn.complete', async ($, e, next) => {
538    const result = await next(e)
539    if (e.agentId !== undefined && !e.isAborted && isActive(await read($, run))) {
540      const type = await agentType($, e.agentId)
541      if (type === 'dev' || type === 'review') {
542        await change($, r => {
543          const [next2, seq] = bump(r)
544          return type === 'dev' ? { ...next2, lastChange: seq } : { ...next2, lastReview: seq }
545        })
546      }
547    }
548    return result
549  })
550
551  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
552    const below = await next(e)
553    const current = await read($, run)
554    if (!isActive(current) || e.props.hasSurvey) return below
555    const { Box, Button, Text } = $.ui.resolve(e)
556    const counts = taskCounts(current)
557    const mark = (gate: Gate | null, holds: boolean) => (holds && isOpen(gate) ? '✓' : '○')
558
559    return (
560      <Box flexDirection="column">
561        {below}
562        <Box key="pipeline-row" flexDirection="row" columnGap={1} alignItems="center">
563          <Text dimColor>pipeline</Text>
564          <Text bold>{current.task || 'task?'}</Text>
565          {counts.total > 1 && <Text color={counts.done === counts.total ? 'green' : 'cyan'}>{`${counts.done}/${counts.total}`}</Text>}
566          <Text>{`${current.phase} ${PHASES[current.phase]}`}</Text>
567          <Text color={isOpen(current.status) ? 'green' : 'yellow'}>{`status ${mark(current.status, true)}`}</Text>
568          <Text color={isOpen(current.grill) ? 'green' : 'yellow'}>{`grill ${mark(current.grill, true)}`}</Text>
569          <Text color={qcHolds(current) ? 'green' : 'yellow'}>{`qc ${mark(current.qc, qcHolds(current))}`}</Text>
570          <Button key="pipeline-open" label="open" onPress={() => $.ui.open({ id: PANE, title: 'pipeline' })} />
571        </Box>
572      </Box>
573    )
574  })
575
576  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
577    const { Box, Button, Link, Text } = $.ui.resolve(e)
578    const current = await read($, run)
579    if (current === null) return <Text dimColor>No pipeline run in this session. /pipeline-gate start [TASK] starts one by hand.</Text>
580    if (current.isDone) {
581      const ended = endedLine(current)
582      return (
583        <Box flexDirection="column" rowGap={1}>
584          <Text key="pipeline-ended" bold>{`${ended.charAt(0).toUpperCase()}${ended.slice(1)}.`}</Text>
585          {blockLine(current) !== '' && <Text key="pipeline-ended-tasks" dimColor>{`tasks: ${blockLine(current)}`}</Text>}
586          {current.pr !== undefined && (
587            <Box key="pipeline-ended-pr" flexDirection="row" columnGap={1}>
588              <Text dimColor>PR</Text>
589              <Link href={current.pr} label={current.pr} />
590            </Box>
591          )}
592          <Text key="pipeline-ended-next" dimColor>Nothing is gated. The next pipeline starts a new run; /pipeline-gate start [TASK] starts one by hand.</Text>
593        </Box>
594      )
595    }
596    const now = await $.clock.now()
597    const ago = (at: number) => {
598      const minutes = Math.max(0, Math.round((now - at) / 60_000))
599      return minutes < 1 ? 'just now' : minutes < 60 ? `${minutes}m ago` : `${Math.floor(minutes / 60)}h${minutes % 60}m ago`
600    }
601    const hasCards = e.surface !== 'terminal'
602    const card = (key: string, children: RenderChildren) => (
603      <Box key={key} flexDirection="column" rowGap={hasCards ? 1 : 0} borderStyle={hasCards ? 'round' : undefined} borderDimColor={hasCards ? true : undefined}>
604        {children}
605      </Box>
606    )
607    const evidence = qcEvidence(current)
608    const tasks = tasksOf(current)
609    const counts = taskCounts(current)
610    const taskRow = (task: BlockTask) => (
611      <Box key={`task-${task.key}`} flexDirection="row" columnGap={1}>
612        <Text color={task.state === 'done' ? 'green' : task.state === 'active' ? 'cyan' : undefined} dimColor={task.state === 'pending'}>
613          {task.state === 'done' ? '✓' : task.state === 'active' ? '●' : '○'}
614        </Text>
615        <Text bold={task.state === 'active'} dimColor={task.state === 'pending'}>
616          {task.key}
617        </Text>
618        {task.title !== '' && <Text dimColor>{task.title}</Text>}
619        {task.state !== 'pending' && <Text dimColor>{`${task.state === 'done' ? 'done' : 'in work'} ${ago(task.at)}`}</Text>}
620        {taskLink(task) !== '' && <Link href={taskLink(task)} label="open in Odoo" />}
621      </Box>
622    )
623    const gateRow = (name: GateName, holds: boolean, extra: RenderChildren) => {
624      const gate = current[name]
625      const isUp = holds && isOpen(gate)
626      return (
627        <Box key={`gate-${name}`} flexDirection="column">
628          <Box flexDirection="row" columnGap={1}>
629            <Text color={isUp ? 'green' : 'yellow'}>{isUp ? '✓' : '○'}</Text>
630            <Text bold>{GATE_LABELS[name]}</Text>
631            <Text dimColor>{gate === null ? 'closed' : `${gate.how} · ${ago(gate.at)}`}</Text>
632          </Box>
633          {extra}
634        </Box>
635      )
636    }
637
638    return (
639      <Box flexDirection="column" rowGap={1}>
640        <Box key="pipeline-head" flexDirection="column">
641          <Text bold>{`pipeline ${current.task || '(task not set yet)'}${tasks.length > 1 ? ` · block of ${tasks.length}` : ''}`}</Text>
642          <Text dimColor>{`started ${ago(current.startedAt)} · dev ${closedForDev(current).length === 0 ? 'allowed' : 'gated'} · PR ${qcHolds(current) ? 'allowed' : 'gated'}`}</Text>
643        </Box>
644        {tasks.length > 1 &&
645          card(
646            'pipeline-tasks',
647            <Box flexDirection="column">
648              <Text bold>Tasks</Text>
649              <Box flexDirection="row">
650                <Text color="green">{'■'.repeat(counts.done)}</Text>
651                <Text color="cyan">{'■'.repeat(counts.active)}</Text>
652                <Text dimColor>{'□'.repeat(counts.pending)}</Text>
653              </Box>
654              <Text dimColor>{blockLine(current)}</Text>
655              {tasks.map(task => taskRow(task))}
656            </Box>,
657          )}
658        {card(
659          'pipeline-phases',
660          <Box flexDirection="column">
661            <Text bold>Phases</Text>
662            {PHASES.map((name, i) => {
663              const reached = (current.phaseAt[i] ?? 0) > 0
664              // a phase passed over without being entered (the optional GIF) reads as skipped, not done
665              const isSkipped = i < current.phase && !reached
666              return (
667                <Box flexDirection="row" columnGap={1}>
668                  <Text
669                    color={i < current.phase && !isSkipped ? 'green' : i === current.phase ? 'cyan' : undefined}
670                    dimColor={i > current.phase || isSkipped}
671                  >
672                    {isSkipped ? '–' : i < current.phase ? '✓' : i === current.phase ? '●' : '○'}
673                  </Text>
674                  <Text bold={i === current.phase} dimColor={i > current.phase || isSkipped}>
675                    {`${i} ${name}${isSkipped ? ' · skipped' : ''}`}
676                  </Text>
677                  {reached && <Text dimColor>{ago(current.phaseAt[i] ?? 0)}</Text>}
678                </Box>
679              )
680            })}
681          </Box>,
682        )}
683        {card(
684          'pipeline-gates',
685          <Box flexDirection="column" rowGap={1}>
686            <Text bold>Gates</Text>
687            {gateRow('status', true, null)}
688            {gateRow(
689              'grill',
690              true,
691              !isOpen(current.grill) && (
692                <Box flexDirection="row" columnGap={1} paddingLeft={2} alignItems="center">
693                  <Text dimColor>after you agree with the Alignment Summary:</Text>
694                  <Button key="grill-confirm" label="confirm" onPress={() => confirmGrill($, 'confirmed by you')} />
695                  <Button key="grill-mechanical" label="mechanical" onPress={() => confirmGrill($, 'mechanical task, grill skipped by you')} />
696                </Box>
697              ),
698            )}
699            {gateRow(
700              'qc',
701              qcHolds(current),
702              <Box flexDirection="column" paddingLeft={2}>
703                <Text dimColor>{`since the last code change: review ${evidence.review ? '✓' : '○'} · green tests ${evidence.tests ? '✓' : '○'}`}</Text>
704                {current.lastTests !== '' && <Text dimColor>{`last test run: ${current.lastTests}`}</Text>}
705                <Text dimColor>{roundsLine(current)}</Text>
706              </Box>,
707            )}
708          </Box>,
709        )}
710        {current.blocked.length > 0 &&
711          card(
712            'pipeline-blocked',
713            <Box flexDirection="column">
714              <Text bold>Blocked</Text>
715              {current.blocked.map(block => (
716                <Text dimColor>{`${ago(block.at)}  ${block.what}`}</Text>
717              ))}
718            </Box>,
719          )}
720      </Box>
721    )
722  })
723}
724
hooks/gates.ts 580 lines
1import type { BlockTask, Gate, GateName, Run, TaskState } from '../types'
2import { TICKET_PREFIXES } from './config'
3
4export const PHASES = [
5  'Memory bootstrap',
6  'Task reading',
7  'Development',
8  'QC gate',
9  'Documentation',
10  'Demo GIF (optional)',
11  'Pull request',
12  'Memory closure',
13] as const
14
15export const GATE_LABELS: Record<GateName, string> = {
16  status: 'Teams status',
17  grill: 'grill alignment',
18  qc: 'QC verdict',
19}
20
21// the grill dialog: a press on its first two options opens the gate, as the pane's buttons do
22export const ASK_CONFIRM = 'Confirm'
23export const ASK_MECHANICAL = 'Mechanical'
24export const ASK_NOT_YET = 'Not yet'
25export const ASK_HEADER = 'Grill gate'
26const ASK_TAIL = 'waits on the grill gate. Do you agree with the Alignment Summary?'
27
28const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
29const WORKTREE = /\/\.worktrees\/(?!_env\/)[A-Za-z0-9][A-Za-z0-9._-]*\//
30// what the documenter writes: never a code change, so it never voids a QC pass
31const DOC_PATH = /\/readme\/|\/README\.(?:rst|md)$|\/static\/description\/|\.puml$/
32const TEST_SUMMARY = /(\d+) failed, (\d+) error\(s\) of (\d+) tests/g
33const PR_CREATE = /\bgh\s+pr\s+create\b/
34const PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/
35// A task key is one of the ticket prefixes and a number, so prose naming a month column (JAN-2026),
36// a standard (ISO-9001) or a project the prefixes do not name stays out of the block; without a
37// prefix, any word-dash-number. project_key numbers a project's tasks from an unpadded sequence, so a
38// key's number never starts with 0: product codes are zero-padded (RAW-000010, ASM-001640).
39const KEY_PREFIX =
40  TICKET_PREFIXES.length === 0
41    ? '[A-Z][A-Z0-9]{1,9}'
42    : `(?:${TICKET_PREFIXES.map(prefix => prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`
43const TASK_KEY = new RegExp(`\\b${KEY_PREFIX}-[1-9]\\d*\\b`)
44
45export function newRun(task: string, now: number, hasStatusGate = true): Run {
46  return {
47    task,
48    startedAt: now,
49    phase: 0,
50    phaseAt: PHASES.map((_, i) => (i === 0 ? now : 0)),
51    status: hasStatusGate ? null : { isOpen: true, how: 'no Teams status flow in this project', at: now },
52    grill: null,
53    qc: null,
54    qcSeq: 0,
55    seq: 0,
56    lastChange: 0,
57    lastReview: 0,
58    lastGreen: 0,
59    lastTests: '',
60    blocked: [],
61    isAskMuted: false,
62    isDone: false,
63  }
64}
65
66export function isActive(run: Run | null): run is Run {
67  return run !== null && !run.isDone
68}
69
70export function filePathOf(tool: string, input: Record<string, unknown>): string | null {
71  if (!FILE_TOOLS.has(tool)) return null
72  const path = typeof input.file_path === 'string' ? input.file_path : input.notebook_path
73  return typeof path === 'string' ? path : null
74}
75
76export function isWorktreeCode(path: string): boolean {
77  return WORKTREE.test(path)
78}
79
80export function isDocPath(path: string): boolean {
81  return DOC_PATH.test(path)
82}
83
84// One simple command of a shell line: its words with the quotes taken off, and the here-documents fed
85// to it. REDIRECT stands before a redirection's target, which is no word of the command.
86type ShellCommand = { words: string[]; heredocs: string[] }
87const REDIRECT = '\u0000>'
88const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/
89// what may stand before the program a simple command runs
90const RESERVED = new Set(['!', '{', 'if', 'then', 'elif', 'else', 'while', 'until', 'do'])
91// programs that run the program after them, past their own options and a count or a duration
92const WRAPPERS = new Set(['builtin', 'command', 'env', 'exec', 'nice', 'nohup', 'sudo', 'time', 'timeout'])
93const SHELLS = new Set(['bash', 'dash', 'ksh', 'sh', 'zsh'])
94
95// Splits a shell line the way the shell does, far enough to tell which programs it runs: quotes and
96// here-documents are text, $( ) and backticks are commands of their own. Nested, the scan stops at
97// the `)` that closes its $( ), and `end` is where it stopped.
98function scanShell(src: string, start = 0, isNested = false): { commands: ShellCommand[]; end: number } {
99  const commands: ShellCommand[] = []
100  const pending: { delimiter: string; stripsTabs: boolean; command: ShellCommand }[] = []
101  let current: ShellCommand = { words: [], heredocs: [] }
102  let word: string | null = null
103  let depth = 0
104  const endWord = () => {
105    if (word !== null) current.words.push(word)
106    word = null
107  }
108  const endCommand = () => {
109    endWord()
110    if (current.words.length > 0) commands.push(current)
111    current = { words: [], heredocs: [] }
112  }
113  // a substitution's commands are the line's commands too; its text stays in the word
114  const substitute = (from: number): number => {
115    const inner = scanShell(src, from + 2, true)
116    commands.push(...inner.commands)
117    word = (word ?? '') + src.slice(from, inner.end + 1)
118    return inner.end + 1
119  }
120  const backticks = (from: number): number => {
121    let close = from + 1
122    while (close < src.length && src.charAt(close) !== '`') close += src.charAt(close) === '\\' ? 2 : 1
123    commands.push(...scanShell(src.slice(from + 1, close)).commands)
124    word = (word ?? '') + src.slice(from, close + 1)
125    return close + 1
126  }
127  // <<DELIM, <<-DELIM, <<'DELIM': the body starts on the next line
128  const heredoc = (from: number): number => {
129    let at = from + 2
130    const stripsTabs = src.charAt(at) === '-'
131    if (stripsTabs) at++
132    while (src.charAt(at) === ' ' || src.charAt(at) === '\t') at++
133    let delimiter = ''
134    while (at < src.length && !/[\s;&|<>()]/.test(src.charAt(at))) {
135      const c = src.charAt(at)
136      if (c === "'" || c === '"') {
137        const close = src.indexOf(c, at + 1)
138        const stop = close === -1 ? src.length : close
139        delimiter += src.slice(at + 1, stop)
140        at = stop + 1
141      } else {
142        delimiter += c === '\\' ? src.charAt(at + 1) : c
143        at += c === '\\' ? 2 : 1
144      }
145    }
146    pending.push({ delimiter, stripsTabs, command: current })
147    return at
148  }
149  // the bodies of the here-documents the line just ended opened, each up to its delimiter line
150  const readHeredocs = (from: number): number => {
151    let at = from
152    for (const doc of pending) {
153      const lines: string[] = []
154      while (at < src.length) {
155        const newline = src.indexOf('\n', at)
156        const stop = newline === -1 ? src.length : newline
157        const line = doc.stripsTabs ? src.slice(at, stop).replace(/^\t+/, '') : src.slice(at, stop)
158        at = stop + 1
159        if (line === doc.delimiter) break
160        lines.push(line)
161      }
162      doc.command.heredocs.push(lines.join('\n'))
163    }
164    pending.length = 0
165    return at
166  }
167
168  let i = start
169  while (i < src.length) {
170    const c = src.charAt(i)
171    const next = src.charAt(i + 1)
172    if (c === '\\') {
173      // an escaped character is text; an escaped newline joins the lines
174      if (next !== '\n') word = (word ?? '') + next
175      i += 2
176    } else if (c === "'") {
177      const close = src.indexOf("'", i + 1)
178      const stop = close === -1 ? src.length : close
179      word = (word ?? '') + src.slice(i + 1, stop)
180      i = stop + 1
181    } else if (c === '"') {
182      word = word ?? ''
183      i++
184      while (i < src.length && src.charAt(i) !== '"') {
185        const d = src.charAt(i)
186        if (d === '\\' && i + 1 < src.length && '$`"\\\n'.includes(src.charAt(i + 1))) {
187          if (src.charAt(i + 1) !== '\n') word += src.charAt(i + 1)
188          i += 2
189        } else if (d === '$' && src.charAt(i + 1) === '(') i = substitute(i)
190        else if (d === '`') i = backticks(i)
191        else {
192          word += d
193          i++
194        }
195      }
196      i++
197    } else if (c === '`') i = backticks(i)
198    else if (c === '$' && next === '(') i = substitute(i)
199    else if (c === '#' && word === null) {
200      const newline = src.indexOf('\n', i)
201      i = newline === -1 ? src.length : newline
202    } else if (c === ' ' || c === '\t') {
203      endWord()
204      i++
205    } else if (c === '\n') {
206      endCommand()
207      i = readHeredocs(i + 1)
208    } else if (c === '(') {
209      endCommand()
210      depth++
211      i++
212    } else if (c === ')') {
213      endCommand()
214      if (depth === 0 && isNested) return { commands, end: i }
215      depth = Math.max(0, depth - 1)
216      i++
217    } else if (c === ';' || c === '|' || (c === '&' && next !== '>')) {
218      endCommand()
219      i++
220    } else if (c === '<' && next === '<' && src.charAt(i + 2) !== '<') {
221      endWord()
222      i = heredoc(i)
223    } else if (c === '<' || c === '>' || c === '&') {
224      // a redirection (2>&1, &>log, <<<text): a file descriptor before it is no word either
225      if (word !== null && /^\d+$/.test(word)) word = null
226      endWord()
227      current.words.push(REDIRECT)
228      i++
229      while (i < src.length && '<>&|'.includes(src.charAt(i))) i++
230    } else {
231      word = (word ?? '') + c
232      i++
233    }
234  }
235  endCommand()
236  return { commands, end: src.length }
237}
238
239// the program a simple command runs, then its arguments: past assignments, redirections, reserved
240// words and the wrappers that run the program after them
241function programOf(words: readonly string[]): string[] {
242  const args = words.filter((word, i) => word !== REDIRECT && words[i - 1] !== REDIRECT)
243  let at = 0
244  let isWrapped = false
245  while (at < args.length) {
246    const word = args[at] ?? ''
247    if (ASSIGNMENT.test(word) || RESERVED.has(word)) at++
248    else if (WRAPPERS.has(word)) {
249      isWrapped = true
250      at++
251    } else if (isWrapped && /^(?:-|\d+(?:\.\d+)?[smhd]?$)/.test(word)) at++
252    else break
253  }
254  return args.slice(at)
255}
256
257// gh pr create, or its alias gh pr new; a --repo may stand before the subcommand
258function isGhPrCreate(args: readonly string[]): boolean {
259  const words = args.filter((word, i) => !word.startsWith('-') && !/^(?:-R|--repo)$/.test(args[i - 1] ?? ''))
260  return words[0] === 'pr' && (words[1] === 'create' || words[1] === 'new')
261}
262
263// A command line that runs gh pr create: as a program of its own (after `cd … &&`, in a $( ) or
264// backticks, under env or timeout), or through a shell's -c script, eval, or a here-document fed to a
265// shell. The words inside a quoted argument, or a here-document fed to anything else, are text and
266// no command: a `kb add` note may name it. Nested more than a few shells deep, the plain text decides.
267export function isPrCreate(command: string, depth = 0): boolean {
268  if (depth > 3) return PR_CREATE.test(command)
269  return scanShell(command).commands.some(({ words, heredocs }) => {
270    const [program = '', ...args] = programOf(words)
271    const name = program.slice(program.lastIndexOf('/') + 1)
272    if (name === 'gh') return isGhPrCreate(args)
273    if (name === 'eval') return isPrCreate(args.join(' '), depth + 1)
274    if (!SHELLS.has(name)) return false
275    const script = args.findIndex(arg => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg))
276    return script === -1 ? heredocs.some(body => isPrCreate(body, depth + 1)) : isPrCreate(args[script + 1] ?? '', depth + 1)
277  })
278}
279
280// the pull request a gh pr create printed, '' when none
281export function prUrlIn(output: string): string {
282  return PR_URL.exec(output)?.[0] ?? ''
283}
284
285export function taskKeyIn(text: string): string {
286  return TASK_KEY.exec(text)?.[0] ?? ''
287}
288
289// every task key in the text, once each, in order: the block a pipeline started with several takes on
290export function taskKeysIn(text: string): string[] {
291  return [...new Set(text.match(new RegExp(TASK_KEY.source, 'g')) ?? [])]
292}
293
294export function tasksOf(run: Run): BlockTask[] {
295  return run.tasks ?? []
296}
297
298// a block saved before keys were bound to the ticket prefix can hold a word that is no key (JAN-2026)
299export function withoutStrayTasks(run: Run): Run {
300  const tasks = tasksOf(run).filter(task => taskKeyIn(task.key) === task.key)
301  return tasks.length === tasksOf(run).length ? run : { ...run, tasks }
302}
303
304export function hasTask(run: Run, key: string): boolean {
305  return tasksOf(run).some(task => task.key === key)
306}
307
308// The record URL in a task item, kept only when it opens a record in the production web client
309// (`webUrl`, then `#` or `?`): a link the person clicks never leads anywhere else.
310export function taskUrlIn(item: string, webUrl: string): string {
311  const url = /https:\/\/\S+/.exec(item)?.[0] ?? ''
312  const base = webUrl.replace(/\/+$/, '')
313  return base !== '' && (url.startsWith(`${base}#`) || url.startsWith(`${base}?`)) ? url.slice(0, 500) : ''
314}
315
316// Tasks given as "KIO-1234", "KIO-1234 short title", either with the task's record URL, join the block
317// as pending; one already in it keeps its state and takes a new title or URL when one is given.
318export function addTasks(run: Run, items: readonly string[], now: number, webUrl = ''): Run {
319  let tasks = tasksOf(run)
320  for (const item of items) {
321    const key = taskKeyIn(item.toUpperCase())
322    if (key === '') continue
323    const url = taskUrlIn(item, webUrl)
324    const text = item.replace(/https?:\/\/\S+/g, ' ')
325    const title = text.slice(text.toUpperCase().indexOf(key) + key.length).replace(/^[\s:·,-]+/, '').trim().slice(0, 80)
326    const known = tasks.find(task => task.key === key)
327    if (known === undefined) tasks = [...tasks, { key, title, state: 'pending', at: now, url }]
328    else if ((title !== '' && title !== known.title) || (url !== '' && url !== known.url)) {
329      tasks = tasks.map(task => (task.key === key ? { ...task, title: title || task.title, url: url || task.url } : task))
330    }
331  }
332  return tasks === tasksOf(run) ? run : { ...run, tasks }
333}
334
335// moves the named tasks to `state`; a key not in the block joins it in that state
336export function moveTasks(run: Run, keys: readonly string[], state: TaskState, now: number): Run {
337  const withAll = addTasks(run, keys, now)
338  const wanted = new Set(keys.map(key => taskKeyIn(key.toUpperCase())).filter(key => key !== ''))
339  const tasks = tasksOf(withAll).map(task => (wanted.has(task.key) && task.state !== state ? { ...task, state, at: now } : task))
340  return { ...withAll, tasks }
341}
342
343export function taskCounts(run: Run): Record<TaskState, number> & { total: number } {
344  const tasks = tasksOf(run)
345  const count = (state: TaskState) => tasks.filter(task => task.state === state).length
346  return { pending: count('pending'), active: count('active'), done: count('done'), total: tasks.length }
347}
348
349// "2/11 done · 4 in work · 5 pending", or '' for a run of one task
350export function blockLine(run: Run): string {
351  const counts = taskCounts(run)
352  return counts.total > 1 ? `${counts.done}/${counts.total} done · ${counts.active} in work · ${counts.pending} pending` : ''
353}
354
355// Every `N failed, M error(s) of K tests` line of an Odoo run: green when all are clean and K adds up
356// to more than zero (a bare --test-tags name runs 0 tests and only looks green).
357export function testSummary(output: string): { isGreen: boolean; text: string } | null {
358  const lines = [...output.matchAll(TEST_SUMMARY)]
359  if (lines.length === 0) return null
360  const failed = lines.reduce((sum, m) => sum + Number(m[1]), 0)
361  const errors = lines.reduce((sum, m) => sum + Number(m[2]), 0)
362  const tests = lines.reduce((sum, m) => sum + Number(m[3]), 0)
363  return { isGreen: failed === 0 && errors === 0 && tests > 0, text: `${failed} failed, ${errors} error(s) of ${tests} tests` }
364}
365
366export function isOpen(gate: Gate | null): boolean {
367  return gate?.isOpen === true
368}
369
370export function closedForDev(run: Run): GateName[] {
371  return (['status', 'grill'] as const).filter(name => !isOpen(run[name]))
372}
373
374export function qcHolds(run: Run): boolean {
375  return isOpen(run.qc) && run.qcSeq > run.lastChange
376}
377
378// what a QC pass rests on, since the last code change
379export function qcEvidence(run: Run): { review: boolean; tests: boolean } {
380  return { review: run.lastReview > run.lastChange, tests: run.lastGreen > run.lastChange }
381}
382
383export function bump(run: Run): [Run, number] {
384  const seq = run.seq + 1
385  return [{ ...run, seq }, seq]
386}
387
388export function withBlock(run: Run, what: string, at: number): Run {
389  return { ...run, blocked: [{ what, at }, ...run.blocked].slice(0, 5) }
390}
391
392export function devRefusal(run: Run, what: string, asked = ''): string {
393  const names = closedForDev(run).map(name => GATE_LABELS[name])
394  const closed = `${names.join(' and ')} ${names.length > 1 ? 'gates are' : 'gate is'}`
395  const how = [
396    !isOpen(run.status) ? 'the status opens on a successful Teams send (my-status send)' : '',
397    !isOpen(run.grill)
398      ? 'the grill gate opens only when the user presses confirm or mechanical, in the pipeline pane or in the dialog the mod opens when a step waits on it'
399      : '',
400  ].filter(part => part !== '')
401  const refusal = `pipeline-gates: ${what} is refused, the ${closed} closed: ${how.join('; ')}. A user who decides to go on anyway types /pipeline-gate open <gate> <reason>.`
402  return asked === '' ? refusal : `${refusal} ${asked}`
403}
404
405// The dialog asks only when the grill gate is the one still shut for dev, and once per message of the
406// person's: after a "not yet" or a dialog nobody answered, a retry is refused without asking again.
407export function mayAskGrill(run: Run): boolean {
408  const closed = closedForDev(run)
409  return closed.length === 1 && closed[0] === 'grill' && run.isAskMuted !== true
410}
411
412export function grillQuestion(task: string, what: string): string {
413  return `${task || 'pipeline'}: ${what} ${ASK_TAIL}`
414}
415
416// An AskUserQuestion that resolved itself while the person was away (afkTimeoutMs) carries no press of
417// theirs: when it is the grill dialog, its answers are dropped.
418export function isAwayGrillAnswer(questions: readonly { header?: string; question: string }[], result: unknown): boolean {
419  const isGrill = questions.some(asked => asked.header === ASK_HEADER && asked.question.endsWith(ASK_TAIL))
420  return isGrill && (result as { afkTimeoutMs?: unknown } | null)?.afkTimeoutMs !== undefined
421}
422
423// what the refusal tells the model after a dialog that did not open the gate
424export function askedNote(answer: string): string {
425  if (answer === ASK_NOT_YET) return 'The user answered Not yet in the grill dialog: stop and wait for them.'
426  if (answer === '') {
427    return 'Nobody answered the grill dialog (dismissed, or it closed while the user was away): tell the user the pipeline waits on their confirm, and stop.'
428  }
429  return `Instead of choosing, the user wrote: "${answer.slice(0, 500)}". That does not open the gate: answer them, then call again.`
430}
431
432// what a QC pass still lacks since the last code change
433export function qcMissing(run: Run): string[] {
434  const evidence = qcEvidence(run)
435  return [
436    !evidence.review ? 'a review agent that finished after the last code change' : '',
437    !evidence.tests ? 'a green Odoo test run (more than 0 tests) after the last code change' : '',
438  ].filter(part => part !== '')
439}
440
441export function prRefusal(run: Run): string {
442  const missing = [...qcMissing(run), 'a pass recorded with mcp__pipeline-gates__qc_verdict']
443  return `pipeline-gates: gh pr create is refused until the QC gate passes; missing: ${missing.join(', ')}.`
444}
445
446// The QC verdict the pipeline records: a pass is taken only on its evidence.
447export function recordVerdict(run: Run, verdict: string, summary: string, now: number): Run | string {
448  if (verdict === 'blocking') {
449    const [next, seq] = bump(run)
450    return { ...next, qc: { isOpen: false, how: `blocking: ${summary}`, at: now }, qcSeq: seq }
451  }
452  if (verdict !== 'pass') return 'pipeline-gates: verdict must be pass or blocking.'
453  const missing = qcMissing(run)
454  if (missing.length > 0) return `pipeline-gates: the pass is refused; missing: ${missing.join(', ')}.`
455  const [next, seq] = bump(run)
456  return { ...next, qc: { isOpen: true, how: `pass: ${summary}`, at: now }, qcSeq: seq }
457}
458
459export const MAX_FIX_ROUNDS = 3
460
461// A fix round: dev work handed out in Phases 2-3 after a review finished since the last round began.
462// Several dev agents spawned for one round count once.
463export function isNewRound(run: Run): boolean {
464  return run.phase >= 2 && run.phase <= 3 && run.lastReview > (run.roundSeq ?? 0)
465}
466
467export function roundsLeft(run: Run): number {
468  return MAX_FIX_ROUNDS + (run.extraRounds ?? 0) - (run.fixRounds ?? 0)
469}
470
471export function startRound(run: Run): Run {
472  const [next, seq] = bump(run)
473  return { ...next, fixRounds: (run.fixRounds ?? 0) + 1, roundSeq: seq }
474}
475
476export function grantRounds(run: Run): Run {
477  return { ...run, extraRounds: (run.extraRounds ?? 0) + MAX_FIX_ROUNDS }
478}
479
480export function roundsLine(run: Run): string {
481  return `fix rounds: ${run.fixRounds ?? 0} of ${MAX_FIX_ROUNDS + (run.extraRounds ?? 0)}`
482}
483
484export function roundsRefusal(run: Run): string {
485  return `pipeline-gates: fix round ${(run.fixRounds ?? 0) + 1} is refused, the QC gate still blocks after ${run.fixRounds ?? 0} rounds. Stop and report to the user what still blocks, what keeps coming back, and the choice: narrow the design, split the rest into a follow-up task, or more rounds. Only the user grants more: /pipeline-gate open rounds <reason> (three more).`
486}
487
488// A finished agent re-reads its whole context on every call, and writes it to the cache again after a pause.
489export const RESUME_REFUSAL =
490  'pipeline-gates: a fix round goes to a fresh dev agent, not into one that already worked: spawn dev with a brief (the verified findings with their decisive lines, and `git diff --cached --stat <REVIEWED_TREE>` for what earlier rounds changed).'
491
492// SendMessage's `to`: a name or an agent id, with a " [ref]" a listing may have shown
493export function addressOf(to: unknown): string {
494  return typeof to === 'string' ? to.replace(/\s*\[[^\]]*\]\s*$/, '').trim() : ''
495}
496
497// A pipeline split over two sessions: the mother grills and closes, a child develops and opens the PR.
498// The child loads the skill as `child <TASK-KEYS>`. Every session's run sits in the mod's store under
499// run:<session id>, which is how one session reads another's.
500const CHILD_ARGS = /^\s*child\b/i
501
502export function isChildArgs(args: string): boolean {
503  return CHILD_ARGS.test(args)
504}
505
506// how a run names another session's run to the person: its task and the start of its session id
507export function runName(run: Run, sessionId: string): string {
508  return `the ${run.task || 'pipeline'} run of session ${sessionId.slice(0, 8)}`
509}
510
511// the keys a run works on: its task and its block's
512export function runKeys(run: Run): string[] {
513  return [...new Set([run.task, ...tasksOf(run).map(task => task.key)].filter(key => key !== ''))]
514}
515
516function isOfTasks(run: Run, keys: readonly string[]): boolean {
517  return keys.some(key => run.task === key || hasTask(run, key))
518}
519
520// A gate opened in that run itself: by the person's press or their /pipeline-gate open, the Teams
521// send, or a project with no status flow. A gate a run took from another one is never passed on.
522function isOpenedThere(gate: Gate | null): boolean {
523  return isOpen(gate) && gate?.from === undefined
524}
525
526// The run a child takes its gates from: in progress, working on `task` (its task or one of its
527// block), with the Teams status and the grill both opened there.
528export function isMotherRunFor(other: Run, task: string): boolean {
529  return isActive(other) && task !== '' && isOfTasks(other, [task]) && isOpenedThere(other.status) && isOpenedThere(other.grill)
530}
531
532// A child's run takes the status and grill gates the person opened in the mother, each naming the run
533// it came from; a gate the child opened itself stays as it is. The QC gate is never taken.
534export function takeGates(run: Run, mother: Run, motherId: string, now: number): Run {
535  const source = runName(mother, motherId)
536  const taken = (own: Gate | null, given: Gate | null): Gate | null =>
537    isOpen(own) || given === null ? own : { isOpen: true, how: `${given.how}, taken from ${source}`, at: now, from: motherId }
538  return { ...run, status: taken(run.status, mother.status), grill: taken(run.grill, mother.grill), mother: motherId }
539}
540
541// What lets a run close at Phase 7 without a QC pass of its own: another run for its tasks that
542// recorded a QC pass or a PR (the child of a mother that grilled and handed off).
543export function closesOn(other: Run, keys: readonly string[]): string {
544  if (!isOfTasks(other, keys)) return ''
545  if ((other.pr ?? '') !== '') return `PR ${other.pr}`
546  return isOpen(other.qc) ? `QC ${other.qc?.how ?? 'pass'}` : ''
547}
548
549function closureRefusal(run: Run): string {
550  const keys = runKeys(run).join(', ') || 'this task'
551  return `pipeline-gates: Phase 7 is refused until the QC gate passes in this run, or a run for ${keys} in another session recorded a QC pass or a PR; none has.`
552}
553
554// `closure`: the other run this one closes on, named for the person ('' when none was found)
555export function enterPhase(run: Run, phase: number, task: string, now: number, closure = ''): Run | string {
556  if (!Number.isInteger(phase) || phase < 0 || phase >= PHASES.length) return `phase must be 0 to ${PHASES.length - 1}`
557  if (phase >= 2 && closedForDev(run).length > 0) return devRefusal(run, `Phase ${phase}`)
558  const isClosure = phase === PHASES.length - 1
559  if (isClosure && !qcHolds(run) && closure === '') return closureRefusal(run)
560  if (phase >= 6 && !isClosure && !qcHolds(run)) return prRefusal(run)
561  // development entered anew (the next task of a block) counts its rounds afresh; back from QC it does not
562  const isNewCycle = phase === 2 && run.phase !== 2 && run.phase !== 3
563  return {
564    ...run,
565    ...(isNewCycle ? { fixRounds: 0, roundSeq: run.seq, extraRounds: 0 } : {}),
566    ...(isClosure && !qcHolds(run) ? { closedOn: closure } : {}),
567    task: task !== '' ? task : run.task,
568    phase,
569    phaseAt: run.phaseAt.map((at, i) => (i === phase && at === 0 ? now : at)),
570    isDone: phase === PHASES.length - 1,
571  }
572}
573
574export function openGate(run: Run, name: GateName, how: string, now: number): Run {
575  const gate: Gate = { isOpen: true, how, at: now }
576  if (name !== 'qc') return { ...run, [name]: gate }
577  const [next, seq] = bump(run)
578  return { ...next, qc: gate, qcSeq: seq }
579}
580
types/index.d.ts 54 lines
1export type GateName = 'status' | 'grill' | 'qc'
2
3// how a gate opened (or why the QC gate stays shut), and when; `from`: the session whose run a child
4// took the gate from (absent for a gate opened in this run)
5export type Gate = { isOpen: boolean; how: string; at: number; from?: string }
6
7// one task of the block a run works through, and where it stands; the agent moves it
8export type TaskState = 'pending' | 'active' | 'done'
9// `url`: the task's record in the production web client, '' or absent when none was given
10export type BlockTask = { key: string; title: string; state: TaskState; at: number; url?: string }
11
12// One pipeline run. The seq fields order what happened: a QC pass counts only when the review and
13// the green test run it rests on came after the last code change, and it holds only until the next.
14export type Run = {
15  task: string
16  startedAt: number
17  phase: number
18  phaseAt: number[]
19  status: Gate | null
20  grill: Gate | null
21  qc: Gate | null
22  qcSeq: number
23  seq: number
24  lastChange: number
25  lastReview: number
26  lastGreen: number
27  lastTests: string
28  blocked: { what: string; at: number }[]
29  // the block of tasks this run works through, one run for all of them (absent in a run stored earlier)
30  tasks?: BlockTask[]
31  // the grill dialog was declined or went unanswered: it asks again only after the person's next message
32  // (absent in a run stored before the dialog existed)
33  isAskMuted?: boolean
34  // fix rounds: dev work handed out after a review, the seq the last one began at, and the rounds the
35  // person granted beyond the first three (absent in a run stored before rounds were counted)
36  fixRounds?: number
37  roundSeq?: number
38  extraRounds?: number
39  // the pull request a gh pr create of this run printed (absent until one did)
40  pr?: string
41  // a child's run: the mother session whose open status and grill gates it took (absent elsewhere)
42  mother?: string
43  // a run closed at Phase 7 on another run's QC pass or PR, named for the person (absent otherwise)
44  closedOn?: string
45  // Phase 7 ends a run, and so does the person's /pipeline-gate end; the run stays, to say how it ended
46  isDone: boolean
47}
48
49declare module 'claude-code' {
50  interface PluginState {
51    'pipeline-gates': { run: Run | null }
52  }
53}
54