SLOPSHOPPER

sdlc-monitor

SDLC control pane: start, watch, answer and stop pipelines (/sdlc-monitor)

panebandguardcommandtoaststatus
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sdlc-monitor
│ ┃ SDLC control ✕ › fix the failing auth test and add an audit log call │ ┃ SDLC control 0 running · 0 paused · up to 2 │ ┃ [ ◀ ] [ ▶ ] columns 1-2 of 7 [ Run selected ⏺ Read(src/auth.ts) │ ┃ ┌─────────────────────────┐ ┌─────────────── ⎿ Read 6 lines │ ┃ │ Backlog 0 │ │ Spec ⏺ Update(src/auth.ts) │ ┃ │ Nothing pending │ │ nothing here ⎿ 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 │ ┃ │ ┃ › /sdlc-monitor │ ┃ ⎿ sdlc-monitor: SDLC control opened: 0 running · 0 paused, 0 pendi │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ [ SDLC ] [ CONFIG ] 0 pending ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
[ SDLC ] [ CONFIG ] 0 pending
Pane · SDLC control
SDLC control 0 running · 0 paused · up to 2 at once [ Refre [ ◀ ] [ ▶ ] columns 1-2 of 7 [ Run selected (0) ] [ Clear ] ┌─────────────────────────┐ ┌─────────────────────────┐ │ Backlog 0 │ │ Spec 0 │ │ Nothing pending │ │ nothing here │ └─────────────────────────┘ └─────────────────────────┘
Pane · CONFIG
CONFIG [ Add provider ] model list --json: unexpected output
README

production-retail-and-wholesale

Supports production, sales, billing and inventory management.

See AGENTS.md for the implementation plan, provisioning details and contribution guidelines.

API Documentation & Swagger UI

API documentation is available via Swagger UI. The OpenAPI specification is generated from JSDoc comments in server/index.js.

A pre-commit hook is configured to automatically generate or update the tools/openapi-spec.json file whenever changes to server/index.js are committed. This ensures the specification is always up-to-date with the code.

To view the Swagger UI locally:

  1. Ensure the specification is generated: If you haven't made a commit yet or want to manually regenerate: ``bash npm run generate-spec ` Alternatively, committing any change to server/index.js` will trigger the pre-commit hook.
  1. Start the main API server: This server runs the actual API endpoints. ``bash cd server npm start ` This usually runs on http://localhost:3000`.
  1. Start the Swagger UI server: In a separate terminal, run: ``bash npm run start:swagger ` This server is dedicated to serving the Swagger UI and typically runs on http://localhost:3001`.
  1. Access the UI: Open your browser and navigate to http://localhost:3001/docs.

Logging

The server logs with pino. Requires Node 22 or later.

  • JSON output (Kubernetes/GKE): one JSON object per line on stdout with severity (pino trace/debug → DEBUG, info → INFO, warn → WARNING, error → ERROR, fatal → CRITICAL), message, an ISO timestamp, serviceContext and httpRequest for requests. The GKE logging agent reads it as jsonPayload with severity. Query problems with severity>=WARNING.
  • Pretty output locally: human-readable lines. LOG_FORMAT=json|pretty forces a format; otherwise JSON is used when KUBERNETES_SERVICE_HOST is set or NODE_ENV=production, else pretty.
  • LOG_LEVEL: trace, debug, info (default) or warn. The level never goes below warn: error, fatal, silent and unknown values fall back to warn.
  • X-Request-Id: every response carries it. A valid incoming value is reused, otherwise a UUID is generated. Error entries carry the same id.
  • Trace correlation: set GOOGLE_CLOUD_PROJECT in the Deployment so X-Cloud-Trace-Context is linked to the entry.
  • Tests: logs are discarded under Jest unless LOG_IN_TESTS=1.
  • Request bodies, headers, cookies and query strings are never logged.

Graft setup (required for the SDLC workflow)

The Plan stage of scripts/sdlc.sh and the /plan command use graft, a prebuilt code graph, to find the files a change touches. Each developer needs it installed and built once. If graft is missing, the Claude hooks do nothing silently and the Plan stage loses its code graph.

  1. Install (needs Node.js and npm): ``bash npm install -g @nanonets/graft graft --version # confirm it is on your PATH ` Update later with graft upgrade`.
  2. Build the graph from the repo root (free, no API key). The graft/ folder is git-ignored, so everyone builds their own: ``bash graft build graft check # exits non-zero if the graph is stale; rerun graft build to refresh ``
  3. Start Claude Code in the repo. .mcp.json registers the graft MCP server (graft mcp). On first use Claude Code asks you to approve project MCP servers; approve graft.
  4. Try it: graft ask "where is the sales invoice calculated" --source.

Two ways Claude uses graft

  • Hooks (default). .claude/settings.json runs .claude/helpers/graft-hooks.cjs at session start, after edits and at stop. This injects a repo map into the session and keeps the graph in sync. The helper looks for graft in several places (a machine-specific path first, then local and global node_modules), so the path baked into it is harmless on other machines.
  • MCP tools. Claude can call graft_find_code, graft_find_all, graft_trace_calls, graft_file_api and graft_repo_map through the server in .mcp.json.

Running integration tests

Start a throwaway Postgres, then run the suite against it:

docker run -d --name prw-db -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app -e POSTGRES_DB=app -p 5432:5432 postgres:16
DATABASE_URL=postgres://app:app@localhost:5432/app npm run test:integration

The suite creates and drops its own prw_test_* database, so it never touches the data in DATABASE_URL's database. Without DATABASE_URL it fails with DATABASE_URL is required for integration tests.

SDLC pipeline: integration tests

Integration tests (npm run test:integration) are a required part of the pipeline locally. scripts/sdlc.sh runs them through scripts/sdlc-integration.sh after the unit tests, at the Implement, Test repair and Review checks. The database is chosen in this order, first match wins:

  1. DATABASE_URL set in your shell.
  2. DATABASE_URL in the repo-root .env (the file the server reads), if its host is this machine and it answers. This is the fast path: no container to start.
  3. A throwaway postgres:16 container started with Docker and removed afterwards.

SDLC_DB=docker skips 1 and 2. A non-local host in .env is ignored with a warning unless SDLC_ALLOW_REMOTE_DB=1. The suite creates and drops its own prw_test_* databases, so several runs can share one server (the database user needs CREATEDB). server/.env is not read by anything; use the repo-root .env.

CI skips them temporarily, with a visible warning. To enable them in CI, set the CI/CD variable SDLC_INTEGRATION_CI=run and provide DATABASE_URL (for example from a postgres:16 service). No code change is needed.

SDLC pipeline: flaky tests in Test repair

Before the Test repair pre-check, scripts/sdlc.sh re-runs once every failing test that test-issues.md does not claim (only those tests, one jest run per test file). A test that passes on the re-run is treated as flaky and not rejected. The pipeline prints:

WARNING: flaky test passed on re-run, not rejected: <key>

and appends one line per flaky test to Docs/backlog/<slug>/logs/flaky-tests.md:

<key> :: first run: failed :: re-run: passed

That file is under logs/, so it is git-ignored and never committed. A test that fails again, or is missing from the re-run, stays failing and is rejected as before.

SDLC pipeline: what the Ship stage commits

Prompts, models and effort per stage. Each agent's prompt lives in scripts/prompts/prompt-<stage>.md (spec, plan, red-tests, implement, test-repair, test-audit, review) and is read by scripts/sdlc.sh at run time, so you can edit a prompt without touching the script. Placeholders: {{DOCS}}, {{LOG}}, {{TEST_DIR}}, {{TEST_CMD}}, {{RED_SHA}}, {{SLUG}}. Manual inputs are still appended after the prompt. Each stage has its own default model and effort (stage_defaults() in the script: Spec opus/medium, Plan opus/medium, Red tests sonnet/medium, Implement sonnet/medium, Test repair sonnet/medium, Test audit opus/medium, Review opus/medium). Override per stage with MODEL_<STAGE> and EFFORT_<STAGE> (SPEC, PLAN, RED_TESTS, IMPLEMENT, TEST_REPAIR, TEST_AUDIT, REVIEW), or for every stage without its own value with SDLC_MODEL and SDLC_EFFORT. Effort is low, medium, high, xhigh or max; an invalid value exits 1 before the agent runs. Example: MODEL_IMPLEMENT=opus EFFORT_IMPLEMENT=high bash scripts/sdlc-mod.sh run <slug>. Custom models and providers. Stages run through Claude Code, so a non-Anthropic model goes through a provider: an Anthropic-compatible endpoint such as a LiteLLM or OpenRouter gateway. Providers live first in a user-level registry file, models.json, managed with bash scripts/sdlc-mod.sh model … (below) or the CONFIG pane of the control pane. Its path is the first match of: SDLC_MODELS_FILE (used as given); $XDG_CONFIG_HOME/sdlc/models.json (not on Windows); %APPDATA%\sdlc\models.json (Windows); ~/.config/sdlc/models.json otherwise. WSL and the Windows host share one file only when both set SDLC_MODELS_FILE to the same file. The registry holds the NAME of the environment variable that carries a provider's key, never the key: export that variable in your shell profile, because a key written only in .env is not used for a registry provider. The endpoint must be https, or http to localhost, 127.0.0.1 or [::1] only, so a key never travels in clear text to another host. The file is read each time an agent starts, so a change needs no restart; a broken file stops the run with its path. A provider in the registry wins as a whole over the same name in SDLC_PROVIDER*. The SDLC_PROVIDER* variables are the fallback, for CI and headless runs: these providers live in the repo-root .env (git-ignored; copy the commented block from .env.example): SDLC_PROVIDERS=name1,name2 and, per provider, SDLC_PROVIDER_<NAME>_ENDPOINT, _API_KEY, _MODELS (comma list of the model names you allow) and optionally _EFFORT=yes (pass --effort; off by default because many models reject it). Select a model as <provider>/<model>, split at the first /, for example MODEL_IMPLEMENT=openrouter/openai/gpt-5 or SDLC_MODEL=local/llama3:8b; a name without / is an Anthropic model. Startup fails (exit 1, before any agent runs) for an unlisted provider, a missing endpoint or key, or a model not in _MODELS. Only the SDLC_PROVIDER* keys are read from .env and shell values win. The key is exported only into the subshell that starts claude (never on a command line or in a log), ANTHROPIC_API_KEY is emptied for that call so an Anthropic key is never sent to a third party, and the pane and status.json show <provider>/<model>. Every provider model gets the same tools, permissions and turn limit as a Claude one; whether it edits files and calls tools well depends on the model and the gateway.

The resolved model and effort of every stage, and of the running agent, are written to status.json (models, model, effort); the /sdlc-monitor pipeline view shows them under each stage box and next to the running agent, and watch prints them in the status line.

At the start of a run (FROM=spec) scripts/sdlc.sh records every file that is already modified, staged or untracked in Docs/backlog/<slug>/logs/baseline.json. The Ship stage (scripts/sdlc-ship.sh) then commits exactly the files the cycle created, changed or deleted since that snapshot, anywhere in the repo, in one feat(<slug>) commit, and ticks the item in Docs/backlog/index.md in a second commit. Anything else the developer had staged is left staged.

Skipped files are never committed; they are listed with the reason in Docs/backlog/<slug>/logs/ship-skipped.md and in the DONE message:

ReasonFiles
pre-existing local changesfiles that were already modified before the run and changed again
sensitive file.env, .env.* (not .env.example), *.pem, *.key, *.p12, id_rsa*, *.keystore
local or agent configuration.vscode/, .idea/, .claude/
generatednode_modules/, .DS_Store
too largefiles over 1 MiB

Keys added to a git-ignored .env during the run are copied, with the placeholder value change-me (never the real value), into the sibling .env.example, which is committed. If nothing changed, Ship prints WARNING: nothing to commit and the run still succeeds. Resuming with any FROM other than spec reuses the existing baseline, or creates one with a warning (files changed before the resume then count as pre-existing).

Interactive SDLC: control pane and parallel pipelines

scripts/sdlc-mod.sh runs the normal pipeline (scripts/sdlc.sh, unchanged) for one backlog item in its own git worktree, so several items can run at once. Two Claude Code plugins in .claude/plugins/ add the interface and the guard rails.

bash scripts/sdlc-mod.sh run <slug>     # start or resume; worktree at ../<repo>-sdlc/<slug>, branch sdlc/<slug>
bash scripts/sdlc-mod.sh stop <slug>    # interrupt the pipeline and everything it started
bash scripts/sdlc-mod.sh status         # one line per run
bash scripts/sdlc-mod.sh watch <slug>    # live view of one pipeline, read from its worktree (--once prints one frame; WATCH_INTERVAL seconds, default 3)
bash scripts/sdlc-mod.sh changes <slug> [--json]   # files changed in the pipeline's worktree: "<changed> <uncommitted>"
bash scripts/sdlc-mod.sh discard <slug> [--yes] [--stop]   # delete its worktree, branch and run record (without --yes: show what would go, exit 6)
bash scripts/sdlc-mod.sh restart <slug> [--yes]   # stop it if running, discard it, start again from Spec
bash scripts/sdlc-mod.sh model list [--json]   # the registry providers, their models and whether each key variable is set
bash scripts/sdlc-mod.sh model add <provider> --endpoint <url> --key-env <VAR> --models a,b [--effort]   # create a provider, or replace every field of an existing one
bash scripts/sdlc-mod.sh model add-model <provider> <model>      # add one model to a provider
bash scripts/sdlc-mod.sh model remove-model <provider> <model>   # remove one model (not the last: use remove)
bash scripts/sdlc-mod.sh model remove <provider>                 # remove a provider with all its models
bash scripts/sdlc-mod.sh model test <provider>/<model>           # one request to <endpoint>/v1/messages: "ok", or the failure line

discard and restart throw away the item's worktree, its local branch sdlc/<slug> (including unpushed commits and uncommitted files) and its run record, but first save the branch tip in .git/sdlc-runs/<slug>.discarded; the command it prints, git branch sdlc/<slug> <sha>, brings the work back. discard refuses a running pipeline unless --stop is given, which stops it first (after --yes); restart stops it itself. restart refuses an item already merged into the base branch (exit 5).

At most 2 pipelines run at once (SDLC_MAX_PARALLEL, exit code 3 when full). Run records live in .git/sdlc-runs/. The wrapper links server/node_modules, graft and .env into each worktree.

Control pane (sdlc-monitor plugin). Start Claude with claude --plugin-dir .claude/plugins/sdlc-monitor, then press the SDLC or CONFIG button above the prompt, or type /sdlc-monitor or /sdlc-config.

  • Overview: the pending backlog items with checkboxes, a Run selected button (extra items wait in a queue until a slot frees), and one row per pipeline with its state: running, paused, done, failed, interrupted. Each row ends with how many files the pipeline has changed (N files changed (M uncommitted), or no changes yet while running); the pipeline view shows the same in a Files line. Counts refresh with the pane, and every 10 s for finished pipelines.
  • Open a pipeline: stage chips, progress bar, the current agent with elapsed time and attempt, test progress, artifacts and recent output.
  • Paused for answers: a toast appears, the row shows Answer, and the pipeline view lists each Spec question with its suggested answer. Press Use suggested or type your own, then Submit answers and resume.
  • Interrupt: Stop (press twice to confirm). A failed or interrupted pipeline offers Resume (from Implement if it got past Red tests).
  • Manual input per stage: a failed, interrupted or stopped pipeline shows one text box per agent stage (Spec, Plan, Red tests, Implement, Review) and a Resume at <stage> button. Press Enter to save the text; it goes into Docs/backlog/<slug>/manual-inputs.md under ## <stage> and the pipeline hands it to that stage's agent as binding instructions (it cannot override the rule that the tests are locked). Resume points: FROM=spec|plan|red-tests|implement|test-repair|review ./scripts/sdlc.sh <slug>; any other value exits 1 before anything is changed; plan and red-tests refuse once the red-tests commit exists (restart the run to redo them); review resumes from the latest locked tests commit. FROM=test-repair resumes at Test repair after a run stopped there for a non-verdict reason (the repair agent or auditor failed to run, or the claims failed the pre-check; the run prints the exact FROM=test-repair command when it can resume). It skips Implement and keeps test-issues.md, and first checks, reporting every failure together and calling no agent: the red-tests commit exists, the claim file has at least one valid claim, server/__tests__ is unchanged since the red-tests commit (otherwise the restore command git checkout <sha> -- server/__tests__ && git clean -fd server/__tests__ is printed, never run), the implementation changed outside server/__tests__/ and Docs/, the repair was not already accepted (then use FROM=review), and the claims pass the pre-check. FROM=implement deletes test-issues.md and prints a warning first. The same file can be edited by hand.
  • Discard and start over: Discard (press twice to confirm) stops the pipeline if it is running and deletes its worktree and branch. The pane stays on the item and shows Start (and the command that brings the old branch back). Start runs it again from Spec, and the running pipeline shows Stop and Discard again. Discard is offered for any pipeline the wrapper started.
  • Files changed per stage: scripts/sdlc.sh marks the working tree at the start of every stage and at exit (node scripts/sdlc-changes.cjs mark), crediting the stage that ends with the files that changed while it ran, including files it committed (Red tests). Later commits that only collect earlier work (Commit) are not credited with it, and .env, .claude/, node_modules and other skipped files are never listed. The result is Docs/backlog/<slug>/logs/stage-files.json; the run view of the pane shows a "Files changed per stage" list (first 8 per stage, then "+N more").
  • Refused actions (a stage agent runs headless, so an action outside its allowed tools is refused): the agent runs with --output-format json and the refusals are read from its result. The run pauses (exit 2), and the pane lists each one with Allow this run, Allow always (saved in .claude/sdlc-permissions.json in the main working tree) and Deny; when none is left the run resumes at that stage (a restart of the stage, not a continuation). A path under .claude/ cannot be opened by an allow rule, so allowing it runs that stage with permission checks off (--permission-mode bypassPermissions), and the pane says so; it is never saved as an always rule. From a terminal: bash scripts/sdlc-mod.sh permit <slug> allow|always|deny [n|all], then resume the run. State: Docs/backlog/<slug>/logs/permissions.json.
  • CONFIG pane (CONFIG button or /sdlc-config): a provider list and a form. The list shows each model registry provider with its endpoint, key variable and key set / key NOT set, an Edit button per provider, Test per model (the result is a toast), and Remove per model and per provider (press twice to confirm). Add provider opens the form: provider name, endpoint, API key variable NAME (not the key), models (comma list) and an effort-flag toggle. Save stores the provider and returns to the list; Save and add another keeps an empty form open; Cancel returns without saving. Edit opens the same form filled with the stored values (the name is fixed) and Save replaces them, so removing a model from the comma list removes it. A new provider whose name already exists is refused; use Edit. A rejected save shows its line as a toast and keeps what you typed. The key-variable field takes a variable name, never a key.

Guard (sdlc-guard plugin). Loaded into every pipeline agent by the wrapper. It reads the current stage from status.json and refuses writes the stage does not allow: Spec and Plan write only that item's docs, Red tests write no source, Implement and Review never touch server/__tests__. It also refuses a doc written before the one it builds on.

Backlog

Docs/backlog/index.md lists the work items. List them with a status filter:

npm run backlog
npm run backlog -- pending,in-progress
npm run backlog -- blocked --json

In Claude Code: /backlog-list blocked.

Markers in index.md: [ ] pending, [x] completed, [!] blocked, [~] parked (kept for later; scripts/sdlc.sh skips it, and a trailing (parked: reason) shows in the NOTE column). A [ ] item whose sdlc/<slug> branch exists (local or origin) is shown as in-progress. Statuses are pending, in-progress, blocked, parked, completed (aliases open and done, or all). The command only reads, it never changes files.

To stop the inline context injected by the hooks, remove the graft entries under hooks in .claude/settings.json on your machine (do not commit that change). The MCP server stays available through .mcp.json. To turn graft off completely, also remove graft from .mcp.json locally.

Source 2 files
hooks/register.tsx 1705 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentRow, Claim, ConfigForm, ConfigProvider, PendingItem, PermissionAsk, Question, Run, RunState, Snapshot } from '../types'
5
6const PANE = 'sdlc'
7const CONFIG_PANE = 'config'
8// How often the background loop refreshes; the Refresh button reloads at once when needed.
9const EVERY_MS = 20000
10const PENDING_EVERY_MS = 10000
11const CAP = 2
12const WRAPPER = 'scripts/sdlc-mod.sh'
13// How often the file counts of a running pipeline are recomputed when nothing else about it changed (see loadChanges).
14const CHANGES_EVERY_MS = 15000
15// The stage names status.json carries (scripts/sdlc.sh strips the numbering).
16const STAGES = ['Spec', 'Plan', 'Red tests', 'Implement', 'Test repair', 'Review', 'Commit']
17// How long the Start button stays a "Starting…" note while the wrapper creates the worktree.
18const LAUNCH_GRACE_MS = 20000
19// Agent stages that take a manual input: the FROM value that resumes at the stage, and the "## <key>" section of manual-inputs.md.
20const INPUT_STAGES = [
21  { key: 'spec', label: 'Spec' },
22  { key: 'plan', label: 'Plan' },
23  { key: 'red-tests', label: 'Red tests' },
24  { key: 'implement', label: 'Implement' },
25  { key: 'review', label: 'Review' },
26]
27// Files listed per stage in the run view before "+N more".
28const FILES_SHOWN = 8
29const RESUME_AT_IMPLEMENT = ['Implement', 'Test repair', 'Review', 'Commit']
30// Stages before Implement that a failed run resumes at, so a Plan failure does not run Spec (and its questions) again.
31const RESUME_AT_STAGE: Record<string, string> = { Plan: 'plan', 'Red tests': 'red-tests' }
32
33const EMPTY: Snapshot = { now: 0, runs: [], pending: [], discarded: {} }
34const snapshot = atom({ plugin: 'sdlc-monitor', key: 'snapshot' } as const, EMPTY)
35const agents = atom({ plugin: 'sdlc-monitor', key: 'agents' } as const, {} as Record<string, AgentRow>)
36const view = atom({ plugin: 'sdlc-monitor', key: 'view' } as const, '')
37const selected = atom({ plugin: 'sdlc-monitor', key: 'selected' } as const, {} as Record<string, boolean>)
38const queue = atom({ plugin: 'sdlc-monitor', key: 'queue' } as const, [] as string[])
39const confirmStop = atom({ plugin: 'sdlc-monitor', key: 'confirmStop' } as const, '')
40const confirmDiscard = atom({ plugin: 'sdlc-monitor', key: 'confirmDiscard' } as const, '')
41// Pipelines whose Test repair claim is shown (the Show claim button in the Test repair box).
42const showClaim = atom({ plugin: 'sdlc-monitor', key: 'showClaim' } as const, {} as Record<string, boolean>)
43const launching = atom({ plugin: 'sdlc-monitor', key: 'launching' } as const, {} as Record<string, number>)
44const draft = atom({ plugin: 'sdlc-monitor', key: 'draft' } as const, {} as Record<string, string>)
45const boardOffset = atom({ plugin: 'sdlc-monitor', key: 'boardOffset' } as const, 0)
46const notice = atom({ plugin: 'sdlc-monitor', key: 'notice' } as const, '')
47// What a button press is working on ('' when idle), and the spinner frame drawn beside it.
48const busy = atom({ plugin: 'sdlc-monitor', key: 'busy' } as const, '')
49// The key of the button whose action is running ('' when none): it shows the spinner, and no other action starts until it ends.
50const working = atom({ plugin: 'sdlc-monitor', key: 'working' } as const, '')
51const frame = atom({ plugin: 'sdlc-monitor', key: 'frame' } as const, 0)
52// True while any refresh runs (the background loop, a button, a command): the Refresh button spins and takes no press until it ends.
53const refreshing = atom({ plugin: 'sdlc-monitor', key: 'refreshing' } as const, false)
54const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
55const SPIN_MS = 250
56const spinGlyph = (n: number) => SPIN[n % SPIN.length]
57const EMPTY_FORM: ConfigForm = { provider: '', endpoint: '', keyEnv: '', models: '', effort: false }
58const CONFIG_FIELDS: { key: 'provider' | 'endpoint' | 'keyEnv' | 'models'; label: string }[] = [
59  { key: 'provider', label: 'provider name (saved in lowercase)' },
60  { key: 'endpoint', label: 'endpoint' },
61  { key: 'keyEnv', label: 'API key variable NAME (not the key)' },
62  { key: 'models', label: 'models (comma list)' },
63]
64const configList = atom({ plugin: 'sdlc-monitor', key: 'configList' } as const, null as Record<string, ConfigProvider> | null)
65const configError = atom({ plugin: 'sdlc-monitor', key: 'configError' } as const, '')
66const configForm = atom({ plugin: 'sdlc-monitor', key: 'configForm' } as const, EMPTY_FORM)
67// 'list' is the provider list; 'form' is the add / edit form. configEditing is the provider being edited, '' for a new one.
68const configView = atom({ plugin: 'sdlc-monitor', key: 'configView' } as const, 'list' as 'list' | 'form')
69const configEditing = atom({ plugin: 'sdlc-monitor', key: 'configEditing' } as const, '')
70const configConfirmProvider = atom({ plugin: 'sdlc-monitor', key: 'configConfirmProvider' } as const, '')
71const configConfirmModel = atom({ plugin: 'sdlc-monitor', key: 'configConfirmModel' } as const, null as { provider: string; model: string } | null)
72
73// the palette of the board design: a dark ground, one hue per state, grey for what is secondary
74const P = {
75  ground: '#14181f',
76  column: '#10141a',
77  card: '#181d25',
78  cardSelected: '#12303a',
79  line: '#2d333b',
80  edge: '#3d444d',
81  text: '#d0d7de',
82  strong: '#e6edf3',
83  muted: '#8b949e',
84  run: '#56d4dd',
85  wait: '#e3b341',
86  fail: '#ff7b72',
87  done: '#7ee787',
88}
89
90const GLYPH: Record<RunState, string> = { starting: '◌', running: '●', paused: '⏸', done: '✔', failed: '✘', interrupted: '■', stopped: '✘' }
91const COLOR: Record<RunState, string> = { starting: P.run, running: P.run, paused: P.wait, done: P.done, failed: P.fail, interrupted: P.wait, stopped: P.fail }
92const ORDER: Record<RunState, number> = { running: 0, paused: 1, starting: 2, failed: 3, stopped: 3, interrupted: 3, done: 4 }
93
94type StageState = 'done' | 'active' | 'failed' | 'paused' | 'pending'
95const STAGE_GLYPH: Record<StageState, string> = { done: '✔', active: '●', failed: '✘', paused: '⏸', pending: '○' }
96const STAGE_COLOR: Record<StageState, string> = { done: P.done, active: P.run, failed: P.fail, paused: P.wait, pending: P.muted }
97
98const bar = (done: number, total: number, width: number) => {
99  const filled = total ? Math.round((width * done) / total) : 0
100
101  return '█'.repeat(filled) + '░'.repeat(width - filled)
102}
103
104const clock = (ms: number) => {
105  const s = Math.max(0, Math.floor(ms / 1000))
106
107  return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
108}
109
110const parse = (text: string | null): Record<string, unknown> | null => {
111  try {
112    return text ? JSON.parse(text) : null
113  } catch {
114    return null
115  }
116}
117
118const cut = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
119
120// questions.md as the Spec agent writes it: "### Q<n>: <title>", a body, "**Suggested:** ...", "**Answer:**".
121function parseQuestions(text: string): Question[] {
122  const out: Question[] = []
123  let q: Question | null = null
124  let part: 'body' | 'suggested' | 'answer' = 'body'
125  for (const line of text.split('\n')) {
126    const head = line.match(/^### Q(\d+):\s*(.*)$/)
127    if (head) {
128      q = { n: Number(head[1]), title: head[2].trim(), body: '', suggested: '' }
129      out.push(q)
130      part = 'body'
131    } else if (q) {
132      if (/^\*\*Suggested:\*\*/.test(line)) {
133        part = 'suggested'
134        q.suggested = line.replace(/^\*\*Suggested:\*\*\s*/, '')
135      } else if (/^\*\*Answer:\*\*/.test(line)) {
136        part = 'answer'
137      } else if (part === 'body') {
138        q.body = `${q.body}${q.body ? ' ' : ''}${line.trim()}`.trim()
139      } else if (part === 'suggested' && line.trim()) {
140        q.suggested = `${q.suggested} ${line.trim()}`
141      }
142    }
143  }
144
145  return out
146}
147
148// Returns manual-inputs.md with the "## <key>" section set to value (an empty value removes it).
149function setManualInput(text: string, key: string, value: string): string {
150  const sections: Record<string, string> = {}
151  let cur = ''
152  for (const line of text.split('\n')) {
153    const head = line.match(/^## (\S+)\s*$/)
154    if (head) {
155      cur = head[1]
156      sections[cur] = ''
157    } else if (cur) sections[cur] += `${line}\n`
158  }
159  sections[key] = `${value.trim()}\n`
160
161  return INPUT_STAGES.filter(st => (sections[st.key] ?? '').trim())
162    .map(st => `## ${st.key}\n${sections[st.key].trim()}\n`)
163    .join('\n')
164}
165
166// Puts each answer on its "**Answer:**" line, in question order.
167function fillAnswers(text: string, answers: Record<number, string>): string {
168  let n = 0
169
170  return text
171    .split('\n')
172    .map(line => {
173      const head = line.match(/^### Q(\d+):/)
174      if (head) n = Number(head[1])
175
176      return /^\*\*Answer:\*\*/.test(line) && answers[n] ? `**Answer:** ${answers[n]}` : line
177    })
178    .join('\n')
179}
180
181function testCounts(log: string | null): Run['tests'] {
182  const m = (log ?? '').match(/^Tests:\s+(?:(\d+) failed, )?(?:(\d+) skipped, )?(?:(\d+) passed, )?(\d+) total/m)
183
184  return m ? { failed: Number(m[1] ?? 0), passed: Number(m[3] ?? 0), total: Number(m[4]) } : null
185}
186
187async function readText($: EngineInterface, path: string): Promise<string | null> {
188  try {
189    return (await $.fs.read(path)) as string
190  } catch {
191    return null
192  }
193}
194
195async function names($: EngineInterface, path: string): Promise<{ name: string; kind: string }[]> {
196  try {
197    return await $.fs.list(path)
198  } catch {
199    return []
200  }
201}
202
203async function isAlive($: EngineInterface, pid: number): Promise<boolean> {
204  if (!pid) return false
205  try {
206    return (await $.process.run(['kill', '-0', String(pid)])).exitCode === 0
207  } catch {
208    return false
209  }
210}
211
212// The main working tree and the git common dir, as absolute paths. Every repo-relative path below hangs on them, so the pane
213// behaves the same whatever directory the session is in, including a pipeline's own worktree (whose copy of the wrapper would
214// read another root, another worktree folder and no run records). '' for both when git does not say: relative paths then.
215let repoCache: { root: string; common: string } | null = null
216async function repoInfo($: EngineInterface): Promise<{ root: string; common: string }> {
217  if (!repoCache) {
218    let common = ''
219    let root = ''
220    try {
221      common = (await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'])).stdout.trim()
222    } catch {
223      // not in a git checkout
224    }
225    if (common.startsWith('/') && common.endsWith('/.git')) root = common.slice(0, -'/.git'.length)
226    if (!common.startsWith('/')) common = ''
227    // no usable answer: do not cache it, so a later call (git came up, the directory changed) asks again
228    if (!root) return { root: '', common }
229    repoCache = { root, common }
230  }
231
232  return repoCache
233}
234
235// A path inside the main working tree.
236async function repoPath($: EngineInterface, rel: string): Promise<string> {
237  const { root } = await repoInfo($)
238
239  return root ? `${root}/${rel}` : rel
240}
241
242const wrapperPath = ($: EngineInterface) => repoPath($, WRAPPER)
243
244let pendingAt = 0
245let pendingCache: PendingItem[] = []
246
247// Where sdlc-mod.sh keeps its run records: one folder shared by every worktree.
248async function registryDir($: EngineInterface): Promise<string> {
249  const { common } = await repoInfo($)
250
251  return `${common || '.git'}/sdlc-runs`
252}
253
254async function loadPending($: EngineInterface, now: number): Promise<PendingItem[]> {
255  if (now - pendingAt < PENDING_EVERY_MS && pendingAt) return pendingCache
256  try {
257    const r = await $.process.run(['node', await repoPath($, 'scripts/backlog-list.cjs'), 'pending', '--json'])
258    const rows = JSON.parse(r.stdout) as { slug: string; type: string | null; priority: string | null; title: string }[]
259    pendingCache = rows.map(x => ({ slug: x.slug, type: x.type ?? '-', priority: x.priority ?? '-', title: x.title }))
260  } catch {
261    pendingCache = []
262  }
263  pendingAt = now
264
265  return pendingCache
266}
267
268// Files a pipeline has changed, counted by the wrapper inside the pipeline's own worktree. A pipeline started by hand has
269// no record, so its changes cannot be told apart from the developer's own work: no counts. A pipeline is recounted only when
270// something about it changed (its state, stage or status.json time), a running one also every CHANGES_EVERY_MS, and every
271// one on Refresh. All the pipelines due are counted in one wrapper call (`changes --all <slug>...`); the rest reuse the last
272// result, null included.
273const changesCache = new Map<string, { at: number; sig: string; value: Run['changes'] }>()
274const changeSig = (run: Run) => `${run.state}|${run.stage}|${run.updated}`
275
276function countDue(run: Run, now: number, force: boolean): boolean {
277  if (!run.managed) return false
278  const hit = changesCache.get(run.slug)
279  if (force || !hit || hit.sig !== changeSig(run)) return true
280
281  return run.state === 'running' && now - hit.at >= CHANGES_EVERY_MS
282}
283
284async function loadChanges($: EngineInterface, runs: Run[], now: number, force: boolean) {
285  const due = runs.filter(r => countDue(r, now, force))
286  if (due.length) {
287    let counted: Record<string, { changed?: unknown; uncommitted?: unknown }> = {}
288    try {
289      const r = await $.process.run(['bash', await wrapperPath($), 'changes', '--all', ...due.map(x => x.slug)])
290      if (r.exitCode === 0) counted = (JSON.parse(r.stdout) as { runs?: typeof counted }).runs ?? {}
291    } catch {
292      counted = {}
293    }
294    for (const run of due) {
295      const j = counted[run.slug]
296      const value = j && typeof j.changed === 'number' && typeof j.uncommitted === 'number' ? { changed: j.changed, uncommitted: j.uncommitted } : null
297      changesCache.set(run.slug, { at: now, sig: changeSig(run), value })
298    }
299  }
300  for (const run of runs) run.changes = run.managed ? (changesCache.get(run.slug)?.value ?? null) : null
301}
302
303// The files each stage changed, from logs/stage-files.json (written by scripts/sdlc.sh; an unreadable file reads as none).
304function parseStageFiles(text: string | null): Record<string, string[]> {
305  const stages = parse(text)?.stages
306  if (!stages || typeof stages !== 'object') return {}
307  const out: Record<string, string[]> = {}
308  for (const [name, list] of Object.entries(stages as Record<string, unknown>)) {
309    if (Array.isArray(list)) out[name] = list.filter((f): f is string => typeof f === 'string')
310  }
311
312  return out
313}
314
315// The undecided asks in logs/permissions.json (an unreadable or malformed file reads as none).
316// test-issues.md: what the Implement agent claimed is wrong with a test, one "<file> :: <test name> :: <why>" line each.
317function parseClaims(text: string | null): Claim[] {
318  return (text ?? '').split('\n').map(l => l.trim()).filter(Boolean).map(line => {
319    const [file = '', test = '', ...why] = line.split(' :: ')
320
321    return why.length ? { file, test, why: why.join(' :: ') } : { file: '', test: '', why: line }
322  })
323}
324
325// Why the pipeline refused the claim: the REJECT lines of the latest Test repair section of run.out.
326function claimRejects(runOut: string): string[] {
327  const at = runOut.lastIndexOf('== 4b Test repair')
328  if (at < 0) return []
329
330  return runOut.slice(at).split('\n').filter(l => /^(REJECT|TEST REPAIR REJECTED)/.test(l)).map(l => l.trim())
331}
332
333function parsePermissions(text: string | null): PermissionAsk[] {
334  const j = parse(text)
335  const list = j && Array.isArray(j.pending) ? j.pending : []
336
337  return list
338    .filter((a): a is Record<string, unknown> => !!a && typeof a === 'object' && typeof (a as Record<string, unknown>).tool === 'string')
339    .map(a => ({ stage: String(a.stage ?? ''), tool: String(a.tool), detail: String(a.detail ?? ''), rule: String(a.rule ?? ''), protected: a.protected === true }))
340}
341
342// The stage to resume at once every ask of a stage is decided; spec starts from the beginning, and the audit step resumes at implement.
343const resumeKey = (stage: string) => (stage === 'spec' ? '' : stage === 'test-audit' ? 'implement' : stage)
344
345// Decides one ask (or all) through the wrapper; when none is left, the run resumes at the stage that was refused.
346async function decidePermission($: EngineInterface, run: Run, which: string, choice: 'allow' | 'always' | 'deny') {
347  await act($, `perm-${choice}:${which}`, `Saving your answer for ${run.slug}`, () => decideNow($, run, which, choice))
348}
349
350async function decideNow($: EngineInterface, run: Run, which: string, choice: 'allow' | 'always' | 'deny') {
351  const r = await $.process.run(['bash', await wrapperPath($), 'permit', run.slug, choice, which])
352  if (r.exitCode !== 0) {
353    await notify($, firstLine(r.stderr) || `permit failed (exit ${r.exitCode})`)
354
355    return
356  }
357  const left = Number(firstLine(r.stdout))
358  const stage = run.permissions[which === 'all' ? 0 : Number(which)]?.stage ?? ''
359  await notify($, `${choice === 'deny' ? 'Denied' : 'Allowed'}${left > 0 ? `: ${left} more to decide` : ''}`)
360  await refresh($)
361  if (left === 0) await launchWithNotice($, run.slug, resumeKey(stage))
362}
363
364// Why a stage failed: the last lines of that stage's own log (plan.log, review.log, the newest spec-N.log or impl-N.log), else of run.out.
365async function failureReason($: EngineInterface, docs: string, stage: string, runOut: string): Promise<string[]> {
366  const logs = (await names($, `${docs}/logs`)).filter(f => f.kind === 'file').map(f => f.name)
367  const key = stage.toLowerCase().replace(/[^a-z]/g, '')
368  const prefix = key === 'redtests' ? 'red' : key === 'implement' ? 'impl' : key === 'spec' ? 'spec' : key
369  const own = logs.filter(f => f === `${prefix}.log` || new RegExp(`^${prefix}-\\d+\\.log$`).test(f)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
370  const text = prefix && own.length ? await readText($, `${docs}/logs/${own[own.length - 1]}`) : null
371  const lines = (text ?? runOut).split('\n').filter(l => l.trim())
372
373  return lines.slice(-12)
374}
375
376// One pipeline: the wrapper's record, the pipeline's own status.json, and what it has written so far.
377async function loadRun($: EngineInterface, slug: string, worktree: string, reg: Record<string, unknown> | null): Promise<Run> {
378  const root = worktree || (await repoInfo($)).root || '.'
379  const docs = `${root}/Docs/backlog/${slug}`
380  const status = parse(await readText($, `${docs}/logs/status.json`))
381  const files = [
382    ...(await names($, docs)).filter(f => f.kind === 'file').map(f => f.name),
383    ...(await names($, `${docs}/logs`)).filter(f => /^(impl|spec)-\d+\.log$/.test(f.name)).map(f => f.name),
384  ]
385  const runOut = (await readText($, `${docs}/logs/run.out`)) ?? ''
386  const stageName = String(status?.stage ?? '')
387  const questionsText = await readText($, `${docs}/questions.md`)
388  const pid = Number(reg?.pid ?? status?.pid ?? 0)
389  const alive = await isAlive($, pid)
390
391  let state: RunState
392  if (reg?.interrupted === true) state = 'interrupted'
393  else if (status?.state === 'done') state = 'done'
394  else if (status?.state === 'paused') state = 'paused'
395  else if (status?.state === 'failed') state = 'failed'
396  else if (status?.state === 'running') state = alive ? 'running' : 'stopped'
397  else if (reg?.state === 'running' && alive) state = 'starting'
398  else if (reg?.state === 'exited' && reg.exit_code !== '0' && reg.exit_code !== '2') state = 'failed'
399  else state = alive ? 'starting' : 'stopped'
400
401  return {
402    slug,
403    worktree: root,
404    state,
405    stage: String(status?.stage ?? ''),
406    agent: String(status?.agent ?? ''),
407    model: String(status?.model ?? ''),
408    effort: String(status?.effort ?? ''),
409    models: (status?.models && typeof status.models === 'object' ? status.models : {}) as Run['models'],
410    attempt: String(status?.attempt ?? ''),
411    agentStarted: String(status?.agent_started ?? ''),
412    runStarted: String(status?.run_started ?? reg?.started ?? ''),
413    updated: String(status?.updated ?? ''),
414    note: String(status?.note ?? ''),
415    pid,
416    files,
417    tests: testCounts(await readText($, `${docs}/logs/tests.log`)),
418    tail: runOut.split('\n').filter(l => l.trim()).slice(-8),
419    stageFiles: parseStageFiles(await readText($, `${docs}/logs/stage-files.json`)),
420    permissions: parsePermissions(await readText($, `${docs}/logs/permissions.json`)),
421    claims: parseClaims(await readText($, `${docs}/test-issues.md`)),
422    claimRejects: claimRejects(runOut),
423    reason: state === 'failed' || state === 'stopped' ? await failureReason($, docs, stageName, runOut) : [],
424    questions: questionsText ? parseQuestions(questionsText) : [],
425    managed: reg !== null,
426    message: String(reg?.message ?? ''),
427    // filled in by loadChanges once every run is loaded
428    changes: null,
429    base: String(reg?.base ?? ''),
430  }
431}
432
433async function collect($: EngineInterface, force = false): Promise<Snapshot> {
434  const now = await $.clock.now()
435  const dir = await registryDir($)
436  const runs: Run[] = []
437  const seen = new Set<string>()
438
439  const discarded: Record<string, string> = {}
440  for (const f of await names($, dir)) {
441    if (f.kind === 'file' && f.name.endsWith('.discarded')) {
442      discarded[f.name.replace(/\.discarded$/, '')] = ((await readText($, `${dir}/${f.name}`)) ?? '').trim()
443      continue
444    }
445    if (f.kind !== 'file' || !f.name.endsWith('.json')) continue
446    const reg = parse(await readText($, `${dir}/${f.name}`))
447    if (!reg || typeof reg.slug !== 'string') continue
448    seen.add(reg.slug)
449    runs.push(await loadRun($, reg.slug, String(reg.worktree ?? ''), reg))
450  }
451  // A pipeline started by hand with scripts/sdlc.sh in this working tree has no record: find it by its status file.
452  for (const d of await names($, await repoPath($, 'Docs/backlog'))) {
453    if (d.kind === 'dir' && !seen.has(d.name) && (await readText($, await repoPath($, `Docs/backlog/${d.name}/logs/status.json`)))) {
454      runs.push(await loadRun($, d.name, '', null))
455    }
456  }
457  runs.sort((a, b) => ORDER[a.state] - ORDER[b.state] || b.updated.localeCompare(a.updated))
458  await loadChanges($, runs, now, force)
459
460  return { now, runs, pending: await loadPending($, now), discarded }
461}
462
463// Starts (or resumes) a pipeline in the background: it outlives this pane and this session.
464// Waits 3 seconds: a wrapper that refuses or crashes by then is reported, with the last lines of its output. Returns '' or that error.
465const LAUNCH_SCRIPT =
466  `out="\${TMPDIR:-/tmp}/sdlc-launch-$0.out"; nohup bash "\${SDLC_WRAPPER:-${WRAPPER}}" run "$0" </dev/null >"$out" 2>&1 & pid=$!; sleep 3; ` +
467  'if ! kill -0 $pid 2>/dev/null; then wait $pid; rc=$?; if [ $rc -ne 0 ] && [ $rc -ne 2 ]; then tail -5 "$out" >&2; echo "exit $rc" >&2; exit $rc; fi; fi'
468
469async function launch($: EngineInterface, slug: string, from: string): Promise<string> {
470  const env: Record<string, string> = { SDLC_MAX_PARALLEL: String(CAP), SDLC_WRAPPER: await wrapperPath($) }
471  if (from) env.FROM = from
472  try {
473    const r = await $.process.run(['bash', '-c', LAUNCH_SCRIPT, slug], { env })
474    if (r.exitCode === 0) return ''
475
476    return `${slug} did not start: ${(r.stderr || r.stdout || `exit ${r.exitCode}`).trim()}`
477  } catch (e) {
478    return `${slug} did not start: ${String((e as { message?: string })?.message ?? e)}`
479  }
480}
481
482// Shows a message in the toast and keeps it in the notice row, which has a Copy button, until it is dismissed.
483async function notify($: EngineInterface, text: string) {
484  await update($, notice, () => text)
485  $.ui.toast(text)
486}
487
488// Runs `work` with a loader line (label plus spinner) shown until it ends.
489async function withBusy<T>($: EngineInterface, label: string, work: () => Promise<T>): Promise<T> {
490  await update($, busy, () => label)
491  try {
492    return await work()
493  } finally {
494    await update($, busy, () => '')
495  }
496}
497
498// Runs one button's action: its label turns into a spinner until `work` has completely finished, and a second press is ignored meanwhile.
499// The caller changes what the button shows next (confirm flags, notices) inside `work`, after the action is done.
500async function act<T>($: EngineInterface, key: string, label: string, work: () => Promise<T>): Promise<T | undefined> {
501  if (await read($, working)) return undefined
502  await update($, working, () => key)
503  try {
504    return await withBusy($, label, work)
505  } finally {
506    await update($, working, () => '')
507  }
508}
509
510// A button's label while its own action runs: the spinner and `doing`, else its normal text.
511const labelOf = (now: string, spin: string, key: string, text: string, doing: string) => (now === key ? `${spin} ${doing}` : text)
512
513// Reloads until the run has left running/starting (a stop takes a moment to show in the registry), at most `tries` times 300 ms.
514async function settled($: EngineInterface, slug: string, tries = 20) {
515  for (let i = 0; i < tries; i++) {
516    const s = await refresh($)
517    const r = s.runs.find(x => x.slug === slug)
518    if (!r || (r.state !== 'running' && r.state !== 'starting')) return
519    await $.clock.sleep(300)
520  }
521}
522
523// Starts or resumes one run and reports a refusal; used by every Start / Resume button.
524async function launchWithNotice($: EngineInterface, slug: string, from: string): Promise<boolean> {
525  const err = await withBusy($, `Starting ${slug}${from ? ` at ${from}` : ''}`, () => launch($, slug, from))
526  if (err) await notify($, err)
527  await refresh($)
528
529  return !err
530}
531
532// Runs a wrapper command that changes a run; returns '' on success, else the line to show (its error, or the exit code).
533async function wrapperChange($: EngineInterface, args: string[]): Promise<string> {
534  try {
535    const r = await $.process.run(['bash', await wrapperPath($), ...args])
536
537    return r.exitCode === 0 ? '' : firstLine(r.stderr) || firstLine(r.stdout) || `failed (exit ${r.exitCode})`
538  } catch (e) {
539    return firstLine(String((e as { message?: string })?.message ?? e)) || 'failed'
540  }
541}
542
543async function stopRun($: EngineInterface, slug: string) {
544  return wrapperChange($, ['stop', slug])
545}
546
547// Stops the pipeline if it runs, then deletes its worktree, branch and run record (the branch tip is saved).
548async function discardRun($: EngineInterface, slug: string) {
549  return wrapperChange($, ['discard', slug, '--yes', '--stop'])
550}
551
552async function startRun($: EngineInterface, slug: string) {
553  await act($, 'start', `Starting ${slug}`, () => startNow($, slug))
554}
555
556async function startNow($: EngineInterface, slug: string) {
557  const now = await $.clock.now()
558  await update($, launching, l => ({ ...l, [slug]: now }))
559  await launchWithNotice($, slug, '')
560}
561
562const resumeFrom = (run: Run) => (RESUME_AT_IMPLEMENT.includes(run.stage) ? 'implement' : RESUME_AT_STAGE[run.stage] ?? '')
563
564// The refresh in progress, if any. A second caller does not start another one: it gets the running one's result, and a forced
565// refresh (the Refresh button) waits for it to end and then runs its own, so two refreshes never overlap.
566let inFlight: Promise<Snapshot> | null = null
567
568async function refresh($: EngineInterface, force = false): Promise<Snapshot> {
569  while (inFlight) {
570    if (!force) return inFlight
571    await inFlight.catch(() => undefined)
572  }
573  await update($, refreshing, () => true)
574  inFlight = refreshNow($, force)
575  try {
576    return await inFlight
577  } finally {
578    inFlight = null
579    await update($, refreshing, () => false)
580  }
581}
582
583async function refreshNow($: EngineInterface, force: boolean): Promise<Snapshot> {
584  const s = await collect($, force)
585  await update($, snapshot, () => s)
586  const pressed = await read($, launching)
587  const left = Object.fromEntries(Object.entries(pressed).filter(([k]) => !s.runs.some(r => r.slug === k)))
588  if (Object.keys(left).length !== Object.keys(pressed).length) await update($, launching, () => left)
589
590  return s
591}
592
593// Starts as many of the selected items as the cap allows; the rest wait in the queue.
594async function runSelected($: EngineInterface) {
595  await act($, 'run-selected', 'Starting the selected items', () => runSelectedNow($))
596}
597
598async function runSelectedNow($: EngineInterface) {
599  const pick = await read($, selected)
600  const slugs = Object.keys(pick).filter(k => pick[k])
601  if (!slugs.length) return
602  const s = await read($, snapshot)
603  const running = s.runs.filter(r => r.state === 'running' || r.state === 'starting').length
604  const free = Math.max(0, CAP - running)
605  let refused = false
606  for (const slug of slugs.slice(0, free)) if (!(await launchWithNotice($, slug, ''))) refused = true
607  await update($, queue, q => [...q, ...slugs.slice(free).filter(x => !q.includes(x))])
608  await update($, selected, () => ({}))
609  if (!refused) await notify($, `Started ${Math.min(free, slugs.length)}, queued ${Math.max(0, slugs.length - free)} (at most ${CAP} run at once).`)
610  await refresh($)
611}
612
613// Starts queued items whenever a slot is free.
614async function drainQueue($: EngineInterface, s: Snapshot) {
615  const waiting = await read($, queue)
616  if (!waiting.length) return
617  const running = s.runs.filter(r => r.state === 'running' || r.state === 'starting').length
618  if (running >= CAP) return
619  const next = waiting[0]
620  await update($, queue, q => q.filter(x => x !== next))
621  await launchWithNotice($, next, '')
622}
623
624// Saves the developer's text for one stage; the pipeline hands it to that stage's agent.
625async function saveManualInput($: EngineInterface, run: Run, key: string, value: string) {
626  const path = `${run.worktree}/Docs/backlog/${run.slug}/manual-inputs.md`
627  await $.fs.write(path, setManualInput((await readText($, path)) ?? '', key, value))
628  await notify($, `Input saved for ${key} of ${run.slug}.`)
629}
630
631async function submitAnswers($: EngineInterface, run: Run) {
632  await act($, 'submit-answers', `Saving the answers of ${run.slug}`, () => submitNow($, run))
633}
634
635async function submitNow($: EngineInterface, run: Run) {
636  const drafts = await read($, draft)
637  const path = `${run.worktree}/Docs/backlog/${run.slug}/questions.md`
638  const text = await readText($, path)
639  if (!text) return
640  const answers: Record<number, string> = {}
641  for (const q of run.questions) answers[q.n] = drafts[`${run.slug}:${q.n}`] ?? ''
642  await $.fs.write(path, fillAnswers(text, answers))
643  await update($, draft, d => Object.fromEntries(Object.entries(d).filter(([k]) => !k.startsWith(`${run.slug}:`))))
644  await launchWithNotice($, run.slug, '')
645  await notify($, `Answers saved, ${run.slug} resumed.`)
646  await refresh($)
647}
648
649// ---- CONFIG pane: providers and models of the model registry, through `sdlc-mod.sh model ...` ----
650
651const firstLine = (text: string): string => (text.split('\n').map(l => l.trim()).find(Boolean) ?? '')
652
653// Runs `sdlc-mod.sh model <args>`; `line` is the message line to show: stdout on success, else stderr, else stdout.
654async function runModel($: EngineInterface, args: string[]): Promise<{ ok: boolean; stdout: string; line: string }> {
655  try {
656    const r = await $.process.run(['bash', await wrapperPath($), 'model', ...args])
657    const ok = r.exitCode === 0
658
659    return { ok, stdout: r.stdout, line: ok ? firstLine(r.stdout) : firstLine(r.stderr) || firstLine(r.stdout) || `failed (exit ${r.exitCode})` }
660  } catch (e) {
661    return { ok: false, stdout: '', line: firstLine(String((e as { message?: string })?.message ?? e)) || 'failed' }
662  }
663}
664
665async function loadConfig($: EngineInterface) {
666  const r = await runModel($, ['list', '--json'])
667  const providers = r.ok ? parse(r.stdout)?.providers : null
668
669  if (providers && typeof providers === 'object' && !Array.isArray(providers)) {
670    const list: Record<string, ConfigProvider> = {}
671    for (const [name, v] of Object.entries(providers as Record<string, Record<string, unknown>>)) {
672      const models = Array.isArray(v?.models) && v.models.every(m => typeof m === 'string') ? (v.models as string[]) : []
673      list[name] = { endpoint: String(v?.endpoint ?? ''), api_key_env: String(v?.api_key_env ?? ''), models, effort: v?.effort === true, key_set: v?.key_set === true }
674    }
675    await update($, configList, () => list)
676    await update($, configError, () => '')
677  } else {
678    await update($, configList, () => null)
679    await update($, configError, () => r.line || 'model list --json: unexpected output')
680  }
681}
682
683async function openConfig($: EngineInterface) {
684  await act($, 'config-open', 'Opening CONFIG', () => openConfigNow($))
685}
686
687async function openConfigNow($: EngineInterface) {
688  await update($, configView, () => 'list')
689  await update($, configEditing, () => '')
690  await update($, configConfirmProvider, () => '')
691  await update($, configConfirmModel, () => null)
692  await loadConfig($)
693  await $.ui.open({ id: CONFIG_PANE, title: 'CONFIG' })
694}
695
696// Arguments of `model add` for the form. `add` replaces the provider's stored endpoint, key variable, models and effort flag with these.
697const addArgs = (form: ConfigForm): string[] => [
698  'add', form.provider, '--endpoint', form.endpoint, '--key-env', form.keyEnv, '--models', form.models,
699  ...(form.effort ? ['--effort'] : []),
700]
701
702async function showForm($: EngineInterface, provider: string) {
703  const list = await read($, configList)
704  const p = provider && list && Object.prototype.hasOwnProperty.call(list, provider) ? list[provider] : null
705  await update($, configForm, () => (p ? { provider, endpoint: p.endpoint, keyEnv: p.api_key_env, models: p.models.join(','), effort: p.effort } : EMPTY_FORM))
706  await update($, configEditing, () => (p ? provider : ''))
707  await update($, configView, () => 'form')
708}
709
710async function showListNow($: EngineInterface) {
711  await loadConfig($)
712  await update($, configView, () => 'list')
713  await update($, configEditing, () => '')
714  await update($, configForm, () => EMPTY_FORM)
715}
716
717async function showList($: EngineInterface) {
718  await act($, 'config-cancel', 'Loading the providers', () => showListNow($))
719}
720
721// Saves the form. A new provider whose name is taken is refused (it would overwrite the stored one: use Edit).
722// `another` stays on an empty form for the next provider; otherwise the pane goes back to the list. A rejected save stays on the form.
723async function saveForm($: EngineInterface, another: boolean) {
724  await act($, another ? 'config-save-another' : 'config-save', 'Saving the provider', () => saveNow($, another))
725}
726
727async function saveNow($: EngineInterface, another: boolean) {
728  const typed = await read($, configForm)
729  // The registry only takes lowercase names: OpenRouter is stored as openrouter.
730  const form = { ...typed, provider: typed.provider.trim().toLowerCase() }
731  const editing = await read($, configEditing)
732  const list = await read($, configList)
733  if (!editing && list && Object.prototype.hasOwnProperty.call(list, form.provider)) {
734    await notify($, `${form.provider} already exists: press Edit on it`)
735
736    return
737  }
738  const r = await runModel($, addArgs({ ...form, provider: editing || form.provider }))
739  await notify($, r.line)
740  if (!r.ok) return
741  await loadConfig($)
742  if (another) {
743    await update($, configForm, () => EMPTY_FORM)
744    await update($, configEditing, () => '')
745  } else {
746    await showListNow($)
747  }
748}
749
750async function testModel($: EngineInterface, provider: string, model: string) {
751  await act($, `config-test:${provider}/${model}`, `Testing ${provider}/${model}: waiting for the provider to answer (up to 10 s)`, async () => {
752    const r = await runModel($, ['test', `${provider}/${model}`])
753    await notify($, `${provider}/${model}: ${r.ok ? 'ok' : r.line}`)
754    await loadConfig($)
755  })
756}
757
758async function removeModel($: EngineInterface, provider: string, model: string) {
759  await act($, `config-remove-model:${provider}/${model}`, `Removing ${provider}/${model}`, async () => {
760    const r = await runModel($, ['remove-model', provider, model])
761    await notify($, r.line)
762    await loadConfig($)
763    await update($, configConfirmModel, () => null)
764  })
765}
766
767async function removeProvider($: EngineInterface, provider: string) {
768  await act($, `config-remove-provider:${provider}`, `Removing ${provider}`, async () => {
769    const r = await runModel($, ['remove', provider])
770    await notify($, r.line)
771    await loadConfig($)
772    await update($, configConfirmProvider, () => '')
773  })
774}
775
776// Pipeline stage (as the monitor names it) -> the sdlc.sh stages whose agents run in it.
777const STAGE_AGENTS: Record<string, string[]> = {
778  Spec: ['spec'], Plan: ['plan'], 'Red tests': ['red-tests'], Implement: ['implement'], 'Test repair': ['test-repair', 'test-audit'], Review: ['review'],
779}
780const modelOf = (m?: { model: string; effort: string }) => (m ? `${m.model} · ${m.effort}` : '')
781// "opus · medium" for a stage; the Test repair stage lists its repair and audit agents. '' when status.json has no model data.
782const stageModel = (run: Run, name: string) => {
783  const keys = STAGE_AGENTS[name] ?? []
784  if (keys.length === 1) return modelOf(run.models[keys[0]])
785  return keys.map(k => (run.models[k] ? `${k.replace('test-', '')} ${modelOf(run.models[k])}` : '')).filter(Boolean).join(' / ')
786}
787
788function stageStates(run: Run): { name: string; state: StageState }[] {
789  const isGone = run.state === 'stopped'
790  const at = STAGES.indexOf(run.stage)
791  const wasRepaired = run.files.includes('test-repair-1.md')
792
793  return STAGES.map((name, i): { name: string; state: StageState } => {
794    if (run.state === 'done' || i < at) return { name, state: 'done' }
795    if (at < 0 || i > at) return { name, state: 'pending' }
796    if (run.state === 'paused') return { name, state: 'paused' }
797
798    return { name, state: run.state === 'failed' || run.state === 'interrupted' || isGone ? 'failed' : 'active' }
799  }).filter(st => st.name !== 'Test repair' || st.state === 'active' || st.state === 'failed' || wasRepaired || run.claims.length > 0)
800}
801
802const summary = (runs: Run[], queued: number) => {
803  const n = (state: RunState) => runs.filter(r => r.state === state).length
804  const parts = [`${n('running') + n('starting')} running`, `${n('paused')} paused`]
805  if (queued) parts.push(`${queued} queued`)
806
807  return parts.join(' · ')
808}
809
810const stateLine = (run: Run, now: number) => {
811  if (run.state === 'running' && run.note) return `${run.stage || 'Starting'} · waiting: ${run.note}`
812  if (run.state === 'running') return `${run.stage || 'Starting'} · ${run.agent || '…'}${run.model ? ` (${run.model} · ${run.effort})` : ''} · ${clock(now - Date.parse(run.agentStarted))}${run.attempt ? ` · attempt ${run.attempt}` : ''}`
813  if (run.state === 'paused' && run.permissions.length) return `needs a decision: ${run.permissions.length} refused action${run.permissions.length === 1 ? '' : 's'}`
814  if (run.state === 'paused' && !run.questions.length) return `paused at ${run.stage || 'start'}`
815  if (run.state === 'paused') return `needs answers: ${run.questions.length} question${run.questions.length === 1 ? '' : 's'}`
816  if (run.state === 'done') return 'done'
817  if (run.state === 'interrupted') return `interrupted at ${run.stage || 'start'}`
818  if (run.state === 'stopped') return `stopped (process gone) at ${run.stage || 'start'}`
819  if (run.state === 'failed') return run.message ? `failed: ${run.message}` : `failed at ${run.stage || 'start'}`
820
821  return 'starting'
822}
823
824// The overview row: the state line, then the file counts when there is something to say.
825function oneLine(run: Run, now: number): string {
826  const line = stateLine(run, now)
827  const c = run.changes
828  if (!c) return line
829  if (c.changed === 0 && c.uncommitted === 0) return run.state === 'running' ? `${line} · no changes yet` : line
830
831  return `${line} · ${c.changed} file${c.changed === 1 ? '' : 's'} changed (${c.uncommitted} uncommitted)`
832}
833
834async function sweepAgents($: EngineInterface) {
835  let list: Awaited<ReturnType<EngineInterface['agent']['list']>> = []
836  try {
837    list = await $.agent.list()
838  } catch {
839    return
840  }
841  await update($, agents, rows => {
842    const next = { ...rows }
843    for (const a of list) {
844      const was = next[a.id]
845      next[a.id] = {
846        id: a.id,
847        label: a.name ?? (a.description || a.type),
848        status: String(a.status),
849        tools: was?.tools ?? 0,
850        lastTool: was?.lastTool ?? '',
851        tokens: was?.tokens ?? 0,
852      }
853    }
854
855    return next
856  })
857}
858
859// Copies `text` to the clipboard of the surface that was pressed, and says whether it worked.
860async function copyText($: EngineInterface, text: string, surface: unknown) {
861  const r = await $.ui.copy({ text, surface } as never)
862  $.ui.toast(r.isCopied ? 'Copied' : `Could not copy (${r.reason})`)
863}
864
865// Every paused pipeline, at the top of the pane (board or pipeline view) and above the prompt, so a pause is noticed
866// wherever the developer is. Open goes to that pipeline. Nothing when no pipeline is paused.
867function attentionBanner($: EngineInterface, els: { Box: any; Text: any; Button: any }, runs: Run[], where: 'pane' | 'band') {
868  const { Box, Text, Button } = els
869  const paused = runs.filter(r => r.state === 'paused')
870  if (!paused.length) return null
871
872  return (
873    <Box flexDirection="column" borderStyle={where === 'pane' ? 'round' : undefined} borderColor={P.wait} paddingX={where === 'pane' ? 1 : 0} backgroundColor={P.ground}>
874      {paused.map(r => (
875        <Box key={`attention-${where}-${r.slug}`} gap={1} flexWrap="wrap" backgroundColor={P.ground}>
876          <Text bold color={P.wait} backgroundColor={P.ground}>⚠ Action needed:</Text>
877          <Text color={P.text} backgroundColor={P.ground}>{r.slug} · {r.stage || 'start'} · {stateLine(r, 0)}</Text>
878          <Button
879            key={`attention-${where}-open-${r.slug}`}
880            label="Open"
881            variant="primary"
882            onPress={async () => {
883              await update($, view, () => r.slug)
884              if (where === 'band') await $.ui.open({ id: PANE, title: 'SDLC control' })
885            }}
886          />
887        </Box>
888      ))}
889    </Box>
890  )
891}
892
893// The loader line (while a button press is working) and the last notice with Copy and Dismiss; both stay until they are gone.
894async function feedback($: EngineInterface, els: { Box: any; Text: any; Button: any }) {
895  const { Box, Text, Button } = els
896  const label = await read($, busy)
897  const spin = SPIN[(await read($, frame)) % SPIN.length]
898  const message = await read($, notice)
899  if (!label && !message) return null
900
901  return (
902    <Box flexDirection="column" backgroundColor={P.ground}>
903      {label && <Text color={P.wait} backgroundColor={P.ground}>{spin} {label}...</Text>}
904      {message && (
905        <Box gap={1} flexWrap="wrap" backgroundColor={P.ground}>
906          <Text color={P.run} backgroundColor={P.ground}>{message}</Text>
907          <Button key="notice-copy" label="Copy" onPress={(press: { surface?: unknown }) => copyText($, message, press?.surface)} />
908          <Button key="notice-dismiss" label="Dismiss" onPress={() => update($, notice, () => '')} />
909        </Box>
910      )}
911    </Box>
912  )
913}
914
915// Why a failed run failed, with a Copy button.
916function reasonBox($: EngineInterface, els: { Box: any; Text: any; Button: any }, run: Run) {
917  const { Box, Text, Button } = els
918  if (!run.reason.length) return null
919  const text = run.reason.join('\n')
920
921  return (
922    <Box flexDirection="column" backgroundColor={P.ground}>
923      <Box gap={1} backgroundColor={P.ground}>
924        <Text bold color={P.fail} backgroundColor={P.ground}>Why it failed{run.stage ? ` (${run.stage})` : ''}</Text>
925        <Button key="reason-copy" label="Copy" onPress={(press: { surface?: unknown }) => copyText($, text, press?.surface)} />
926      </Box>
927      {run.reason.map((line, i) => (
928        <Text key={`reason-${i}`} color={P.muted} backgroundColor={P.ground}>{line}</Text>
929      ))}
930    </Box>
931  )
932}
933
934const BOARD_COLS = ['Backlog', 'Spec', 'Plan', 'Red tests', 'Implement', 'Review', 'Done']
935// narrowest a board column is drawn; the pane shows as many whole columns as fit
936const COL_MIN = 24
937// the share of the pane the selected pipeline's details take
938const DETAIL_SHARE = 0.75
939// the board column of each stage in STAGES: Test repair belongs to Implement, Commit to Done
940const STAGE_COLUMN = [1, 2, 3, 4, 4, 5, 6]
941
942const stageColumn = (run: Run): number => {
943  if (run.state === 'done') return 6
944  const i = STAGES.indexOf(run.stage)
945
946  return i < 0 ? 1 : STAGE_COLUMN[i]
947}
948
949// How many whole columns fit in `width`, and the first one drawn: the stored offset, moved so the selected column shows.
950function boardWindow(width: number, first: number, selected: number): { visible: number; first: number } {
951  const visible = Math.min(BOARD_COLS.length, Math.max(1, Math.floor(width / COL_MIN)))
952  let at = first
953  if (selected >= 0 && selected < at) at = selected
954  if (selected > at + visible - 1) at = selected - visible + 1
955
956  return { visible, first: Math.min(Math.max(0, at), BOARD_COLS.length - visible) }
957}
958
959// The kanban board: the backlog and the pipelines by stage, with the controls to start, queue and clear runs.
960async function boardView($: EngineInterface, els: { Box: any; Text: any; Button: any }, s: Snapshot, o: { width: number; current: string; narrow: boolean }) {
961  const { Box, Text, Button } = els
962  const pick = await read($, selected)
963  const waiting = await read($, queue)
964  const rows = Object.values(await read($, agents))
965  const spin = spinGlyph(await read($, frame))
966  const now = await read($, working)
967  const reloading = await read($, refreshing)
968  const chosen = Object.keys(pick).filter(k => pick[k]).length
969  const running = s.runs.filter(r => r.state === 'running' || r.state === 'starting').length
970  const currentRun = s.runs.find(r => r.slug === o.current)
971  const selCol = currentRun ? stageColumn(currentRun) : o.current ? 0 : -1
972  const { visible, first } = boardWindow(o.width, await read($, boardOffset), selCol)
973  const shown = BOARD_COLS.slice(first, first + visible)
974  const colW = Math.max(COL_MIN, Math.floor(o.width / visible))
975  const step = (by: number) => update($, boardOffset, () => Math.min(Math.max(0, first + by), BOARD_COLS.length - visible))
976  const started = (slug: string) => s.runs.some(r => r.slug === slug)
977
978  const backlog = s.pending.filter(p => !started(p.slug) && !waiting.includes(p.slug))
979  const sorted = [...s.runs].sort((a, b) => ORDER[a.state] - ORDER[b.state])
980
981  const card = (key: string, edge: string, fill: string, children: any) => (
982    <Box key={`card-${key}`} flexDirection="column" borderStyle="single" borderColor={edge} backgroundColor={fill}>
983      {children}
984    </Box>
985  )
986
987  return (
988    <Box flexDirection="column" width={o.width} backgroundColor={P.ground}>
989      <Box gap={1} paddingX={1} flexWrap="wrap" backgroundColor={P.ground}>
990        <Text bold color={P.strong} backgroundColor={P.ground}>
991          SDLC control
992        </Text>
993        <Text color={P.muted} backgroundColor={P.ground}>
994          {summary(s.runs, waiting.length)} · up to {CAP} at once
995        </Text>
996        {/* reloads now and recounts every pipeline's files. While any refresh runs, its own or the background one, it spins and a press is ignored. */}
997        <Button
998          key="refresh"
999          label={reloading ? `${spin} Refreshing...` : labelOf(now, spin, 'refresh', 'Refresh', 'Refreshing...')}
1000          onPress={async () => {
1001            if (await read($, refreshing)) return
1002            await act($, 'refresh', 'Refreshing', () => refresh($, true))
1003          }}
1004        />
1005      </Box>
1006      {!o.narrow && (await feedback($, { Box, Text, Button }))}
1007      <Box gap={1} paddingX={1} flexWrap="wrap" backgroundColor={P.ground}>
1008        <Button key="board-left" label="◀" hotkey="h" onPress={() => step(-1)} />
1009        <Button key="board-right" label="▶" hotkey="l" onPress={() => step(1)} />
1010        <Text color={P.muted} backgroundColor={P.ground}>
1011          columns {first + 1}-{first + visible} of {BOARD_COLS.length}
1012        </Text>
1013        <Button key="run-selected" label={labelOf(now, spin, 'run-selected', `Run selected (${chosen})`, 'Starting...')} variant="primary" onPress={() => runSelected($)} />
1014        <Button key="clear-selected" label="Clear" onPress={() => update($, selected, () => ({}))} />
1015        <Text color={P.muted} backgroundColor={P.ground}>
1016          {running >= CAP ? 'both slots busy: extra items will queue' : `${CAP - running} slot(s) free`}
1017        </Text>
1018      </Box>
1019      <Box gap={1} backgroundColor={P.ground}>
1020        {shown.map((name, i) => {
1021          const col = first + i
1022          const runs = sorted.filter(r => stageColumn(r) === col)
1023          const count = col === 0 ? backlog.length + waiting.length : runs.length
1024
1025          return (
1026            <Box key={`col-${col}`} flexDirection="column" width={colW - 1} borderStyle="single" borderColor={P.line} backgroundColor={P.column}>
1027              <Box justifyContent="space-between" paddingX={1} backgroundColor={P.column}>
1028                <Text bold color={P.strong} backgroundColor={P.column}>
1029                  {name}
1030                </Text>
1031                <Text color={P.muted} backgroundColor={P.column}>
1032                  {count}
1033                </Text>
1034              </Box>
1035              {col === 0 && s.pending.length === 0 && waiting.length === 0 && (
1036                <Text color={P.muted} backgroundColor={P.column}>
1037                  {' '}Nothing pending
1038                </Text>
1039              )}
1040              {col === 0 &&
1041                backlog.map(p => {
1042                  const isOn = pick[p.slug] === true
1043                  const isCur = p.slug === o.current
1044                  const fill = isOn || isCur ? P.cardSelected : P.card
1045
1046                  return card(
1047                    p.slug,
1048                    isCur ? P.run : isOn ? P.run : P.edge,
1049                    fill,
1050                    <Box key={`pending-${p.slug}`} flexDirection="column" backgroundColor={fill}>
1051                      <Box gap={1} backgroundColor={fill}>
1052                        <Button key={`sel-${p.slug}`} label={cut(`${isOn ? '[x]' : '[ ]'} ${p.slug}`, colW - 19)} onPress={() => update($, selected, m => ({ ...m, [p.slug]: !m[p.slug] }))} />
1053                        <Button key={`more-${p.slug}`} label="Open" variant={isCur ? 'primary' : undefined} onPress={() => update($, view, () => p.slug)} />
1054                      </Box>
1055                      <Text color={P.muted} backgroundColor={fill}>
1056                        {cut(`${p.type} ${p.priority} · ${p.title}`, (colW - 7) * 2)}
1057                      </Text>
1058                    </Box>,
1059                  )
1060                })}
1061              {col === 0 &&
1062                waiting.map(slug =>
1063                  card(
1064                    `queued-${slug}`,
1065                    P.edge,
1066                    P.card,
1067                    <Box key={`queued-${slug}`} flexDirection="column" backgroundColor={P.card}>
1068                      <Text color={P.muted} backgroundColor={P.card}>
1069                        {cut(`◌ ${slug} queued`, (colW - 7) * 2)}
1070                      </Text>
1071                    </Box>,
1072                  ),
1073                )}
1074              {col !== 0 && runs.length === 0 && (
1075                <Text color={P.muted} backgroundColor={P.column}>
1076                  {' '}nothing here
1077                </Text>
1078              )}
1079              {col !== 0 &&
1080                runs.map(r => {
1081                  const isCur = r.slug === o.current
1082                  const fill = isCur ? P.cardSelected : P.card
1083                  const edge = isCur ? P.run : r.state === 'paused' ? P.wait : r.state === 'failed' || r.state === 'stopped' ? P.fail : P.edge
1084
1085                  return card(
1086                    r.slug,
1087                    edge,
1088                    fill,
1089                    <Box key={`run-${r.slug}`} flexDirection="column" backgroundColor={fill}>
1090                      <Button key={`open-${r.slug}`} label={cut(`${r.state === 'running' || r.state === 'starting' ? spin : GLYPH[r.state]} ${r.slug}`, colW - 11)} variant={r.state === 'paused' || isCur ? 'primary' : undefined} onPress={() => update($, view, () => r.slug)} />
1091                      <Text color={COLOR[r.state]} backgroundColor={fill}>
1092                        {cut(oneLine(r, s.now), (colW - 7) * 2)}
1093                      </Text>
1094                    </Box>,
1095                  )
1096                })}
1097            </Box>
1098          )
1099        })}
1100      </Box>
1101      {!o.narrow && rows.length > 0 && (
1102        <Box flexDirection="column" borderStyle="single" borderColor={P.line} paddingX={1} backgroundColor={P.ground}>
1103          <Text bold color={P.text} backgroundColor={P.ground}>
1104            Subagents of this session
1105          </Text>
1106          {rows.slice(0, 6).map(r => (
1107            <Text key={r.id} color={P.muted} backgroundColor={P.ground}>
1108              {r.label} · {r.status} · {r.tools} tools{r.lastTool ? ` (${r.lastTool})` : ''} · {r.tokens.toLocaleString()} tok
1109            </Text>
1110          ))}
1111        </Box>
1112      )}
1113    </Box>
1114  )
1115}
1116
1117let previous: Record<string, RunState> = {}
1118let isFirst = true
1119
1120// One refresh of the background loop: reload, start queued items, report state changes and update the status line.
1121// The loop never runs two at once (see `ticking`).
1122async function tick($: EngineInterface) {
1123  const s = await refresh($)
1124  await drainQueue($, s)
1125  await sweepAgents($)
1126  const now: Record<string, RunState> = {}
1127  for (const r of s.runs) {
1128    now[r.slug] = r.state
1129    if (!isFirst && previous[r.slug] && previous[r.slug] !== r.state) {
1130      if (r.state === 'paused') await notify($, `${r.slug} is paused: ${stateLine(r, 0)}`)
1131      else if (r.state === 'failed' || r.state === 'stopped') await notify($, `${r.slug} failed at ${r.stage || 'start'}`)
1132      else if (r.state === 'done') await notify($, `${r.slug} is done`)
1133    }
1134  }
1135  previous = now
1136  isFirst = false
1137  const q = await read($, queue)
1138  const active = s.runs.filter(r => r.state === 'running' || r.state === 'starting' || r.state === 'paused')
1139  $.ui.status(active.length || q.length ? `sdlc ${summary(s.runs, q.length)}` : undefined)
1140}
1141
1142let ticking = false
1143
1144export const register: Register = on => {
1145  on('session.start', async ($, e, next) => {
1146    await $.command.register({ name: 'sdlc-monitor', description: 'Open the SDLC control pane: start, watch, answer and stop pipelines' })
1147    await $.command.register({ name: 'sdlc-config', description: 'Open the CONFIG pane: providers and models of the model registry' })
1148    $.clock.every(SPIN_MS, async () => {
1149      // the frame turns while a button works and while any pipeline runs, so its card and stage box can spin
1150      const live = (await read($, snapshot)).runs.some(r => r.state === 'running' || r.state === 'starting')
1151      if (live || (await read($, busy)) || (await read($, working)) || (await read($, refreshing))) await update($, frame, n => n + 1)
1152    })
1153    $.clock.every(EVERY_MS, async () => {
1154      // a tick that is still running (a slow refresh, a start from the queue) is never joined by the next one
1155      if (ticking) return
1156      ticking = true
1157      try {
1158        await tick($)
1159      } finally {
1160        ticking = false
1161      }
1162    })
1163
1164    return next(e)
1165  })
1166
1167  on('command.run', { command: 'sdlc-monitor' }, async $ => {
1168    await refresh($)
1169    await sweepAgents($)
1170    await $.ui.open({ id: PANE, title: 'SDLC control' })
1171    const s = await read($, snapshot)
1172
1173    return { text: `SDLC control opened: ${summary(s.runs, 0)}, ${s.pending.length} pending.` }
1174  })
1175
1176  on('command.run', { command: 'sdlc-config' }, async $ => {
1177    await openConfig($)
1178
1179    return { text: 'CONFIG opened: providers and models.' }
1180  })
1181
1182  // Per-agent tool counts, for the session's own subagents (a headless `claude -p` stage is a separate process).
1183  on('tool.call', async ($, e, next) => {
1184    if (e.agentId) {
1185      const id = e.agentId
1186      await update($, agents, rows => {
1187        const was = rows[id] ?? { id, label: id.slice(0, 8), status: 'running', tools: 0, lastTool: '', tokens: 0 }
1188
1189        return { ...rows, [id]: { ...was, tools: was.tools + 1, lastTool: e.tool } }
1190      })
1191    }
1192
1193    return next(e)
1194  })
1195
1196  on('turn.complete', async ($, e, next) => {
1197    const u = e.usage
1198
1199    if (e.agentId && u) {
1200      const id = e.agentId
types/index.d.ts 120 lines
1export type Question = { n: number; title: string; body: string; suggested: string }
2
3export type RunState = 'starting' | 'running' | 'paused' | 'done' | 'failed' | 'interrupted' | 'stopped'
4
5// An action the pipeline's agent was refused (from Docs/backlog/<slug>/logs/permissions.json).
6export type PermissionAsk = {
7  stage: string
8  tool: string
9  detail: string
10  rule: string
11  // a path under .claude/: no allow rule lifts that refusal, only running the stage without permission checks
12  protected: boolean
13}
14
15export type Run = {
16  // files each stage changed, by stage name (from logs/stage-files.json); empty for a run that predates it
17  stageFiles: Record<string, string[]>
18  // actions refused and not decided yet; a paused run with these waits for Allow or Deny, then resumes at the stage
19  permissions: PermissionAsk[]
20  // test-issues.md: the tests the Implement agent claims are wrong, and why the pipeline rejected the claim (REJECT lines of run.out)
21  claims: Claim[]
22  claimRejects: string[]
23  // the last lines of the failed stage's log, else of run.out; empty unless the run failed or stopped
24  reason: string[]
25  slug: string
26  worktree: string
27  state: RunState
28  stage: string
29  agent: string
30  // Model and effort of the running agent, and of every stage (from status.json; empty for runs started before this was recorded).
31  model: string
32  effort: string
33  models: Record<string, { model: string; effort: string }>
34  attempt: string
35  agentStarted: string
36  runStarted: string
37  updated: string
38  // why a running pipeline is waiting (for example "usage limit, resets 1:10am (Asia/Dubai)"); empty while it works
39  note: string
40  pid: number
41  files: string[]
42  tests: { passed: number; failed: number; total: number } | null
43  tail: string[]
44  questions: Question[]
45  // false for a pipeline started by hand with scripts/sdlc.sh: it has no wrapper record, so no Stop or Resume
46  managed: boolean
47  // why the wrapper refused to start it (already merged, cap reached, no brief)
48  message: string
49  // files changed in the pipeline's own worktree (sdlc-mod.sh changes); null when unavailable (unmanaged, discarded, call failed)
50  changes: { changed: number; uncommitted: number } | null
51  // the base branch from the run record, '' when it has none
52  base: string
53}
54
55export type PendingItem = { slug: string; type: string; priority: string; title: string }
56
57// discarded: slug -> the command that brings its discarded branch back (kept by sdlc-mod.sh discard)
58export type Snapshot = { now: number; runs: Run[]; pending: PendingItem[]; discarded: Record<string, string> }
59
60export type AgentRow = {
61  id: string
62  label: string
63  status: string
64  tools: number
65  lastTool: string
66  tokens: number
67}
68
69export type ConfigProvider = { endpoint: string; api_key_env: string; models: string[]; effort: boolean; key_set: boolean }
70export type ConfigForm = { provider: string; endpoint: string; keyEnv: string; models: string; effort: boolean }
71
72declare module 'claude-code' {
73  interface PluginState {
74    'sdlc-monitor': {
75      snapshot: Snapshot
76      agents: Record<string, AgentRow>
77      // which pipeline the pane shows: '' is the overview
78      view: string
79      selected: Record<string, boolean>
80      queue: string[]
81      // the slug whose Stop button is waiting for a second press
82      confirmStop: string
83      // the slug whose Discard and restart button is waiting for a second press
84      confirmDiscard: string
85      // slug -> when Start was pressed, so a second press does not start it twice
86      launching: Record<string, number>
87      // answers typed for a paused run, keyed `<slug>:<question number>`
88      draft: Record<string, string>
89      // index of the first board column drawn
90      boardOffset: number
91      notice: string
92      // what a button press is working on; '' when idle
93      busy: string
94      // key of the button whose action is running (its label is a spinner); '' when none
95      working: string
96      // the spinner frame shown beside it
97      frame: number
98      // true while any refresh runs: the Refresh button spins and takes no press
99      refreshing: boolean
100      // the last `model list --json` result; null when never loaded or the last load failed
101      configList: Record<string, ConfigProvider> | null
102      // the message line of a failed `model list --json`; '' otherwise
103      configError: string
104      // the four form values stored by Enter
105      configForm: ConfigForm
106      // the provider whose Remove waits for a second press; '' when none
107      // which CONFIG page is drawn: the provider list or the add / edit form
108      configView: 'list' | 'form'
109      // the provider the form edits; '' for a new one
110      configEditing: string
111      configConfirmProvider: string
112      // the model whose Remove waits for a second press
113      configConfirmModel: { provider: string; model: string } | null
114    }
115  }
116}
117
118// One line of test-issues.md: "<file> :: <test name> :: <why>" (a line in another shape keeps its text in `why`).
119export type Claim = { file: string; test: string; why: string }
120