g-cauc: Garrett's caucus of AI models. Spec, product pass, foreman, build and review skills, plus the /board pane and the permission advisor.

Garrett's caucus: AI models from different companies that have to agree before anything ships.
One way of working for every project Garrett runs: ideas go into GitHub issues, agents turn them into agreed specs, and approved specs get built, reviewed, merged and deployed to staging without anyone watching. Production is Garrett's tap until a project has 10 clean staging runs.
g-cauc is instructions, not software. The loop is Claude Desktop scheduled tasks, the queue is GitHub Issues, the judge is GitHub's required checks, and the workers are the Claude, Codex and Cursor command-line tools. Nothing here holds state; state lives in GitHub and git. Design and research: ~/code/nessy/docs/proposals/2026-10-01-no-harness.md. Diagram: https://claude.ai/artifact/TzKoUxmuhAmwQT2fWCHxEb
Status: v1, 2026-10-01, untested. CallFlow is the pilot.
| Path | What it is |
|---|---|
skills/spec | The CTO session. Garrett and Claude plan together: kickoff for a new project or phase, or one feature. Ends in a spec PR. |
skills/propose | The product pass, run hourly. Turns idea issues into spec PRs, gets the CTO's agreement, turns merged specs into build issues. |
skills/cto-review | The CTO's review of a spec, run unattended by the product pass on the other model family. |
skills/foreman | One pass over every project: carries failures back to builders, starts reviews, starts builds, exits. |
skills/build | One build issue to one pull request, tests first. Also used for fix rounds. |
skills/agent-review | Cross-family review of one pull request. Sets the agent-review status. |
skills/adopt | Brings a repo up to the contract below, as one PR. |
templates/ | The AGENTS.md outline, CLAUDE.md, the spec format, the label set. |
lanes.md | The lanes (CLI, model, subscription), how many jobs each may run at once, launch commands, and how to tell a lane is out. |
routing.md | Which model for which job, the fallback order when a lane is out, and the cross-family rule. |
BRAND.md | The board's colors, type and shapes: status colors for state, and each project's own color for which project a thing belongs to. |
writing.md | How agents write for people: the part of Simplified Technical English (ASD-STE100) that g-cauc uses, and the check to run before posting. |
vendor/simplified-technical-english/ | The full STE rules, word list and check tool, copied from github.com/0xpili/simplified-technical-english (MIT; the word list belongs to ASD, see its NOTICE.md). |
projects.md | The projects the product pass and foreman serve, in priority order. |
tasks/ | The instructions for the three Desktop scheduled tasks: product pass, foreman, 7am digest. |
hooks/ | The mod: /board, the quiet line above the prompt, and the permission advisor. /board has a page for each project (its phase, pipeline, agents, CI and merges), an All page with a card for each project, a Fleet page for what the projects share (lanes, running jobs, the Claude plan, the runner pool), Allow, and a job view with each worker's thinking and commands. Each project shows in its own color from projects.md. It reads GitHub only on demand: when /board opens and the last read is more than 2 minutes old, and on /board refresh or the Refresh button. Its timers read local data only. All sessions share the last read. Two sessions can read at once, which is rare and costs about 19 points. All stop for 10 minutes after a rate limit. The quiet line shows the age of the last read. On the Desktop app it draws SVG; in a terminal, colored text. Tests in tests/. |
.claude-plugin/ | The plugin and marketplace manifests, so Claude Code installs all of this as one plugin. |
scripts/install.sh | Links every skill into ~/.codex/skills for Codex. Claude gets them from the plugin. |
scripts/dashboard.mjs | The progress page, ~/code/g-cauc/dashboard/index.html: each project's board (ready, building, in review, needs Garrett, merged in the last 24 hours), merged PRs per day for 14 days on one scale, the median time from PR open to merge, the latest merges, and CI: the jobs running and queued, the latest finished runs, and each runner pool machine with its load and slots. It reads GitHub with gh, the worker jobs on this Mac, the slice worktrees, and each machine in runner/hosts over SSH, and it uses no model. It reads GitHub only when you run it: node scripts/dashboard.mjs open writes the page and opens it. uninstall removes the old launchd agent com.gcauc.dashboard. An open page reloads itself every minute, so it shows the next write. It covers projects.md and each repo in runner/repos. |
scripts/labels.sh | Creates or updates the label set on a repo. |
runner/ | The CI runner pool on Garrett's Mac: a Linux VM, a job image, and gcauc-runner, which gives every CI job a fresh container with a one-job runner registration. See runner/README.md. |
The kit never assumes a language or framework. It only calls these entry points and reads their exit codes, so a Python, TypeScript, Go or mixed project all look the same from outside.
| Entry point | What it must do |
|---|---|
scripts/done --fast | Lint, type check and the tests for what changed, fast enough to run many times per build. Exit 0 means green. CI runs it on every push to a PR. |
scripts/done --full | Everything, including the full end-to-end suite on a fresh stack. CI runs it once in each review round of a PR, and on every push to main. |
scripts/dev up / down | Boots the app and its services for one worktree, on ports that do not collide with another worktree. |
scripts/dev testdb -- CMD | Runs CMD against a throwaway database that is never the dev database. |
scripts/deploy staging | Deploys main to staging, then runs the smoke end-to-end pass against it. |
AGENTS.md | The map every tool reads (outline in templates/AGENTS.md), including a Test layers table and an Autonomy: line. |
CLAUDE.md | @AGENTS.md plus any Claude-only lines. |
| GitHub | Branch protection on main (PR only, CI and agent-review required, no bypass), auto-merge allowed, the label set, Issues on. |
| CI | Every workflow job that runs project code uses runs-on: [self-hosted, gcauc], the runner pool in runner/, not GitHub's hosted runners (hosted minutes ran out on CallFlow on 2026-10-04). |
Fast on every push, full once in each review round. A push to a PR runs scripts/done --fast, plus any quick job the project adds for the changed code. The full suite runs on a PR only when the ci:full label is added, and on every push to main. The foreman starts each review when the PR opens or a fix is pushed. It does not wait for CI. In a project whose full suite has a workflow file of its own, it adds ci:full at the same time. The fast checks, the full suite and the review then run side by side on the head commit. A later push does not run it again: the next review round adds the label again. The full run sets a commit status, and branch protection requires that status. The status is the merge gate, not the job, because GitHub counts a skipped job as a passed required check. Garrett asked for this on 2026-10-12. In the week before, Bison Brain ran the full suite 2.6 times for each merged PR, and CallFlow 3.3 times.
Which test tools sit behind scripts/done is the project's choice and is written in its Test layers table: pytest, Vitest, Jest, Playwright, simulated phone calls, data checks. Every acceptance check in a spec names its layer and the command that proves it.
Autonomy: attended until the project's walking skeleton has passed every gate once with Garrett watching. Then Autonomy: unattended, which is what lets agents push feature branches and open PRs there without asking.
Ideas and specs:
idea: Garrett opened it (one line is enough). Any issue Garrett opens with no lifecycle label counts as an idea.proposed: the product pass opened a spec PR for it.agreed: product and CTO have both signed off on the spec PR's current commit. Waiting on Garrett.Build issues:
ready: the foreman may start it once everything in its Blocked by list is closed.building: a worker has it.in-review: its PR is open; CI and the cross-family review run.needs:garrett: parked with one question and a default. The queue keeps moving.The foreman never touches an issue that is not ready. Nothing is ready until its spec was agreed by product and CTO and merged by Garrett. The one exception is a review follow-up of size S and normal risk: the product pass makes it ready with no spec, and the 7am digest lists it (Garrett, 2026-10-12).
Other labels: spec (spec PRs), ci:full (the foreman adds it once for each head commit, and CI then runs the full suite on that commit beside the review), from-review (advisory findings: a size S, normal-risk one goes to ready with no spec, and the rest go into one hardening spec), risk:high (data, auth, money, migrations, deploy: Garrett merges the build PR too unless he delegated it, as CallFlow's D23 does), size:s, size:m, size:l, lane:<name>, area:<name> (per project, so work in different areas runs in parallel).
Claude Code (the skills, /board and the permission advisor), once:
claude plugin marketplace add garrettyarmo/g-cauc
claude plugin install g-cauc@g-cauc
Install from GitHub, not from the local folder: the local folder may be on a feature branch, and the installed plugin would follow it. After a change lands on main, bump version in .claude-plugin/plugin.json, then claude plugin marketplace update g-cauc, claude plugin update g-cauc@g-cauc and /reload-plugins in open sessions. While working on the mod itself, load the folder directly with claude --plugin-dir ~/code/g-cauc and run claude plugin test in it.
Codex reads the same skills through links:
~/code/g-cauc/scripts/install.sh
~/code/g-cauc/scripts/labels.sh garrettyarmo/callflow
The CI runner pool (once per Mac; it serves every repo in runner/repos):
~/code/g-cauc/runner/gcauc-runner up
~/code/g-cauc/runner/gcauc-runner install
The kit ships with Garrett's setup as its defaults. To run it for yourself:
~/code/g-cauc, set the plugin's "g-cauc folder" in /config.projects.md with your repos.lanes.md to match your subscriptions: set Max jobs to 0 for any lane you do not have.scripts/labels.sh <owner>/<repo> on each repo, then the adopt skill in each one.hooks/register.js 955 lines1// g-cauc mod: the /board pane, the quiet line above the prompt, and the
2// permission advisor. It reads the process list and job logs on a timer. It
3// reads GitHub only on demand. It holds no state of record (GitHub and git do).
4// It keeps a shared cache in $.store, so every session shows the last read.
5
6import {
7 parseProjects, parseLanes, summarizeProject, parseJobs, laneOf, modelName, parseEtime,
8 fmtDuration, parseLsof, parseLog, bar, bandText, suggestedRules, withAllowed, labelsOf, parseClaudeAgents,
9 asArray, sanitize, callKey, monogram,
10} from './lib.js'
11import { parseRuns, parseRunJobs, parseRunners, parseRepoSlots, doneTimings, budgetsFromDone, refusalMessage, summarizeCi, ciBand, vmName } from './ci.js'
12import { colored, progress, pill, cells, dots, budgetTone, badge, ring, pipeline, projectColor } from './draw.js'
13
14const PANE = 'g-cauc-board'
15// GitHub budget. Every Claude Code session on the Mac runs this module.
16// All of them share one GraphQL limit (5,000 an hour, across Garrett's tokens).
17// So the board reads GitHub only on demand: when /board opens on an old shared
18// snapshot, and on /board refresh or the Refresh button. Each read costs about
19// 19 points. Two sessions can read at once: on demand, that is rare and cheap.
20// Every session stops for a while after GitHub says "rate limit". The timers
21// read local data (jobs, logs, lanes) and pick up the snapshot any session saved.
22const FRESH_MS = 2 * 60_000 // opening /board reads GitHub when the snapshot is older than this
23const PAUSE_MS = 10 * 60_000 // the stop after a rate limit
24// The CI snapshot's store key names its shape, so a session never reads a
25// snapshot an older version of the board wrote.
26const CI_SNAPSHOT = 'ci-snapshot-2'
27const APPROVALS_TO_SUGGEST = 10
28// How much GitHub a refresh reads: none (a timer), only an old snapshot (opening /board), or now (Refresh).
29const LOCAL = 0
30const IF_OLD = 1
31const NOW = 2
32
33let home = ''
34// Where projects.md, lanes.md and limits/ live: the plugin's kit_dir setting.
35let kitSetting = '~/code/g-cauc'
36let kitDir = ''
37let projects = []
38let jobs = []
39let recent = []
40let lanes = []
41let claudeLimits = []
42let refreshedAt = 0
43// CI across projects: { at, projects: [{ name, repo, key, vm, ci, error }], billing }. vm is the
44// state of the project's own runner VM, or '' when the pool does not serve the repo.
45let ci = { at: 0, projects: [], billing: null }
46let ghLogin = null
47let billingAt = 0
48let lastError = ''
49// Set when a command's output says GitHub's rate limit is spent; read after a gather.
50let rateLimited = false
51let pausedUntil = 0
52// Open PRs per repo from this gather's project read, so the CI read reuses them.
53const openPrsByRepo = new Map()
54let busy = false
55let again = LOCAL
56
57let paneOpen = false
58let tab = 'all'
59let selected = null
60let detail = null
61let showThinking = false
62
63// Tool calls that went to a permission prompt, by tool_use_id, until they run or expire.
64let asks = new Map()
65let allow = {}
66
67export function register(on, options) {
68 if (options && typeof options.kit_dir === 'string' && options.kit_dir.trim()) kitSetting = options.kit_dir.trim()
69 on('session.start', async ($, e, next) => {
70 const result = await next(e)
71 await $.command.register({ name: 'board', description: 'g-cauc: each project\'s plan, agents and CI; the shared lanes and pool; allow-list suggestions', argumentHint: '[refresh]', immediate: true })
72 home = (await $.env.get('HOME')) || ''
73 kitDir = kitSetting.replace(/^~(?=\/|$)/, home).replace(/\/$/, '')
74 $.clock.after(1500, () => refresh($, LOCAL))
75 $.clock.every(60_000, () => refresh($, LOCAL))
76 $.clock.every(4_000, () => followJob($))
77 return result
78 })
79
80 on('command.run', { command: 'board' }, async ($, e) => {
81 if (String(e.args || '').trim() === 'refresh') {
82 refresh($, NOW)
83 return { text: 'g-cauc: refreshing' }
84 }
85 paneOpen = true
86 await $.ui.open({ id: PANE, title: 'g-cauc', focus: true, closeOnEscape: true })
87 // Opening the board shows the shared snapshot at once and reads GitHub only when the snapshot is old.
88 refresh($, IF_OLD)
89 return {}
90 })
91
92 on('ui.close', async ($, e, next) => {
93 if (e.id === PANE) paneOpen = false
94 return next(e)
95 })
96
97 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
98 const line = bandText(projects, jobs)
99 const cib = ciBand(ci.projects)
100 const survey = (e.props && e.props.hasSurvey) || e.hasSurvey
101 if ((!line && !cib) || survey) return next(e)
102 const E = $.ui.resolve(e)
103 const theirs = await next(e)
104 const parts = [E.Text({ dimColor: true, children: [(line || 'g-cauc') + (cib ? ' · ' + cib.text : '')] })]
105 if (cib && cib.alert) parts.push(colored(E, e.surface, 'bad', ' · ' + cib.alert, { bold: true }))
106 const age = refreshedAt ? ' · ' + fmtDuration(((await $.clock.now()) - refreshedAt) / 1000) + ' ago' : ''
107 parts.push(E.Text({ dimColor: true, children: [' /board' + age] }))
108 const mine = E.Box({ flexDirection: 'row', children: parts })
109 return E.Box({ flexDirection: 'column', children: theirs ? [theirs, mine] : [mine] })
110 })
111
112 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
113 if (e.requestId !== PANE) return next(e)
114 const E = $.ui.resolve(e)
115 const width = (e.props && e.props.bodyColumns) || 80
116 return boardView($, E, width, e.surface)
117 })
118
119 // Permission advisor: a dialog you answered, then the same call running,
120 // counts as one approval of each rule Claude Code suggested for it.
121 // The order for one call: tool.check says ask, the dialog opens
122 // (PermissionRequest), and only an approved call runs (PostToolUse, same id).
123 on('tool.check', async ($, e, next) => {
124 const verdict = await next(e)
125 if (verdict && verdict.decision === 'ask' && e.tool_use_id && next.origin && next.origin.plugin === 'engine') {
126 const now = await $.clock.now()
127 for (const [id, a] of asks) if (now - a.at > 30 * 60_000) asks.delete(id)
128 asks.set(e.tool_use_id, { tool: e.tool, key: callKey(e.tool, e.input), at: now, rules: null, cwd: '' })
129 }
130 return verdict
131 })
132
133 on('classic.PermissionRequest', async ($, e, next) => {
134 const rules = suggestedRules(e.permission_suggestions)
135 if (rules.length) {
136 // The dialog belongs to the open ask for the same call (tool and command
137 // or path). Anything else, including no match, counts nothing.
138 // A dialog opens seconds after its call is checked, so only calls checked in
139 // the last 2 minutes qualify (an ask the auto-mode classifier denied never
140 // gets a dialog and must not swallow a later one); the oldest of those wins,
141 // since dialogs arrive in call order.
142 const key = callKey(e.tool_name, e.tool_input)
143 const now = await $.clock.now()
144 const match = [...asks.values()].filter((a) => a.key === key && !a.rules && now - a.at < 120_000)
145 const ask = match.length ? match[0] : null
146 if (ask) {
147 ask.rules = rules
148 ask.cwd = e.cwd
149 }
150 }
151 return next(e)
152 })
153
154 on('classic.PostToolUse', async ($, e, next) => {
155 const ask = asks.get(e.tool_use_id)
156 if (ask) {
157 asks.delete(e.tool_use_id)
158 if (ask.rules) await countApproval($, ask)
159 }
160 return next(e)
161 })
162}
163
164// ---------- gathering ----------
165
166// stdout of a command that exited 0, or null.
167async function sh($, argv, cwd) {
168 try {
169 const r = await $.process.run(argv, cwd ? { cwd, timeoutMs: 30_000 } : { timeoutMs: 30_000 })
170 if (r.exitCode !== 0 && /API rate limit/i.test(String(r.stderr || '') + String(r.stdout || ''))) rateLimited = true
171 return r.exitCode === 0 ? r.stdout : null
172 } catch {
173 return null
174 }
175}
176
177// stdout whatever the exit code: ps and lsof exit 1 when one of several pids is gone.
178async function shAny($, argv) {
179 try {
180 const r = await $.process.run(argv, { timeoutMs: 30_000 })
181 return r.stdout || ''
182 } catch {
183 return ''
184 }
185}
186
187async function readText($, path) {
188 try {
189 if (!(await $.fs.exists(path))) return ''
190 return String(await $.fs.read(path))
191 } catch {
192 return ''
193 }
194}
195
196// Two sessions can hit a rate limit at once, and $.store has no atomic write.
197// So each stop has its own key, named by its end, and no session rewrites it.
198// A slow session cannot shorten a later stop. An expired key never changes, so any session may delete it.
199async function readPause($, now) {
200 let until = 0
201 for (const k of await $.store.keys()) {
202 if (!k.startsWith('gh-pause')) continue
203 const pause = await $.store.get(k)
204 const end = Number(pause && pause.until) || 0
205 if (end > now) until = Math.max(until, end)
206 else if (k.startsWith('gh-pause-')) await $.store.delete(k)
207 }
208 return until
209}
210
211async function refresh($, gh) {
212 if (busy) {
213 again = Math.max(again, gh)
214 return
215 }
216 busy = true
217 let cached = null
218 try {
219 const now = await $.clock.now()
220 pausedUntil = await readPause($, now)
221 cached = await $.store.get('snapshot')
222 const ciCached = await $.store.get(CI_SNAPSHOT)
223 lanes = parseLanes(await readText($, kitDir + '/lanes.md'))
224 // Refresh skips the age check. It never skips the pause.
225 const old = !cached || !ciCached || now - Math.min(cached.at, ciCached.at) >= FRESH_MS
226 if (!pausedUntil && (gh === NOW || (gh === IF_OLD && old))) {
227 rateLimited = false
228 openPrsByRepo.clear()
229 projects = await gatherProjects($, cached)
230 await $.store.set('snapshot', { at: now, projects, lanes })
231 ci = await gatherCi($, ciCached, now)
232 await $.store.set(CI_SNAPSHOT, ci)
233 if (rateLimited) {
234 // The stop runs from the rate-limit answer, not from the start of the refresh
235 pausedUntil = (await $.clock.now()) + PAUSE_MS
236 await $.store.set('gh-pause-' + pausedUntil, { until: pausedUntil })
237 // An older board reads only gh-pause
238 await $.store.set('gh-pause', { until: pausedUntil })
239 }
240 refreshedAt = now
241 } else {
242 if (cached) {
243 projects = cached.projects
244 refreshedAt = cached.at
245 }
246 if (ciCached) ci = ciCached
247 }
248 jobs = await gatherJobs($)
249 recent = await gatherRecent($)
250 lanes = await withLaneState($, lanes)
251 allow = await loadAllow($)
252 await toastNewNeeds($)
253 lastError = ''
254 } catch (err) {
255 lastError = String((err && err.message) || err)
256 // Nothing on screen yet (a cold start): show the last snapshot any session saved.
257 if (projects.length === 0 && cached && Array.isArray(cached.projects)) {
258 projects = cached.projects.map((p) => ({ ...p, stale: true }))
259 try {
260 lanes = await withLaneState($, cached.lanes || [])
261 } catch {
262 lanes = []
263 }
264 }
265 } finally {
266 busy = false
267 $.ui.invalidate('ui.render')
268 if (again) {
269 const next = again
270 again = LOCAL
271 refresh($, next)
272 }
273 }
274}
275
276// A file as it is on origin/main (the checkout can lag behind), else as it is on disk.
277async function readMain($, path, file) {
278 const shown = await sh($, ['git', '-C', path, 'show', 'origin/main:' + file])
279 return shown !== null ? shown : readText($, path + '/' + file)
280}
281
282async function specFiles($, path) {
283 const listed = await sh($, ['git', '-C', path, 'ls-tree', '--name-only', 'origin/main', 'specs/'])
284 if (listed !== null) return listed.split('\n').map((l) => l.replace(/^specs\//, '').trim()).filter(Boolean)
285 try {
286 return (await $.fs.list(path + '/specs')).map((f) => f.name)
287 } catch {
288 return []
289 }
290}
291
292async function gatherProjects($, cached) {
293 const list = parseProjects(await readText($, kitDir + '/projects.md'), home)
294 if (list.length === 0) throw new Error('could not read any project from ' + kitDir.replace(home, '~') + '/projects.md. The board shows the last good data.')
295 const out = []
296 for (const p of list) {
297 try {
298 const issues = asArray(await sh($, ['gh', 'issue', 'list', '--repo', p.repo, '--state', 'all', '--limit', '300', '--json', 'number,title,state,labels,body,url']))
299 const openPrs = asArray(await sh($, ['gh', 'pr', 'list', '--repo', p.repo, '--state', 'open', '--limit', '50', '--json', 'number,title,labels,url,headRefName,mergeStateStatus,statusCheckRollup']))
300 if (openPrs) openPrsByRepo.set(p.repo, openPrs)
301 const mergedPrs = asArray(await sh($, ['gh', 'pr', 'list', '--repo', p.repo, '--state', 'merged', '--limit', '20', '--json', 'number,title,mergedAt,url']))
302 if (!issues || !openPrs || !mergedPrs) throw new Error('gh could not read ' + p.repo + '. The board shows the last good data.')
303 const roadmap = await readMain($, p.path, 'ROADMAP.md')
304 const agents = await readMain($, p.path, 'AGENTS.md')
305 const specs = []
306 for (const name of await specFiles($, p.path)) {
307 const m = name.match(/^(\d{3})-.*\.md$/)
308 if (!m) continue
309 const text = await readMain($, p.path, 'specs/' + name)
310 const title = ((text.match(/^#\s+(.+)$/m) || [])[1] || name).replace(/^(Spec\s+)?\d{3}\s*[:.]\s*/i, '')
311 specs.push({ num: m[1], file: name, title, text: text.slice(0, 2000) })
312 }
313 const summary = summarizeProject({
314 issues,
315 openPrs,
316 mergedPrs,
317 roadmap,
318 specs,
319 autonomy: ((agents.match(/^Autonomy:\s*(\w+)/m) || [])[1] || 'unknown'),
320 now: Date.now(),
321 })
322 for (const k of ['building', 'inReview', 'ready']) summary[k] = summary[k].map((i) => ({ number: i.number, title: i.title, url: i.url, labels: labelsOf(i), waitingOn: i.waitingOn || [] }))
323 // Titles of open issues and PRs by number (one numbering on GitHub), for job rows.
324 const titles = {}
325 for (const x of [...issues.filter((i) => i.state === 'OPEN'), ...openPrs]) titles[x.number] = sanitize(String(x.title || ''), 200)
326 out.push({ ...p, summary, titles, key: p.path.split('/').pop() })
327 } catch (err) {
328 const before = [...projects, ...((cached && cached.projects) || [])].find((x) => x.repo === p.repo)
329 const fallback = before ? before.summary : summarizeProject({ issues: [], openPrs: [], mergedPrs: [], roadmap: '', specs: [], autonomy: 'unknown' })
330 out.push({ ...p, key: p.path.split('/').pop(), summary: fallback, stale: true, error: String((err && err.message) || err) })
331 }
332 }
333 return out
334}
335
336async function gatherJobs($) {
337 const agents = await sh($, ['claude', 'agents', '--json'])
338 const claudeJobs = agents === null ? [] : parseClaudeAgents(agents, home, Date.now()).map((j) => ({ ...j, lane: 'claude' }))
339 // Without claude agents --json, fall back to Claude workers' own process lines.
340 const found = parseJobs(await shAny($, ['pgrep', '-lf', 'ak:']), { claude: agents === null })
341 if (found.length === 0) return claudeJobs
342 const pids = found.map((j) => j.pid).join(',')
343 const etimes = new Map()
344 for (const line of (await shAny($, ['ps', '-o', 'pid=,etime=', '-p', pids])).split('\n')) {
345 const m = line.trim().match(/^(\d+)\s+(\S+)/)
346 if (m) etimes.set(Number(m[1]), parseEtime(m[2]))
347 }
348 const logs = parseLsof(await shAny($, ['lsof', '-a', '-d', '1', '-Fpn', '-p', pids]))
349 return [...found.map((j) => ({ ...j, lane: laneOf(j.cli, j.model), elapsed: etimes.get(j.pid) || 0, log: logs.get(j.pid) || '' })), ...claudeJobs]
350}
351
352async function gatherRecent($) {
353 const out = []
354 for (const p of projects) {
355 const dir = p.path + '_wt/logs'
356 const names = ((await sh($, ['/bin/ls', '-t', dir])) || '').split('\n').filter(Boolean).slice(0, 8)
357 for (const n of names) out.push({ project: p.key, name: n, path: dir + '/' + n })
358 }
359 return out.slice(0, 12)
360}
361
362async function withLaneState($, base) {
363 const now = Date.now()
364 const result = []
365 for (const l of base) {
366 // The first line is the reset time; the foreman may add a line naming its test job.
367 const until = (await readText($, kitDir + '/limits/' + l.lane)).split('\n')[0].trim()
368 const out = until && Date.parse(until) > now ? until : ''
369 result.push({ ...l, running: jobs.filter((j) => j.lane === l.lane).length, outUntil: out })
370 }
371 try {
372 const u = await $.session.usage()
373 claudeLimits = (u && u.rateLimits) || []
374 } catch {
375 claudeLimits = []
376 }
377 return result
378}
379
380// ---------- CI ----------
381
382const repoOk = (r) => /^[\w.-]+\/[\w.-]+$/.test(r)
383
384// Facts about one finished run that never change: whether GitHub refused it,
385// and the done timings in its log. Cached per run in $.store.
386async function runFacts($, repo, run) {
387 const jobsOfRun = parseRunJobs(await sh($, ['gh', 'api', `repos/${repo}/actions/runs/${run.id}/jobs?per_page=50`]), run) || []
388 const facts = { refused: null, fast: null, full: null }
389 for (const j of jobsOfRun) {
390 if (j.conclusion === 'failure' && j.steps.length === 0) {
391 const msg = refusalMessage(asArray(await sh($, ['gh', 'api', `repos/${repo}/check-runs/${j.id}/annotations`])))
392 if (msg) facts.refused = msg
393 }
394 if (j.name === 'done' && j.steps.length && repoOk(repo)) {
395 // The job's log path is an argument, not part of the script, and a failed gh call exits 3.
396 const lines = await sh($, ['sh', '-c', 'out=$(gh api "$1") || exit 3; printf "%s\\n" "$out" | grep -E "done --(fast|full): " | tail -4; exit 0', 'sh', `repos/${repo}/actions/jobs/${Number(j.id)}/logs`])
397 if (lines === null) facts.retry = true
398 for (const t of doneTimings(lines || '')) facts[t.mode] = t
399 }
400 }
401 return facts
402}
403
404async function gatherCi($, cached, now) {
405 const repoSlots = parseRepoSlots(await readText($, kitDir + '/runner/repos'))
406 const out = []
407 for (const p of projects) {
408 const key = p.path.split('/').pop()
409 const vm = repoSlots.some((x) => x.repo === p.repo) ? ((await sh($, ['limactl', 'list', vmName(p.repo), '--format', '{{.Status}}'])) || '').trim() || 'not created' : ''
410 try {
411 if (!repoOk(p.repo)) throw new Error('not a GitHub repo name: ' + p.repo)
412 const runs = parseRuns(await sh($, ['gh', 'api', `repos/${p.repo}/actions/runs?per_page=40`]))
413 if (!runs) throw new Error('gh could not read the Actions runs of ' + p.repo + '. The board shows the last good data.')
414 const liveJobs = []
415 for (const r of runs.filter((x) => x.status !== 'completed').slice(0, 8)) {
416 liveJobs.push(...(parseRunJobs(await sh($, ['gh', 'api', `repos/${p.repo}/actions/runs/${r.id}/jobs?per_page=50`]), r) || []))
417 }
418 const runners = parseRunners(await sh($, ['gh', 'api', `repos/${p.repo}/actions/runners?per_page=100`])) || []
419 const prs = openPrsByRepo.get(p.repo) || asArray(await sh($, ['gh', 'pr', 'list', '--repo', p.repo, '--state', 'open', '--limit', '50', '--json', 'number,title,labels,url,headRefName,mergeStateStatus,statusCheckRollup'])) || []
420 // GitHub's single merge state hides BEHIND under BLOCKED, so ask git whether the head contains main.
421 const behind = {}
422 for (const pr of prs.slice(0, 30)) {
423 if (!/^[\w./-]+$/.test(String(pr.headRefName || ''))) continue
424 try {
425 const r = await $.process.run(['git', '-C', p.path, 'merge-base', '--is-ancestor', 'origin/main', 'origin/' + pr.headRefName], { timeoutMs: 10_000 })
426 if (r.exitCode === 0) behind[pr.number] = false
427 else if (r.exitCode === 1) behind[pr.number] = true
428 } catch {
429 // unknown: GitHub's merge state decides
430 }
431 }
432 const facts = {}
433 let fetched = 0
434 const keep = new Set()
435 for (const r of runs.filter((x) => x.status === 'completed').slice(0, 20)) {
436 const k = 'ci-run\u0000' + p.repo + '\u0000' + r.id
437 keep.add(k)
438 let f = await $.store.get(k)
439 if ((!f || (f.retry && (f.tries || 0) < 3)) && fetched < 4) {
440 fetched += 1
441 const tries = ((f && f.tries) || 0) + 1
442 f = { ...(await runFacts($, p.repo, r)), tries }
443 await $.store.set(k, f)
444 }
445 if (f) facts[r.id] = f
446 }
447 for (const k of await $.store.keys()) if (k.startsWith('ci-run\u0000' + p.repo + '\u0000') && !keep.has(k)) await $.store.delete(k)
448 const budgets = budgetsFromDone(await readMain($, p.path, 'scripts/done'))
449 const slotCount = (repoSlots.find((x) => x.repo === p.repo) || {}).slots ?? null
450 out.push({ name: p.name, repo: p.repo, key, vm, ci: summarizeCi({ runs, jobs: liveJobs, runners, slots: slotCount, prs, facts, budgets, now, behind }) })
451 } catch (err) {
452 const before = [...ci.projects, ...((cached && cached.projects) || [])].find((x) => x.repo === p.repo && x.ci)
453 out.push({ name: p.name, repo: p.repo, key, vm, ci: before ? before.ci : null, stale: true, error: String((err && err.message) || err) })
454 }
455 }
456 return { at: now, projects: out, billing: await billing($, cached) }
457}
458
459// Actions minutes this month, when the gh token has the user scope. A GitHub read reads them at most every 10 minutes.
460async function billing($, cached) {
461 if (Date.now() - billingAt < 10 * 60_000) return (cached && cached.billing) || ci.billing
462 billingAt = Date.now()
463 if (!ghLogin) ghLogin = ((await sh($, ['gh', 'api', 'user', '--jq', '.login'])) || '').trim() || null
464 if (!ghLogin) return { error: 'gh is not signed in' }
465 const raw = await sh($, ['gh', 'api', `users/${ghLogin}/settings/billing/actions`])
466 try {
467 const b = JSON.parse(raw || '')
468 return { used: b.total_minutes_used ?? null, included: b.included_minutes ?? null, paid: b.total_paid_minutes_used ?? null }
469 } catch {
470 return { error: 'billing needs the gh "user" scope (gh auth refresh -s user)' }
471 }
472}
473
474async function toastNewNeeds($) {
475 // No snapshot yet (a cold start before the first read): nothing to compare.
476 if (!projects.length) return
477 const seen = await $.store.get('needsSeen')
478 const ok = projects.filter((p) => !p.stale)
479 const kept = Array.isArray(seen) ? seen.filter((k) => projects.some((p) => p.stale && k.startsWith(p.repo + '#'))) : []
480 const now = [...kept, ...ok.flatMap((p) => p.summary.needs.map((n) => `${p.repo}#${n.number}`))]
481 if (Array.isArray(seen)) {
482 const fresh = ok.flatMap((p) => p.summary.needs.filter((n) => !seen.includes(`${p.repo}#${n.number}`)).map((n) => `${p.name} #${n.number}`))
483 if (fresh.length) $.ui.toast('g-cauc: ' + fresh.join(', ') + (fresh.length === 1 ? ' needs you' : ' need you') + ' (/board)')
484 }
485 await $.store.set('needsSeen', now)
486}
487
488async function followJob($) {
489 if (!paneOpen || tab !== 'job' || !selected) return
490 const text = (await sh($, ['tail', '-c', '400000', selected.path])) || ''
491 detail = parseLog(text)
492 $.ui.invalidate('ui.render')
493}
494
495// ---------- permission advisor ----------
496
497// The working tree the session is in, so a rule takes effect where the prompts happen.
498async function treeRoot($, cwd) {
499 const top = ((await sh($, ['git', 'rev-parse', '--show-toplevel'], cwd)) || '').trim()
500 return top || cwd
501}
502
503// One store key per rule, read right before each write, so sessions racing
504// on different rules never overwrite each other.
505const allowKey = (root, rule) => 'allow\u0000' + root + '\u0000' + rule
506
507async function loadAllow($) {
508 const all = {}
509 for (const k of await $.store.keys()) {
510 if (!k.startsWith('allow\u0000')) continue
511 const [, root, rule] = k.split('\u0000')
512 all[root] = all[root] || {}
513 all[root][rule] = await $.store.get(k)
514 }
515 return all
516}
517
518async function countApproval($, ask) {
519 const root = await treeRoot($, ask.cwd)
520 for (const rule of ask.rules) {
521 const key = allowKey(root, rule)
522 const r = (await $.store.get(key)) || { count: 0, state: 'counting' }
523 r.count += 1
524 if (r.state === 'counting' && r.count >= APPROVALS_TO_SUGGEST) {
525 r.state = 'suggested'
526 $.ui.toast(`g-cauc: you approved ${rule} ${r.count} times. To stop the prompts for it, open /board → Allow.`)
527 }
528 await $.store.set(key, r)
529 }
530 allow = await loadAllow($)
531 $.ui.invalidate('ui.render')
532}
533
534async function decideRule($, root, rule, verdict) {
535 if (verdict === 'apply') {
536 const path = root + '/.claude/settings.json'
537 let current = {}
538 if (await $.fs.exists(path)) {
539 try {
540 current = JSON.parse(String(await $.fs.read(path)))
541 } catch {
542 $.ui.toast('g-cauc: .claude/settings.json is not valid JSON. The board did not change it.')
543 return
544 }
545 }
546 const next = withAllowed(current, [rule])
547 if (!next) {
548 $.ui.toast('g-cauc: .claude/settings.json has a permissions shape that the board does not edit. The board did not change it.')
549 return
550 }
551 await $.fs.write(path, JSON.stringify(next, null, 2) + '\n')
552 $.ui.toast(`g-cauc: added ${rule} to ${path.replace(home, '~')}. Commit it with this branch so every worktree gets it.`)
553 }
554 const key = allowKey(root, rule)
555 const r = (await $.store.get(key)) || { count: 0 }
556 await $.store.set(key, { ...r, state: verdict === 'apply' ? 'applied' : 'dismissed' })
557 allow = await loadAllow($)
558 $.ui.invalidate('ui.render')
559}
560
561// ---------- drawing ----------
562//
563// Pages: All (a card per project), one page per project (its plan, the agents
564// on it and its CI), Fleet (what the projects share: lanes, running jobs, the
565// Claude plan and the runner pool), Allow and Job. Each project is drawn in its
566// own color from projects.md; status colors mean only state (BRAND.md).
567
568function suggestions() {
569 const out = []
570 for (const [root, rules] of Object.entries(allow || {})) {
571 for (const [rule, r] of Object.entries(rules)) if (r.state === 'suggested') out.push({ root, rule, count: r.count })
572 }
573 return out
574}
575
576const projectTab = (p) => 'p-' + p.key
577const ciOf = (key) => ci.projects.find((c) => c.key === key) || null
578const projectOf = (key) => projects.find((p) => p.key === key) || null
579
580// A project's color, or the muted tone for a project the board does not list.
581function colorOf(key) {
582 const i = projects.findIndex((p) => p.key === key)
583 return i < 0 ? 'muted' : projectColor(projects[i], i)
584}
585
586function projectBadge(E, surface, key, size) {
587 const p = projectOf(key)
588 return badge(E, surface, monogram(p ? p.name : key), colorOf(key), size)
589}
590
591// What in a project wants Garrett: questions and specs to merge, and CI that cannot run.
592function attention(p) {
593 const c = ciOf(p.key)
594 const ciAlert = c && c.ci ? (c.ci.stuck ? `${c.ci.stuck} stuck` : c.ci.refusal ? 'CI refused' : '') : ''
595 return { needs: p.summary.needs.length, ci: ciAlert }
596}
597
598function boardView($, E, width, surface) {
599 const { Box, Text, Button } = E
600 const redraw = () => $.ui.invalidate('ui.render')
601 const sugg = suggestions()
602 if (tab.startsWith('p-') && !projects.some((p) => projectTab(p) === tab)) tab = 'all'
603 if ((tab === 'allow' && !sugg.length) || (tab === 'job' && !selected)) tab = 'all'
604 const navButton = (id, label, hotkey) => Button({ key: 'tab-' + id, label, ...(hotkey ? { hotkey } : {}), plain: true, dimColor: tab !== id, onPress: () => { tab = id; redraw() } })
605 const nav = [navButton('all', 'All', '0')]
606 projects.forEach((p, i) => {
607 const a = attention(p)
608 nav.push(row(E, [projectBadge(E, surface, p.key, 16), navButton(projectTab(p), p.name, i < 9 ? String(i + 1) : ''), ...(a.needs || a.ci ? [colored(E, surface, 'bad', '●')] : [])]))
609 })
610 nav.push(navButton('fleet', `Fleet ${jobs.length}`, 'f'))
611 if (sugg.length) nav.push(navButton('allow', `Allow ${sugg.length}`, 'a'))
612 if (selected) nav.push(navButton('job', 'Job', 'j'))
613 const age = refreshedAt ? fmtDuration((Date.now() - refreshedAt) / 1000) + ' ago' : 'loading'
614 const status = Box({
615 flexDirection: 'row',
616 columnGap: 2,
617 children: [
618 Text({ dimColor: true, children: [busy ? 'refreshing…' : 'updated ' + age] }),
619 Button({ key: 'refresh', label: 'Refresh', hotkey: 'r', plain: true, dimColor: true, onPress: () => { refresh($, NOW) } }),
620 ...(pausedUntil > Date.now() ? [colored(E, surface, 'warn', `GitHub rate limit: paused for ${Math.ceil((pausedUntil - Date.now()) / 60_000)} more min`)] : []),
621 ...(lastError ? [colored(E, surface, 'bad', lastError.slice(0, 80))] : []),
622 ],
623 })
624 let body
625 if (tab === 'fleet') body = fleetView($, E, width, surface)
626 else if (tab === 'allow') body = allowView($, E, sugg)
627 else if (tab === 'job') body = jobView($, E, width, surface)
628 else if (tab.startsWith('p-')) body = projectView($, E, projects.find((p) => projectTab(p) === tab), width, surface)
629 else body = overviewView($, E, width, surface)
630 return Box({ flexDirection: 'column', rowGap: 1, children: [Box({ flexDirection: 'row', columnGap: 3, children: nav }), status, Box({ flexDirection: 'column', rowGap: 1, children: body })] })
631}
632
633// Cut text to n columns, so a row stays one line in a narrow pane.
634function fit(text, n) {
635 const t = sanitize(String(text || ''), 2000).replace(/\n/g, ' ')
636 return t.length > n ? t.slice(0, Math.max(1, n - 1)) + '…' : t
637}
638
639function linkOrText(E, url, label, surface) {
640 const { Link, Text } = E
641 label = sanitize(label, 300).replace(/\n/g, ' ')
642 return surface === 'desktop' && /^https?:\/\//.test(String(url || '')) ? Link({ href: url, label }) : Text({ wrap: 'truncate-end', children: [label] })
643}
644
645// A row's main text: one line, cut at the end when the pane is narrow.
646function line(E, text, extra = {}) {
647 return E.Text({ ...extra, wrap: 'truncate-end', children: [sanitize(text, 2000)] })
648}
649
650// A titled group of rows. The title is short, uppercase and dim (BRAND.md).
651function section(E, title, children) {
652 const { Box, Text } = E
653 return Box({ flexDirection: 'column', children: [Text({ bold: true, dimColor: true, children: [title.toUpperCase()] }), ...children] })
654}
655
656function row(E, children) {
657 return E.Box({ flexDirection: 'row', columnGap: 1, alignItems: 'center', children })
658}
659
660const roleWord = (role) => (/review/.test(role) ? 'review' : /fix/.test(role) ? 'fix' : 'build')
661const roleLabel = (j) => roleWord(j.role) + (j.round ? ' r' + j.round : '')
662
663// The stages of a project's work, left to right.
664function stagesOf(s) {
665 return [
666 { label: 'ideas', n: s.ideas || 0 },
667 { label: 'ready', n: s.ready.filter((i) => !i.waitingOn.length).length },
668 { label: 'building', n: s.building.length },
669 { label: 'open PRs', n: Math.max(s.openPrs || 0, s.inReview.length) },
670 { label: 'merged 24h', n: s.mergedToday || 0 },
671 ]
672}
673
674function phaseBlock(E, s, hex, surface, size, width) {
675 const { Box, Text } = E
676 if (!s.phase) return Text({ dimColor: true, children: ['No current phase in ROADMAP.md'] })
677 return row(E, [
678 ring(E, surface, s.phase.done, s.phase.total, hex, size),
679 Box({ flexDirection: 'column', children: [Text({ bold: true, children: [fit(`Phase ${s.phase.n} · ${s.phase.title}`, Math.max(20, width))] }), Text({ dimColor: true, children: [`${s.phase.done} of ${s.phase.total} rows done`] })] }),
680 ])
681}
682
683// Busy slots filled in the project's color, idle ones outlined, offline ones empty.
684function poolCells(E, surface, c, hex, pad = 0) {
685 return cells(E, surface, c.pool.slots.map((st) => (st === 'busy' ? { fill: hex } : st === 'idle' ? { outline: hex } : {})), `${c.pool.busy} of ${c.pool.slots.length} slots busy`, pad)
686}
687
688// Running agents by model, as "grok 4.7 ×2, composer 2.5".
689function modelsOf(list) {
690 const counts = new Map()
691 for (const j of list) {
692 const m = modelName(j.model) || j.lane
693 counts.set(m, (counts.get(m) || 0) + 1)
694 }
695 return [...counts].map(([m, n]) => (n > 1 ? `${m} ×${n}` : m)).join(', ')
696}
697
698function overviewView($, E, width, surface) {
699 const { Text, Box } = E
700 if (projects.length === 0) return [Text({ dimColor: true, children: [refreshedAt ? 'No projects in ' + kitDir.replace(home, '~') + '/projects.md.' : 'Reading GitHub…'] })]
701 return projects.map((p) => projectCard($, E, p, width - 2, surface))
702}
703
704function projectCard($, E, p, inner, surface) {
705 const { Box, Text, Button } = E
706 const s = p.summary
707 const hex = colorOf(p.key)
708 const mine = jobs.filter((j) => j.project === p.key)
709 const c = ciOf(p.key)
710 const a = attention(p)
711 const children = [
712 row(E, [projectBadge(E, surface, p.key, 18), Text({ bold: true, children: [p.name] }), Text({ dimColor: true, children: [s.autonomy] }), ...(a.needs ? [pill(E, surface, `${a.needs} for you`, 'bad')] : [])]),
713 phaseBlock(E, s, hex, surface, 34, inner - 8),
714 pipeline(E, surface, stagesOf(s), hex),
715 row(E, [Text({ dimColor: true, children: ['Agents'] }), line(E, fit(mine.length ? modelsOf(mine) : 'none running', Math.max(10, inner - 8)))]),
716 ]
717 if (c && c.ci) {
718 children.push(row(E, [
719 Text({ dimColor: true, children: ['CI '] }),
720 ...(c.ci.pool.slots.length ? [poolCells(E, surface, c.ci, hex)] : []),
721 ...(c.ci.recent.length ? [dots(E, surface, c.ci.recent.slice(0, 10).map((r) => r.conclusion).reverse())] : [Text({ dimColor: true, children: ['no runs yet'] })]),
722 ...(a.ci ? [pill(E, surface, a.ci, 'bad')] : []),
723 ]))
724 }
725 children.push(Button({ key: 'open-' + p.key, label: `Open ${p.name} ›`, plain: true, dimColor: true, onPress: () => { tab = projectTab(p); $.ui.invalidate('ui.render') } }))
726 if (p.error) children.push(colored(E, surface, 'bad', fit(p.error, Math.max(20, inner))))
727 return Box({ key: 'card-' + p.key, flexDirection: 'column', children })
728}
729
730// An issue or PR title by number, from what the board already read.
731function titleOf(p, n) {
732 if (p.titles && p.titles[n]) return p.titles[n]
733 const s = p.summary
734 const i = [...s.building, ...s.inReview, ...s.ready].find((x) => x.number === n)
735 if (i) return i.title
736 const c = ciOf(p.key)
737 const pr = c && c.ci ? c.ci.prs.find((x) => x.number === n) : null
738 return pr ? pr.title : ''
739}
740
741function projectView($, E, p, width, surface) {
742 const { Text, Box, Button } = E
743 const s = p.summary
744 const hex = colorOf(p.key)
745 const out = []
746 out.push(row(E, [projectBadge(E, surface, p.key, 22), Text({ bold: true, children: [p.name] }), Text({ dimColor: true, children: [s.autonomy] }), ...(p.stale ? [pill(E, surface, 'last good data', 'warn')] : [])]))
747 const plan = [phaseBlock(E, s, hex, surface, 44, width - 12)]
748 if (s.phase && s.phase.exit) plan.push(Text({ dimColor: true, children: [fit('Exit: ' + s.phase.exit, Math.max(40, width - 2))] }))
749 for (const sp of s.specs) plan.push(row(E, [progress(E, surface, sp.done, sp.total, { width: 150, cells: 10, color: hex }), Text({ children: [`${sp.done}/${sp.total}`] }), line(E, fit(`spec ${sp.num} ${sp.title}`, Math.max(20, width - 30)), { dimColor: true })]))
750 out.push(Box({ flexDirection: 'column', children: plan }))
751 out.push(pipeline(E, surface, stagesOf(s), hex))
752 if (s.needs.length) out.push(section(E, 'Needs you', s.needs.map((n) => row(E, [pill(E, surface, n.kind === 'spec' ? 'spec to merge' : 'question', 'bad'), linkOrText(E, n.url, fit(`#${n.number} ${n.title}`, Math.max(20, width - 20)), surface)]))))
753 const mine = jobs.filter((j) => j.project === p.key)
754 const working = mine.map((j) => row(E, [
755 Button({ key: `row-${p.key}-${j.issue}`, plain: true, label: fit(`#${j.issue} ${titleOf(p, j.issue)}`.trim(), Math.max(20, width - 36)) + ' ›', onPress: () => openJob($, j) }),
756 pill(E, surface, roleLabel(j), 'muted'),
757 Text({ dimColor: true, children: [`${modelName(j.model) || j.lane} · ${fmtDuration(j.elapsed)}`] }),
758 ]))
759 for (const i of [...s.building, ...s.inReview]) {
760 if (mine.some((j) => j.issue === i.number)) continue
761 working.push(row(E, [line(E, fit(`#${i.number} ${i.title}`, Math.max(20, width - 24)), { dimColor: true }), Text({ dimColor: true, children: [i.labels.includes('in-review') ? 'in review, no agent' : 'building, no agent'] })]))
762 }
763 out.push(section(E, 'Working now', working.length ? working : [Text({ dimColor: true, children: [`No agent is working on ${p.name}.`] })]))
764 const next = s.ready.slice(0, 6)
765 if (next.length) out.push(section(E, 'Next', next.map((i) => row(E, [line(E, fit(`#${i.number} ${i.title}`, Math.max(20, width - 24))), i.waitingOn.length ? colored(E, surface, 'muted', `waits on #${i.waitingOn.join(', #')}`) : pill(E, surface, 'ready', 'good')]))))
766 out.push(section(E, 'CI', ciRows(E, ciOf(p.key), hex, width, surface)))
767 if (s.merged.length) out.push(section(E, 'Merged', s.merged.map((m) => row(E, [colored(E, surface, 'good', '✓'), Text({ dimColor: true, children: [fit(`#${m.number} ${m.title}`, width - 4)] })]))))
768 const logs = recent.filter((r) => r.project === p.key).slice(0, 4)
769 if (logs.length) out.push(section(E, 'Logs', logs.map((r) => Button({ key: 'log-' + r.path, plain: true, dimColor: true, label: fit(r.name, Math.max(40, width - 4)), onPress: () => openJob($, { path: r.path, project: p.key, title: `${p.name} ${r.name}` }) }))))
770 if (s.ideas) out.push(Text({ dimColor: true, children: [`${s.ideas} idea${s.ideas === 1 ? '' : 's'} waiting for the product pass`] }))
771 if (p.error) out.push(colored(E, surface, 'bad', p.error.slice(0, 100)))
772 return out
773}
774
775const checkTone = (state) => (state === 'pass' ? 'good' : state === 'fail' ? 'bad' : state === 'skip' ? 'muted' : 'warn')
776const checkMark = (state) => (state === 'pass' ? '✓' : state === 'fail' ? '✗' : state === 'skip' ? '-' : '…')
777
778// One project's CI: its slots, the jobs running and waiting, recent results
779// and timings, and its open PRs' checks (only the ones not yet passing).
780function ciRows(E, p, hex, width, surface) {
781 const { Text } = E
782 if (!p) return [Text({ dimColor: true, children: [refreshedAt ? 'No CI data yet.' : 'Reading GitHub…'] })]
783 if (!p.ci) return [colored(E, surface, 'bad', p.error || 'No CI data.')]
784 const c = p.ci
785 const rows = []
786 if (c.pool.slots.length) rows.push(row(E, [Text({ children: ['Pool'] }), poolCells(E, surface, c, hex), Text({ dimColor: true, children: [`${c.pool.busy} busy · ${c.pool.idle} idle${c.pool.offline ? ` · ${c.pool.offline} offline` : ''}`] })]))
787 if (c.refusal) rows.push(row(E, [pill(E, surface, 'refused', 'bad'), colored(E, surface, 'bad', `${c.refusal.message} (${c.refusal.runs} run${c.refusal.runs === 1 ? '' : 's'})`)]))
788 for (const j of c.running) {
789 rows.push(row(E, [
790 line(E, fit(`${j.prs.length ? 'PR ' + j.prs[0] : j.branch} · ${j.name}`, Math.max(20, width - 40))),
791 pill(E, surface, j.slot ? 'slot ' + j.slot : 'GitHub-hosted', 'muted'),
792 Text({ dimColor: true, children: [`${fmtDuration(j.elapsed || 0)}${j.step ? ' · ' + fit(j.step, 28) : ''}`] }),
793 ]))
794 }
795 for (const j of c.queued) {
796 rows.push(row(E, [line(E, fit(`${j.prs.length ? 'PR ' + j.prs[0] : j.branch} · ${j.name}`, Math.max(20, width - 30))), pill(E, surface, (j.stuck ? 'stuck ' : j.status === 'queued' ? 'queued ' : j.status + ' ') + fmtDuration(j.wait), j.stuck ? 'bad' : j.status === 'queued' ? 'warn' : 'muted')]))
797 if (j.stuck) rows.push(Text({ dimColor: true, children: [fit(` wants ${j.labels.join(', ') || 'no labels'} · pool has ${c.pool.labels.join(', ') || 'none'}`, width - 2)] }))
798 }
799 if (c.recent.length) {
800 const passed = c.recent.filter((r) => r.conclusion === 'success').length
801 rows.push(row(E, [dots(E, surface, c.recent.map((r) => r.conclusion).reverse()), Text({ dimColor: true, children: [`${passed} of ${c.recent.length} passed`] })]))
802 for (const mode of ['fast', 'full']) {
803 const list = c.timings[mode]
804 if (!list.length) continue
805 const last = list[0]
806 const budget = c.timings.budgets[mode]
807 const avg = Math.round(list.slice(0, 5).reduce((a, b) => a + b, 0) / Math.min(list.length, 5))
808 rows.push(row(E, [
809 progress(E, surface, budget ? last : 0, budget || 1, { width: 150, cells: 10, color: budgetTone(last, budget) }),
810 Text({ children: [budget ? `${last}s of ${budget}s` : `${last}s`] }),
811 Text({ dimColor: true, children: [`done --${mode} · avg ${avg}s`] }),
812 ]))
813 }
814 }
815 for (const pr of c.prs.slice(0, 8)) {
816 const states = Object.entries(pr.checks)
817 const open = states.filter(([, state]) => state !== 'pass')
818 rows.push(row(E, [
819 linkOrText(E, pr.url, fit(`#${pr.number} ${pr.title}`, Math.max(16, width - 52)), surface),
820 ...(states.length && !open.length ? [pill(E, surface, '✓ checks', 'good')] : open.map(([name, state]) => pill(E, surface, `${checkMark(state)} ${name}`, checkTone(state)))),
821 ...(pr.behind ? [pill(E, surface, 'behind main', 'warn')] : []),
822 ]))
823 }
824 if (!rows.length) rows.push(Text({ dimColor: true, children: ['Quiet: nothing running, no open PRs.'] }))
825 if (p.error) rows.push(colored(E, surface, 'bad', p.error.slice(0, 100)))
826 return rows
827}
828
829// What the projects share: the lanes (each cell a job, in its project's color),
830// the running jobs, the Claude plan, and the runner pool.
831function fleetView($, E, width, surface) {
832 const { Text, Button } = E
833 const out = []
834 const rank = (key) => {
835 const i = projects.findIndex((p) => p.key === key)
836 return i < 0 ? projects.length : i
837 }
838 if (projects.length) out.push(row(E, projects.map((p) => row(E, [projectBadge(E, surface, p.key, 14), Text({ dimColor: true, children: [p.name + ' '] })]))))
839 const laneSpan = Math.max(1, ...lanes.map((l) => Math.max(l.max, jobs.filter((j) => j.lane === l.lane).length)))
840 const laneRows = lanes.map((l) => {
841 const here = jobs.filter((j) => j.lane === l.lane).sort((a, b) => rank(a.project) - rank(b.project))
842 const n = Math.max(l.max, here.length)
843 const status = l.outUntil ? pill(E, surface, 'out until ' + l.outUntil.slice(5, 16).replace('T', ' '), 'bad') : l.max === 0 ? pill(E, surface, 'off', 'muted') : pill(E, surface, 'on', 'good')
844 return row(E, [
845 cells(E, surface, Array.from({ length: n }, (_, k) => (here[k] ? { fill: colorOf(here[k].project) } : {})), `${here.length} of ${l.max} ${l.lane} jobs`, laneSpan),
846 Text({ dimColor: true, children: [`${here.length}/${l.max}`] }),
847 Text({ dimColor: l.max === 0, bold: l.max > 0, children: [l.lane] }),
848 Text({ dimColor: true, children: [l.family] }),
849 status,
850 ])
851 })
852 out.push(section(E, 'Lanes', laneRows.length ? laneRows : [Text({ dimColor: true, children: ['No lanes in lanes.md.'] })]))
853 const running = jobs.map((j) => {
854 const p = projectOf(j.project)
855 return row(E, [
856 projectBadge(E, surface, j.project, 14),
857 Button({ key: 'job-' + j.pid, plain: true, label: `${p ? p.name : j.project} #${j.issue} ›`, onPress: () => openJob($, j) }),
858 pill(E, surface, roleLabel(j), 'muted'),
859 Text({ dimColor: true, children: [`${modelName(j.model) || j.lane} · ${fmtDuration(j.elapsed)}`] }),
860 ])
861 })
862 out.push(section(E, 'Running', running.length ? running : [Text({ dimColor: true, children: ['No g-cauc jobs running.'] })]))
863 if (claudeLimits.length) {
864 out.push(section(E, 'Claude plan', claudeLimits.map((r) => {
865 const pct = Math.round(r.percentUsed)
866 return row(E, [
867 progress(E, surface, pct, 100, { width: 150, cells: 10, color: pct < 70 ? 'good' : pct < 90 ? 'warn' : 'bad' }),
868 Text({ children: [`${pct}%`] }),
869 Text({ dimColor: true, children: [`${r.kind.replace(/_/g, ' ')}${r.resetsAt ? ' · resets ' + String(r.resetsAt).slice(5, 16).replace('T', ' ') : ''}`] }),
870 ])
871 })))
872 }
873 // Each project the pool serves has its own VM: its slots, then the VM's state.
874 const pools = ci.projects.filter((c) => c.vm || (c.ci && c.ci.pool.slots.length))
875 if (pools.length) {
876 const widest = Math.max(1, ...pools.map((c) => (c.ci ? c.ci.pool.slots.length : 0)))
877 const rows = pools.map((c) => row(E, [
878 projectBadge(E, surface, c.key, 14),
879 ...(c.ci ? [poolCells(E, surface, c.ci, colorOf(c.key), widest), Text({ dimColor: true, children: [`${c.ci.pool.busy} busy · ${c.ci.pool.idle} idle${c.ci.pool.offline ? ` · ${c.ci.pool.offline} offline` : ''}`] })] : []),
880 ...(c.vm ? [pill(E, surface, 'VM ' + c.vm.toLowerCase(), /running/i.test(c.vm) ? 'good' : 'bad')] : []),
881 ]))
882 out.push(section(E, 'Runner pool', rows))
883 }
884 const b = ci.billing
885 if (b) out.push(Text({ dimColor: true, children: [b.error ? 'Actions minutes: ' + b.error : `Actions minutes this month: ${b.used ?? '?'}${b.included ? ' of ' + b.included + ' included' : ''}${b.paid ? `, ${b.paid} paid` : ''}`] }))
886 return out
887}
888
889function allowView($, E, sugg) {
890 const { Text, Box, Button } = E
891 const out = [Text({ dimColor: true, children: [`Rules you approved ${APPROVALS_TO_SUGGEST} or more times. Allow writes them to the project's .claude/settings.json.`] })]
892 for (const s of sugg) {
893 out.push(Box({
894 flexDirection: 'row',
895 columnGap: 2,
896 children: [
897 Text({ children: [`${s.rule}`] }),
898 Text({ dimColor: true, children: [`${s.count}x ${s.root.replace(home, '~')}`] }),
899 Button({ key: `apply-${s.root}-${s.rule}`, label: 'Allow', onPress: () => decideRule($, s.root, s.rule, 'apply') }),
900 Button({ key: `dismiss-${s.root}-${s.rule}`, label: 'Dismiss', plain: true, dimColor: true, onPress: () => decideRule($, s.root, s.rule, 'dismiss') }),
901 ],
902 }))
903 }
904 return out
905}
906
907function openJob($, j) {
908 if (!j.path && !j.log) return
909 selected = {
910 project: j.project || '',
911 path: j.path || j.log,
912 title: j.title || `${j.project} #${j.issue} · ${j.role} round ${j.round} · ${modelName(j.model) || j.lane}`,
913 url: projects.find((p) => p.key === j.project) ? `https://github.com/${projects.find((p) => p.key === j.project).repo}/issues/${j.issue}` : '',
914 }
915 detail = null
916 tab = 'job'
917 followJob($)
918 $.ui.invalidate('ui.render')
919}
920
921function jobView($, E, width, surface) {
922 const { Text, Box, Button, Code } = E
923 if (!selected) return [Text({ dimColor: true, children: ['Pick a job on a project page or on Fleet.'] })]
924 const head = Box({
925 flexDirection: 'row',
926 columnGap: 2,
927 children: [
928 ...(selected.project ? [projectBadge(E, surface, selected.project, 16)] : []),
929 Text({ bold: true, children: [selected.title] }),
930 Button({ key: 'thinking', label: showThinking ? 'Hide thinking' : 'Show thinking', hotkey: 't', plain: true, dimColor: true, onPress: () => { showThinking = !showThinking; $.ui.invalidate('ui.render') } }),
931 ...(selected.url ? [linkOrText(E, selected.url, 'issue', surface)] : []),
932 ],
933 })
934 if (!detail) return [head, Text({ dimColor: true, children: ['Reading the log…'] })]
935 if (detail.format === 'empty') return [head, Text({ dimColor: true, children: ['The log is empty so far.'] })]
936 if (detail.format === 'text') return [head, Text({ dimColor: true, children: ['Plain-text log (launch with stream-json or --json for steps and thinking):'] }), Code({ source: sanitize(detail.steps[0].text, 9000) })]
937 const rows = []
938 for (const s of detail.steps.slice(-60)) {
939 if (s.kind === 'thinking') {
940 const lines = s.text.trim().split('\n').length
941 rows.push(showThinking ? Text({ dimColor: true, italic: true, children: [sanitize(s.text.trim(), 2000)] }) : Text({ dimColor: true, children: [`› thinking (${lines} line${lines === 1 ? '' : 's'})`] }))
942 } else if (s.kind === 'cmd') {
943 const cmd = Text({ children: [sanitize(fit(`$ ${s.text}`, Math.max(40, width - 24)), 400)] })
944 rows.push(s.exit === null ? cmd : row(E, [cmd, pill(E, surface, `exit ${s.exit}` + (s.ms ? ` · ${fmtDuration(s.ms / 1000)}` : ''), s.exit === 0 ? 'good' : 'bad')]))
945 } else if (s.kind === 'tool') {
946 rows.push(Text({ dimColor: true, children: [sanitize(`· ${s.text}`, 400)] }))
947 } else if (s.kind === 'say') {
948 rows.push(Text({ children: [sanitize(s.text.trim(), 3000)] }))
949 } else if (s.kind === 'result') {
950 rows.push(row(E, [pill(E, surface, s.text.startsWith('failed') ? 'failed' : 'finished', s.text.startsWith('failed') ? 'bad' : 'good'), Text({ children: [sanitize(s.text.replace(/^(failed|finished):?\s*/, ''), 300) + (s.ms ? ` in ${fmtDuration(s.ms / 1000)}` : '')] })]))
951 }
952 }
953 return [head, ...rows]
954}
955hooks/lib.js 491 lines1// Pure helpers for the g-cauc mod: parsing and summarizing only, no mods API.
2// register.js gathers the raw text (gh output, files, process lists) and these
3// functions turn it into what the board and the band show.
4
5// Rows of the first markdown table whose header row starts with `firstHeader`.
6export function tableRows(md, firstHeader) {
7 const lines = String(md || '').split('\n')
8 const rows = []
9 let inTable = false
10 for (const line of lines) {
11 const t = line.trim()
12 if (!t.startsWith('|')) {
13 if (inTable) break
14 continue
15 }
16 const cells = t.replace(/^\|/, '').replace(/\|$/, '').split('|').map((c) => c.trim())
17 if (!inTable) {
18 if (cells[0].toLowerCase() === firstHeader.toLowerCase()) inTable = true
19 continue
20 }
21 if (cells.every((c) => /^:?-+:?$/.test(c))) continue
22 rows.push(cells)
23 }
24 return rows
25}
26
27const strip = (s) => String(s || '').replace(/`/g, '').trim()
28const expandHome = (p, home) => strip(p).replace(/^~(?=\/|$)/, home)
29
30// projects.md: | Priority | Project | Path | Repo | Color | Notes |
31// Color is optional (an older file has Notes in its place): a hex, or null.
32export function parseProjects(md, home) {
33 return tableRows(md, 'Priority')
34 .map((c) => ({ priority: Number(c[0]) || 99, name: strip(c[1]), path: expandHome(c[2], home), repo: strip(c[3]), color: /^#[0-9a-f]{6}$/i.test(strip(c[4])) ? strip(c[4]).toUpperCase() : null }))
35 .filter((p) => p.name && p.path && p.repo)
36 .sort((a, b) => a.priority - b.priority)
37}
38
39// A project's badge: the first letters of its first two words, camel case
40// counting as two words ("CallFlow" CF, "Bison Brain" BB, "g-cauc" gc).
41export function monogram(name) {
42 const words = String(name || '').replace(/([a-z])([A-Z])/g, '$1 $2').split(/[\s_-]+/).filter(Boolean)
43 return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] || '?').slice(0, 2)).slice(0, 2)
44}
45
46// lanes.md: | Lane | Family | Subscription | Weight | Max jobs | Status |
47export function parseLanes(md) {
48 return tableRows(md, 'Lane').map((c) => ({
49 lane: strip(c[0]),
50 family: strip(c[1]),
51 weight: strip(c[3]),
52 max: Number(strip(c[4])) || 0,
53 status: strip(c[5]).split(':')[0].split(';')[0],
54 }))
55}
56
57// ROADMAP.md: "## Phase N: Title" headings, each with an "Exit:" paragraph.
58export function parseRoadmap(md) {
59 const phases = []
60 let cur = null
61 let inExit = false
62 for (const line of String(md || '').split('\n')) {
63 const h = line.match(/^##\s+Phase\s+(\d+)\s*[:.]\s*(.+?)\s*$/i)
64 if (h) {
65 cur = { n: Number(h[1]), title: h[2].replace(/\s*\(.*\)\s*$/, ''), exit: '' }
66 phases.push(cur)
67 inExit = false
68 continue
69 }
70 if (/^##\s/.test(line)) {
71 cur = null
72 continue
73 }
74 if (!cur) continue
75 const ex = line.match(/^Exit:\s*(.*)$/)
76 if (ex) {
77 inExit = true
78 cur.exit = ex[1].trim()
79 continue
80 }
81 if (inExit && !cur.exit && line.trim()) cur.exit = line.replace(/^[-*]\s*/, '').trim()
82 }
83 return phases
84}
85
86// The phase a spec belongs to: a "Phase: N" line near its top, else a phase
87// whose title shares a word run with the spec's file name.
88export function specPhase(specFile, specText, phases) {
89 const head = String(specText || '').split('\n').slice(0, 15).join('\n')
90 const m = head.match(/Phase[:\s]+(\d+)/i)
91 if (m) return Number(m[1])
92 const slug = String(specFile).replace(/^\d+-/, '').replace(/\.md$/, '').replace(/-/g, ' ').toLowerCase()
93 const hit = phases.find((p) => slug && (p.title.toLowerCase().includes(slug) || slug.includes(p.title.toLowerCase())))
94 return hit ? hit.n : null
95}
96
97// gh output as an array, or null when the call failed or answered something else.
98export function asArray(json) {
99 if (typeof json !== 'string' || !json.trim()) return null
100 try {
101 const v = JSON.parse(json)
102 return Array.isArray(v) ? v : null
103 } catch {
104 return null
105 }
106}
107
108// Text from logs, made safe to draw: no ANSI escapes, no control characters
109// other than tab and newline, and no more than `max` characters.
110export function sanitize(text, max = 9000) {
111 const t = String(text || '').replace(/\u001b\[[0-9;?]*[ -\/]*[@-~]/g, '').replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
112 return t.length > max ? '…' + t.slice(-(max - 1)) : t
113}
114
115const exitOf = (v) => (typeof v === 'number' && Number.isInteger(v) ? v : typeof v === 'string' && /^-?\d{1,10}$/.test(v) ? Number(v) : null)
116
117export const labelsOf = (issue) => (issue.labels || []).map((l) => (typeof l === 'string' ? l : l.name))
118
119// "Spec 002 row 7: ..." in the title, or "Spec: specs/002-name.md" in the body.
120export function issueSpec(issue) {
121 const t = String(issue.title || '').match(/Spec\s+(\d{3})\b/i)
122 if (t) return t[1]
123 const b = String(issue.body || '').match(/specs\/(\d{3})[-\w]*\.md/)
124 return b ? b[1] : null
125}
126
127// Issue numbers this issue waits on: "Blocked by #12" lines, or #refs in the
128// build plan row's "Blocked by" column.
129export function blockers(body) {
130 const text = String(body || '')
131 const found = new Set()
132 for (const m of text.matchAll(/Blocked by[^\n#]*((?:#\d+[\s,and]*)+)/gi)) {
133 for (const n of m[1].matchAll(/#(\d+)/g)) found.add(Number(n[1]))
134 }
135 const lines = text.split('\n')
136 const hi = lines.findIndex((l) => /\|\s*Blocked by\s*\|/i.test(l))
137 if (hi >= 0) {
138 const col = lines[hi].split('|').map((c) => c.trim().toLowerCase()).indexOf('blocked by')
139 for (const row of lines.slice(hi + 2)) {
140 if (!row.trim().startsWith('|')) break
141 const cell = row.split('|')[col] || ''
142 for (const n of cell.matchAll(/#(\d+)/g)) found.add(Number(n[1]))
143 }
144 }
145 return [...found]
146}
147
148// Everything the Plan tab and the band need for one project.
149export function summarizeProject({ issues, openPrs, mergedPrs, roadmap, specs, autonomy, now }) {
150 const phases = parseRoadmap(roadmap)
151 const byNumber = new Map(issues.map((i) => [i.number, i]))
152 const isOpen = (n) => {
153 const i = byNumber.get(n)
154 return i ? i.state === 'OPEN' : false
155 }
156 const specOf = new Map()
157 for (const s of specs) specOf.set(s.num, { ...s, phase: specPhase(s.file, s.text, phases) })
158
159 const build = issues.filter((i) => issueSpec(i) && !labelsOf(i).includes('idea') && !labelsOf(i).includes('spec'))
160 const perSpec = new Map()
161 for (const i of build) {
162 const num = issueSpec(i)
163 const p = perSpec.get(num) || { num, done: 0, total: 0 }
164 p.total += 1
165 if (i.state === 'CLOSED') p.done += 1
166 perSpec.set(num, p)
167 }
168 const specRows = [...perSpec.values()]
169 .map((p) => ({ ...p, title: (specOf.get(p.num) || {}).title || 'Spec ' + p.num, phase: (specOf.get(p.num) || {}).phase ?? null }))
170 .sort((a, b) => a.num.localeCompare(b.num))
171
172 const openSpecs = specRows.filter((s) => s.done < s.total)
173 const phaseNums = openSpecs.map((s) => s.phase).filter((n) => n !== null)
174 const currentN = phaseNums.length ? Math.min(...phaseNums) : null
175 const current = currentN !== null ? phases.find((p) => p.n === currentN) || null : null
176 const inPhase = current ? specRows.filter((s) => s.phase === current.n) : openSpecs
177 const phaseDone = inPhase.reduce((a, s) => a + s.done, 0)
178 const phaseTotal = inPhase.reduce((a, s) => a + s.total, 0)
179
180 const open = issues.filter((i) => i.state === 'OPEN')
181 const has = (i, l) => labelsOf(i).includes(l)
182 const ready = open
183 .filter((i) => has(i, 'ready'))
184 .map((i) => ({ ...i, waitingOn: blockers(i.body).filter(isOpen) }))
185 .sort((a, b) => a.waitingOn.length - b.waitingOn.length || a.number - b.number)
186 const needs = [
187 ...open.filter((i) => has(i, 'needs:garrett')).map((i) => ({ kind: 'issue', number: i.number, title: i.title, url: i.url })),
188 ...openPrs.filter((p) => labelsOf(p).includes('agreed')).map((p) => ({ kind: 'spec', number: p.number, title: p.title, url: p.url })),
189 ]
190 return {
191 autonomy,
192 phase: current ? { n: current.n, title: current.title, exit: current.exit, done: phaseDone, total: phaseTotal } : null,
193 specs: openSpecs,
194 building: open.filter((i) => has(i, 'building')),
195 inReview: open.filter((i) => has(i, 'in-review')),
196 ready,
197 needs,
198 ideas: open.filter((i) => has(i, 'idea')).length,
199 // Open PRs other than spec PRs: work in review or CI, however the project labels its issues.
200 openPrs: openPrs.filter((p) => !labelsOf(p).includes('spec')).length,
201 merged: mergedPrs.slice(0, 4),
202 // Merges in the 24 hours before now, from the PRs gh returned.
203 mergedToday: now ? mergedPrs.filter((p) => now - Date.parse(p.mergedAt) < 86_400_000).length : 0,
204 }
205}
206
207// `pgrep -lf ak:` output: keep the agent CLIs, drop the shells that launched them.
208export function parseJobs(out, { claude = false } = {}) {
209 const jobs = []
210 for (const line of String(out || '').split('\n')) {
211 const m = line.match(/^\s*(\d+)\s+(.*)$/)
212 if (!m) continue
213 const cmd = m[2]
214 const argv0 = cmd.split(/\s+/)[0]
215 // The `muse` launcher execs a versioned binary, muse-bin-<version>.
216 const base = argv0.split('/').pop().replace(/^muse-bin-.*/, 'muse')
217 // Claude workers are listed by `claude agents --json` (parseClaudeAgents), so skip them here.
218 if (!['cursor-agent', 'codex', 'muse', ...(claude ? ['claude'] : [])].includes(base)) continue
219 const mk = cmd.match(/\[ak:([\w.-]+)#(\d+):([\w-]+):(\d+)\]/)
220 if (!mk) continue
221 const model = (cmd.match(/(?:--model|\s-m)\s+(\S+)/) || [])[1] || ''
222 jobs.push({ pid: Number(m[1]), cli: base, model, project: mk[1], issue: Number(mk[2]), role: mk[3], round: Number(mk[4]) })
223 }
224 return jobs
225}
226
227// `claude agents --json`: background sessions the foreman named ak-<project>-<issue>-<role>.
228export function parseClaudeAgents(json, home, now) {
229 let list = []
230 try {
231 list = JSON.parse(json || '[]')
232 } catch {
233 return []
234 }
235 const out = []
236 for (const a of Array.isArray(list) ? list : []) {
237 const m = String(a.name || '').match(/^ak-([\w.]+)-(\d+)-([\w-]+)$/)
238 if (!m || !a.sessionId || !a.cwd) continue
239 out.push({
240 pid: a.pid || 0,
241 cli: 'claude',
242 model: 'opus',
243 project: m[1],
244 issue: Number(m[2]),
245 role: m[3],
246 round: 0,
247 elapsed: a.startedAt ? Math.max(0, (now - a.startedAt) / 1000) : 0,
248 log: `${home}/.claude/projects/${String(a.cwd).replace(/[^A-Za-z0-9]/g, '-')}/${a.sessionId}.jsonl`,
249 status: a.status || '',
250 })
251 }
252 return out
253}
254
255export function laneOf(cli, model) {
256 if (cli === 'claude') return 'claude'
257 if (cli === 'codex') return 'codex'
258 if (cli === 'muse') return 'muse'
259 const m = String(model).toLowerCase()
260 if (m.startsWith('composer')) return 'composer'
261 if (m.includes('grok')) return 'grok'
262 if (m.startsWith('gemini')) return 'gemini'
263 return 'cursor'
264}
265
266// Friendly model names for the rows.
267export function modelName(model) {
268 const m = String(model).toLowerCase()
269 if (!m) return ''
270 if (m.startsWith('composer')) return 'Composer ' + (m.match(/composer-([\d.]+)/) || [])[1]
271 const g = m.match(/grok-([\d.]+)-?(\w+)?/)
272 if (g) return 'Grok ' + g[1] + (g[2] && !/fast/.test(g[2]) ? ' ' + g[2] : '')
273 if (m.startsWith('gemini')) return 'Gemini ' + (m.match(/gemini-([\d.]+)/) || [])[1]
274 const mu = m.match(/^muse-(\w+)-([\d.]+)/)
275 if (mu) return 'Muse ' + mu[1][0].toUpperCase() + mu[1].slice(1) + ' ' + mu[2]
276 if (m.startsWith('gpt')) return m.replace(/^gpt-/, 'GPT-').replace(/-(high|xhigh|low|medium)$/, ' $1')
277 if (m.includes('opus')) return 'Opus'
278 if (m.includes('sonnet')) return 'Sonnet'
279 return model
280}
281
282// ps etime "[[dd-]hh:]mm:ss" to seconds.
283export function parseEtime(s) {
284 const t = String(s || '').trim()
285 if (!t) return 0
286 const [d, rest] = t.includes('-') ? t.split('-') : ['0', t]
287 const parts = rest.split(':').map(Number)
288 while (parts.length < 3) parts.unshift(0)
289 return Number(d) * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]
290}
291
292export function fmtDuration(sec) {
293 if (sec < 60) return Math.max(0, Math.round(sec)) + 's'
294 if (sec < 3600) return Math.round(sec / 60) + 'm'
295 const h = Math.floor(sec / 3600)
296 return h + 'h' + String(Math.round((sec % 3600) / 60)).padStart(2, '0')
297}
298
299// `lsof -Fpn -a -d 1 -p ...`: where each process sends its standard output.
300export function parseLsof(out) {
301 const map = new Map()
302 let pid = null
303 for (const line of String(out || '').split('\n')) {
304 if (line.startsWith('p')) pid = Number(line.slice(1))
305 else if (line.startsWith('n') && pid !== null) map.set(pid, line.slice(1))
306 }
307 return map
308}
309
310const clip = (s, n) => {
311 const t = String(s || '').replace(/\s+$/, '')
312 return t.length > n ? t.slice(0, n - 1) + '…' : t
313}
314
315// One job log, as a list of steps. Understands Cursor's stream-json, Codex's
316// --json events, Muse's --json events, and falls back to the plain text tail for anything else.
317export function parseLog(text) {
318 const lines = String(text || '').split('\n').filter((l) => l.trim())
319 const jsonish = lines.filter((l) => l.trim().startsWith('{')).length
320 if (lines.length === 0) return { format: 'empty', steps: [] }
321 if (jsonish < lines.length / 2) {
322 return { format: 'text', steps: [{ kind: 'text', text: sanitize(lines.slice(-120).join('\n'), 9000) }] }
323 }
324 const steps = []
325 let thinking = null
326 const flushThinking = () => {
327 if (thinking && thinking.text.trim()) steps.push(thinking)
328 thinking = null
329 }
330 // Muse streams its words in run.output.delta pieces between tool results.
331 let saying = null
332 const flushSaying = () => {
333 if (saying && saying.text.trim()) steps.push(saying)
334 saying = null
335 }
336 for (const line of lines) {
337 let ev
338 try {
339 ev = JSON.parse(line)
340 } catch {
341 continue
342 }
343 // Muse exec --json
344 if (typeof ev.payload_type === 'string' && ev.payload) {
345 const p = ev.payload
346 if (ev.payload_type === 'run.output.delta') {
347 if (!saying) saying = { kind: 'say', text: '' }
348 saying.text += p.text || ''
349 continue
350 }
351 if (ev.payload_type === 'tool.result') {
352 flushSaying()
353 const tool = (p.correlation_facts && p.correlation_facts.tool_name) || ''
354 if (tool === 'bash') {
355 let r = {}
356 try {
357 r = JSON.parse(p.text || '{}') || {}
358 } catch {}
359 steps.push({ kind: 'cmd', text: clip(r.command, 140), exit: exitOf(r.exit_code), ms: null, out: clip(r.output || '', 600) })
360 } else if (p.edit_facts && p.edit_facts.path) steps.push({ kind: 'tool', text: 'edit ' + clip(p.edit_facts.path, 100) })
361 else steps.push({ kind: 'tool', text: tool || 'tool' })
362 continue
363 }
364 if (/^run\.terminal\./.test(ev.payload_type)) {
365 flushSaying()
366 const done = p.terminal === 'completed'
367 steps.push({ kind: 'result', text: done ? 'finished' : 'failed: ' + clip(p.reason || p.text || p.terminal || '', 200), ms: null })
368 }
369 continue
370 }
371 // Cursor stream-json
372 if (ev.type === 'thinking') {
373 if (ev.subtype === 'delta') {
374 if (!thinking) thinking = { kind: 'thinking', text: '' }
375 thinking.text += ev.text || ''
376 } else flushThinking()
377 continue
378 }
379 if (ev.type === 'assistant' && ev.message) {
380 flushThinking()
381 // Cursor sends text only; a Claude transcript also carries thinking and tool calls.
382 for (const c of ev.message.content || []) {
383 if (c.type === 'thinking' && String(c.thinking || '').trim()) steps.push({ kind: 'thinking', text: c.thinking })
384 else if (c.type === 'text' && String(c.text || '').trim()) steps.push({ kind: 'say', text: c.text })
385 else if (c.type === 'tool_use') {
386 const inp = c.input || {}
387 if (c.name === 'Bash') steps.push({ kind: 'cmd', text: clip(inp.command, 140), exit: null, ms: null, out: '' })
388 else steps.push({ kind: 'tool', text: c.name + (inp.file_path || inp.pattern || inp.description ? ' ' + clip(inp.file_path || inp.pattern || inp.description, 100) : '') })
389 }
390 }
391 continue
392 }
393 if (ev.type === 'tool_call' && ev.subtype === 'completed' && ev.tool_call) {
394 flushThinking()
395 const [name, call] = Object.entries(ev.tool_call)[0] || []
396 const args = (call && call.args) || {}
397 const ok = (call && call.result && call.result.success) || {}
398 if (name === 'shellToolCall') {
399 steps.push({ kind: 'cmd', text: clip(args.command, 140), exit: exitOf(ok.exitCode), ms: exitOf(ok.executionTime), out: clip(ok.stdout || ok.stderr || '', 600) })
400 } else {
401 const target = args.path || args.filePath || args.pattern || args.query || ''
402 steps.push({ kind: 'tool', text: String(name || 'tool').replace(/ToolCall$/, '') + (target ? ' ' + clip(target, 100) : '') })
403 }
404 continue
405 }
406 if (ev.type === 'result') {
407 flushThinking()
408 steps.push({ kind: 'result', text: ev.is_error ? 'failed' : 'finished', ms: exitOf(ev.duration_ms) })
409 continue
410 }
411 // Codex exec --json
412 if (/^item\.(completed|updated)$/.test(ev.type || '') && ev.item) {
413 if (ev.type === 'item.updated') continue
414 flushThinking()
415 const it = ev.item
416 if (it.type === 'reasoning') steps.push({ kind: 'thinking', text: it.text || it.summary || '' })
417 else if (it.type === 'agent_message') steps.push({ kind: 'say', text: it.text || '' })
418 else if (it.type === 'command_execution') steps.push({ kind: 'cmd', text: clip(it.command, 140), exit: exitOf(it.exit_code), ms: null, out: clip(it.aggregated_output || '', 600) })
419 else if (it.type === 'file_change') steps.push({ kind: 'tool', text: 'edit ' + (it.changes || []).map((c) => c.path).join(', ') })
420 else steps.push({ kind: 'tool', text: it.type })
421 continue
422 }
423 if (ev.type === 'turn.completed') {
424 flushThinking()
425 steps.push({ kind: 'result', text: 'finished', ms: null })
426 }
427 if (ev.type === 'turn.failed' || ev.type === 'error') {
428 flushThinking()
429 steps.push({ kind: 'result', text: 'failed: ' + clip((ev.error && ev.error.message) || ev.message || '', 200), ms: null })
430 }
431 }
432 flushThinking()
433 flushSaying()
434 return { format: 'json', steps: steps.map((st) => ({ ...st, text: sanitize(st.text, 9000), out: st.out ? sanitize(st.out, 600) : st.out })) }
435}
436
437export function bar(done, total, width = 10) {
438 if (!total) return '░'.repeat(width)
439 const full = Math.max(0, Math.min(width, Math.round((done / total) * width)))
440 return '█'.repeat(full) + '░'.repeat(width - full)
441}
442
443// The one dim line above the prompt, or null when there is nothing to say.
444export function bandText(projects, jobs) {
445 const running = jobs.length
446 const needs = projects.reduce((a, p) => a + p.summary.needs.length, 0)
447 if (running === 0 && needs === 0) return null
448 const lead = projects.find((p) => p.summary.phase) || projects[0]
449 const parts = ['g-cauc']
450 if (lead && lead.summary.phase) parts.push(`${lead.name} ${lead.summary.phase.done}/${lead.summary.phase.total}`)
451 if (running) parts.push(`${running} running`)
452 if (needs) parts.push(`${needs} need${needs === 1 ? 's' : ''} you`)
453 return parts.join(' · ')
454}
455
456// Permission advisor: the part of a tool call's input that identifies it, so a
457// permission dialog and the call it belongs to compare equal even when one
458// side carries extra fields.
459export function callKey(tool, input) {
460 const i = input && typeof input === 'object' ? input : {}
461 const skip = new Set(['description', 'timeout', 'run_in_background'])
462 const canon = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? Object.keys(v).filter((k) => !skip.has(k)).sort().map((k) => [k, canon(v[k])]) : v)
463 return tool + '\u0000' + JSON.stringify(canon(i))
464}
465
466// Permission advisor: the rule strings in a PermissionRequest's own
467// "don't ask again" suggestions, such as "Bash(gh pr view:*)".
468export function suggestedRules(suggestions) {
469 const out = []
470 for (const s of suggestions || []) {
471 if (!s || s.type !== 'addRules' || s.behavior !== 'allow') continue
472 for (const r of s.rules || []) out.push(r.ruleContent ? `${r.toolName}(${r.ruleContent})` : r.toolName)
473 }
474 return [...new Set(out)]
475}
476
477// Add rules to a settings object's permissions.allow, keeping everything else.
478// Returns null when the file's shape is not one this can safely extend.
479export function withAllowed(settings, rules) {
480 const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
481 if (settings !== undefined && settings !== null && !isObj(settings)) return null
482 const s = settings ? JSON.parse(JSON.stringify(settings)) : {}
483 if (s.permissions !== undefined && !isObj(s.permissions)) return null
484 s.permissions = s.permissions || {}
485 if (s.permissions.allow !== undefined && !Array.isArray(s.permissions.allow)) return null
486 const allow = Array.isArray(s.permissions.allow) ? s.permissions.allow : []
487 for (const r of rules) if (!allow.includes(r)) allow.push(r)
488 s.permissions.allow = allow
489 return s
490}
491hooks/ci.js 248 lines1// Pure helpers for the CI tab: parse what `gh` returns about Actions runs,
2// jobs, runners and pull request checks, and summarize it per project.
3// register.js makes the calls; nothing here touches the mods API.
4
5const ACTIVE = new Set(['queued', 'in_progress', 'waiting', 'requested', 'pending'])
6const secs = (a, b) => (a && b ? Math.max(0, Math.round((Date.parse(b) - Date.parse(a)) / 1000)) : null)
7
8function json(text) {
9 if (typeof text !== 'string' || !text.trim()) return null
10 try {
11 return JSON.parse(text)
12 } catch {
13 return null
14 }
15}
16
17// `gh api repos/R/actions/runs`: the runs, newest first.
18export function parseRuns(text) {
19 const v = json(text)
20 if (!v || !Array.isArray(v.workflow_runs)) return null
21 return v.workflow_runs.map((r) => ({
22 id: r.id,
23 workflow: r.name || '',
24 status: r.status || '',
25 conclusion: r.conclusion || null,
26 branch: r.head_branch || '',
27 title: r.display_title || '',
28 event: r.event || '',
29 createdAt: r.created_at || null,
30 startedAt: r.run_started_at || r.created_at || null,
31 updatedAt: r.updated_at || null,
32 url: r.html_url || '',
33 prs: (r.pull_requests || []).map((p) => p.number),
34 }))
35}
36
37// `gh api repos/R/actions/runs/ID/jobs`: one run's jobs, with their steps.
38export function parseRunJobs(text, run) {
39 const v = json(text)
40 if (!v || !Array.isArray(v.jobs)) return null
41 return v.jobs.map((j) => {
42 const steps = (j.steps || []).map((s) => ({ name: s.name || '', status: s.status || '', conclusion: s.conclusion || null }))
43 const current = steps.find((s) => s.status === 'in_progress')
44 return {
45 id: j.id,
46 runId: run ? run.id : j.run_id,
47 workflow: run ? run.workflow : j.workflow_name || '',
48 branch: run ? run.branch : j.head_branch || '',
49 prs: run ? run.prs : [],
50 name: j.name || '',
51 status: j.status || '',
52 conclusion: j.conclusion || null,
53 createdAt: j.created_at || null,
54 startedAt: j.started_at || null,
55 completedAt: j.completed_at || null,
56 runner: j.runner_name || null,
57 labels: Array.isArray(j.labels) ? j.labels.map(String) : typeof j.labels === 'string' ? [j.labels] : [],
58 steps,
59 step: current ? current.name : null,
60 url: j.html_url || '',
61 }
62 })
63}
64
65// `gh api repos/R/actions/runners`: the pool's registrations for one repo.
66export function parseRunners(text) {
67 const v = json(text)
68 if (!v || !Array.isArray(v.runners)) return null
69 return v.runners.map((r) => ({
70 name: r.name || '',
71 status: r.status || '',
72 busy: Boolean(r.busy),
73 labels: (Array.isArray(r.labels) ? r.labels : []).map((l) => (typeof l === 'string' ? l : l && l.name)).filter(Boolean),
74 slot: Number(((r.name || '').match(/-(\d+)-\d+$/) || [])[1]) || null,
75 }))
76}
77
78// The runner VM of a repo, named as runner/gcauc-runner names it: gcauc-<repo>, lower case,
79// anything but a letter, a digit or a dash made a dash.
80export function vmName(repo) {
81 return 'gcauc-' + String(repo || '').split('/').pop().toLowerCase().replace(/[^a-z0-9-]/g, '-')
82}
83
84// runner/repos: "owner/repo slots [cpus] [memory GiB]" per line, # comments.
85export function parseRepoSlots(text) {
86 return String(text || '')
87 .split('\n')
88 .map((l) => l.replace(/#.*/, '').trim())
89 .filter(Boolean)
90 .map((l) => l.split(/\s+/))
91 .filter((p) => /^[\w.-]+\/[\w.-]+$/.test(p[0]))
92 .map((p) => ({ repo: p[0], slots: Number(p[1]) || 0 }))
93}
94
95// The lines scripts/done prints at the end:
96// "done --fast: green in 127s" or "done --fast: 230s is over the 200s budget".
97export function doneTimings(text) {
98 const out = []
99 for (const line of String(text || '').split('\n')) {
100 const green = line.match(/done --(fast|full): green in (\d+)s/)
101 if (green) {
102 out.push({ mode: green[1], seconds: Number(green[2]), green: true })
103 continue
104 }
105 const over = line.match(/done --(fast|full): (\d+)s is over the (\d+)s budget/)
106 if (over) out.push({ mode: over[1], seconds: Number(over[2]), green: false, budget: Number(over[3]) })
107 }
108 return out
109}
110
111// Budgets from a project's scripts/done defaults, such as ${CALLFLOW_FAST_BUDGET:-200}.
112export function budgetsFromDone(text) {
113 const t = String(text || '')
114 const fast = t.match(/FAST_BUDGET:-(\d+)/)
115 const full = t.match(/FULL_BUDGET:-(\d+)/)
116 return { fast: fast ? Number(fast[1]) : null, full: full ? Number(full[1]) : null }
117}
118
119// A job GitHub never started: it failed with no steps, and an annotation says why.
120export function refusalMessage(annotations) {
121 for (const a of Array.isArray(annotations) ? annotations : []) {
122 const m = String(a.message || '')
123 if (a.annotation_level === 'failure' && /not started|spending limit|payments have failed|billing/i.test(m)) {
124 return /spending limit|payments have failed|billing/i.test(m) ? 'GitHub refused jobs at the spending limit' : m.slice(0, 120)
125 }
126 }
127 return null
128}
129
130// The latest state of each named check on a PR's head commit.
131export function latestChecks(rollup) {
132 const out = {}
133 const done = (c) => !(c.status && c.status !== 'COMPLETED') && !(c.state && /PENDING|EXPECTED/.test(c.state))
134 // Unfinished runs rank above every finished one; finished ones rank by time, then order.
135 const rank = (c, i) => (!done(c) ? Number.MAX_SAFE_INTEGER - 1000 + i : Date.parse(c.completedAt || c.startedAt || '') || i)
136 const seen = {}
137 ;(Array.isArray(rollup) ? rollup : []).forEach((c, i) => {
138 const name = c.name || c.context
139 if (!name) return
140 const when = rank(c, i)
141 if (seen[name] !== undefined && seen[name] > when) return
142 seen[name] = when
143 let state
144 if (c.__typename === 'StatusContext' || c.state) {
145 state = { SUCCESS: 'pass', FAILURE: 'fail', ERROR: 'fail', PENDING: 'running', EXPECTED: 'running' }[c.state] || 'running'
146 } else if (c.status && c.status !== 'COMPLETED') {
147 state = 'running'
148 } else {
149 state = { SUCCESS: 'pass', NEUTRAL: 'pass', SKIPPED: 'skip' }[c.conclusion] || 'fail'
150 }
151 out[name] = state
152 })
153 return out
154}
155
156const KEY_CHECKS = ['done', 'agent-review', 'guard']
157
158// One state per pool slot. A slot can hold more than one registration at a
159// time (each job gets a fresh one-job runner), so a slot is busy when any of
160// its registrations is busy, idle when one is online, and offline otherwise.
161// Slots run from 1 to the configured count, or higher when a runner sits on a
162// higher slot; a runner whose name carries no slot number is a slot of its own.
163export function slotStates(runners, configured) {
164 const bySlot = new Map()
165 const loose = []
166 for (const r of runners) {
167 if (r.slot) bySlot.set(r.slot, [...(bySlot.get(r.slot) || []), r])
168 else loose.push([r])
169 }
170 const total = Math.max(configured || 0, ...bySlot.keys(), 0)
171 const groups = []
172 for (let n = 1; n <= total; n++) groups.push(bySlot.get(n) || [])
173 groups.push(...loose)
174 return groups.map((regs) => (regs.some((r) => r.busy) ? 'busy' : regs.some((r) => r.status === 'online') ? 'idle' : 'offline'))
175}
176
177// Everything the CI tab shows for one project.
178export function summarizeCi({ runs, jobs, runners, slots, prs, facts, budgets, now, behind }) {
179 const pool = (runners || []).filter((r) => r.labels.includes('gcauc'))
180 const states = slotStates(pool, slots ?? null)
181 const idleSlot = states.includes('idle')
182 const poolLabels = [...new Set(pool.flatMap((r) => r.labels))]
183 const live = (jobs || []).filter((j) => ACTIVE.has(j.status))
184 const running = live
185 .filter((j) => j.status === 'in_progress')
186 .map((j) => {
187 const r = pool.find((x) => x.name === j.runner)
188 return { ...j, slot: r ? r.slot : null, hosted: !r, elapsed: secs(j.startedAt, new Date(now).toISOString()) }
189 })
190 const queued = live
191 .filter((j) => j.status !== 'in_progress')
192 .map((j) => {
193 const wait = secs(j.createdAt, new Date(now).toISOString()) || 0
194 return { ...j, wait, stuck: j.status === 'queued' && wait > 120 && idleSlot }
195 })
196 const completed = (runs || []).filter((r) => r.status === 'completed').slice(0, 20)
197 const recent = completed.map((r) => ({ id: r.id, conclusion: r.conclusion, seconds: secs(r.startedAt, r.updatedAt), title: r.title, workflow: r.workflow }))
198 const timings = { fast: [], full: [], budgets: budgets || { fast: null, full: null } }
199 let refusedRuns = 0
200 let refusedMessage = null
201 for (const r of completed) {
202 const f = (facts || {})[r.id]
203 if (!f) continue
204 if (f.fast) timings.fast.push(f.fast.seconds)
205 if (f.full) timings.full.push(f.full.seconds)
206 if (f.refused) {
207 refusedRuns += 1
208 refusedMessage = refusedMessage || f.refused
209 }
210 }
211 const prRows = (prs || []).map((p) => {
212 const checks = latestChecks(p.statusCheckRollup)
213 const shown = {}
214 for (const k of KEY_CHECKS) if (checks[k]) shown[k] = checks[k]
215 for (const [k, v] of Object.entries(checks)) if (v === 'fail' && !shown[k]) shown[k] = v
216 const known = behind ? behind[p.number] : undefined
217 return { number: p.number, title: p.title || '', url: p.url || '', behind: typeof known === 'boolean' ? known : p.mergeStateStatus === 'BEHIND', checks: shown }
218 })
219 return {
220 pool: { configured: slots ?? null, slots: states, busy: states.filter((s) => s === 'busy').length, idle: states.filter((s) => s === 'idle').length, offline: states.filter((s) => s === 'offline').length, labels: poolLabels, runners: pool },
221 running,
222 queued,
223 stuck: queued.filter((j) => j.stuck).length,
224 recent,
225 timings,
226 refusal: refusedRuns ? { runs: refusedRuns, message: refusedMessage } : null,
227 prs: prRows,
228 }
229}
230
231// The CI part of the quiet line, and whether it needs attention.
232export function ciBand(projects) {
233 const all = (projects || []).filter((p) => p.ci)
234 if (all.length === 0) return null
235 const running = all.reduce((a, p) => a + p.ci.running.length, 0)
236 const queued = all.reduce((a, p) => a + p.ci.queued.length, 0)
237 const busy = all.reduce((a, p) => a + p.ci.pool.busy, 0)
238 const total = all.reduce((a, p) => a + p.ci.pool.slots.length, 0)
239 const stuck = all.reduce((a, p) => a + p.ci.stuck, 0)
240 const refused = all.some((p) => p.ci.refusal)
241 if (!running && !queued && !stuck && !refused) return null
242 const parts = [`CI ${running} running`]
243 if (queued) parts.push(`${queued} queued`)
244 if (total) parts.push(`pool ${busy}/${total}`)
245 const alert = stuck ? `${stuck} stuck` : refused ? 'refused by GitHub' : ''
246 return { text: parts.join(' · '), alert }
247}
248hooks/draw.js 193 lines1// Drawing helpers for the board. On the Desktop app they draw small SVGs
2// (badges, rings, pipeline strips, bars, pills, cells, result dots); in a
3// terminal the same calls draw colored text. Every color here comes from
4// BRAND.md: status tones for state, and each project's own color (from
5// projects.md) for which project a thing belongs to. Each helper takes the
6// element table from $.ui.resolve(e) and the surface name; none touches the
7// mods API.
8
9import { sanitize } from './lib.js'
10
11const TONES = {
12 good: { hex: '#22A06B', ink: '#FFFFFF', term: 'green' },
13 warn: { hex: '#E0A21A', ink: '#111111', term: 'yellow' },
14 bad: { hex: '#E5484D', ink: '#FFFFFF', term: 'red' },
15 muted: { hex: '#8A8F98', ink: '#FFFFFF', term: 'gray' },
16}
17// Project colors when projects.md gives none, in priority order.
18const PROJECT_FALLBACK = ['#017272', '#F48327', '#5B5BD6', '#C2185B', '#2E7D32', '#0277BD']
19const TRACK = 'rgba(127,127,127,0.24)'
20const LABEL = TONES.muted.hex
21const FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif"
22
23const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
24const isDesktop = (surface, E) => surface === 'desktop' && Boolean(E.Svg)
25const isHex = (c) => /^#[0-9a-f]{6}$/i.test(String(c || ''))
26
27function luminance(hex) {
28 const lin = (v) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
29 const [r, g, b] = [1, 3, 5].map((i) => lin(parseInt(hex.slice(i, i + 2), 16) / 255))
30 return 0.2126 * r + 0.7152 * g + 0.0722 * b
31}
32
33// Text on a filled shape: white or near black, whichever contrasts more.
34export function ink(hex) {
35 const l = luminance(hex)
36 return 1.05 / (l + 0.05) >= (l + 0.05) / 0.05 ? '#FFFFFF' : '#111111'
37}
38
39// The nearest named terminal color to a hex, by hue.
40export function termName(hex) {
41 const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
42 const max = Math.max(r, g, b)
43 const d = max - Math.min(r, g, b)
44 if (d < 0.08) return 'gray'
45 const h = (max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4) * 60
46 const hue = (h + 360) % 360
47 return hue < 15 || hue >= 330 ? 'red' : hue < 70 ? 'yellow' : hue < 165 ? 'green' : hue < 200 ? 'cyan' : hue < 260 ? 'blue' : 'magenta'
48}
49
50// A status tone by name, or a project color given as a hex.
51function tone(name) {
52 if (isHex(name)) return { hex: name.toUpperCase(), ink: ink(name), term: termName(name) }
53 return TONES[name] || TONES.muted
54}
55
56// A project's color: its own from projects.md, else the fallback for its place.
57export function projectColor(p, index) {
58 return p && isHex(p.color) ? p.color.toUpperCase() : PROJECT_FALLBACK[Math.max(0, index) % PROJECT_FALLBACK.length]
59}
60
61function svg(E, w, h, body, alt) {
62 return E.Svg({ source: `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>`, alt: sanitize(alt, 200), width: w, height: h })
63}
64
65// Text in a tone: a hex on the Desktop app, a named color in a terminal.
66export function colored(E, surface, name, text, extra = {}) {
67 text = sanitize(text, 2000)
68 const t = tone(name)
69 return E.Text({ ...extra, color: surface === 'desktop' ? t.hex : t.term, children: [text] })
70}
71
72// A project's badge: its monogram on a rounded square in its color.
73export function badge(E, surface, label, hex, size = 18) {
74 label = sanitize(label, 4)
75 const t = tone(hex)
76 if (isDesktop(surface, E)) {
77 const w = Math.round(size * 1.25)
78 return svg(E, w, size, `<rect width="${w}" height="${size}" rx="4" fill="${t.hex}"/><text x="${w / 2}" y="${size / 2 + 3.8}" text-anchor="middle" font-family="${esc(FONT)}" font-size="${Math.round(size * 0.58)}" font-weight="600" fill="${t.ink}">${esc(label)}</text>`, label)
79 }
80 return E.Box({ flexShrink: 0, children: [E.Text({ bold: true, color: t.term, children: [label] })] })
81}
82
83// A ring for a fraction done, in a project's color. The count goes beside it, as text.
84export function ring(E, surface, done, total, hex, size = 40) {
85 const frac = total > 0 ? Math.max(0, Math.min(1, done / total)) : 0
86 if (isDesktop(surface, E)) {
87 const r = size / 2 - 3
88 const len = 2 * Math.PI * r
89 const arc = frac > 0 ? `<circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="none" stroke="${tone(hex).hex}" stroke-width="4" stroke-linecap="round" stroke-dasharray="${(len * frac).toFixed(1)} ${len.toFixed(1)}" transform="rotate(-90 ${size / 2} ${size / 2})"/>` : ''
90 return svg(E, size, size, `<circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="none" stroke="${TRACK}" stroke-width="4"/>${arc}`, `${done} of ${total} done`)
91 }
92 return E.Text({ color: tone(hex).term, children: [`${Math.round(frac * 100)}%`] })
93}
94
95// Where a project's work sits: stages joined by a line, each node filled in
96// the project's color when it holds work, with its count inside.
97export function pipeline(E, surface, stages, hex) {
98 const t = tone(hex)
99 if (isDesktop(surface, E)) {
100 const step = 66
101 const w = stages.length * step
102 const nodes = stages
103 .map((s, i) => {
104 const x = i * step + step / 2
105 const full = s.n > 0
106 const node = full ? `<circle cx="${x}" cy="11" r="9.5" fill="${t.hex}"/>` : `<circle cx="${x}" cy="11" r="8.75" fill="none" stroke="${TRACK}" stroke-width="1.5"/>`
107 const count = `<text x="${x}" y="14.6" text-anchor="middle" font-family="${esc(FONT)}" font-size="10" font-weight="600" fill="${full ? t.ink : LABEL}">${s.n > 99 ? '99+' : s.n}</text>`
108 const label = `<text x="${x}" y="33" text-anchor="middle" font-family="${esc(FONT)}" font-size="10" font-weight="500" fill="${LABEL}">${esc(s.label)}</text>`
109 return node + count + label
110 })
111 .join('')
112 const line = `<line x1="${step / 2}" y1="11" x2="${w - step / 2}" y2="11" stroke="${TRACK}" stroke-width="2"/>`
113 return svg(E, w, 38, line + nodes, stages.map((s) => `${s.n} ${s.label}`).join(', '))
114 }
115 const parts = []
116 stages.forEach((s, i) => {
117 if (i) parts.push(E.Text({ dimColor: true, children: [' › '] }))
118 parts.push(E.Text({ dimColor: s.n === 0, color: s.n ? t.term : undefined, bold: s.n > 0, children: [`${s.n}`] }))
119 parts.push(E.Text({ dimColor: true, children: [' ' + s.label] }))
120 })
121 return E.Box({ flexDirection: 'row', children: parts })
122}
123
124// A progress bar. Desktop: a rounded SVG bar. Terminal: heavy line characters.
125export function progress(E, surface, done, total, { width = 160, cells = 12, color = 'muted' } = {}) {
126 const frac = total > 0 ? Math.max(0, Math.min(1, done / total)) : 0
127 if (isDesktop(surface, E)) {
128 const w = Math.round(width)
129 const fill = Math.round(w * frac)
130 return svg(E, w, 8, `<rect width="${w}" height="8" rx="4" fill="${TRACK}"/>${fill > 0 ? `<rect width="${Math.max(fill, 8)}" height="8" rx="4" fill="${tone(color).hex}"/>` : ''}`, `${done} of ${total}`)
131 }
132 const full = Math.round(cells * frac)
133 return E.Box({
134 flexDirection: 'row',
135 children: [E.Text({ color: tone(color).term, children: ['━'.repeat(full)] }), E.Text({ dimColor: true, children: ['━'.repeat(cells - full)] })],
136 })
137}
138
139// A status pill. Desktop: a rounded filled label. Terminal: a colored dot and word.
140export function pill(E, surface, label, name = 'muted') {
141 label = sanitize(label, 80).replace(/\n/g, ' ')
142 const t = tone(name)
143 if (isDesktop(surface, E)) {
144 const w = Math.round(String(label).length * 6.3 + 16)
145 return svg(E, w, 18, `<rect width="${w}" height="18" rx="9" fill="${t.hex}"/><text x="${w / 2}" y="12.5" text-anchor="middle" font-family="${esc(FONT)}" font-size="11" font-weight="600" fill="${t.ink}">${esc(label)}</text>`, String(label))
146 }
147 return E.Box({ flexShrink: 0, children: [E.Text({ color: t.term, children: [`● ${label}`] })] })
148}
149
150// A row of square cells, each { fill } (a hex: busy), { outline } (a hex: idle)
151// or {} (empty): pool slots, and lane capacity colored by the project using it.
152// `pad` keeps the strip as wide as `pad` cells, so rows of strips line up.
153export function cells(E, surface, list, alt, pad = 0) {
154 list = list.slice(0, 48)
155 const span = Math.min(48, Math.max(list.length, pad, 1))
156 if (isDesktop(surface, E)) {
157 const w = span * 18
158 const body = list
159 .map((c, i) => {
160 const x = i * 18 + 1
161 if (c.fill) return `<rect x="${x}" y="1" width="14" height="14" rx="4" fill="${tone(c.fill).hex}"/>`
162 if (c.outline) return `<rect x="${x + 0.75}" y="1.75" width="12.5" height="12.5" rx="3.5" fill="none" stroke="${tone(c.outline).hex}" stroke-width="1.5"/>`
163 return `<rect x="${x}" y="1" width="14" height="14" rx="4" fill="${TRACK}"/>`
164 })
165 .join('')
166 return svg(E, w, 16, body, alt || `${list.filter((c) => c.fill).length} of ${list.length} in use`)
167 }
168 return E.Box({
169 flexDirection: 'row',
170 children: [
171 ...list.map((c) => E.Text({ color: c.fill || c.outline ? tone(c.fill || c.outline).term : 'gray', dimColor: !c.fill && !c.outline, children: [c.fill ? '■ ' : '□ '] })),
172 ...(span > list.length ? [E.Text({ children: [' '.repeat(span - list.length)] })] : []),
173 ],
174 })
175}
176
177// Recent results, oldest to newest, as dots colored by conclusion.
178export function dots(E, surface, results) {
179 const toneOf = (c) => (c === 'success' ? 'good' : c === 'failure' || c === 'timed_out' || c === 'startup_failure' ? 'bad' : c === 'cancelled' ? 'muted' : 'warn')
180 if (isDesktop(surface, E)) {
181 const w = Math.max(results.length, 1) * 11
182 return svg(E, w, 12, results.map((c, i) => `<circle cx="${i * 11 + 5}" cy="6" r="4" fill="${tone(toneOf(c)).hex}"/>`).join(''), `${results.filter((c) => c === 'success').length} of ${results.length} recent runs passed`)
183 }
184 return E.Box({ flexDirection: 'row', children: results.map((c) => E.Text({ color: tone(toneOf(c)).term, children: ['●'] })) })
185}
186
187// The tone for a time against its budget: green under 70 percent, amber under 90, red after.
188export function budgetTone(seconds, budget) {
189 if (!budget) return 'muted'
190 const r = seconds / budget
191 return r < 0.7 ? 'good' : r < 0.9 ? 'warn' : 'bad'
192}
193