SLOPSHOPPER

ci

CI routing and pipeline diagram: which CI backends exist (from a config file), whether they are usable, which repo or conversation uses which, and a Diagramme…

panecommandtoaststatuspromptprocess
v0.2.0MITupdated 2026-10-16julian-passebecq/claude-mod/mods/ci
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ci
│ ┃ CI routing ✕ › fix the failing auth test and add an audit log call │ ┃ ▸ Routage Diagramme │ ┃ checked never · ci.py failed: exit 0 r: Refr ⏺ Read(src/auth.ts) │ ┃ No data yet: run /ci or press Refresh. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /ci │ ⎿ ci: ci: exit 0 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · CI routing
▸ Routage Diagramme checked never · ci.py failed: exit 0 r: Refresh No data yet: run /ci or press Refresh.
README

ci

Now also inside Référence (mods/reference, tab CI, /reference ci [diagramme …]): same drawing (hooks/draw.tsx, diagram.ts, view.ts, synced there), same caches through scanner/ci.py. /ci keeps working while this mod is loaded; once it is unloaded, Référence answers it (route and clear need this mod).

Two tabs in one side pane, Routage and Diagramme. Nothing here blocks or rewrites a tool call, and nothing calls a model.

CommandWhat it does
/ciOpens Routage: the CI backends from your config, whether each one is usable now, and which repo or conversation uses which.
/ci refreshSame, after a fresh status check (tokens present yes/no, runners online, running and pending jobs).
`/ci route <repo-path\session-id\here\session> <backend-id>, /ci clear <target>`Write or clear a route in ~/.claude/ci-routing.json.
/ci diagrammeOpens Diagramme, the pipeline view.
/ci diagramme refreshSame, and reads gh / glab again now (1 to 3 minutes for about a hundred repos).
`/ci diagramme claude\codex\inconnu\tout and hote\app\conv`Same, with that filter and grouping already set. The Diagramme opens on Claude Code only unless pipelines.default_who says codex, all or unknown; the Codex button is next to it.
/ci relaisThe Claude ↔ Codex summary from the last scan: per agent, PRs opened, fixed, merged, commits, CI pass rate of its PRs and of its runs; hand-offs and dependencies.
/ci relais refreshRuns scanner/relais.mjs in the background (1-3 min) and writes ~/.claude/ci-cache/interactions.json, the file the Cockpit reads.
/ci closeCloses the pane.

Diagramme

From top to bottom:

  1. One sentence describes the current state, for example « 2 pipelines en cours, 1 rouge dans datapass-react (job lint), runner local à 6/18, attente runner ~45s (médiane de 12 jobs) ».
  2. Filters are real buttons: Tout · Claude Code · Codex · inconnu.
  3. Résumé (folded at start): runs today and over 7 days, pass rate, minutes per CI host, the local runner's queue (jobs running and pending, runners online, median queue wait), and the same figures per author and per app. On desktop it also shows a static picture (authors → CI hosts → results). The picture cannot be clicked; the buttons stay buttons.
  4. En cours: one entry per running pipeline. Each shows « vert ou rouge vers HH:MM » and a text Gantt, one bar per job grouped by stage, drawn by lib/core/gantt.mjs, the same renderer and legend as factory's Workflow screen: ░ file, █ fini, ▓ en cours, ▒ échoué, ┄ estimation, │ maintenant. The Gantt is 24 cells wide, so it stays readable at side-panel width.
  5. Rouges: the latest run of each lane that really failed. Each red job comes with the command that prints its log, for example gh run view <id> -R owner/repo --log-failed or glab ci trace <job-id> -R group/repo, plus its link. The mod shows these commands and never runs them. A job with allow_failure is orange, never red, and a cancelled or skipped run is grey.
  6. Pipelines par hôte / par app / par conversation: one lane per repo × CI host: app ──▶ CI host ──▶ [stage: job ✔ 1m02, …] ▶ [stage …] ──▶ ✔ vert 1m20 · il y a 2 h, followed by the lane's last runs (✔✔✘●…), who made them, the branch or MR, and the conversation. The Gantt ▸ button opens that lane's newest run as a Gantt. Each group can be folded.

