SLOPSHOPPER

AI-native SDLC

Hook-enforced approval gates for Claude Code: intent → spec → plan → build → verify → review, with a status bar and one-click approvals.

bandspinnerguardtoastprompttool
★ 3v0.10.0MITupdated 2026-10-22Sennjen/claude-sdlc/plugins/ai-sdlc
A shopper browsing a rack in a slop shop
README

AI-native SDLC for Claude Code and Codex

Claude Code writes code fast, and skips the parts of the job that keep a team safe: agreeing on what to build, writing it down, and waiting for a human to say yes. This plugin puts those steps back, and enforces them with hooks instead of asking nicely in a prompt.

Every change moves through Intent → Spec → Plan → Build → Verify → Review. Claude writes each artifact under docs/sdlc/<feature>/, and you approve it. Until the plan is approved, Claude cannot edit code. When it is done, the Definition of Done runs your verify commands, and independent code and security reviewer agents check the change before the PR.

The workflow follows the AI-native SDLC playbook from Anthropic Academy. This plugin is an independent project, not made or endorsed by Anthropic.

What you get

  • Approval gates. Only a message you type, sdlc approve intent|spec|plan, records an approval, with the artifact's sha256, your name and the time. Editing an approved artifact reopens its approval. Claude cannot approve for you.
  • A code gate. Code edits wait for an approved intent, spec and plan whose hashes still match. Small changes can skip the ceremony with sdlc trivial.
  • A Definition of Done. When code changed, the Stop hook runs your verify commands and sends Claude back on a failure.
  • Locked tests for bug fixes. Tests written to reproduce a bug stay read-only until you unlock them, so the fix cannot bend the tests.
  • Deploy and push gates. Merges, publishes, deploys and pushes to protected branches ask you first.
  • Independent reviewers. The sdlc-reviewer agent reviews the diff against the spec, the plan and your REVIEW.md with fresh context. The sdlc-security-reviewer agent checks it separately for vulnerabilities the change introduces.
  • A status bar. A band above the prompt shows the feature, its stage and the one action that moves it on, such as Approve spec. The prompt's typeahead completes sdlc ... commands.

Get started

claude plugin marketplace add Sennjen/claude-sdlc
claude plugin install ai-sdlc@ai-sdlc

Then run /ai-sdlc:init in your project. It detects the verify commands, adds a short CLAUDE.md section and REVIEW.md, and writes sdlc.config.json, the switch that turns the plugin on for that repository. Without sdlc.config.json the plugin does nothing. After a plugin update, /ai-sdlc:init update proposes what the new templates add to the project's REVIEW.md and sdlc.config.json, and keeps the project's own rules.

Requirements: Claude Code 2.1.293 or newer for the status bar (the gates work on older versions), python3 3.9 or newer, and git. The plugin is for Claude Code: it uses hooks, a bin/ command and a UI module, which claude.ai chat and Cowork don't load.

Codex

Register the repository's .agents/plugins/marketplace.json, install ai-sdlc@ai-sdlc, review and trust its hooks, then invoke $ai-sdlc:init in the target project. Codex uses AGENTS.md and an inline status block with contextual buttons in chat on clients with inline visualization support. Other clients use a text fallback. Use $ai-sdlc:status to refresh it. Old buttons expire when their displayed state changes. Protected edits and gated deploys are denied and require a user action outside the agent.

See the Codex guide for local installation and compatibility. The other sections of this README describe the Claude Code interface.

What the plugin runs, reads and stores

Everything runs on your machine. The plugin makes no network requests and sends no data anywhere.

  • Runs: python3 with the plugin's own scripts/sdlc.py from its hooks and its UI module; git to read the repository (git config user.name, diffs and hashes of the change); the verify commands you list in sdlc.config.json, through your shell, when a turn that changed code ends. When you click a file or PR link in the bar, it opens the file in the desktop app's Files pane, or runs open or xdg-open.
  • Reads: the repository, sdlc.config.json, and the output of the tools Claude runs, to find the URL from gh pr create or glab mr create.
  • Decides: its hooks allow, deny or ask about Claude's tool calls (the gates above). It never changes your Claude Code settings or permission mode.
  • Stores, inside your repository: the artifacts and approvals.json under docs/sdlc/, and its state in .sdlc/ (the active feature, per-session flags, the test lock, review verdicts, PR URLs and an audit.log). Approvals and the audit log record your git user name, or your OS user name when git has none, and the time.

More

The full documentation, with every gate, command and limit, is in the repository README. Report problems in GitHub Issues.

MIT License. See LICENSE.