Where the data comes from

  • Repos: every git clone under pipelines.roots (max_depth deep), the paths in pipelines.repos, and every repo that has a route. A GitHub remote and a GitLab remote of the same clone (a CI mirror on GitLab) count as one app.
  • Runs: gh run list plus gh run view --json jobs (jobs of the newest jobs_runs runs only) for GitHub, and glab api in GET for GitLab pipelines and jobs. The CI host comes from the jobs' runner tag (local-windows → the local runner) or from a shared runner (→ GitLab SaaS). A GitLab pipeline whose jobs were not read gets the host of the same project's recent pipelines and is marked *.
  • Who made the run:
  • Claude Code: a Co-Authored-By: Claude trailer in the commit (read with git log -1 in the local clone), a claude/* or worktree-agent-* branch, or a PR/MR opened by a Claude Code conversation.
  • Codex: a codex/* branch, a Codex trailer, or a Codex author.
  • inconnu for anything else. The mod never guesses. The patterns are in pipelines.attribution.
  • Conversation: the mod reads ~/.claude/projects/*/*.jsonl read-only and looks for the output of gh pr create and glab mr create (the PR/MR URL, and the branch from --head / --source-branch or the line's gitBranch). The conversation title comes from the transcript's custom-title entry. Results are cached per file (size and mtime) in ~/.claude/ci-conversations-cache.json.
  • Estimates:
  • Per job: the median of the last successful runs of the same job, which needs at least 3 of them. The history of those runs is kept across refreshes in the pipelines cache.
  • Later stages: a job in a later stage starts when the previous stage ends, plus the runner's median queue wait.
  • Fallback: when the job history is too short, the median duration of the lane's last successful pipelines (at least 3). When that is also too short, the view says « pas assez d'historique » and gives the sample size.
  • One estimate rule: the scanner sends its samples (samples_s per job, durations_s per pipeline) and the view recomputes the median and the end with lib/core/estimate.mjs, the rule factory's Workflow ETA uses (at least 3 samples, never an end in the past). The runner line reads like runnerLine() of lib/core/runner.mjs (tests/core.test.mjs checks both on invented runs); a hooks module cannot import runner.mjs itself (it reads files with node:fs).
  • Refresh: on Rafraîchir, /ci diagramme refresh, or when the cache (~/.claude/ci-pipelines-cache.json) is older than cache_minutes. There is no timer.

Labels, colours and limits are in ci.config.example.json → pipelines. Copy it to ~/.claude/ci.config.json and set pipelines.roots.

Claude ↔ Codex (scanner/relais.mjs)

A Node scanner, read-only, that builds one row per PR/MR over the last relais.days days (30 by default):

  • opened_by: branch prefix (claude/, worktree-agent-, codex/), then a body mark (« Generated with Claude Code », Codex marks), then the author, then the first commit.
  • fixed_by: the agents of the commits after the first one (trailer Co-Authored-By: Claude / Codex, or an agent author; an unmarked commit on an agent's branch counts for that agent).
  • merged_by: the agent whose transcript ran gh pr merge <n> or glab mr merge <n> for that repo (~/.claude/projects/**/*.jsonl, ~/.codex/sessions/**/*.jsonl, files touched in the window only; a cd <dir> before the command, -R owner/repo or a PR URL tell the repo). Otherwise « unknown », never a guess.
  • handoffs: agent switches along opener → commits → merger; depends_on: « depends on #N », « after #N », « stacked on #N », or a base branch that is another PR's head.
  • CI: the PR's checks (GitHub rollup, GitLab MR pipeline), and the runs per agent from the Diagramme's cache (ci-pipelines-cache.json).

Output: ~/.claude/ci-cache/interactions.json (schema, generated, days, repos[].prs[], repos[].totals, totals.by_agent.{claude,codex,unknown}, errors). The rules are in scanner/relais_core.mjs (pure); tests/relais.test.mjs checks them on invented repos.

node mods/ci/scanner/relais.mjs --days 7 --summary   # scan and print the summary
node mods/ci/scanner/relais.mjs --cached --summary   # print the last scan

Tests

python -I -m unittest discover -s mods/ci/tests -p "test_*.py"
node --test mods/ci/tests/core.test.mjs mods/ci/tests/relais.test.mjs
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test mods/ci

All test data is invented: repos, runs, job history and transcripts.

Source 7 files
hooks/register.tsx 264 lines
1// ci mod: which CI backends exist, whether they are usable, and which repo or conversation uses which.
2//   /ci                         backends + status + the route for this conversation, opens the CI routing pane
3//   /ci refresh                 the same after a fresh status check
4//   /ci route <target> <id>     writes the routing file (target: a repo path, a session id, `here` or `session`)
5//   /ci clear <target>
6//   /ci diagramme [refresh] [claude|codex|inconnu|tout] [hote|app|conv]
7//                               the « Diagramme » tab: repo → CI host → stages/jobs → result, last runs, who made them
8//   /ci relais [refresh]        Claude ↔ Codex per repo/PR (who opened, fixed, merged, hand-offs, CI pass rate per agent),
9//                               from scanner/relais.mjs, written to ~/.claude/ci-cache/interactions.json for the Cockpit
10// Everything runs through scanner/ci.py (standard library). The mod shows and informs: it never denies,
11// blocks or rewrites a tool call. Its only writes are the routing file (/ci route, /ci clear, a Clear button)
12// and its caches. The Diagramme reads gh/glab (GET only), git log and local transcripts; no polling.
13// The drawing is in draw.tsx (pure), shared with the Référence hub (mods/reference).
14import { atom, read, update } from 'claude-code'
15import type { EngineInterface, Register } from 'claude-code'
16
17import type { GroupBy, Snapshot, WhoFilter } from '../types'
18import { diagramText, effectiveWho, parseDiagram, parseDiagramWords } from './diagram'
19import { drawCi } from './draw'
20import { PANE, parseArgs, parseSnapshot, promptNote, resolveTarget, summary } from './view'
21
22const snapshot = atom({ plugin: 'ci', key: 'snapshot' } as const, '')
23const checking = atom({ plugin: 'ci', key: 'checking' } as const, false)
24const error = atom({ plugin: 'ci', key: 'error' } as const, '')
25const tab = atom({ plugin: 'ci', key: 'tab' } as const, 'routing' as 'routing' | 'diagram')
26const diagram = atom({ plugin: 'ci', key: 'diagram' } as const, '')
27const fetching = atom({ plugin: 'ci', key: 'fetching' } as const, false)
28// '' = the config default (pipelines.default_who, Claude Code when absent); a filter button or word sets it
29const who = atom({ plugin: 'ci', key: 'who' } as const, '' as WhoFilter | '')
30const group = atom({ plugin: 'ci', key: 'group' } as const, 'host' as GroupBy)
31const foldedA = atom({ plugin: 'ci', key: 'folded' } as const, [] as string[])
32
33const root = ($: EngineInterface) => $.plugin.root.replace(/\\/g, '/')
34const safe = async <T,>(work: Promise<T>, fallback: T): Promise<T> => {
35  try {
36    return await work
37  } catch {
38    return fallback
39  }
40}
41
42/** Runs `python -I ci.py <args>` and parses its JSON; `{ error }` on any failure, never a throw. */
43const ci = async ($: EngineInterface, args: string[], timeoutMs = 20000): Promise<{ ok: true; json: any; text: string } | { ok: false; error: string }> => {
44  try {
45    const r = await $.process.run(['python', '-I', `${root($)}/scanner/ci.py`, ...args], { timeoutMs })
46    let json: any
47    try {
48      json = JSON.parse(r.stdout)
49    } catch {
50      json = undefined
51    }
52    if (r.exitCode !== 0 || !json) return { ok: false, error: json?.error ?? (r.stderr.trim().split('\n').pop() || `exit ${r.exitCode}`) }
53    return { ok: true, json, text: r.stdout }
54  } catch (err) {
55    return { ok: false, error: String(err) }
56  }
57}
58
59const where = async ($: EngineInterface) => ({
60  cwd: (await safe($.session.cwd(), '')).replace(/\\/g, '/'),
61  id: await safe($.session.id(), ''),
62})
63
64/** `show` for this conversation; `check` runs the network status check when the cache is stale, `force` always. */
65const refresh = async ($: EngineInterface, mode: 'cache' | 'check' | 'force' = 'cache'): Promise<Snapshot | undefined> => {
66  const { cwd, id } = await where($)
67  const args = ['show', '--cwd', cwd, ...(id ? ['--session', id] : [])]
68  if (mode === 'check') args.push('--check')
69  if (mode === 'force') args.push('--refresh')
70  if (mode !== 'cache') await update($, checking, () => true)
71  const r = await ci($, args, mode === 'cache' ? 20000 : 120000)
72  if (mode !== 'cache') await update($, checking, () => false)
73  if (!r.ok) {
74    await update($, error, () => r.error)
75    return undefined
76  }
77  await update($, error, () => '')
78  await update($, snapshot, () => r.text)
79  const s = r.json as Snapshot
80  if (s.options?.status_line !== false) $.ui.status(s.current ? `CI: ${s.current.backend}` : undefined)
81  return s
82}
83
84// One background check at a time per module copy; it runs on a timer so it outlives the command.
85let busy = false
86const checkSoon = ($: EngineInterface, force = false) => {
87  if (busy) return
88  busy = true
89  $.clock.after(0, async () => {
90    try {
91      await refresh($, force ? 'force' : 'check')
92    } finally {
93      busy = false
94    }
95  })
96}
97
98/** `ci.py pipelines` from its cache; `check` fetches from gh/glab when the cache is stale, `force` always. */
99const loadDiagram = async ($: EngineInterface, mode: 'cache' | 'check' | 'force' = 'cache') => {
100  const args = ['pipelines', ...(mode === 'check' ? ['--check'] : mode === 'force' ? ['--refresh'] : [])]
101  if (mode !== 'cache') await update($, fetching, () => true)
102  const r = await ci($, args, mode === 'cache' ? 20000 : 300000)
103  if (mode !== 'cache') await update($, fetching, () => false)
104  if (!r.ok) {
105    await update($, error, () => r.error)
106    return undefined
107  }
108  await update($, error, () => '')
109  await update($, diagram, () => r.text)
110  return parseDiagram(r.text)
111}
112
113let fetchBusy = false
114const fetchSoon = ($: EngineInterface, force = false) => {
115  if (fetchBusy) return
116  fetchBusy = true
117  $.clock.after(0, async () => {
118    try {
119      await loadDiagram($, force ? 'force' : 'check')
120    } finally {
121      fetchBusy = false
122    }
123  })
124}
125
126/** `node scanner/relais.mjs --summary [args]` → its text, or the error; never a throw. */
127const relais = async ($: EngineInterface, args: string[], timeoutMs = 20000): Promise<{ ok: true; text: string } | { ok: false; error: string }> => {
128  try {
129    const r = await $.process.run(['node', `${root($)}/scanner/relais.mjs`, '--summary', ...args], { timeoutMs })
130    let json: any
131    try {
132      json = JSON.parse(r.stdout)
133    } catch {
134      json = undefined
135    }
136    if (r.exitCode !== 0 || !json?.text) return { ok: false, error: json?.error ?? (r.stderr.trim().split('\n').pop() || `exit ${r.exitCode}`) }
137    return { ok: true, text: json.text }
138  } catch (err) {
139    return { ok: false, error: String(err) }
140  }
141}
142
143let relaisBusy = false
144const relaisSoon = ($: EngineInterface) => {
145  if (relaisBusy) return
146  relaisBusy = true
147  $.clock.after(0, async () => {
148    try {
149      const r = await relais($, [], 600000)
150      $.ui.toast(r.ok ? r.text.split('\n')[0]! : `ci relais: ${r.error}`)
151    } finally {
152      relaisBusy = false
153    }
154  })
155}
156
157export const register: Register = on => {
158  on('session.start', async ($, e, next) => {
159    await $.command.register({
160      name: 'ci',
161      description: 'CI routing: backends, their status, and which repo or conversation uses which (route / clear)',
162      argumentHint: '[refresh] | diagramme [refresh] [claude|codex|inconnu|tout] [hote|app|conv] | relais [refresh] | close | route <repo|session|here> <backend-id> | clear <repo|session|here>',
163    })
164    const ran = await next(e)
165    // the route for the status line and the prompt note; cache only, no network at start
166    $.clock.after(0, () => void refresh($, 'cache'))
167    return ran
168  })
169
170  on('command.run', { command: 'ci' }, async ($, e) => {
171    if ((e.args ?? '').trim().toLowerCase() === 'close') {
172      await $.ui.close({ id: PANE.id })
173      return {}
174    }
175    const relaisWords = (e.args ?? '').trim().toLowerCase().split(/\s+/)
176    if (relaisWords[0] === 'relais' || relaisWords[0] === 'codex-claude') {
177      // Claude <-> Codex dataset (scanner/relais.mjs, read-only, written to ~/.claude/ci-cache/interactions.json)
178      if (relaisWords[1] === 'refresh') {
179        relaisSoon($)
180        return { text: 'ci relais: lecture gh/glab et des transcripts en arrière-plan (1-3 min), puis /ci relais' }
181      }
182      const r = await relais($, ['--cached'])
183      return { text: r.ok ? r.text : `ci relais: ${r.error}` }
184    }
185    const p = parseArgs(e.args ?? '')
186    if (p.kind === 'usage') return { text: p.text }
187    if (p.kind === 'diagram') {
188      const w = parseDiagramWords(p.words)
189      if (w.who) await update($, who, () => w.who!)
190      if (w.group) await update($, group, () => w.group!)
191      await update($, tab, () => 'diagram' as const)
192      await $.ui.open({ id: PANE.id, title: PANE.title })
193      const d = await loadDiagram($, 'cache')
194      if (!d) return { text: `ci: ${await read($, error)}` }
195      if (w.refresh || d.stale) fetchSoon($, w.refresh)
196      return { text: diagramText(w.refresh ? { ...d, stale: true } : d, effectiveWho(await read($, who), d), await read($, group), Date.now()) }
197    }
198    const { cwd, id } = await where($)
199    if (p.kind === 'route' || p.kind === 'clear') {
200      const target = resolveTarget(p.target, cwd, id)
201      const args = p.kind === 'route'
202        ? ['route', target, p.backend, '--by', id ? `session ${id}` : 'session', '--cwd', cwd]
203        : ['clear', target, '--cwd', cwd]
204      const r = await ci($, args)
205      if (!r.ok) return { text: `ci: ${r.error}` }
206      await refresh($, 'cache')
207      return {
208        text: p.kind === 'route'
209          ? `ci: ${r.json.kind} ${r.json.key} → ${r.json.backend}${r.json.warning ? ` (${r.json.warning})` : ''}`
210          : `ci: cleared ${r.json.removed} route(s) for ${r.json.key}`,
211      }
212    }
213    await update($, tab, () => 'routing' as const)
214    await $.ui.open({ id: PANE.id, title: PANE.title })
215    const s = await refresh($, 'cache')
216    if (!s) return { text: `ci: ${await read($, error)}` }
217    if (p.refresh || s.stale) checkSoon($, p.refresh)
218    return { text: summary(p.refresh ? { ...s, stale: true } : s) }
219  })
220
221  // The route as information for the model, only when the config sets prompt_note: true (default off: it would add
222  // text to every request). Nothing is blocked or rewritten.
223  on('prompt.compose', async ($, e, next) => {
224    const result = await next(e)
225    const s = parseSnapshot(await read($, snapshot))
226    const note = s && s.options?.prompt_note === true ? promptNote(s) : undefined
227    if (!note) return result
228    return { ...result, sections: [...result.sections, { id: 'ci:route', text: note, scope: 'session' as const }] }
229  })
230
231  on('ui.render', { component: 'Pane', requestId: PANE.id }, async ($, e) => {
232    const dg = parseDiagram(await read($, diagram))
233    return drawCi($.ui.resolve(e), {
234      surface: e.surface,
235      tab: await read($, tab),
236      snapshot: parseSnapshot(await read($, snapshot)),
237      diagram: dg,
238      error: await read($, error),
239      checking: await read($, checking),
240      fetching: await read($, fetching),
241      who: effectiveWho(await read($, who), dg),
242      group: await read($, group),
243      folded: await read($, foldedA),
244      now: Date.now(),
245      onTab: async t => {
246        await update($, tab, () => t)
247        if (t === 'diagram') {
248          const d = await loadDiagram($, 'cache')
249          if (!d || d.stale) fetchSoon($)
250        } else await refresh($, 'cache')
251      },
252      onCheck: force => checkSoon($, force),
253      onFetch: force => fetchSoon($, force),
254      onWho: async f => { await update($, who, () => f) },
255      onGroup: async x => { await update($, group, () => x) },
256      onToggle: async k => { await update($, foldedA, (cur: string[]) => (cur.includes(k) ? cur.filter(x => x !== k) : [...cur, k])) },
257      onClear: async key => {
258        await ci($, ['clear', key])
259        await refresh($, 'cache')
260      },
261    })
262  })
263}
264
hooks/diagram.ts 434 lines
1// Pure helpers of the ci mod's « Diagramme » view: filters, lanes, text segments and the static SVG overview.
2// No `$`, so tests call them directly. Labels and colors come from the config (pipelines.labels / colors /
3// svg_colors); the French defaults below apply only to keys the config leaves out.
4import type { App, Diagram, DiagramLabels, GroupBy, Job, Run, RunStatus, Stats, Who, WhoFilter } from '../types'
5import { MIN_SAMPLES, estimateOf, etaOf } from '../lib/core/estimate.mjs'
6import { COLORS, SYMBOLS, axis as ganttAxis, gantt as coreGantt, legend as ganttLegend } from '../lib/core/gantt.mjs'
7
8export const DEFAULT_LABELS: Required<Omit<DiagramLabels, 'status'>> & { status: Record<RunStatus, string> } = {
9  tab_routing: 'Routage',
10  tab_diagram: 'Diagramme',
11  all: 'Tout',
12  claude: 'Claude Code',
13  codex: 'Codex',
14  unknown: 'inconnu',
15  by_host: 'par hôte',
16  by_app: 'par app',
17  by_conv: 'par conversation',
18  no_conv: 'sans conversation connue',
19  today: "aujourd'hui",
20  week: '7 jours',
21  pass_rate: 'réussite',
22  minutes: 'min',
23  queue: 'file du runner local',
24  last_runs: 'derniers runs',
25  no_runs: 'aucun run lu',
26  not_fetched: "non lu (gh/glab absent, pas d'accès ou pas de CI)",
27  status: { success: 'vert', failed: 'rouge', running: 'en cours', queued: 'en attente', cancelled: 'annulé', skipped: 'sauté' },
28}
29export const DEFAULT_COLORS: Record<RunStatus, string> = {
30  success: 'success', failed: 'error', running: 'warning', queued: 'warning', cancelled: 'subtle', skipped: 'subtle',
31}
32export const DEFAULT_SVG: Record<string, string> = {
33  success: '#2da44e', failed: '#cf222e', running: '#bf8700', queued: '#bf8700', cancelled: '#8c959f', skipped: '#8c959f',
34  line: '#8c959f', text: '#8c959f', box: '#2f81f7',
35}
36export const MARK: Record<RunStatus, string> = { success: '✔', failed: '✘', running: '●', queued: '◌', cancelled: '⊘', skipped: '–' }
37
38export const labelsOf = (d: Pick<Diagram, 'labels'> | undefined) => ({
39  ...DEFAULT_LABELS,
40  ...(d?.labels ?? {}),
41  status: { ...DEFAULT_LABELS.status, ...(d?.labels?.status ?? {}) },
42})
43export type L = ReturnType<typeof labelsOf>
44export const colorOf = (d: Pick<Diagram, 'colors'> | undefined, s: RunStatus): string => d?.colors?.[s] ?? DEFAULT_COLORS[s]
45
46/** Filter buttons, Claude Code first (the default), then the Codex button, then everything and the unattributed. */
47export const WHO_FILTERS: WhoFilter[] = ['claude', 'codex', 'all', 'unknown']
48/** Claude only unless the config (pipelines.default_who) says otherwise. */
49export const DEFAULT_WHO: WhoFilter = 'claude'
50/** The filter in use: the viewer's choice, else the config default, else Claude only. */
51export const effectiveWho = (chosen: WhoFilter | '' | undefined, d: Pick<Diagram, 'default_who'> | undefined): WhoFilter =>
52  chosen && (WHO_FILTERS as string[]).includes(chosen) ? chosen
53    : d?.default_who && (WHO_FILTERS as string[]).includes(d.default_who) ? d.default_who
54    : DEFAULT_WHO
55export const GROUPS: GroupBy[] = ['host', 'app', 'conv']
56export const whoLabel = (L: L, w: WhoFilter): string => (w === 'all' ? L.all : L[w])
57export const groupLabel = (L: L, g: GroupBy): string => (g === 'host' ? L.by_host : g === 'app' ? L.by_app : L.by_conv)
58
59/** `/ci diagramme [refresh] [claude|codex|inconnu|tout] [hote|app|conv]` → which filter words were typed. */
60export const parseDiagramWords = (words: string[]): { refresh: boolean; who?: WhoFilter; group?: GroupBy } => {
61  const out: { refresh: boolean; who?: WhoFilter; group?: GroupBy } = { refresh: false }
62  for (const raw of words) {
63    const w = raw.toLowerCase()
64    if (w === 'refresh' || w === 'check') out.refresh = true
65    else if (w === 'tout' || w === 'all') out.who = 'all'
66    else if (w === 'claude') out.who = 'claude'
67    else if (w === 'codex') out.who = 'codex'
68    else if (w === 'inconnu' || w === 'unknown') out.who = 'unknown'
69    else if (w === 'hote' || w === 'hôte' || w === 'host') out.group = 'host'
70    else if (w === 'app' || w === 'apps' || w === 'repo') out.group = 'app'
71    else if (w === 'conv' || w === 'conversation' || w === 'session') out.group = 'conv'
72  }
73  return out
74}
75
76export const fmtDur = (s: number | null | undefined): string => {
77  if (s == null) return '?'
78  if (s < 60) return `${s}s`
79  const m = Math.floor(s / 60)
80  if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}`
81  return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
82}
83
84export const ago = (iso: string | null | undefined, now: number): string => {
85  const t = iso ? Date.parse(iso) : NaN
86  if (!Number.isFinite(t)) return '?'
87  const m = Math.max(0, Math.round((now - t) / 60000))
88  if (m < 60) return `il y a ${m} min`
89  if (m < 48 * 60) return `il y a ${Math.round(m / 60)} h`
90  return `il y a ${Math.round(m / 1440)} j`
91}
92
93export const hostLabel = (d: Diagram, id: string): string =>
94  d.hosts.find(h => h.id === id)?.label ?? (id === 'gitlab' ? 'GitLab (runner inconnu)' : id)
95
96export const runsOf = (d: Diagram, who: WhoFilter): Run[] =>
97  d.apps.flatMap(a => a.runs).filter(r => who === 'all' || r.who === who)
98
99/** One lane = one app on one CI host: its runs newest first. */
100export type Lane = { key: string; app: string; backend: string; host: string; runs: Run[] }
101export type Group = { key: string; title: string; lanes: Lane[]; runs: Run[] }
102
103const lanesOf = (d: Diagram, runs: Run[]): Lane[] => {
104  const m = new Map<string, Lane>()
105  for (const r of runs) {
106    const key = `${r.app}|${r.backend}`
107    let l = m.get(key)
108    if (!l) m.set(key, (l = { key, app: r.app, backend: r.backend, host: hostLabel(d, r.backend), runs: [] }))
109    l.runs.push(r)
110  }
111  const ls = [...m.values()]
112  for (const l of ls) l.runs.sort((a, b) => (b.created ?? '').localeCompare(a.created ?? ''))
113  return ls.sort((a, b) => (b.runs[0]?.created ?? '').localeCompare(a.runs[0]?.created ?? ''))
114}
115
116/** Lanes grouped by CI host, by app or by the conversation that opened the PR/MR. */
117export const groups = (d: Diagram, who: WhoFilter, by: GroupBy): Group[] => {
118  const L = labelsOf(d)
119  const runs = runsOf(d, who)
120  const m = new Map<string, { title: string; runs: Run[] }>()
121  for (const r of runs) {
122    const [key, title] = by === 'host'
123      ? [r.backend, hostLabel(d, r.backend)]
124      : by === 'app'
125        ? [r.app, r.app]
126        : r.conv
127          ? [r.conv.id, `${r.conv.title || r.conv.id}${r.conv.title ? ` · ${r.conv.id.slice(0, 8)}` : ''}${r.conv.project ? ` · ${r.conv.project}` : ''}`]
128          : ['', L.no_conv]
129    let g = m.get(key)
130    if (!g) m.set(key, (g = { title, runs: [] }))
131    g.runs.push(r)
132  }
133  const out = [...m.entries()].map(([key, g]) => ({ key, title: g.title, runs: g.runs, lanes: lanesOf(d, g.runs) }))
134  // the "no conversation" group last, the others by most recent run
135  return out.sort((a, b) => (a.key === '' ? 1 : b.key === '' ? -1 : 0) || (b.lanes[0]?.runs[0]?.created ?? '').localeCompare(a.lanes[0]?.runs[0]?.created ?? ''))
136}
137
138export const stats = (runs: Run[]): Stats => {
139  const done = runs.filter(r => r.status === 'success' || r.status === 'failed')
140  const ok = done.filter(r => r.status === 'success').length
141  return {
142    runs: runs.length, success: ok, failed: done.length - ok,
143    running: runs.filter(r => r.status === 'running' || r.status === 'queued').length,
144    pass_rate: done.length ? Math.round((100 * ok) / done.length) : null,
145    minutes: Math.round(runs.reduce((s, r) => s + (r.duration_s ?? 0), 0) / 6) / 10,
146  }
147}
148export const statsText = (L: L, s: Stats): string =>
149  `${s.runs} runs · ${s.pass_rate == null ? '?' : `${s.pass_rate} %`} ${L.pass_rate} · ${s.failed} ${L.status.failed}` +
150  `${s.running ? ` · ${s.running} ${L.status.running}` : ''} · ${s.minutes} ${L.minutes}`
151
152/** A piece of text with an optional run status (the pane colors it). */
153export type Seg = { text: string; status?: RunStatus; dim?: boolean; bold?: boolean; color?: string }
154
155/** app ──▶ host ──▶ [stage: job ✔ 1m02, …] ▶ [stage …] ──▶ ✔ vert 1m20 · il y a 2 h, for the lane's newest run. */
156export const laneSegs = (L: L, lane: Lane, now: number): Seg[] => {
157  const r = lane.runs[0]!
158  const segs: Seg[] = [{ text: lane.app, bold: true }, { text: ' ──▶ ', dim: true }, { text: lane.host }]
159  if (r.host_inferred) segs.push({ text: '*', dim: true })
160  segs.push({ text: ' ──▶ ', dim: true })
161  const withJobs = lane.runs.find(x => x.jobs && x.jobs.length)
162  const jobs = r.jobs ?? null
163  if (jobs && jobs.length) {
164    const stages: string[] = []
165    for (const j of jobs) if (!stages.includes(j.stage)) stages.push(j.stage)
166    stages.forEach((st, i) => {
167      if (i) segs.push({ text: ' ▶ ', dim: true })
168      segs.push({ text: `[${st}: `, dim: true })
169      jobs.filter(j => j.stage === st).forEach((j, k) => {
170        if (k) segs.push({ text: ', ', dim: true })
171        segs.push({ text: `${j.name} ` })
172        segs.push({ text: MARK[j.status], status: j.allow_failure && j.status === 'failed' ? 'running' : j.status })
173        segs.push({ text: ` ${fmtDur(j.duration_s)}`, dim: true })
174      })
175      segs.push({ text: ']', dim: true })
176    })
177  } else {
178    segs.push({ text: withJobs ? '[jobs non lus pour ce run]' : '[jobs non lus]', dim: true })
179  }
180  segs.push({ text: ' ──▶ ', dim: true })
181  segs.push({ text: `${MARK[r.status]} ${L.status[r.status]}`, status: r.status, bold: true })
182  segs.push({ text: ` ${fmtDur(r.duration_s)} · ${ago(r.created, now)}`, dim: true })
183  return segs
184}
185
186/** « derniers runs : ✔✔✘● · claude 6 · codex 2 · inconnu 1 · branche / conversation » for a lane. */
187export const historySegs = (L: L, lane: Lane, n = 10): Seg[] => {
188  const segs: Seg[] = [{ text: `   ${L.last_runs} : `, dim: true }]
189  for (const r of lane.runs.slice(0, n)) segs.push({ text: MARK[r.status], status: r.status })
190  const by = (w: Who) => lane.runs.filter(r => r.who === w).length
191  const who = (['claude', 'codex', 'unknown'] as Who[]).filter(w => by(w)).map(w => `${L[w]} ${by(w)}`).join(' · ')
192  const r = lane.runs[0]!
193  const where = r.mr != null ? `MR !${r.mr}` : r.branch || '?'
194  segs.push({ text: ` · ${who} · ${where}${r.conv ? ` · ${r.conv.title || r.conv.id}` : ''}`, dim: true })
195  return segs
196}
197
198export const segsText = (segs: Seg[]): string => segs.map(s => s.text).join('')
199
200/** The global summary as lines (also the text /ci diagramme answers with). */
201export const summaryLines = (d: Diagram, who: WhoFilter, now: number): string[] => {
202  const L = labelsOf(d)
203  const runs = runsOf(d, who)
204  const today0 = new Date(now)
205  today0.setHours(0, 0, 0, 0)
206  const week0 = now - 7 * 86400000
207  const when = (r: Run) => (r.created ? Date.parse(r.created) : NaN)
208  const today = runs.filter(r => when(r) >= today0.getTime())
209  const week = runs.filter(r => when(r) >= week0)
210  const lines = [
211    `${L.today} : ${statsText(L, stats(today))}`,
212    `${L.week} : ${statsText(L, stats(week))}`,
213  ]
214  const per = (key: (r: Run) => string, name: (k: string) => string) => {
215    const m = new Map<string, Run[]>()
216    for (const r of week) m.set(key(r), [...(m.get(key(r)) ?? []), r])
217    return [...m.entries()].sort((a, b) => b[1].length - a[1].length).map(([k, rs]) => {
218      const s = stats(rs)
219      return `${name(k)} ${s.runs} (${s.pass_rate == null ? '?' : `${s.pass_rate} %`}, ${s.minutes} ${L.minutes})`
220    })
221  }
222  lines.push(`hôtes : ${per(r => r.backend, k => hostLabel(d, k)).join(' · ') || '—'}`)
223  if (who === 'all') lines.push(`auteurs : ${per(r => r.who, k => L[k as Who] ?? k).join(' · ') || '—'}`)
224  const apps = per(r => r.app, k => k)
225  lines.push(`apps : ${apps.slice(0, 8).join(' · ') || '—'}${apps.length > 8 ? ` · +${apps.length - 8}` : ''}`)
226  const q = d.summary?.queue
227  if (q) {
228    const n = (x: number | null) => (x == null ? '?' : String(x))
229    lines.push(`${L.queue} (${q.label}, tag ${q.tag}) : ${n(q.running)} jobs en cours, ${n(q.pending)} en attente, ` +
230      `${n(q.runners_online)} runner(s) en ligne, ${q.pipelines_open} pipeline(s) ouverts lus`)
231  }
232  return lines
233}
234
235export const diagramText = (d: Diagram, who: WhoFilter, group: GroupBy, now: number): string => {
236  const L = labelsOf(d)
237  const head = `CI · ${L.tab_diagram} · lu ${d.generated ?? 'jamais'}${d.stale ? ' (rafraîchissement)' : ''} · ${whoLabel(L, who)} · ${groupLabel(L, group)}`
238  if (!d.generated) return `${head}\naucune donnée : /ci diagramme refresh`
239  return [head, headline(d, who), ...summaryLines(d, who, now)].join('\n')
240}
241
242export const appsWithoutRuns = (d: Diagram): App[] => d.apps.filter(a => !a.runs.length)
243
244const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!)
245
246/** Static overview: authors → CI hosts → results, boxes with counts. A picture only: filters stay real buttons. */
247export const overviewSvg = (d: Diagram, who: WhoFilter, width = 560): string => {
248  const C = { ...DEFAULT_SVG, ...(d.svg_colors ?? {}) }
249  const L = labelsOf(d)
250  const runs = runsOf(d, who)
251  const hosts = [...new Set(runs.map(r => r.backend))].sort()
252  const authors = (['claude', 'codex', 'unknown'] as Who[]).filter(w => runs.some(r => r.who === w))
253  const rows = Math.max(hosts.length, authors.length, 1)
254  const rowH = 34
255  const h = rows * rowH + 30
256  const colW = Math.floor((width - 40) / 3)
257  const x = [10, 20 + colW, 30 + 2 * colW]
258  const y = (i: number, n: number) => 24 + i * rowH + ((rows - n) * rowH) / 2
259  const parts: string[] = []
260  const box = (bx: number, by: number, text: string, sub: string) =>
261    parts.push(`<rect x="${bx}" y="${by}" width="${colW}" height="${rowH - 8}" rx="5" fill="none" stroke="${C.box}" stroke-width="1.2"/>` +
262      `<text x="${bx + 8}" y="${by + 17}" font-size="11" fill="${C.text}" font-family="sans-serif">${esc(text)} <tspan font-weight="bold">${esc(sub)}</tspan></text>`)
263  const line = (x1: number, y1: number, x2: number, y2: number) =>
264    parts.push(`<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${C.line}" stroke-width="1" opacity="0.6"/>`)
265  parts.push(`<text x="${x[0]}" y="14" font-size="10" fill="${C.text}" font-family="sans-serif">auteur</text>`)
266  parts.push(`<text x="${x[1]}" y="14" font-size="10" fill="${C.text}" font-family="sans-serif">hôte CI</text>`)
267  parts.push(`<text x="${x[2]}" y="14" font-size="10" fill="${C.text}" font-family="sans-serif">résultat</text>`)
268  authors.forEach((w, i) => {
269    hosts.forEach((hId, k) => {
270      if (runs.some(r => r.who === w && r.backend === hId)) line(x[0] + colW, y(i, authors.length) + 13, x[1], y(k, hosts.length) + 13)
271    })
272    box(x[0], y(i, authors.length), L[w], String(runs.filter(r => r.who === w).length))
273  })
274  hosts.forEach((hId, k) => {
275    const rs = runs.filter(r => r.backend === hId)
276    const s = stats(rs)
277    line(x[1] + colW, y(k, hosts.length) + 13, x[2], y(k, hosts.length) + 13)
278    box(x[1], y(k, hosts.length), hostLabel(d, hId).slice(0, 28), String(rs.length))
279    // result bar: share of each status
280    const by = y(k, hosts.length)
281    let bx = x[2]
282    const order: RunStatus[] = ['success', 'failed', 'running', 'queued', 'cancelled', 'skipped']
283    for (const st of order) {
284      const n = rs.filter(r => r.status === st).length
285      if (!n) continue
286      const w = Math.max(2, Math.round(((colW - 70) * n) / rs.length))
287      parts.push(`<rect x="${bx}" y="${by + 5}" width="${w}" height="${rowH - 18}" fill="${C[st]}"/>`)
288      bx += w
289    }
290    parts.push(`<text x="${x[2] + colW - 64}" y="${by + 17}" font-size="11" fill="${C.text}" font-family="sans-serif">${s.pass_rate == null ? '?' : s.pass_rate + ' %'} · ${s.minutes} ${esc(L.minutes)}</text>`)
291  })
292  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${h}" viewBox="0 0 ${width} ${h}">${parts.join('')}</svg>`
293}
294
295// ---- user-friendly layer: headline sentence, ETA, Gantt, log commands ---------------------------------------------
296
297/** A job or run that is red for real: failed and not allowed to fail. */
298export const isRed = (x: { status: RunStatus; allow_failure?: boolean }): boolean => x.status === 'failed' && !x.allow_failure
299
300export const clock = (iso: string | null | undefined): string => {
301  const t = iso ? new Date(iso) : null
302  if (!t || Number.isNaN(t.getTime())) return '?'
303  return `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`
304}
305
306/** ms of a past successful duration list in seconds. */
307const msOf = (xs: number[] | undefined) => (xs ?? []).filter(x => Number.isFinite(x)).map(x => x * 1000)
308
309/**
310 * End time (ISO) of the run, recomputed with lib/core/estimate.mjs when the scanner sent the samples (pipeline basis:
311 * the median of the lane's last successful pipelines from the run's creation, never before now), else the scanner's.
312 */
313export const etaOfRun = (r: Run, now: number): string | null => {
314  const e = r.estimate
315  if (!e) return null
316  if (e.basis === 'pipeline' && e.durations_s && r.created) {
317    const end = etaOf(estimateOf(msOf(e.durations_s)), Date.parse(r.created), now)
318    if (end) return new Date(end.mid).toISOString()
319  }
320  return e.eta
321}
322
323/** « vert ou rouge vers 22:40 (médiane de 5 pipelines) », or why there is no estimate. */
324export const etaText = (r: Run, now: number = Date.now()): string => {
325  const e = r.estimate
326  if (!e) return ''
327  const eta = etaOfRun(r, now)
328  if (!eta) return `${e.reason ?? "pas assez d'historique"} (${e.samples} run(s) connus, ${MIN_SAMPLES} au moins)`
329  const basis = e.basis === 'jobs' ? `médiane des jobs, ${e.samples} runs au moins` : `médiane de ${e.samples} pipelines`
330  return `vert ou rouge vers ${clock(eta)} (${basis})`
331}
332
333/** The command that prints the log of a red job (shown, never run by the mod). */
334export const logCommand = (r: Run, j?: Job): string =>
335  r.forge === 'github'
336    ? `gh run view ${r.id} -R ${r.slug} --log-failed`
337    : `glab ci trace ${j?.id ?? '<job>'} -R ${r.slug}`
338
339/** Newest run of each lane, filtered by who. */
340export const latestRuns = (d: Diagram, who: WhoFilter): Run[] => {
341  const m = new Map<string, Run>()
342  for (const r of runsOf(d, who)) {
343    const k = `${r.app}|${r.backend}`
344    const cur = m.get(k)
345    if (!cur || (r.created ?? '') > (cur.created ?? '')) m.set(k, r)
346  }
347  return [...m.values()]
348}
349
350/** Every running or queued pipeline (not only the newest of each lane), newest first. */
351export const liveRuns = (d: Diagram, who: WhoFilter): Run[] =>
352  runsOf(d, who).filter(r => r.status === 'running' || r.status === 'queued')
353    .sort((a, b) => (b.created ?? '').localeCompare(a.created ?? ''))
354
355/** One plain French sentence: « 2 pipelines en cours, 1 rouge dans datapass-react (job lint), runner local à 6/18 ». */
356export const headline = (d: Diagram, who: WhoFilter): string => {
357  const last = latestRuns(d, who)
358  const running = liveRuns(d, who).length
359  const reds = last.filter(isRed).sort((a, b) => (b.created ?? '').localeCompare(a.created ?? ''))
360  const parts: string[] = []
361  parts.push(running ? `${running} pipeline${running > 1 ? 's' : ''} en cours` : 'aucun pipeline en cours')
362  if (reds.length) {
363    const r = reds[0]!
364    const jobs = (r.jobs ?? []).filter(isRed).map(j => j.name)
365    const where = `${r.app}${jobs.length ? ` (job${jobs.length > 1 ? 's' : ''} ${jobs.slice(0, 2).join(', ')}${jobs.length > 2 ? '…' : ''})` : ''}`
366    const more = reds.length > 1 ? ` et ${reds.length - 1} autre${reds.length > 2 ? 's' : ''}` : ''
367    parts.push(`${reds.length} rouge${reds.length > 1 ? 's' : ''} dans ${where}${more}`)
368  } else parts.push('aucun rouge')
369  const q = d.summary?.queue
370  if (q && q.running != null) parts.push(`runner local à ${q.running}/${q.concurrent ?? '?'}`)
371  if (q && q.wait_s != null) parts.push(`attente runner ~${fmtDur(Math.round(q.wait_s))} (médiane de ${q.wait_n} jobs)`)
372  return parts.join(', ')
373}
374
375/**
376 * One Gantt row: the job, then a bar of `width` cells drawn by lib/core/gantt.mjs, the renderer factory's Workflow
377 * screen uses too (░ file, █ fini, ▓ en cours, ▒ échoué, ┄ estimation, │ maintenant), then its time. A running job's
378 * estimated end comes from lib/core/estimate.mjs over the samples the scanner sent (else the scanner's own end).
379 */
380export type GanttRow = { stage: string; name: string; cells: Seg[]; text: string; red: boolean }
381export const GANTT = SYMBOLS
382export const GANTT_LEGEND: string = ganttLegend()
383
384const ganttStatus = (j: Job): string => (j.status === 'cancelled' || j.status === 'skipped' ? 'canceled' : j.status === 'success' ? 'done' : j.status)
385
386/** Estimated end (ms) of a job: core estimate over its samples from its real start, else the scanner's end. */
387export const jobEnd = (r: Run, j: Job, now: number): number | null => {
388  const e = r.estimate?.jobs?.[j.name]
389  if (!e) return null
390  const started = j.started ? Date.parse(j.started) : NaN
391  if (j.status === 'running' && Number.isFinite(started) && e.samples_s) {
392    const end = etaOf(estimateOf(msOf(e.samples_s)), started, now)
393    if (end) return end.mid
394  }
395  return e.end ? Date.parse(e.end) : null
396}
397
398export const gantt = (r: Run, now: number, width = 28): { rows: GanttRow[]; start: number; end: number; axis: string; legend: string } => {
399  const t = (s: string | null | undefined) => (s ? Date.parse(s) : NaN)
400  const fin = (x: number) => (Number.isFinite(x) ? x : undefined)
401  const jobs = (r.jobs ?? []).filter(j => Number.isFinite(t(j.created)) || Number.isFinite(t(j.started)))
402  const g = coreGantt(jobs.map(j => ({
403    label: j.name,
404    status: ganttStatus(j),
405    queuedMs: fin(t(j.created)),
406    startMs: fin(t(j.started)),
407    endMs: fin(t(j.finished)),
408    estEndMs: jobEnd(r, j, now) ?? undefined,
409  })), now, width)
410  const rows: GanttRow[] = jobs.map((j, i) => {
411    const going = j.status === 'running' || j.status === 'queued'
412    const e = r.estimate?.jobs?.[j.name]
413    const end = jobEnd(r, j, now)
414    const cells: Seg[] = (g.rows[i]?.segs ?? []).map((sg: { text: string; kind: string }) => ({
415      text: sg.text, color: (COLORS as Record<string, string>)[sg.kind], dim: sg.kind === 'empty' || sg.kind === 'queue' || sg.kind === 'est',
416    }))
417    const tail = going
418      ? (end ? `fin ~${clock(new Date(end).toISOString())} (n=${e?.n})` : e ? `pas assez d'historique (n=${e.n})` : MARK[j.status])
419      : `${MARK[j.status]} ${fmtDur(j.duration_s)}${j.queued_s ? ` + ${fmtDur(j.queued_s)} en file` : ''}`
420    return { stage: j.stage, name: j.name, cells, text: tail, red: isRed(j) }
421  })
422  return { rows, start: g.t0, end: g.t1, axis: ganttAxis(g, 0), legend: GANTT_LEGEND }
423}
424
425export const parseDiagram = (text: string): Diagram | undefined => {
426  if (!text) return undefined
427  try {
428    const d = JSON.parse(text) as Diagram
429    return Array.isArray(d.apps) ? d : undefined
430  } catch {
431    return undefined
432  }
433}
434
hooks/draw.tsx 299 lines
1// ci mod: the pane's drawing (Routage and Diagramme), pure. No `$`: the elements come in as `ui` ($.ui.resolve(e)),
2// the data and every press through `m`, so the ci pane and the Référence hub (mods/reference, a synced copy of this
3// file) draw the same tree. Same output as the drawing that lived in register.tsx before, except the Gantt, now drawn
4// by lib/core/gantt.mjs with factory's symbols and legend.
5import type { Diagram, GroupBy, Run, Snapshot, WhoFilter } from '../types'
6import { GROUPS, MARK, WHO_FILTERS, ago, appsWithoutRuns, clock, colorOf, etaText, gantt, groupLabel, groups, headline, historySegs, hostLabel, isRed, labelsOf, laneSegs, latestRuns, liveRuns, logCommand, overviewSvg, stats, statsText, summaryLines, whoLabel } from './diagram'
7import type { Seg } from './diagram'
8import { checkLine, mark, routeLine, rowColor, statusText, usableText } from './view'
9
10export const MAX_LANES = 40
11export const GANTT_WIDTH = 24
12/** Sections folded until the viewer opens them (the overview stays short at side-panel width). */
13export const FOLDED_AT_START = ['summary']
14
15export type CiTab = 'routing' | 'diagram'
16export type CiModel = {
17  surface: string
18  tab: CiTab
19  snapshot: Snapshot | undefined
20  diagram: Diagram | undefined
21  error: string
22  checking: boolean
23  fetching: boolean
24  who: WhoFilter
25  group: GroupBy
26  folded: string[]
27  now: number
28  onTab: (t: CiTab) => void | Promise<void>
29  onCheck: (force: boolean) => void
30  onFetch: (force: boolean) => void
31  onWho: (w: WhoFilter) => void | Promise<void>
32  onGroup: (g: GroupBy) => void | Promise<void>
33  onToggle: (key: string) => void | Promise<void>
34  onClear: (key: string) => void | Promise<void>
35}
36
37export function drawCi(ui: any, m: CiModel): any {
38  const { Box, Text, Button } = ui
39  const current = m.tab
40  const dRaw = m.diagram
41  const DL = labelsOf(dRaw)
42  const tabs = (
43    <Box flexDirection="row" gap={1}>
44      {(['routing', 'diagram'] as const).map(t => (
45        <Button key={`tab-${t}`} plain bold={current === t} dimColor={current !== t} onPress={() => m.onTab(t)}>
46          {`${current === t ? '▸ ' : ''}${t === 'routing' ? DL.tab_routing : DL.tab_diagram}`}
47        </Button>
48      ))}
49    </Box>
50  )
51  const problem = m.error
52
53  if (current === 'diagram') {
54    const now = m.now
55    const w = m.who
56    const g = m.group
57    const head = (
58      <Box flexDirection="row" gap={1}>
59        <Text dimColor>
60          {m.fetching ? 'lecture gh/glab…' : `lu ${dRaw?.generated ?? 'jamais'}`}
61          {problem ? ` · ci.py: ${problem}` : ''}
62        </Text>
63        <Button key="diag-refresh" hotkey="r" plain dimColor onPress={() => m.onFetch(true)}>
64          Rafraîchir
65        </Button>
66      </Box>
67    )
68    if (!dRaw || !dRaw.generated) {
69      return (
70        <Box flexDirection="column">
71          {tabs}
72          {head}
73          <Text>Pas encore de données : Rafraîchir, ou /ci diagramme refresh (lit gh et glab, ~1-3 min).</Text>
74        </Box>
75      )
76    }
77    const d = dRaw
78    const Svg = m.surface === 'terminal' ? undefined : ui.Svg
79    const folded = new Set(m.folded)
80    const toggle = (k: string) => () => m.onToggle(k)
81    const seg = (s: Seg, i: number) => (
82      <Text key={i} color={s.color ?? (s.status ? colorOf(d, s.status) : undefined)} dimColor={s.dim} bold={s.bold}>{s.text}</Text>
83    )
84    // A section: a header button (▾ open / ▸ folded with its one-line summary), then its body when open.
85    // Sections start open except the ones listed in FOLDED_AT_START (folded keys are toggled from that default).
86    const isOpen = (k: string) => (FOLDED_AT_START.includes(k) ? folded.has(k) : !folded.has(k))
87    const section = (k: string, title: string, oneLine: string, body: () => any) => (
88      <Box key={`sec-${k}`} flexDirection="column">
89        <Button key={`fold-${k}`} plain onPress={toggle(k)}>
90          {`${isOpen(k) ? '▾ ' : '▸ '}${title}${isOpen(k) ? '' : ` · ${oneLine}`}`}
91        </Button>
92        {isOpen(k) ? body() : null}
93      </Box>
94    )
95    const ganttBlock = (r: Run, key: string) => {
96      const gt = gantt(r, now, GANTT_WIDTH)
97      const stagesSeen: string[] = []
98      return (
99        <Box key={`gantt-${key}`} flexDirection="column">
100          <Text dimColor>
101            {'   '}{clock(new Date(gt.start).toISOString())} → {clock(new Date(gt.end).toISOString())} · {gt.legend}
102          </Text>
103          {gt.rows.map((row, i) => {
104            const head = !stagesSeen.includes(row.stage)
105            if (head) stagesSeen.push(row.stage)
106            return (
107              <Box key={`gr-${key}-${i}`} flexDirection="column">
108                {head ? <Text dimColor>{'   '}{row.stage}</Text> : null}
109                <Text wrap="truncate">
110                  <Text color={row.red ? colorOf(d, 'failed') : undefined}>{'   '}{row.name.slice(0, 16).padEnd(16)} </Text>
111                  {row.cells.map(seg)}
112                  <Text dimColor> {row.text}</Text>
113                </Text>
114              </Box>
115            )
116          })}
117          {gt.rows.length === 0 ? <Text dimColor>{'   '}jobs non lus pour ce run</Text> : null}
118        </Box>
119      )
120    }
121    const latest = latestRuns(d, w)
122    const live = liveRuns(d, w)
123    const reds = latest.filter(isRed).sort((a, b) => (b.created ?? '').localeCompare(a.created ?? ''))
124    const gs = groups(d, w, g)
125    let shown = 0
126    const empty = appsWithoutRuns(d)
127    const sum = summaryLines(d, w, now)
128    return (
129      <Box flexDirection="column">
130        {tabs}
131        {head}
132        <Text bold wrap="wrap">{headline(d, w)}</Text>
133        <Box flexDirection="row" gap={1}>
134          {WHO_FILTERS.map(f => (
135            <Button key={`who-${f}`} plain bold={w === f} dimColor={w !== f} onPress={() => m.onWho(f)}>
136              {`${w === f ? '▸ ' : ''}${whoLabel(DL, f)}`}
137            </Button>
138          ))}
139        </Box>
140        {section('summary', 'Résumé', sum[1] ?? '', () => (
141          <Box flexDirection="column">
142            {sum.map((l, i) => <Text key={`sum-${i}`} wrap="wrap">{'  '}{l}</Text>)}
143            {Svg ? <Svg key="ci-overview" source={overviewSvg(d, w)} alt={`auteurs → hôtes CI → résultats (${whoLabel(DL, w)})`} /> : null}
144          </Box>
145        ))}
146        {section('live', `En cours (${live.length})`, live.length ? live.map(r => r.app).slice(0, 3).join(', ') : 'rien', () => (
147          <Box flexDirection="column">
148            {live.length === 0 ? <Text dimColor>{'  '}aucun pipeline en cours</Text> : null}
149            {live.map(r => (
150              <Box key={`live-${r.app}-${r.id}`} flexDirection="column">
151                <Text wrap="wrap">
152                  <Text bold>{'  '}{r.app}</Text>
153                  <Text dimColor> · {hostLabel(d, r.backend)} · {r.mr != null ? `MR !${r.mr}` : r.branch} · </Text>
154                  <Text color={colorOf(d, 'running')}>{etaText(r, now)}</Text>
155                </Text>
156                {ganttBlock(r, `live-${r.app}-${r.id}`)}
157              </Box>
158            ))}
159          </Box>
160        ))}
161        {section('reds', `Rouges (${reds.length})`, reds.length ? reds.map(r => r.app).slice(0, 3).join(', ') : 'aucun', () => (
162          <Box flexDirection="column">
163            {reds.length === 0 ? <Text dimColor>{'  '}aucun rouge sur le dernier run de chaque ligne</Text> : null}
164            {reds.map(r => {
165              const bad = (r.jobs ?? []).filter(isRed)
166              return (
167                <Box key={`red-${r.app}-${r.id}`} flexDirection="column">
168                  <Text wrap="wrap">
169                    <Text color={colorOf(d, 'failed')} bold>{'  '}{MARK.failed} {r.app}</Text>
170                    <Text dimColor> · {hostLabel(d, r.backend)} · {r.mr != null ? `MR !${r.mr}` : r.branch} · {ago(r.created, now)}</Text>
171                  </Text>
172                  {bad.length === 0 ? <Text dimColor wrap="wrap">{'    '}log : {logCommand(r)} · {r.url}</Text> : null}
173                  {bad.map(j => (
174                    <Text key={`rj-${r.id}-${j.name}`} dimColor wrap="wrap">
175                      {'    '}job {j.name} ({j.stage}) · log : {logCommand(r, j)}{j.url ? ` · ${j.url}` : ''}
176                    </Text>
177                  ))}
178                </Box>
179              )
180            })}
181          </Box>
182        ))}
183        {section('lanes', `Pipelines ${groupLabel(DL, g)}`, `${gs.length} groupe(s)`, () => (
184          <Box flexDirection="column">
185            <Box flexDirection="row" gap={1}>
186              {GROUPS.map(x => (
187                <Button key={`group-${x}`} plain bold={g === x} dimColor={g !== x} onPress={() => m.onGroup(x)}>
188                  {`${g === x ? '▸ ' : ''}${groupLabel(DL, x)}`}
189                </Button>
190              ))}
191            </Box>
192            {gs.length === 0 ? <Text dimColor>{DL.no_runs}</Text> : null}
193            {gs.map(gr => (
194              <Box key={`g-${gr.key}`} flexDirection="column">
195                {section(`g:${g}:${gr.key}`, gr.title, statsText(DL, stats(gr.runs)), () => (
196                  <Box flexDirection="column">
197                    <Text dimColor>{'  '}{statsText(DL, stats(gr.runs))}</Text>
198                    {gr.lanes.map(l => {
199                      if (shown >= MAX_LANES) return null
200                      shown += 1
201                      const gk = `gantt:${l.key}`
202                      return (
203                        <Box key={`l-${gr.key}-${l.key}`} flexDirection="column">
204                          <Text wrap="wrap">{'  '}{laneSegs(DL, l, now).map(seg)}</Text>
205                          <Box flexDirection="row" gap={1}>
206                            <Text wrap="wrap">{historySegs(DL, l).map(seg)}</Text>
207                            <Button key={`btn-${gk}-${gr.key}`} plain dimColor onPress={toggle(gk)}>
208                              {folded.has(gk) ? 'Gantt ▾' : 'Gantt ▸'}
209                            </Button>
210                          </Box>
211                          {folded.has(gk) ? ganttBlock(l.runs[0]!, `${gr.key}-${l.key}`) : null}
212                        </Box>
213                      )
214                    })}
215                  </Box>
216                ))}
217              </Box>
218            ))}
219            {shown >= MAX_LANES ? <Text dimColor>… {MAX_LANES} lignes affichées au plus ; filtre ou groupe pour voir le reste.</Text> : null}
220          </Box>
221        ))}
222        <Text> </Text>
223        <Text dimColor wrap="wrap">
224          * hôte déduit des jobs des runs récents du même projet · {empty.filter(a => a.fetched).length} app(s) sans run lu
225          {empty.some(a => !a.fetched) ? ` · ${empty.filter(a => !a.fetched).length} ${DL.not_fetched}` : ''}
226          {' '}· Claude = trailer « Co-Authored-By: Claude », branche claude/* ou worktree-agent-*, ou PR ouverte par une conversation ; Codex = branche codex/*, trailer ou auteur Codex ; le reste « {DL.unknown} ». Estimations : médiane des 3 derniers runs réussis au moins du même job.
227        </Text>
228      </Box>
229    )
230  }
231
232  const s = m.snapshot
233  const head = (
234    <Box flexDirection="row" gap={1}>
235      <Text dimColor>
236        {m.checking ? 'checking…' : `checked ${s?.generated ?? 'never'}`}
237        {problem ? ` · ci.py failed: ${problem}` : ''}
238      </Text>
239      <Button key="refresh" hotkey="r" plain dimColor onPress={() => m.onCheck(true)}>
240        Refresh
241      </Button>
242    </Box>
243  )
244  if (!s) {
245    return (
246      <Box flexDirection="column">
247        {tabs}
248        {head}
249        <Text>No data yet: run /ci or press Refresh.</Text>
250      </Box>
251    )
252  }
253  const L = s.labels
254  const cur = s.current
255  return (
256    <Box flexDirection="column">
257      {tabs}
258      {head}
259      <Text bold>
260        {L.here ?? 'This conversation'}: {cur ? `${cur.backend} (${cur.match} route)` : (L.no_route ?? 'no route')}
261      </Text>
262      <Text> </Text>
263      <Text bold>{L.backends ?? 'Backends'}</Text>
264      {s.backends.map(b => (
265        <Box flexDirection="column">
266          <Text>
267            <Text color={rowColor(L, b)}>{mark(b)} </Text>
268            <Text bold>{b.label}</Text>
269            <Text dimColor>
270              {' '}· {b.id} · {b.kind} · {b.host}
271              {b.runner_tag ? ` · tag ${b.runner_tag}` : ''} · {statusText(L, b.status)}
272            </Text>
273            {b.status === 'active' ? <Text color={rowColor(L, b)}> · {usableText(L, b.check?.usable)}</Text> : null}
274          </Text>
275          <Text dimColor wrap="wrap">{'   '}{checkLine(b)}</Text>
276          {b.notes ? <Text dimColor wrap="wrap">{'   '}{b.notes}</Text> : null}
277        </Box>
278      ))}
279      <Text> </Text>
280      <Text bold>
281        {L.routes ?? 'Routes'} ({s.routes.length}) · {s.routing_file}
282      </Text>
283      {s.routes.length === 0 ? <Text dimColor>none: /ci route here {'<backend-id>'}</Text> : null}
284      {s.routes.map(r => (
285        <Box flexDirection="row" gap={1}>
286          <Text wrap="wrap" bold={cur?.key === r.key}>
287            {cur?.key === r.key ? '▸ ' : '  '}
288            {routeLine(s, r)}
289          </Text>
290          <Button key={`clear-${r.key}`} plain dimColor onPress={() => m.onClear(r.key)}>
291            Clear
292          </Button>
293        </Box>
294      ))}
295      <Text dimColor>Set a route: /ci route {'<repo-path|session-id|here|session> <backend-id>'} · config {s.config}</Text>
296    </Box>
297  )
298}
299
hooks/view.ts 109 lines
1// Pure helpers of the ci mod: argument parsing and text. No `$`, so tests call them directly.
2import type { Backend, Labels, Route, Snapshot, Tri } from '../types'
3
4export const PANE = { id: 'ci-routing', title: 'CI routing' } as const
5
6export type Parsed =
7  | { kind: 'show'; refresh: boolean }
8  | { kind: 'route'; target: string; backend: string }
9  | { kind: 'clear'; target: string }
10  | { kind: 'diagram'; words: string[] }
11  | { kind: 'usage'; text: string }
12
13export const USAGE = 'usage: /ci [refresh] · /ci diagramme [refresh] [claude|codex|inconnu|tout] [hote|app|conv] · /ci route <repo-path|session-id|here|session> <backend-id> · /ci clear <repo-path|session-id|here|session>'
14
15/** `/ci`, `/ci refresh`, `/ci route <target> <backend>`, `/ci clear <target>`. Quotes keep a path with spaces whole. */
16export const parseArgs = (args: string): Parsed => {
17  const words = (args.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map(w => w.replace(/^["']|["']$/g, ''))
18  const [verb = '', ...rest] = words
19  const v = verb.toLowerCase()
20  if (v === '' || v === 'show' || v === 'status') return { kind: 'show', refresh: false }
21  if (v === 'refresh' || v === 'check') return { kind: 'show', refresh: true }
22  if (v === 'diagramme' || v === 'diagram' || v === 'diag' || v === 'pipelines') return { kind: 'diagram', words: rest }
23  if (v === 'route' || v === 'set') {
24    if (rest.length !== 2) return { kind: 'usage', text: USAGE }
25    return { kind: 'route', target: rest[0]!, backend: rest[1]! }
26  }
27  if (v === 'clear' || v === 'unset') {
28    if (rest.length !== 1) return { kind: 'usage', text: USAGE }
29    return { kind: 'clear', target: rest[0]! }
30  }
31  return { kind: 'usage', text: USAGE }
32}
33
34/** `here`/`repo` -> the session's directory, `session`/`this` -> the session id, anything else as typed. */
35export const resolveTarget = (target: string, cwd: string, sessionId: string): string => {
36  const t = target.toLowerCase()
37  if (t === 'here' || t === 'repo' || t === '.') return cwd
38  if (t === 'session' || t === 'this') return sessionId
39  return target
40}
41
42export const usableText = (labels: Labels, u: Tri | undefined): string => labels.usable?.[u ?? 'unknown'] ?? u ?? 'unknown'
43export const statusText = (labels: Labels, s: string): string => labels.status?.[s] ?? s
44
45/** Theme color of a backend row: its usability when active, its status otherwise. */
46export const rowColor = (labels: Labels, b: Backend): string => {
47  const key = b.status !== 'active' ? b.status : (b.check?.usable ?? 'unknown')
48  const fallback: Record<string, string> = { yes: 'success', no: 'error', unknown: 'subtle' }
49  return labels.colors?.[key] ?? fallback[key] ?? 'subtle'
50}
51
52export const mark = (b: Backend): string =>
53  b.status !== 'active' ? '·' : b.check?.usable === 'yes' ? '●' : b.check?.usable === 'no' ? '○' : '?'
54
55const n = (x: number | null | undefined) => (x == null ? '?' : String(x))
56
57/** One line of facts about a backend's check: token, runners, jobs, why. */
58export const checkLine = (b: Backend): string => {
59  const c = b.check
60  if (b.status !== 'active') return b.status
61  if (!c) return 'not checked yet'
62  const parts = [`token ${c.token.present}${c.token.source ? ` (${c.token.source})` : ''}`]
63  if (c.runners) parts.push(`runners ${c.runners.online} online / ${c.runners.total}`)
64  if (c.jobs) parts.push(`jobs ${n(c.jobs.running)} running, ${n(c.jobs.pending)} pending`)
65  for (const a of c.actions) parts.push(`${a.repo}: actions ${a.actions} (${a.why})`)
66  parts.push(c.why)
67  return parts.join(' · ')
68}
69
70export const routeLine = (s: Snapshot, r: Route): string => {
71  const b = s.backends.find(x => x.id === r.backend)
72  return `${r.kind} ${r.key} → ${b?.label ?? r.backend} (${r.backend}) · set by ${r.set_by} · ${r.set_at}`
73}
74
75/** The text /ci answers with. */
76export const summary = (s: Snapshot): string => {
77  const L = s.labels
78  const lines = [`${L.title ?? 'CI routing'} · checked ${s.generated ?? 'never'}${s.stale ? ' (refreshing)' : ''}`]
79  for (const b of s.backends) lines.push(`${mark(b)} ${b.id} · ${b.label} · ${statusText(L, b.status)} · ${b.status === 'active' ? usableText(L, b.check?.usable) : ''}${b.status === 'active' ? ' · ' : ''}${checkLine(b)}`.replace(/ · $/, ''))
80  const cur = s.current
81  lines.push(
82    cur
83      ? `${L.here ?? 'This conversation'}: ${cur.backend} (${cur.match} route ${cur.key}, set by ${cur.set_by} ${cur.set_at})`
84      : `${L.here ?? 'This conversation'}: ${L.no_route ?? 'no route'}`,
85  )
86  lines.push(`${s.routes.length} route(s) in ${s.routing_file}`)
87  return lines.join('\n')
88}
89
90/** The system-prompt note: the route as information, never an instruction to block anything. */
91export const promptNote = (s: Snapshot): string | undefined => {
92  const cur = s.current
93  if (!cur) return undefined
94  const b = s.backends.find(x => x.id === cur.backend)
95  const where = b ? `${b.label} (${b.kind}, ${b.host}${b.runner_tag ? `, runner tag ${b.runner_tag}` : ''})` : cur.backend
96  return `CI route (ci mod): this ${cur.match === 'session' ? 'conversation' : 'repo'} uses CI backend "${cur.backend}": ${where}. ` +
97    `Set by ${cur.set_by} at ${cur.set_at}. Use it for this work's pipelines unless told otherwise; /ci shows all backends and their status.`
98}
99
100export const parseSnapshot = (text: string): Snapshot | undefined => {
101  if (!text) return undefined
102  try {
103    const s = JSON.parse(text) as Snapshot
104    return Array.isArray(s.backends) ? s : undefined
105  } catch {
106    return undefined
107  }
108}
109
lib/core/estimate.mjs 50 lines
1// Canonical copy: lib/core/estimate.mjs (repo root). Every mods/<mod>/lib/core/estimate.mjs is a byte copy made by
2// scripts/sync-libs.mjs: never edit a copy by hand.
3// One estimate rule for Workflows (factory) and pipelines (ci): from past successful durations, the median and the
4// p25-p75 range, ONLY when there are at least MIN_SAMPLES of them; else a fallback list may serve, else no estimate
5// (« pas assez d'historique »). Pure.
6
7export const MIN_SAMPLES = 3
8
9/** n, median, p25, p75 (linear interpolation; same as factory's workflow.mjs quantiles). */
10export function quantiles(xs) {
11  const v = (xs || []).filter((x) => Number.isFinite(x)).sort((a, b) => a - b)
12  if (!v.length) return { n: 0, median: 0, p25: 0, p75: 0 }
13  const q = (p) => {
14    const i = (v.length - 1) * p
15    const lo = Math.floor(i)
16    return v[lo] + (v[Math.min(v.length - 1, lo + 1)] - v[lo]) * (i - lo)
17  }
18  return { n: v.length, median: q(0.5), p25: q(0.25), p75: q(0.75) }
19}
20
21/**
22 * Duration estimate from past successful runs [{ms, ok}] or plain numbers (ms). The first list with at least
23 * `min` successes wins (basis 'primary' or 'fallback'); else {enough: false, n} with the larger sample size.
24 */
25export function estimateOf(runs, { fallback = [], min = MIN_SAMPLES } = {}) {
26  const ok = (xs) => (xs || []).map((r) => (typeof r === 'number' ? r : r && r.ok !== false ? r.ms : NaN)).filter((x) => Number.isFinite(x) && x >= 0)
27  const a = ok(runs)
28  if (a.length >= min) return { enough: true, basis: 'primary', ...quantiles(a) }
29  const b = ok(fallback)
30  if (b.length >= min) return { enough: true, basis: 'fallback', ...quantiles(b) }
31  return { enough: false, basis: null, n: Math.max(a.length, b.length), median: 0, p25: 0, p75: 0 }
32}
33
34/** What is left after `elapsedMs`: {lo, mid, hi} ms (never negative), overrun once past p75. Null without estimate. */
35export function remaining(est, elapsedMs) {
36  if (!est || est.enough === false) return null
37  const e = Math.max(0, elapsedMs || 0)
38  return {
39    lo: Math.max(0, est.p25 - e), mid: Math.max(0, est.median - e), hi: Math.max(0, est.p75 - e),
40    overrun: e > est.p75, n: est.n,
41  }
42}
43
44/** End times {lo, mid, hi} (epoch ms) of something started at startMs, never before now. Null without estimate. */
45export function etaOf(est, startMs, nowMs) {
46  const r = remaining(est, nowMs - startMs)
47  if (!r) return null
48  return { lo: nowMs + r.lo, mid: nowMs + r.mid, hi: nowMs + r.hi, overrun: r.overrun, n: r.n }
49}
50
lib/core/gantt.mjs 111 lines
1// Canonical copy: lib/core/gantt.mjs (repo root). Every mods/<mod>/lib/core/gantt.mjs is a byte copy made by
2// scripts/sync-libs.mjs: never edit a copy by hand.
3// ONE Gantt renderer for Workflow agents (factory) and pipeline jobs (ci), so both look the same. Pure.
4// Input rows: {label, status, queuedMs, startMs, endMs, estEndMs}; status queued | running | done | success | failed |
5// canceled. Output: per row, text segments of exactly `width` cells with one symbol set:
6//   ░ queue   █ done   ▓ running   ▒ failed   ┄ estimate   │ now   · empty
7// svg() draws the same bars as an SVG string: a picture only (not clickable in a mod pane).
8
9export const SYMBOLS = { queue: '░', done: '█', running: '▓', failed: '▒', est: '┄', now: '│', empty: '·' }
10export const LEGEND = { queue: 'file', done: 'fini', running: 'en cours', failed: 'échoué', est: 'estimation', now: 'maintenant' }
11export const COLORS = { queue: '#8b949e', done: '#3fb950', running: '#2f81f7', failed: '#f85149', est: '#8b949e', now: '#d29922', empty: '#8b949e55' }
12
13const fin = (v) => Number.isFinite(v)
14
15/** Kind of the run part of a row. */
16export function runKind(status) {
17  const s = String(status || '').toLowerCase()
18  if (s === 'failed' || s === 'error' || s === 'canceled' || s === 'cancelled') return 'failed'
19  if (s === 'running' || s === 'queued' || s === 'pending') return 'running'
20  return 'done'
21}
22
23const live = (r) => /^(running|queued|pending)$/i.test(String(r.status || ''))
24
25/** Time span shown: earliest queue/start to the latest end, estimated end or now (when something is live). */
26export function span(rows, nowMs) {
27  const starts = rows.flatMap((r) => [r.queuedMs, r.startMs]).filter(fin)
28  const t0 = starts.length ? Math.min(...starts) : nowMs
29  const ends = rows.flatMap((r) => [r.endMs, r.estEndMs, r.startMs]).filter(fin)
30  const t1 = Math.max(t0 + 1000, ...ends, rows.some(live) ? nowMs : t0 + 1000)
31  return { t0, t1 }
32}
33
34/** Rows -> {rows: [{label, status, cells, segs: [{text, kind}]}], t0, t1, width, nowCol}. */
35export function gantt(rows, nowMs, width = 40) {
36  const list = (rows || []).filter((r) => r && (fin(r.queuedMs) || fin(r.startMs)))
37  const w = Math.max(2, Math.floor(width))
38  const { t0, t1 } = span(list, nowMs)
39  const col = (t) => Math.max(0, Math.min(w - 1, Math.floor(((t - t0) / (t1 - t0)) * (w - 1))))
40  const anyLive = list.some(live)
41  const nowCol = anyLive && nowMs >= t0 && nowMs <= t1 ? col(nowMs) : -1
42  const out = list.map((r) => {
43    const kinds = new Array(w).fill('empty')
44    const paint = (a, b, k) => {
45      if (!fin(a) || !fin(b) || b < a) return
46      for (let i = col(a); i <= col(b); i++) kinds[i] = k
47    }
48    const going = live(r)
49    if (fin(r.queuedMs)) paint(r.queuedMs, fin(r.startMs) ? r.startMs : going ? nowMs : r.queuedMs, 'queue')
50    const runEnd = fin(r.endMs) ? r.endMs : going ? nowMs : r.startMs
51    if (fin(r.startMs)) paint(r.startMs, runEnd, runKind(r.status))
52    if (going && fin(r.estEndMs) && r.estEndMs > nowMs) {
53      const from = Math.max(nowMs, fin(runEnd) ? runEnd : nowMs)
54      for (let i = col(from) + 1; i <= col(r.estEndMs); i++) if (kinds[i] === 'empty') kinds[i] = 'est'
55    }
56    if (nowCol >= 0 && kinds[nowCol] === 'empty') kinds[nowCol] = 'now'
57    const segs = []
58    for (const k of kinds) {
59      const last = segs[segs.length - 1]
60      if (last && last.kind === k) last.text += SYMBOLS[k]
61      else segs.push({ text: SYMBOLS[k], kind: k })
62    }
63    return { label: String(r.label ?? ''), status: r.status, cells: kinds, segs }
64  })
65  return { rows: out, t0, t1, width: w, nowCol }
66}
67
68/** The legend line, in symbol order. */
69export function legend(labels = {}) {
70  const L = { ...LEGEND, ...labels }
71  return ['queue', 'done', 'running', 'failed', 'est', 'now'].map((k) => `${SYMBOLS[k]} ${L[k]}`).join('  ')
72}
73
74const clock = (ms) => {
75  const d = new Date(ms)
76  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
77}
78
79/** Axis line: `pad` spaces (label column), then start and end clock times at both ends of the bar. */
80export function axis(g, pad = 0, fmt = clock) {
81  const a = fmt(g.t0)
82  const b = fmt(g.t1)
83  return ' '.repeat(pad) + a + ' '.repeat(Math.max(1, g.width - a.length - b.length)) + b
84}
85
86const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
87
88/** The same Gantt as an SVG string (a picture: labels left, one bar per row). */
89export function svg(g, { cell = 6, row = 14, labelW = 120, colors = {} } = {}) {
90  const C = { ...COLORS, ...colors }
91  const W = labelW + g.width * cell
92  const Hh = Math.max(row, g.rows.length * row)
93  const parts = [`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${Hh}" viewBox="0 0 ${W} ${Hh}">`]
94  g.rows.forEach((r, i) => {
95    const y = i * row
96    parts.push(`<text x="0" y="${y + row - 4}" font-size="${row - 4}" fill="${C.queue}">${esc(r.label)}</text>`)
97    let x = labelW
98    for (const s of r.segs) {
99      const n = [...s.text].length
100      if (s.kind === 'now') parts.push(`<rect x="${x}" y="${y}" width="1" height="${row}" fill="${C.now}"/>`)
101      else if (s.kind !== 'empty') {
102        const dash = s.kind === 'est' ? ' stroke-dasharray="2 2" fill="none" stroke="' + C.est + '"' : ` fill="${C[s.kind]}"`
103        parts.push(`<rect x="${x}" y="${y + 2}" width="${n * cell}" height="${row - 4}"${dash}/>`)
104      }
105      x += n * cell
106    }
107  })
108  parts.push('</svg>')
109  return parts.join('')
110}
111
types/index.d.ts 160 lines
1// Shapes of the JSON that scanner/ci.py prints (`show`) and the `$.state` values of the ci mod.
2
3export type Tri = 'yes' | 'no' | 'unknown'
4export type Check = {
5  id: string
6  /** presence only, never a value: source is 'env:NAME', 'gh', 'glab' or '' */
7  token: { present: Tri; source: string }
8  runners: { online: number; offline: number; total: number } | null
9  jobs: { running: number | null; pending: number | null } | null
10  actions: { repo: string; actions: Tri; why: string }[]
11  usable: Tri
12  why: string
13}
14export type Backend = {
15  id: string
16  label: string
17  kind: 'github' | 'gitlab'
18  host: string
19  runner_tag: string
20  status: 'active' | 'coming-soon' | 'disabled'
21  notes: string
22  group?: string
23  concurrent?: number | string
24  minutes_month?: number
25  check: Check | null
26}
27export type Route = { key: string; kind: 'repo' | 'session'; backend: string; set_by: string; set_at: string }
28export type Labels = {
29  title?: string
30  backends?: string
31  routes?: string
32  here?: string
33  no_route?: string
34  usable?: Partial<Record<Tri, string>>
35  status?: Record<string, string>
36  colors?: Record<string, string>
37}
38export type Snapshot = {
39  generated: string | null
40  stale: boolean
41  config: string
42  routing_file: string
43  labels: Labels
44  options: { status_line: boolean; prompt_note: boolean }
45  backends: Backend[]
46  routes: Route[]
47  current: (Route & { match: 'repo' | 'session' }) | null
48}
49
50// ---- Diagramme view: `ci.py pipelines` (scanner/pipelines.py)
51export type RunStatus = 'success' | 'failed' | 'running' | 'queued' | 'cancelled' | 'skipped'
52export type Who = 'claude' | 'codex' | 'unknown'
53export type Job = {
54  id?: number | string | null
55  name: string
56  stage: string
57  status: RunStatus
58  duration_s: number | null
59  queued_s?: number | null
60  created?: string | null
61  started?: string | null
62  finished?: string | null
63  url?: string
64  /** GitLab allow_failure: a red job that does not make the pipeline red (shown orange, never red) */
65  allow_failure?: boolean
66}
67export type JobEstimate = { n: number; median_s: number | null; start: string | null; end: string | null; samples_s?: number[] }
68export type Estimate = {
69  eta: string | null
70  basis: 'jobs' | 'pipeline' | null
71  samples: number
72  jobs: Record<string, JobEstimate>
73  reason?: string
74  /** successful durations of the lane's last pipelines (basis pipeline, or too few) */
75  durations_s?: number[]
76}
77export type Conv = { id: string; title: string; project: string; pr?: string }
78export type Run = {
79  forge: 'github' | 'gitlab'
80  slug: string
81  backend: string
82  host_inferred?: boolean
83  id: number | string
84  url: string
85  branch: string
86  sha: string
87  event: string
88  title: string
89  workflow: string
90  status: RunStatus
91  created: string | null
92  duration_s: number | null
93  queued_s: number | null
94  jobs: Job[] | null
95  mr: number | null
96  app: string
97  who: Who
98  who_from?: 'conversation'
99  conv: Conv | null
100  /** only for running or queued pipelines */
101  estimate?: Estimate | null
102  host?: string
103}
104export type App = { app: string; path: string; github: string | null; gitlab: string[]; fetched: boolean; runs: Run[] }
105export type Stats = { runs: number; success: number; failed: number; running: number; pass_rate: number | null; minutes: number }
106export type Summary = {
107  today: Stats
108  week: Stats
109  by_host: (Stats & { key: string })[]
110  by_who: (Stats & { key: string })[]
111  by_app: (Stats & { key: string })[]
112  queue: { backend: string; label: string; tag: string; running: number | null; pending: number | null; runners_online: number | null; pipelines_open: number
113    concurrent?: number | null; wait_s?: number | null; wait_n?: number } | null
114}
115export type DiagramLabels = Partial<Record<
116  'tab_routing' | 'tab_diagram' | 'all' | 'claude' | 'codex' | 'unknown' | 'by_host' | 'by_app' | 'by_conv' | 'no_conv' |
117  'today' | 'week' | 'pass_rate' | 'minutes' | 'queue' | 'last_runs' | 'no_runs' | 'not_fetched', string>> & {
118  status?: Partial<Record<RunStatus, string>>
119}
120export type Diagram = {
121  generated: string | null
122  stale: boolean
123  hosts: { id: string; label: string; kind: string; runner_tag: string; status: string }[]
124  labels: DiagramLabels
125  colors?: Partial<Record<RunStatus, string>>
126  svg_colors?: Record<string, string>
127  /** filter the Diagramme opens on (config pipelines.default_who; 'claude' when absent) */
128  default_who?: WhoFilter
129  summary: Summary | null
130  apps: App[]
131  conversations: (Conv & { runs: number })[]
132}
133export type WhoFilter = 'all' | Who
134export type GroupBy = 'host' | 'app' | 'conv'
135
136declare module 'claude-code' {
137  interface PluginState {
138    ci: {
139      /** which tab of the pane shows: CI routing or the pipeline diagram */
140      tab: 'routing' | 'diagram'
141      /** last `ci.py pipelines` output as JSON text ('' before the first read) */
142      diagram: string
143      /** a pipelines fetch (gh/glab) is running */
144      fetching: boolean
145      /** Diagramme filters: who made the run ('' = the config default, Claude Code unless pipelines.default_who says
146       *  otherwise), and how lanes are grouped */
147      who: WhoFilter | ''
148      group: GroupBy
149      /** keys of the Diagramme sections folded by the viewer; `gantt:<lane>` keys are lanes unfolded to their Gantt */
150      folded: string[]
151      /** last `ci.py show` output as JSON text ('' before the first read) */
152      snapshot: string
153      /** a status check (network) is running */
154      checking: boolean
155      /** last error line from ci.py, '' when fine */
156      error: string
157    }
158  }
159}
160