Source 2 files
hooks/ui.tsx 999 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Approval, ExtraFiles, FeatureInfo, ReviewInfo, SdlcState, Stage, StageInfo } from '../types'
5
6// The gates stay in sdlc.py (command hooks). This module only shows their state and
7// sends user-only commands through the same UserPromptSubmit handler a typed
8// `sdlc approve ...` reaches, so approvals keep one code path and one audit trail.
9//
10// Two sites:
11// - the band above the prompt: feature, stage, status and the one action that fits now;
12// - `SDLC` in the prompt footer: unfolds the band into the details (every artifact with
13//   its state and a link that opens it, the session switches, the same actions, `Init`
14//   where the repository has no SDLC yet) and folds it back.
15// Actions that start a skill run its slash command at once, as if the person typed it.
16// Claude can only ask for a test unlock (the `request_test_unlock` tool); the person presses it.
17// The prompt's typeahead completes a typed `sdlc ...` command, and a terminal's native
18// notifications report what the person may be waiting on away from the screen.
19
20const REFRESH_MS = 10_000
21const STAGES: readonly Stage[] = ['intent', 'spec', 'plan']
22
23const stateAtom = atom({ plugin: 'ai-sdlc', key: 'state' } as const, null)
24const errorAtom = atom({ plugin: 'ai-sdlc', key: 'error' } as const, null)
25const busyAtom = atom({ plugin: 'ai-sdlc', key: 'busy' } as const, false)
26const filesAtom = atom({ plugin: 'ai-sdlc', key: 'files' } as const, {
27  progress: false,
28  approvals: false,
29  steps: { done: 0, total: 0 },
30})
31const detailsAtom = atom({ plugin: 'ai-sdlc', key: 'details' } as const, false)
32const hiddenAtom = atom({ plugin: 'ai-sdlc', key: 'hidden' } as const, false)
33const unlockAtom = atom({ plugin: 'ai-sdlc', key: 'unlockRequest' } as const, null)
34
35// The model's way to ask for the test lock to be lifted. It unlocks nothing: the band then
36// offers `Unlock tests`, and only the person's press (or typed command) unlocks. The verify
37// skill tells Claude to call it, so its schema sits in the tool list rather than behind
38// ToolSearch.
39const UNLOCK_TOOL = 'request_test_unlock'
40const UNLOCK_TOOL_SPEC = {
41  name: UNLOCK_TOOL,
42  isDeferred: false,
43  description:
44    'Ask the user to unlock the SDLC test lock. Call it when a locked test file has to change: ' +
45    'the test itself is wrong, or a review found cases that need new tests. It does not unlock ' +
46    'anything; the user presses "Unlock tests" in the SDLC bar or types `sdlc unlock tests`. ' +
47    'After calling it, stop and wait for the user.',
48  inputSchema: {
49    type: 'object',
50    properties: { reason: { type: 'string', description: 'Why the tests must change, in one sentence.' } },
51    required: ['reason'],
52  },
53}
54
55type On = Extract<SdlcState, { enabled: true }>
56type Steps = ExtraFiles['steps']
57type UnlockRequest = { reason: string } | null
58type Action = { key: string; label: string; run: () => unknown }
59
60const script = ($: EngineInterface) => `${$.plugin.root}/scripts/sdlc.py`
61const short = (sha: string | null | undefined) => (sha ? sha.slice(0, 12) : '-')
62const clock = (at: string | null | undefined) => (at ? at.replace('T', ' ').slice(0, 16) : '')
63const featureDir = (s: On) => (s.stages.intent?.path ?? '').replace(/\/intent\.md$/, '')
64const fileUrl = (root: string, rel: string) => `file://${encodeURI(`${root}/${rel}`)}`
65
66// ------------------------------------------------------------------- reading state
67
68let inflight: Promise<SdlcState | null> | null = null
69
70async function fetchState($: EngineInterface): Promise<SdlcState | null> {
71  const sid = await $.session.id()
72  const cwd = await $.session.cwd()
73  try {
74    const r = await $.process.run(['python3', script($), 'cli', 'state', '--session', sid], {
75      cwd,
76      env: { CLAUDE_PROJECT_DIR: cwd },
77      timeoutMs: 15_000,
78    })
79    if (r.exitCode !== 0) {
80      await update($, errorAtom, () => `sdlc.py state exited ${r.exitCode}: ${r.stderr.trim().slice(0, 200)}`)
81      return null
82    }
83    await update($, errorAtom, () => null)
84    return JSON.parse(r.stdout) as SdlcState
85  } catch (err) {
86    await update($, errorAtom, () => `cannot run sdlc.py: ${String(err).slice(0, 200)}`)
87    return null
88  }
89}
90
91const NO_STEPS = { done: 0, total: 0 }
92// plan.md lists its steps as `1. [ ] ...` under `## Work sequence` and is never edited
93// after approval; progress.md records a finished step as `- [x] Step 3: ...`.
94const PLAN_STEP = /^\s*(\d+)\.\s+\[[ xX]\]/gm
95const DONE_STEP = /^\s*-\s*\[[xX]\]\s*Step\s+(\d+)\b/gim
96
97/** Steps of the plan's work sequence, and how many of them progress.md marks done. */
98function countSteps(plan: string, progress: string): { done: number; total: number } {
99  const work = plan.split(/^##\s+/m).find(section => section.startsWith('Work sequence')) ?? ''
100  const numbers = [...work.matchAll(PLAN_STEP)].map(m => Number(m[1]))
101  const done = new Set([...progress.matchAll(DONE_STEP)].map(m => Number(m[1])).filter(n => numbers.includes(n)))
102  return { done: done.size, total: numbers.length }
103}
104
105async function statFiles($: EngineInterface, s: SdlcState): Promise<ExtraFiles> {
106  if (!s.enabled || !s.active) return { progress: false, approvals: false, steps: NO_STEPS }
107  const dir = `${s.root}/${featureDir(s)}`
108  const isFile = (name: string) =>
109    $.fs.stat(`${dir}/${name}`).then(
110      st => st.kind === 'file',
111      () => false,
112    )
113  const text = (name: string) => $.fs.read(`${dir}/${name}`).catch(() => '')
114  const steps = s.stage === 'build' ? countSteps(await text('plan.md'), await text('progress.md')) : NO_STEPS
115  return { progress: await isFile('progress.md'), approvals: await isFile('approvals.json'), steps }
116}
117
118/** A native notification through the person's own channel, for what they may be waiting on
119 *  away from the screen. Only a terminal has a channel (the desktop answers `no-surface`),
120 *  so it goes beside a toast, never in its place. */
121function notify($: EngineInterface, text: string) {
122  try {
123    void $.ui.notify(text, { title: 'SDLC' }).catch(() => undefined)
124  } catch {
125    // an engine before 2.1.295 has no $.ui.notify: the toast alone shows
126  }
127}
128
129function announce($: EngineInterface, prev: SdlcState | null, next: SdlcState) {
130  if (!prev || !prev.enabled || !next.enabled) return
131  if (prev.active === next.active) {
132    for (const stage of STAGES) {
133      if (prev.stages[stage]?.state === 'approved' && next.stages[stage]?.state === 'stale') {
134        $.ui.toast(`${stage}.md changed after approval: it needs a new approval`, { timeoutMs: 8000 })
135      }
136    }
137  }
138  if (prev.code_gate !== next.code_gate) {
139    $.ui.toast(next.code_gate === 'open' ? 'SDLC code gate is open' : 'SDLC code gate is closed')
140  }
141  const last = next.verify.last
142  if (last && last.at !== prev.verify.last?.at) {
143    $.ui.toast(last.ok ? 'SDLC verify passed' : 'SDLC verify failed: Definition of Done not met', {
144      timeoutMs: last.ok ? 4000 : 8000,
145    })
146    // A pass ends the turn, which the engine announces itself; a failure keeps Claude working.
147    if (!last.ok) notify($, 'Verify failed: the Definition of Done is not met')
148  }
149  if (prev.active !== next.active) return
150  announceReview($, 'review', prev.review, next.review, next)
151  announceReview($, 'security review', prev.security, next.security, next)
152  if (next.pr && next.pr.url !== prev.pr?.url) {
153    $.ui.toast(`PR created: ${next.pr.url}`, { timeoutMs: 8000 })
154    notify($, `PR created: ${next.pr.url}`)
155  }
156}
157
158/** A reviewer's new verdict, as a toast and a notification. The PR is next once both reviews
159 *  of the current code passed. */
160function announceReview($: EngineInterface, name: string, prev: ReviewInfo | null, next: ReviewInfo | null, s: On) {
161  if (!next || next.at === prev?.at) return
162  const what = next.verdict === 'changes' ? `${name}: changes required`
163    : reviewState(s) === 'ready' ? `${name} passed: the PR is next` : `${name} passed`
164  $.ui.toast(`SDLC ${what}`, { timeoutMs: 8000 })
165  notify($, what.charAt(0).toUpperCase() + what.slice(1))
166}
167
168/** The draft the person was last told about, so each version of an artifact is announced
169 *  once. A reload forgets it and announces the draft that waits once more. */
170let announcedDraft = ''
171
172/** At the end of Claude's turn: the stage's artifact, written or changed, waits for the
173 *  person's approval. */
174function announceDraft($: EngineInterface, s: SdlcState | null) {
175  if (!s || !s.enabled || !s.active || !s.stage || s.stage === 'build') return
176  const info = s.stages[s.stage]
177  if (!info?.sha256 || (info.state !== 'draft' && info.state !== 'stale')) return
178  const key = `${s.active}/${s.stage}/${info.sha256}`
179  if (key === announcedDraft) return
180  announcedDraft = key
181  notify($, `${s.stage}.md of ${s.active} waits for your approval`)
182}
183
184async function refresh($: EngineInterface): Promise<SdlcState | null> {
185  if (inflight) return inflight
186  inflight = (async () => {
187    try {
188      const next = await fetchState($)
189      if (!next) return null
190      const files = await statFiles($, next)
191      const prev = await read($, stateAtom)
192      announce($, prev, next)
193      // A band hidden with its × comes back when there is something new to do.
194      const where = (s: SdlcState | null) =>
195        s && s.enabled ? `${s.active}/${s.stage}/${s.stage_state}/${reviewState(s)}/${!!s.pr}` : ''
196      if (prev && where(prev) !== where(next)) await update($, hiddenAtom, () => false)
197      // A request ends once the tests are unlocked, by the button or a typed command.
198      if (!next.enabled || !next.tests_locked) await update($, unlockAtom, () => null)
199      await update($, filesAtom, () => files)
200      await update($, stateAtom, () => next)
201      return next
202    } finally {
203      inflight = null
204    }
205  })()
206  return inflight
207}
208
209// ------------------------------------------------------------------- user commands
210
211/** Runs a user-only `sdlc ...` command through sdlc.py's UserPromptSubmit handler. */
212async function runUserCommand($: EngineInterface, line: string): Promise<string | null> {
213  const sid = await $.session.id()
214  const cwd = await $.session.cwd()
215  const payload = { session_id: sid, cwd, hook_event_name: 'UserPromptSubmit', prompt: line }
216  try {
217    const r = await $.process.run(['python3', script($), 'hook', 'prompt'], {
218      cwd,
219      stdin: JSON.stringify(payload),
220      timeoutMs: 20_000,
221    })
222    if (r.exitCode !== 0 || !r.stdout.trim()) return null
223    const out = JSON.parse(r.stdout) as { hookSpecificOutput?: { additionalContext?: string } }
224    return out.hookSpecificOutput?.additionalContext?.split('\n')[0] ?? null
225  } catch {
226    return null
227  }
228}
229
230/** Presses a user command, tells the model what happened, and refreshes the view. */
231async function press($: EngineInterface, line: string): Promise<string | null> {
232  if (await read($, busyAtom)) return null
233  await update($, busyAtom, () => true)
234  try {
235    const msg = await runUserCommand($, line)
236    if (!msg) {
237      $.ui.toast(`sdlc: \`${line}\` failed; type it in the chat instead`, { timeoutMs: 8000 })
238      return null
239    }
240    // The record is already written; if the note to the model is refused, the model still
241    // reads the new state in the next prompt's [SDLC] status line.
242    try {
243      await $.session.append({
244        message: {
245          type: 'user',
246          content: [{ type: 'text', text: `${msg} (The user pressed \`${line}\` in the SDLC UI.)` }],
247        },
248      })
249    } catch {
250      // nothing to undo
251    }
252    $.ui.toast(msg.replace(/^\[SDLC\]\s*/, '').split('. ')[0] ?? msg)
253    await refresh($)
254    return msg
255  } finally {
256    await update($, busyAtom, () => false)
257  }
258}
259
260/** Folds and unfolds the band's details (SDLC in the footer, the feature's name); a band
261 *  hidden with its × comes back unfolded. */
262async function toggleDetails($: EngineInterface) {
263  void refresh($)
264  const wasHidden = await read($, hiddenAtom)
265  await update($, hiddenAtom, () => false)
266  await update($, detailsAtom, open => wasHidden || !open)
267}
268
269/** Puts a command in the prompt for the person to send; `hint` says what is left to type. */
270async function fillCommand($: EngineInterface, command: string, hint?: string) {
271  await update($, detailsAtom, () => false)
272  const filled = await $.prompt.fill({ text: `${command} ` })
273  $.ui.toast(filled.isFilled ? hint ?? `Press Enter to run ${command}` : `Type ${command} in the prompt`)
274}
275
276/** Runs a slash command as if the person typed it and pressed Enter (queued while a turn
277 *  runs); where it cannot run, puts it in the prompt instead. */
278async function runCommand($: EngineInterface, command: string, args = '') {
279  await update($, detailsAtom, () => false)
280  const typed = args ? `${command} ${args}` : command
281  $.ui.toast(`Running ${typed}`)
282  void $.command.run({ command: command.replace(/^\//, ''), args }).catch(() => fillCommand($, typed))
283}
284
285/** Shows one of the desktop's own panes (Files, Diff); false where there is none. */
286async function showPane($: EngineInterface, args: { pane: 'file' | 'diff'; path?: string }): Promise<boolean> {
287  try {
288    if (!(await $.mcp.call('ccd_view', 'show_pane', args)).isError) return true
289  } catch {
290    // not the desktop, or the server is not reachable this way
291  }
292  try {
293    const shown = (await $.tool.call({ tool: 'mcp__ccd_view__show_pane', ...args } as never)) as {
294      deny?: string
295      isError?: boolean
296    }
297    if (!shown.deny && !shown.isError) return true
298  } catch {
299    // no such tool: not the desktop
300  }
301  return false
302}
303
304/** Opens the session's changes in the desktop's Diff pane. */
305async function showChanges($: EngineInterface) {
306  if (!(await showPane($, { pane: 'diff' }))) $.ui.toast('The Diff pane is in the desktop app; run `git diff` here')
307}
308
309/** Opens a file in the desktop's Files pane; where there is none, in the host's default app. */
310async function openFile($: EngineInterface, path: string) {
311  if (await showPane($, { pane: 'file', path })) return
312  await openUrl($, path)
313}
314
315/** Opens a path or URL in the host's default app. */
316async function openUrl($: EngineInterface, target: string) {
317  for (const argv of [['open', target], ['xdg-open', target]]) {
318    try {
319      if ((await $.process.run(argv, { timeoutMs: 10_000 })).exitCode === 0) return
320    } catch {
321      // try the next opener
322    }
323  }
324  $.ui.toast(`Cannot open ${target}`, { timeoutMs: 8000 })
325}
326
327/** Approves the artifact as it was on screen: if the file changed since, nothing is approved. */
328async function approve($: EngineInterface, shown: Approval) {
329  const fresh = await refresh($)
330  const now = fresh && fresh.enabled ? fresh.stages[shown.stage] : undefined
331  if (!now || now.sha256 !== shown.sha256) {
332    $.ui.toast(`${shown.path} changed since it was shown. Review it again.`, { timeoutMs: 8000 })
333    return
334  }
335  await press($, `sdlc approve ${shown.stage}`)
336  const after = await read($, stateAtom)
337  const recorded = after && after.enabled ? after.stages[shown.stage]?.approved_sha256 : null
338  if (recorded && recorded !== shown.sha256) {
339    $.ui.toast(
340      `${shown.path} changed during approval: recorded ${short(recorded)}, shown ${short(shown.sha256)}`,
341      { timeoutMs: 10_000 },
342    )
343  }
344}
345
346/** Both reviews of the code as it is now: `changes` when either asks for changes, `ready`
347 *  when both passed, `none` otherwise (one never ran, or the code changed since). */
348function reviewState(s: On): 'ready' | 'changes' | 'none' {
349  const reviews = [s.review, s.security]
350  if (reviews.some(r => r?.current && r.verdict === 'changes')) return 'changes'
351  return reviews.every(r => r?.current && r.verdict === 'ready') ? 'ready' : 'none'
352}
353
354/** Whether every plan step is done; a plan without numbered steps counts as done when
355 *  verify passes. */
356const isBuilt = (s: On, steps: Steps) => (steps.total === 0 ? !!s.verify.last?.ok : steps.done >= steps.total)
357
358/** The one action that moves the feature on from where it stands. */
359function nextAction($: EngineInterface, s: On, steps: Steps = NO_STEPS): Action | null {
360  if (!s.active) {
361    if (s.fasttrack) return { key: 'fasttrack-off', label: 'End fast-track', run: () => press($, 'sdlc trivial off') }
362    return { key: 'start', label: 'Start feature', run: () => runCommand($, '/ai-sdlc:intent') }
363  }
364  if (s.stage === 'build') {
365    const build = (label: string): Action => ({ key: 'build', label, run: () => runCommand($, '/ai-sdlc:build') })
366    if (!isBuilt(s, steps)) {
367      if (steps.total === 0) return build('Build')
368      return build(steps.done === 0 ? 'Start building' : 'Continue building')
369    }
370    // A finished build goes through review, then the PR; the feature closes once the PR exists.
371    if (s.pr) return { key: 'done', label: 'Close feature', run: () => press($, 'sdlc done') }
372    const review = reviewState(s)
373    if (review === 'ready') return { key: 'pr', label: 'Create PR', run: () => runCommand($, '/ai-sdlc:review', 'pr') }
374    return {
375      key: 'review',
376      label: review === 'changes' ? 'Review again' : 'Review',
377      run: () => runCommand($, '/ai-sdlc:review'),
378    }
379  }
380  const stage = s.stage
381  const info = stage ? s.stages[stage] : undefined
382  if (!stage || !info) return null
383  if (info.state === 'missing') {
384    // The plan skill runs outside plan mode too: plan mode replaces the session's permission
385    // mode (a bypassPermissions session then asks about every Bash read), and the code gate
386    // already keeps code untouched until `sdlc approve plan`.
387    return { key: 'write', label: `Write ${stage}`, run: () => runCommand($, `/ai-sdlc:${stage}`) }
388  }
389  if ((info.state === 'draft' || info.state === 'stale') && info.sha256) {
390    const sha256 = info.sha256
391    return {
392      key: 'approve',
393      label: `${info.state === 'stale' ? 'Re-approve' : 'Approve'} ${stage}`,
394      run: () => approve($, { stage, path: info.path, sha256 }),
395    }
396  }
397  return null
398}
399
400// ---------------------------------------------------------------------- typeahead
401
402/** The `sdlc ...` commands only the person may send, as sdlc.py reads them. */
403const VERBS: readonly Suggestion[] = [
404  { text: 'approve', description: 'approve intent, spec or plan' },
405  { text: 'skip', description: 'skip the spec: sdlc skip spec <reason>' },
406  { text: 'trivial', description: 'fast-track a small change; off ends it' },
407  { text: 'unlock', description: 'unlock the test files' },
408  { text: 'feature', description: 'make another feature active' },
409  { text: 'done', description: 'close the active feature' },
410  { text: 'status', description: 'show the SDLC status' },
411]
412
413type Suggestion = { text: string; description?: string }
414
415/** Rows for the word being typed in a `sdlc ...` line: `sdlc`, the verb, then its one
416 *  argument, taken from the state the band shows. */
417function suggest(s: SdlcState | null, words: string[], token: string): Suggestion[] {
418  if (!s || !s.enabled) return []
419  const prefix = token.toLowerCase()
420  const starting = (rows: readonly Suggestion[]) => rows.filter(r => r.text.startsWith(prefix))
421  if (words.length === 0) {
422    return prefix.length >= 2 ? starting([{ text: 'sdlc', description: 'SDLC commands only you can send' }]) : []
423  }
424  if (words[0]?.toLowerCase() !== 'sdlc' || words.length > 2) return []
425  if (words.length === 1) return starting(VERBS)
426  switch (words[1]?.toLowerCase()) {
427    case 'approve':
428      return starting(STAGES.flatMap(stage => {
429        const info = s.stages[stage]
430        if (!info || info.state === 'missing' || info.state === 'skipped') return []
431        return [{ text: stage, description: stageValueText(info) }]
432      }))
433    case 'skip':
434      return starting([{ text: 'spec', description: 'then the reason' }])
435    case 'trivial':
436      return s.fasttrack ? starting([{ text: 'off', description: 'end fast-track' }]) : []
437    case 'unlock':
438      return starting([{ text: 'tests', description: s.tests_locked ? 'Locked' : 'not locked' }])
439    case 'feature':
440      return starting(otherFeatures(s).map(f => ({ text: f.slug, description: featureText(f) })))
441    default:
442      return []
443  }
444}
445
446export const register: Register = on => {
447  on('session.start', async ($, e, next) => {
448    const started = await next(e)
449    try {
450      await $.tool.register(UNLOCK_TOOL_SPEC)
451    } catch {
452      // an engine without plugin tools: the band simply never offers the request
453    }
454    await refresh($)
455    // The timer catches edits made outside the session (the person's editor). Where
456    // SDLC is off it idles; prompts and tool calls still notice a later /ai-sdlc:init.
457    $.clock.every(REFRESH_MS, () =>
458      void read($, stateAtom).then(s => (s && !s.enabled ? undefined : refresh($))),
459    )
460    return started
461  })
462
463  on('prompt.submit', async ($, e, next) => {
464    const result = await next(e)
465    void refresh($)
466    return result
467  })
468
469  on('tool.call', async ($, e, next) => {
470    if (e.tool === `mcp__${$.plugin.name}__${UNLOCK_TOOL}`) {
471      const s = await refresh($)
472      if (!s || !s.enabled || !s.tests_locked) return { result: 'The test files are not locked; nothing to ask.' }
473      const reason = String((e as { reason?: unknown }).reason ?? '').trim() || 'no reason given'
474      await update($, unlockAtom, () => ({ reason }))
475      await update($, hiddenAtom, () => false)
476      return {
477        result:
478          'The SDLC bar now asks the user to unlock the tests. Stop here and wait: tests stay ' +
479          'read-only until the [SDLC] status no longer says they are locked.',
480      }
481    }
482    const ran = await next(e)
483    if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'].includes(e.tool)) void refresh($)
484    return ran
485  })
486
487  on('turn.complete', async ($, e, next) => {
488    const result = await next(e)
489    // Only the main loop's answer ends Claude's work; a subagent's turn ends inside it.
490    const isMain = !e.agentId && e.reason === 'answer'
491    void refresh($).then(s => (isMain ? announceDraft($, s) : undefined))
492    return result
493  })
494
495  // The prompt's typeahead: the `sdlc ...` commands and their arguments, from the state
496  // the band already holds, beneath the engine's own rows.
497  on('prompt.autocomplete', async ($, e, next) => {
498    const result = await next(e)
499    const words = e.text.slice(0, e.start).trim().split(/\s+/).filter(Boolean)
500    const mine = suggest(await read($, stateAtom), words, e.token)
501    return mine.length > 0 ? { suggestions: [...result.suggestions, ...mine] } : result
502  })
503
504  // The prompt footer: the session modes as the engine draws them, then `SDLC`,
505  // which unfolds the band above the prompt into the details and folds it back.
506  on('ui.render', { component: 'SessionMode' }, async ($, e) => {
507    const { Box, Text, Button } = $.ui.resolve(e)
508    const modes = e.props.modes
509    return (
510      <Box gap={1}>
511        {modes.length > 0 ? <Text dimColor>{modes.join(' & ')}</Text> : null}
512        <Button
513          key="sdlc"
514          label="SDLC"
515          plain
516          onPress={() => toggleDetails($)}
517        />
518      </Box>
519    )
520  })
521
522  // The band: one row (feature, stage, status, next action), or the details.
523  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
524    if (e.props.hasSurvey) return next(e)
525    const s = await read($, stateAtom)
526    const error = await read($, errorAtom)
527    const isOpen = await read($, detailsAtom)
528    if (!isOpen && (!s || !s.enabled || (await read($, hiddenAtom)))) return next(e)
529
530    const els = {
531      ...($.ui.resolve(e) as Elements),
532      surface: e.surface,
533      columns: e.props.bodyColumns,
534      isWorking: e.props.isWorking,
535    }
536    const busy = await read($, busyAtom)
537    const files = await read($, filesAtom)
538    const steps = files.steps
539    const unlock = await read($, unlockAtom)
540    if (!isOpen && s && s.enabled) {
541      return (
542        <els.Box gap={1}>
543          {Summary(els, $, s, steps)}
544          {ActionRow(els, $, s, busy, steps, unlock)}
545          <els.Button key="hide" label="×" role="dismiss" onPress={() => update($, hiddenAtom, () => true)} />
546        </els.Box>
547      )
548    }
549    return Details(els, $, s, error, busy, files, unlock)
550  })
551}
552
553// ---------------------------------------------------------------------- drawing
554
555// The element constructors come from `$.ui.resolve(e)`; each part takes them as its
556// first argument so one tree draws on every surface. The desktop gets vector bars and
557// rules, as its own popovers draw them; the terminal gets text.
558type Elements = { Box: any; Text: any; Button: any; Markdown: any; Svg?: any }
559type Els = Elements & { surface: string; columns: number; isWorking: boolean }
560
561/** Actions that record a decision about a file: held while Claude's turn runs, since the
562 *  file may still be half written (a typed `sdlc approve` waits for the turn the same way). */
563const HELD_WHILE_WORKING = new Set(['approve', 'done'])
564const isHeld = (els: Els, key: string) => els.isWorking && HELD_WHILE_WORKING.has(key)
565
566/** A button that reads as disabled (the API has no `disabled`): dim, and a press only says
567 *  why. Otherwise the button runs `run`, once at a time. */
568function ActionButton(els: Els, $: EngineInterface, a: { key: string; label: string; run: () => unknown },
569  hotkey: string, isPrimary: boolean, busy: boolean) {
570  const { Button } = els
571  if (isHeld(els, a.key)) {
572    return (
573      <Button key={a.key} label={a.label} dimColor
574        onPress={() => $.ui.toast('Available when Claude finishes the current turn')} />
575    )
576  }
577  return (
578    <Button
579      key={a.key}
580      label={busy && a.key === 'approve' ? 'Approving…' : a.label}
581      {...keys(els, hotkey, isPrimary)}
582      onPress={() => (busy ? undefined : a.run())}
583    />
584  )
585}
586
587/** A hotkey and the accent where they help: the terminal. The desktop draws its own quiet
588 *  buttons, as it draws Create PR: no accent and no key badge. */
589const keys = (els: Els, hotkey: string, isPrimary = false) =>
590  els.surface === 'terminal'
591    ? { ...(hotkey ? { hotkey } : {}), variant: isPrimary ? ('primary' as const) : undefined }
592    : {}
593
594const STAGE_NAME: Record<Stage | 'build', string> = { intent: 'Intent', spec: 'Spec', plan: 'Plan', build: 'Build' }
595const STATE_WORD: Record<string, string> = {
596  approved: 'Approved',
597  skipped: 'Skipped',
598  draft: 'Draft',
599  stale: 'Changed',
600  missing: 'Not started',
601}
602// Status words take the person's theme colors (theme keys), so they read in a light, dark or
603// colorblind-friendly theme alike. The desktop's vector bars and rules draw in their own colors.
604const ERROR = 'error'
605const WARNING = 'warning'
606const ACCENT = '#5b8def'
607const TRACK = 'rgba(128,128,128,0.28)'
608
609/** Where the active feature stands, in words: "Spec · waiting for approval". */
610function whereText(s: On, steps: Steps = NO_STEPS): string {
611  if (!s.active) return s.fasttrack ? 'Fast-track on' : 'No active feature'
612  if (s.stage === 'build' && isBuilt(s, steps)) {
613    if (s.pr) return 'Build · PR created'
614    if (reviewState(s) === 'ready') return 'Build · review passed'
615  }
616  if (s.stage === 'build' && steps.total > 0) return `Build · ${steps.done}/${steps.total} steps`
617  if (s.stage === 'build') return `Build · ${s.verify.last?.ok ? 'verify passed' : 'in progress'}`
618  const doing = s.stage_state === 'missing' ? 'not started'
619    : s.stage_state === 'stale' ? 'changed after approval' : 'waiting for approval'
620  return `${STAGE_NAME[s.stage ?? 'intent']} · ${doing}`
621}
622
623/** The band's one row: feature, where it stands (the current artifact a link that opens
624 *  it in the Files pane), a warning when one applies. */
625function Summary(els: Els, $: EngineInterface, s: On, steps: Steps) {
626  const { Box, Text } = els
627  // One or two words: a longer note pushes the band's button onto a second line, and the
628  // reason for an unlock request is already in the chat.
629  const warn = s.verify.last && !s.verify.last.ok ? 'verify failed'
630    : s.stage === 'build' && !s.pr && reviewState(s) === 'changes' ? 'changes required'
631    : s.tests_locked ? 'tests locked' : ''
632  const info = s.stage && s.stage !== 'build' ? s.stages[s.stage] : undefined
633  const isFile = !!info && (info.state === 'draft' || info.state === 'stale')
634  const where = whereText(s, steps)
635  return (
636    <Box gap={1} flexShrink={1} flexGrow={1}>
637      {s.active ? TitleButton(els, $, s.active) : null}
638      {isFile && info ? FileName(els, $, s.root, info.path, true) : null}
639      <Text dimColor wrap="truncate-end">
640        {isFile ? where.slice(where.indexOf('·')) : where}
641      </Text>
642      {warn ? (
643        <Text color={warn === 'tests locked' ? WARNING : ERROR} wrap="truncate-end">
644          {warn}
645        </Text>
646      ) : null}
647    </Box>
648  )
649}
650
651/** The one button for the next action; it runs at once. */
652function ActionRow(els: Els, $: EngineInterface, s: On, busy: boolean, steps: Steps, unlock: UnlockRequest) {
653  const { Box } = els
654  // Claude asked for the locked tests to be unlocked: that is what the build waits on now.
655  // Otherwise a lock is part of the plan (bug-fix flow) and the next build action leads.
656  const action = unlock && s.tests_locked
657    ? { key: 'unlock', label: 'Unlock tests', run: () => press($, 'sdlc unlock tests') }
658    : nextAction($, s, steps)
659  // With no feature there are two ways in: a feature, or a small change on fast-track.
660  const list = [action, !s.active && !s.fasttrack ? fastTrackAction($) : null].filter((a): a is Action => !!a)
661  if (list.length === 0) return null
662  return <Box gap={1}>{list.map((a, i) => ActionButton(els, $, a, i === 0 ? 'a' : 't', i === 0, busy))}</Box>
663}
664
665/** A small change without intent, spec and plan: the person types what it is. */
666function fastTrackAction($: EngineInterface): Action {
667  return {
668    key: 'fasttrack',
669    label: 'Fast-track',
670    run: () => fillCommand($, 'sdlc trivial', 'Type what the small change is, then press Enter'),
671  }
672}
673
674/** A section's title: bold, in the text colour, so it reads as the head of its table
675 *  rather than as one more grey value. */
676function SectionTitle({ Text }: Els, title: string) {
677  return (
678    <Text key={`title-${title}`} bold>
679      {title}
680    </Text>
681  )
682}
683
684/** A thin rule across the body. */
685function Rule({ Svg, Text, surface, columns }: Els, key: string) {
686  if (surface === 'desktop' && Svg) {
687    return (
688      <Svg
689        key={key}
690        alt=""
691        source={`<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="1" viewBox="0 0 1000 1"><rect width="1000" height="1" fill="${TRACK}"/></svg>`}
692      />
693    )
694  }
695  return <Text dimColor>{'─'.repeat(Math.max(8, Math.min(columns, 80)))}</Text>
696}
697
698/** Four segments, intent to build: done in the accent, the current one faint, the rest track. */
699function StageBar({ Svg, Text, surface }: Els, s: On) {
700  const levels = [...STAGES, 'build' as const].map(stage => {
701    const isCurrent = s.stage === stage
702    if (stage === 'build') return isCurrent ? (s.verify.last?.ok ? 1 : 0.4) : 0
703    const state = s.stages[stage]?.state
704    return state === 'approved' || state === 'skipped' ? 1 : isCurrent ? 0.4 : 0
705  })
706  const alt = `Stages: ${[...STAGES, 'build'].map((st, i) => `${st} ${levels[i] === 1 ? 'done' : levels[i] ? 'current' : 'to do'}`).join(', ')}`
707  if (surface === 'desktop' && Svg) {
708    const W = 1000
709    const GAP = 10
710    const w = (W - GAP * 3) / 4
711    const rects = levels
712      .map((level, i) => {
713        const x = i * (w + GAP)
714        const fill = level ? ACCENT : TRACK
715        const opacity = level === 1 || !level ? 1 : level
716        return `<rect x="${x}" y="0" width="${w}" height="6" rx="3" fill="${fill}" fill-opacity="${opacity}"/>`
717      })
718      .join('')
719    return (
720      <Svg
721        key="stages"
722        alt={alt}
723        source={`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="6" viewBox="0 0 ${W} 6">${rects}</svg>`}
724      />
725    )
726  }
727  return (
728    <Text>
729      {[...STAGES, 'build' as const].map((stage, i) => (
730        <Text key={stage} dimColor={!levels[i]} bold={levels[i] === 0.4}>
731          {i ? '  ›  ' : ''}
732          {STAGE_NAME[stage]}
733        </Text>
734      ))}
735    </Text>
736  )
737}
738
739/** The title row: the title (it folds the details) at the left, the close mark at the right. */
740function Head(els: Els, $: EngineInterface, title: string, close: unknown) {
741  return (
742    <els.Box key="head" justifyContent="space-between" gap={2}>
743      {TitleButton(els, $, title)}
744      {close}
745    </els.Box>
746  )
747}
748
749/** The feature's name as a button that folds and unfolds the details, as SDLC in the footer
750 *  does. `plain` draws it as text, with a plate only under the pointer. */
751function TitleButton({ Box, Button, surface }: Els, $: EngineInterface, title: string) {
752  const button = <Button key="feature" label={title} plain onPress={() => toggleDetails($)} />
753  // The desktop pads a button for its hover plate; pull it back so the name lines up with
754  // the text under it. The terminal draws a plain button with no padding.
755  return surface === 'desktop' ? <Box key="feature-box" marginLeft={TITLE_INSET}>{button}</Box> : button
756}
757
758/** The desktop's horizontal padding of a plain button, in cells (about 6 px). */
759const TITLE_INSET = -0.75
760
761/** One row of a section's table: what, and its state. */
762type Line = { key: string; label: unknown; labelText: string; value: unknown; valueText: string }
763
764/** A titled table. Its label and value columns are as wide as their longest entry, so the
765 *  states line up; `minWidth` lets sections sit side by side and wrap when room runs out. */
766function Section(els: Els, key: string, title: string, lines: Line[]) {
767  const { Box, Text } = els
768  const labelWidth = Math.max(...lines.map(l => l.labelText.length)) + 3
769  const valueWidth = Math.max(...lines.map(l => l.valueText.length)) + 3
770  return (
771    <Box key={key} flexDirection="column" flexShrink={0} minWidth={labelWidth + valueWidth}>
772      {SectionTitle(els, title)}
773      {lines.map(l => (
774        <Box key={l.key}>
775          <Box width={labelWidth} flexShrink={0}>
776            {typeof l.label === 'string' ? <Text wrap="truncate-end">{l.label}</Text> : l.label}
777          </Box>
778          <Box width={valueWidth} flexShrink={0}>
779            {typeof l.value === 'string' ? <Text dimColor wrap="truncate-end">{l.value}</Text> : l.value}
780          </Box>
781        </Box>
782      ))}
783    </Box>
784  )
785}
786
787/** Features beside the active one that are not closed: the ones `sdlc feature` switches to. */
788function otherFeatures(s: On): FeatureInfo[] {
789  return s.features.filter(f => f.slug !== s.active && !f.done)
790}
791
792/** Where another feature stands, in words: "Spec · Draft". */
793function featureText(f: FeatureInfo): string {
794  return `${STAGE_NAME[f.stage]}${f.stage_state ? ` · ${STATE_WORD[f.stage_state] ?? f.stage_state}` : ''}`
795}
796
797/** The other features, one Button a row that makes its feature active. The name is the
798 *  row's address and its stage a dim part, so a stage that moves keeps the address. The
799 *  terminal draws each in brackets, so it reads as a control; the desktop as a list row. */
800function OtherFeatures(els: Els, $: EngineInterface, features: FeatureInfo[], busy: boolean) {
801  const { Box, Text, Button } = els
802  return (
803    <Box key="others" flexDirection="column" flexShrink={0}>
804      {SectionTitle(els, 'Other features')}
805      <Box flexDirection="column" alignItems="flex-start" rowGap={els.surface === 'desktop' ? 0.5 : 0}>
806        {features.map(f => (
807          <Button key={`activate-${f.slug}`} label={`Make ${f.slug} active`}
808            {...(els.surface === 'desktop' ? { plain: true } : {})}
809            onPress={() => (busy ? undefined : press($, `sdlc feature ${f.slug}`))}>
810            {f.slug} <Text dimColor>{featureText(f)}</Text>
811          </Button>
812        ))}
813      </Box>
814    </Box>
815  )
816}
817
818/** A file name: a link that opens it when it exists, quiet text when it does not. */
819function FileName({ Markdown, Text }: Els, $: EngineInterface, root: string, rel: string, exists: boolean) {
820  const name = rel.split('/').pop() ?? rel
821  if (!exists) return <Text dimColor>{name}</Text>
822  return (
823    <Markdown
824      key={`open-${name}`}
825      text={`[${name}](${fileUrl(root, rel)})`}
826      onLinkPress={() => void openFile($, `${root}/${rel}`)}
827    />
828  )
829}
830
831/** An artifact's state in one word; who approved or why it was skipped is in approvals.json. */
832function stageValueText(info: StageInfo | undefined): string {
833  const state = info?.state ?? 'missing'
834  return STATE_WORD[state] ?? state
835}
836
837/** The unfolded band, laid out as the desktop's own popovers are: Artifacts and Status
838 *  side by side where the band is wide enough, one under the other where it is not. */
839function Details(
840  els: Els,
841  $: EngineInterface,
842  s: SdlcState | null,
843  error: string | null,
844  busy: boolean,
845  files: ExtraFiles,
846  unlock: UnlockRequest = null,
847) {
848  const { Box, Text, Button } = els
849  const close = (
850    <Button key="close" label="×" role="dismiss" onPress={() => update($, detailsAtom, () => false)} />
851  )
852  if (error) {
853    return (
854      <Box flexDirection="column" gap={1}>
855        {Head(els, $, 'SDLC', close)}
856        <Text color={ERROR}>{error}</Text>
857        <Box>
858          <Button key="retry" label="Retry" {...keys(els, 'r')} onPress={() => void refresh($)} />
859        </Box>
860      </Box>
861    )
862  }
863  if (!s) return <Text dimColor>Reading SDLC state…</Text>
864  if (!s.enabled) {
865    return (
866      <Box flexDirection="column" gap={1}>
867        {Head(els, $, 'SDLC', close)}
868        <Text dimColor>Not enabled in this repository. Init detects the verify commands and adds</Text>
869        <Text dimColor>sdlc.config.json, a CLAUDE.md section, REVIEW.md and docs/sdlc/.</Text>
870        <Box>
871          <Button key="init" label="Init SDLC" {...keys(els, 'i', true)} onPress={() => runCommand($, '/ai-sdlc:init')} />
872        </Box>
873      </Box>
874    )
875  }
876
877  const dir = featureDir(s)
878  const action = nextAction($, s, files.steps)
879
880  const artifacts: Line[] = STAGES.map(stage => {
881    const info = s.stages[stage]
882    const exists = !!info && info.state !== 'missing' && info.state !== 'skipped'
883    const valueText = stageValueText(info)
884    return {
885      key: stage,
886      label: FileName(els, $, s.root, info?.path ?? `${dir}/${stage}.md`, exists),
887      labelText: `${stage}.md`,
888      value: info?.state === 'stale' ? <Text color={WARNING}>{valueText}</Text> : valueText,
889      valueText,
890    }
891  })
892  if (files.progress) {
893    artifacts.push({ key: 'progress', label: FileName(els, $, s.root, `${dir}/progress.md`, true),
894      labelText: 'progress.md', value: 'Build log', valueText: 'Build log' })
895  }
896  if (files.approvals) {
897    artifacts.push({ key: 'approvals', label: FileName(els, $, s.root, `${dir}/approvals.json`, true),
898      labelText: 'approvals.json', value: 'Audit trail', valueText: 'Audit trail' })
899  }
900
901  const last = s.verify.last
902  const verify = s.verify.commands.length === 0 ? 'Not configured'
903    : last ? `${last.ok ? 'Passed' : 'Failed'} ${clock(last.at).slice(11)}` : 'Not run yet'
904  const gate = s.code_gate === 'open' ? 'Open' : 'Closed'
905  const progressText = files.steps.total > 0 && s.stage === 'build'
906    ? `${files.steps.done}/${files.steps.total} steps`
907    : null
908  const status: Line[] = [
909    ...(progressText
910      ? [{ key: 'building', label: 'Building', labelText: 'Building', value: progressText, valueText: progressText }]
911      : []),
912    { key: 'gate', label: 'Code gate', labelText: 'Code gate', value: gate, valueText: gate },
913    { key: 'verify', label: 'Verify', labelText: 'Verify',
914      value: last && !last.ok ? <Text color={ERROR}>{verify}</Text> : verify, valueText: verify },
915  ]
916  if (s.stage === 'build') {
917    const reviewLine = (key: string, label: string, info: ReviewInfo | null): Line => {
918      const text = !info ? 'Not run' : !info.current ? 'Out of date'
919        : info.verdict === 'ready' ? 'Passed' : 'Changes required'
920      const failed = !!info?.current && info.verdict === 'changes'
921      return { key, label, labelText: label, value: failed ? <Text color={ERROR}>{text}</Text> : text, valueText: text }
922    }
923    status.push(reviewLine('review', 'Review', s.review), reviewLine('security', 'Security', s.security))
924  }
925  if (s.pr) {
926    const url = s.pr.url
927    const prText = `#${url.split('/').pop() ?? ''}`
928    status.push({ key: 'pr', label: 'PR', labelText: 'PR', valueText: prText,
929      value: <els.Markdown key="pr-link" text={`[${prText}](${url})`} onLinkPress={() => void openUrl($, url)} /> })
930  }
931  if (s.fasttrack) {
932    status.push({ key: 'fasttrack', label: 'Fast-track', labelText: 'Fast-track', value: 'On', valueText: 'On' })
933  }
934  if (s.tests_locked) {
935    // A short value keeps the three sections side by side; the warning color marks Claude's
936    // unlock request.
937    status.push({ key: 'tests', label: 'Tests', labelText: 'Tests',
938      value: unlock ? <Text color={WARNING}>Locked</Text> : 'Locked', valueText: 'Locked' })
939  }
940
941  // What the person can do now, one button per line.
942  const actions: { key: string; label: string; run: () => unknown; hotkey: string }[] = []
943  if (action) {
944    const label = busy && action.key === 'approve' ? 'Approving…' : action.label
945    actions.push({ key: action.key, label, run: action.run, hotkey: 'a' })
946  }
947  const verified = !!s.verify.last?.ok
948  const steps = files.steps
949  const building = s.active && s.stage === 'build'
950  // With numbered plan steps the build's progress decides; without, the verify result does.
951  const started = steps.total === 0 || steps.done > 0
952  const finished = isBuilt(s, steps)
953  if (building && started && !verified) {
954    actions.push({ key: 'verify', label: 'Run verify', hotkey: 'v', run: () => runCommand($, '/ai-sdlc:verify') })
955  }
956  if (building && started) {
957    actions.push({ key: 'changes', label: 'Show changes', hotkey: 'd', run: () => showChanges($) })
958  }
959  if (building && started && (steps.total > 0 || verified) && action?.key !== 'review') {
960    actions.push({ key: 'review', label: 'Review', hotkey: 'r', run: () => runCommand($, '/ai-sdlc:review') })
961  }
962  if (building && finished && action?.key !== 'done') {
963    actions.push({ key: 'done', label: 'Close feature', hotkey: 'c', run: () => press($, 'sdlc done') })
964  }
965  if (s.tests_locked) actions.push({ key: 'unlock', label: 'Unlock tests', run: () => press($, 'sdlc unlock tests'), hotkey: 'u' })
966  if (s.fasttrack && action?.key !== 'fasttrack-off') {
967    actions.push({ key: 'fasttrack-end', label: 'End fast-track', run: () => press($, 'sdlc trivial off'), hotkey: 'f' })
968  }
969  if (!s.active && !s.fasttrack) actions.push({ ...fastTrackAction($), hotkey: 't' })
970  const others = otherFeatures(s)
971
972  return (
973    <Box flexDirection="column" gap={1}>
974      <Box flexDirection="column">
975        {Head(els, $, s.active ?? 'SDLC', close)}
976        <Text dimColor>{whereText(s, files.steps)}</Text>
977      </Box>
978      {s.active ? StageBar(els, s) : null}
979      {Rule(els, 'rule')}
980      <Box flexWrap="wrap" columnGap={6} rowGap={1}>
981        {s.active ? Section(els, 'artifacts', 'Artifacts', artifacts) : null}
982        {Section(els, 'status', 'Status', status)}
983        {actions.length > 0 ? (
984          // A column of buttons. The desktop lays a row out a whole line tall, so the buttons
985          // stand half a row apart there; the terminal's bracketed buttons need no gap.
986          <Box key="actions" flexDirection="column" flexShrink={0}
987            minWidth={Math.max(...actions.map(a => a.label.length)) + 6}>
988            {SectionTitle(els, 'Actions')}
989            <Box flexDirection="column" alignItems="flex-start" rowGap={els.surface === 'desktop' ? 0.5 : 0}>
990              {actions.map((a, i) => ActionButton(els, $, a, a.hotkey, i === 0, busy))}
991            </Box>
992          </Box>
993        ) : null}
994        {others.length > 0 ? OtherFeatures(els, $, others, busy) : null}
995      </Box>
996    </Box>
997  )
998}
999
types/index.d.ts 78 lines
1export type Stage = 'intent' | 'spec' | 'plan'
2
3export type StageState = 'missing' | 'draft' | 'approved' | 'stale' | 'skipped'
4
5export type StageInfo = {
6  state: StageState
7  path: string
8  sha256: string | null
9  approved_sha256: string | null
10  by: string | null
11  at: string | null
12  reason: string | null
13}
14
15export type FeatureInfo = {
16  slug: string
17  stage: Stage | 'build'
18  stage_state: StageState | null
19  done: boolean
20}
21
22export type VerifyRun = { ok: boolean; at: string | null; report: string | null }
23
24/** A reviewer's last verdict for the active feature (sdlc-reviewer for `review`,
25 *  sdlc-security-reviewer for `security`); `current` while the code it read is unchanged. */
26export type ReviewInfo = { verdict: 'ready' | 'changes'; at: string | null; current: boolean }
27
28/** The PR (or MR) the agent opened for the active feature. */
29export type PrInfo = { url: string; at: string | null }
30
31/** What `sdlc.py cli state --session <id>` prints. */
32export type SdlcState =
33  | { enabled: false }
34  | {
35      enabled: true
36      root: string
37      active: string | null
38      stage: Stage | 'build' | null
39      stage_state: StageState | null
40      stage_label: string | null
41      next_skill: string | null
42      code_gate: 'open' | 'closed'
43      artifact: string | null
44      stages: Partial<Record<Stage, StageInfo>>
45      features: FeatureInfo[]
46      tests_locked: boolean
47      fasttrack: { by: string; at: string; reason: string } | null
48      verify: { commands: string[]; last: VerifyRun | null }
49      review: ReviewInfo | null
50      security: ReviewInfo | null
51      pr: PrInfo | null
52      done?: boolean
53    }
54
55/** An artifact as it was on screen when the person pressed Approve. */
56export type Approval = { stage: Stage; path: string; sha256: string }
57
58/** Feature files beside the stage artifacts that `state` does not report, and the build's
59 *  progress: plan steps done (marked in progress.md) of the plan's total. */
60export type ExtraFiles = { progress: boolean; approvals: boolean; steps: { done: number; total: number } }
61
62declare module 'claude-code' {
63  interface PluginState {
64    'ai-sdlc': {
65      state: SdlcState | null
66      error: string | null
67      busy: boolean
68      files: ExtraFiles
69      /** Whether `SDLC` in the footer unfolded the band into the details. */
70      details: boolean
71      /** Whether the person hid the band with its ×; a new stage or status shows it again. */
72      hidden: boolean
73      /** Claude asked (request_test_unlock) for the locked tests to be unlocked, and why. */
74      unlockRequest: { reason: string } | null
75    }
76  }
77}
78